commit 1591062eef88582c5e8fe61bbaf7c90279f88dc7 Author: yexingqiang Date: Mon Jun 8 10:59:21 2026 +0800 chore: 初始化合力差速器MES采集程序 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..e964c17 --- /dev/null +++ b/.gitignore @@ -0,0 +1,13 @@ +# Visual Studio / .NET build artifacts +[Bb]in/ +[Oo]bj/ +.vs/ +packages/ +*.user +*.suo +*.cache + +# Logs +*.log +输出-调试.txt + diff --git a/AllProject/AllProject.sln b/AllProject/AllProject.sln new file mode 100644 index 0000000..0c5c084 --- /dev/null +++ b/AllProject/AllProject.sln @@ -0,0 +1,91 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.32901.82 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AllProject", "AllProject\AllProject.csproj", "{B1BE81E0-92C2-4917-A371-3B5FEBB9130A}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "00-0Json8.3.1", "..\Common\00-1Json8.3\Json8.3\00-0Json8.3.1.csproj", "{1A10FDB2-1A6A-44A8-AB4D-33387563247E}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "00MesWorkMqtt", "..\Common\00MesWorkMqtt\MesWorkMqtt\00MesWorkMqtt.csproj", "{F55DA1A0-A982-4479-8C47-0D9A5AAF3E18}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "01_01DoWhatPlc", "..\Common\01DoWhatPlc\01_01DoWhatPlc.csproj", "{0D1AF432-439A-4920-8692-43AE139F5530}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "02_02WebApiCallPLC", "..\Common\02WebApiCall\02_02WebApiCallPLC.csproj", "{3E6D1DD5-01C9-435F-9941-61F906CE35BB}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "04-DataBaseAccess", "..\Common\04DataBaseAccess\DataBaseAccess\04-DataBaseAccess.csproj", "{F434E066-4C59-47C8-AA82-6F48CC84501A}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "07BusinessFacade", "..\Common\07WebBusinessFacade\BusinessFacade\07BusinessFacade.csproj", "{F0A0C525-03FD-428A-9B17-7F54AA0E4475}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "08-WebFun_base", "..\Common\08WebFun_base\WebFun_base\08-WebFun_base.csproj", "{D98BE764-ADEB-488D-9714-61E308AA8201}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "09-MesDataFunction", "..\Common\09MesDataFunction\MesDataFunction\09-MesDataFunction.csproj", "{90E76FB4-646D-45E2-95DB-0B8AB4E465D6}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Common", "Common", "{9B678E8D-8B21-4F41-9A5D-DD3FF4E304D0}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SyUpLoad", "..\SyUpLoad\SyUpLoad\SyUpLoad.csproj", "{81604748-73C5-43FA-8E27-BE0AB28618C3}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {B1BE81E0-92C2-4917-A371-3B5FEBB9130A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B1BE81E0-92C2-4917-A371-3B5FEBB9130A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B1BE81E0-92C2-4917-A371-3B5FEBB9130A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B1BE81E0-92C2-4917-A371-3B5FEBB9130A}.Release|Any CPU.Build.0 = Release|Any CPU + {1A10FDB2-1A6A-44A8-AB4D-33387563247E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {1A10FDB2-1A6A-44A8-AB4D-33387563247E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {1A10FDB2-1A6A-44A8-AB4D-33387563247E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {1A10FDB2-1A6A-44A8-AB4D-33387563247E}.Release|Any CPU.Build.0 = Release|Any CPU + {F55DA1A0-A982-4479-8C47-0D9A5AAF3E18}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F55DA1A0-A982-4479-8C47-0D9A5AAF3E18}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F55DA1A0-A982-4479-8C47-0D9A5AAF3E18}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F55DA1A0-A982-4479-8C47-0D9A5AAF3E18}.Release|Any CPU.Build.0 = Release|Any CPU + {0D1AF432-439A-4920-8692-43AE139F5530}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {0D1AF432-439A-4920-8692-43AE139F5530}.Debug|Any CPU.Build.0 = Debug|Any CPU + {0D1AF432-439A-4920-8692-43AE139F5530}.Release|Any CPU.ActiveCfg = Release|Any CPU + {0D1AF432-439A-4920-8692-43AE139F5530}.Release|Any CPU.Build.0 = Release|Any CPU + {3E6D1DD5-01C9-435F-9941-61F906CE35BB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {3E6D1DD5-01C9-435F-9941-61F906CE35BB}.Debug|Any CPU.Build.0 = Debug|Any CPU + {3E6D1DD5-01C9-435F-9941-61F906CE35BB}.Release|Any CPU.ActiveCfg = Release|Any CPU + {3E6D1DD5-01C9-435F-9941-61F906CE35BB}.Release|Any CPU.Build.0 = Release|Any CPU + {F434E066-4C59-47C8-AA82-6F48CC84501A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F434E066-4C59-47C8-AA82-6F48CC84501A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F434E066-4C59-47C8-AA82-6F48CC84501A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F434E066-4C59-47C8-AA82-6F48CC84501A}.Release|Any CPU.Build.0 = Release|Any CPU + {F0A0C525-03FD-428A-9B17-7F54AA0E4475}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F0A0C525-03FD-428A-9B17-7F54AA0E4475}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F0A0C525-03FD-428A-9B17-7F54AA0E4475}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F0A0C525-03FD-428A-9B17-7F54AA0E4475}.Release|Any CPU.Build.0 = Release|Any CPU + {D98BE764-ADEB-488D-9714-61E308AA8201}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {D98BE764-ADEB-488D-9714-61E308AA8201}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D98BE764-ADEB-488D-9714-61E308AA8201}.Release|Any CPU.ActiveCfg = Release|Any CPU + {D98BE764-ADEB-488D-9714-61E308AA8201}.Release|Any CPU.Build.0 = Release|Any CPU + {90E76FB4-646D-45E2-95DB-0B8AB4E465D6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {90E76FB4-646D-45E2-95DB-0B8AB4E465D6}.Debug|Any CPU.Build.0 = Debug|Any CPU + {90E76FB4-646D-45E2-95DB-0B8AB4E465D6}.Release|Any CPU.ActiveCfg = Release|Any CPU + {90E76FB4-646D-45E2-95DB-0B8AB4E465D6}.Release|Any CPU.Build.0 = Release|Any CPU + {81604748-73C5-43FA-8E27-BE0AB28618C3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {81604748-73C5-43FA-8E27-BE0AB28618C3}.Debug|Any CPU.Build.0 = Debug|Any CPU + {81604748-73C5-43FA-8E27-BE0AB28618C3}.Release|Any CPU.ActiveCfg = Release|Any CPU + {81604748-73C5-43FA-8E27-BE0AB28618C3}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {1A10FDB2-1A6A-44A8-AB4D-33387563247E} = {9B678E8D-8B21-4F41-9A5D-DD3FF4E304D0} + {F55DA1A0-A982-4479-8C47-0D9A5AAF3E18} = {9B678E8D-8B21-4F41-9A5D-DD3FF4E304D0} + {0D1AF432-439A-4920-8692-43AE139F5530} = {9B678E8D-8B21-4F41-9A5D-DD3FF4E304D0} + {3E6D1DD5-01C9-435F-9941-61F906CE35BB} = {9B678E8D-8B21-4F41-9A5D-DD3FF4E304D0} + {F434E066-4C59-47C8-AA82-6F48CC84501A} = {9B678E8D-8B21-4F41-9A5D-DD3FF4E304D0} + {F0A0C525-03FD-428A-9B17-7F54AA0E4475} = {9B678E8D-8B21-4F41-9A5D-DD3FF4E304D0} + {D98BE764-ADEB-488D-9714-61E308AA8201} = {9B678E8D-8B21-4F41-9A5D-DD3FF4E304D0} + {90E76FB4-646D-45E2-95DB-0B8AB4E465D6} = {9B678E8D-8B21-4F41-9A5D-DD3FF4E304D0} + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {1E934AE4-5695-475E-9380-9EE6DDD95304} + EndGlobalSection +EndGlobal diff --git a/AllProject/AllProject/AllProject.csproj b/AllProject/AllProject/AllProject.csproj new file mode 100644 index 0000000..aacd931 --- /dev/null +++ b/AllProject/AllProject/AllProject.csproj @@ -0,0 +1,80 @@ + + + + + Debug + AnyCPU + {B1BE81E0-92C2-4917-A371-3B5FEBB9130A} + WinExe + AllProject + AllProject + v4.6.1 + 512 + true + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + Form + + + Form1.cs + + + + + ResXFileCodeGenerator + Resources.Designer.cs + Designer + + + True + Resources.resx + + + SettingsSingleFileGenerator + Settings.Designer.cs + + + True + Settings.settings + True + + + + + + + \ No newline at end of file diff --git a/AllProject/AllProject/App.config b/AllProject/AllProject/App.config new file mode 100644 index 0000000..731f6de --- /dev/null +++ b/AllProject/AllProject/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/AllProject/AllProject/Form1.Designer.cs b/AllProject/AllProject/Form1.Designer.cs new file mode 100644 index 0000000..80eb14f --- /dev/null +++ b/AllProject/AllProject/Form1.Designer.cs @@ -0,0 +1,41 @@ + +namespace AllProject +{ + partial class Form1 + { + /// + /// 必需的设计器变量。 + /// + 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.components = new System.ComponentModel.Container(); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(800, 450); + this.Text = "Form1"; + } + + #endregion + } +} + diff --git a/AllProject/AllProject/Form1.cs b/AllProject/AllProject/Form1.cs new file mode 100644 index 0000000..bf97e02 --- /dev/null +++ b/AllProject/AllProject/Form1.cs @@ -0,0 +1,20 @@ +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 AllProject +{ + public partial class Form1 : Form + { + public Form1() + { + InitializeComponent(); + } + } +} diff --git a/AllProject/AllProject/Program.cs b/AllProject/AllProject/Program.cs new file mode 100644 index 0000000..fa7ceeb --- /dev/null +++ b/AllProject/AllProject/Program.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace AllProject +{ + static class Program + { + /// + /// 应用程序的主入口点。 + /// + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + Application.Run(new Form1()); + } + } +} diff --git a/AllProject/AllProject/Properties/AssemblyInfo.cs b/AllProject/AllProject/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..58df017 --- /dev/null +++ b/AllProject/AllProject/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// 有关程序集的一般信息由以下 +// 控制。更改这些特性值可修改 +// 与程序集关联的信息。 +[assembly: AssemblyTitle("AllProject")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("AllProject")] +[assembly: AssemblyCopyright("Copyright © 2022")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// 将 ComVisible 设置为 false 会使此程序集中的类型 +//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型 +//请将此类型的 ComVisible 特性设置为 true。 +[assembly: ComVisible(false)] + +// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID +[assembly: Guid("b1be81e0-92c2-4917-a371-3b5febb9130a")] + +// 程序集的版本信息由下列四个值组成: +// +// 主版本 +// 次版本 +// 生成号 +// 修订号 +// +//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值 +//通过使用 "*",如下所示: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/AllProject/AllProject/Properties/Resources.Designer.cs b/AllProject/AllProject/Properties/Resources.Designer.cs new file mode 100644 index 0000000..f11efeb --- /dev/null +++ b/AllProject/AllProject/Properties/Resources.Designer.cs @@ -0,0 +1,70 @@ +//------------------------------------------------------------------------------ +// +// 此代码由工具生成。 +// 运行时版本: 4.0.30319.42000 +// +// 对此文件的更改可能导致不正确的行为,如果 +// 重新生成代码,则所做更改将丢失。 +// +//------------------------------------------------------------------------------ + + +namespace AllProject.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("AllProject.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/AllProject/AllProject/Properties/Resources.resx b/AllProject/AllProject/Properties/Resources.resx new file mode 100644 index 0000000..af7dbeb --- /dev/null +++ b/AllProject/AllProject/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/AllProject/AllProject/Properties/Settings.Designer.cs b/AllProject/AllProject/Properties/Settings.Designer.cs new file mode 100644 index 0000000..cf88263 --- /dev/null +++ b/AllProject/AllProject/Properties/Settings.Designer.cs @@ -0,0 +1,29 @@ +//------------------------------------------------------------------------------ +// +// 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 AllProject.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/AllProject/AllProject/Properties/Settings.settings b/AllProject/AllProject/Properties/Settings.settings new file mode 100644 index 0000000..3964565 --- /dev/null +++ b/AllProject/AllProject/Properties/Settings.settings @@ -0,0 +1,7 @@ + + + + + + + diff --git a/Common/00-1Json8.3/Json8.3.1.sln b/Common/00-1Json8.3/Json8.3.1.sln new file mode 100644 index 0000000..66b32b1 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3.1.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.32901.82 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Json8.3.1", "Json8.3\Json8.3.1.csproj", "{1A10FDB2-1A6A-44A8-AB4D-33387563247E}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {1A10FDB2-1A6A-44A8-AB4D-33387563247E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {1A10FDB2-1A6A-44A8-AB4D-33387563247E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {1A10FDB2-1A6A-44A8-AB4D-33387563247E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {1A10FDB2-1A6A-44A8-AB4D-33387563247E}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {D9ACD33B-2F73-4386-803A-D240435BDD0C} + EndGlobalSection +EndGlobal diff --git a/Common/00-1Json8.3/Json8.3/00-0Json8.3.1.csproj b/Common/00-1Json8.3/Json8.3/00-0Json8.3.1.csproj new file mode 100644 index 0000000..42dada8 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/00-0Json8.3.1.csproj @@ -0,0 +1,244 @@ + + + + + Debug + AnyCPU + {1A10FDB2-1A6A-44A8-AB4D-33387563247E} + Library + Properties + Newtonsoft.Json + 00.1Newtonsoft.Json + v4.8 + 512 + true + + + + true + full + false + ..\..\dll\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Bson/BsonBinaryType.cs b/Common/00-1Json8.3/Json8.3/Bson/BsonBinaryType.cs new file mode 100644 index 0000000..638039f --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Bson/BsonBinaryType.cs @@ -0,0 +1,44 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; + +namespace Newtonsoft.Json.Bson +{ + internal enum BsonBinaryType : byte + { + Binary = 0x00, + Function = 0x01, + + [Obsolete("This type has been deprecated in the BSON specification. Use Binary instead.")] + BinaryOld = 0x02, + + [Obsolete("This type has been deprecated in the BSON specification. Use Uuid instead.")] + UuidOld = 0x03, + Uuid = 0x04, + Md5 = 0x05, + UserDefined = 0x80 + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Bson/BsonBinaryWriter.cs b/Common/00-1Json8.3/Json8.3/Bson/BsonBinaryWriter.cs new file mode 100644 index 0000000..5cd2bbf --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Bson/BsonBinaryWriter.cs @@ -0,0 +1,331 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Globalization; +using System.IO; +using System.Text; +using Newtonsoft.Json.Utilities; + +namespace Newtonsoft.Json.Bson +{ + internal class BsonBinaryWriter + { + private static readonly Encoding Encoding = new UTF8Encoding(false); + + private readonly BinaryWriter _writer; + + private byte[] _largeByteBuffer; + + public DateTimeKind DateTimeKindHandling { get; set; } + + public BsonBinaryWriter(BinaryWriter writer) + { + DateTimeKindHandling = DateTimeKind.Utc; + _writer = writer; + } + + public void Flush() + { + _writer.Flush(); + } + + public void Close() + { +#if !(DOTNET || PORTABLE40 || PORTABLE) + _writer.Close(); +#else + _writer.Dispose(); +#endif + } + + public void WriteToken(BsonToken t) + { + CalculateSize(t); + WriteTokenInternal(t); + } + + private void WriteTokenInternal(BsonToken t) + { + switch (t.Type) + { + case BsonType.Object: + { + BsonObject value = (BsonObject)t; + _writer.Write(value.CalculatedSize); + foreach (BsonProperty property in value) + { + _writer.Write((sbyte)property.Value.Type); + WriteString((string)property.Name.Value, property.Name.ByteCount, null); + WriteTokenInternal(property.Value); + } + _writer.Write((byte)0); + } + break; + case BsonType.Array: + { + BsonArray value = (BsonArray)t; + _writer.Write(value.CalculatedSize); + ulong index = 0; + foreach (BsonToken c in value) + { + _writer.Write((sbyte)c.Type); + WriteString(index.ToString(CultureInfo.InvariantCulture), MathUtils.IntLength(index), null); + WriteTokenInternal(c); + index++; + } + _writer.Write((byte)0); + } + break; + case BsonType.Integer: + { + BsonValue value = (BsonValue)t; + _writer.Write(Convert.ToInt32(value.Value, CultureInfo.InvariantCulture)); + } + break; + case BsonType.Long: + { + BsonValue value = (BsonValue)t; + _writer.Write(Convert.ToInt64(value.Value, CultureInfo.InvariantCulture)); + } + break; + case BsonType.Number: + { + BsonValue value = (BsonValue)t; + _writer.Write(Convert.ToDouble(value.Value, CultureInfo.InvariantCulture)); + } + break; + case BsonType.String: + { + BsonString value = (BsonString)t; + WriteString((string)value.Value, value.ByteCount, value.CalculatedSize - 4); + } + break; + case BsonType.Boolean: + { + BsonValue value = (BsonValue)t; + _writer.Write((bool)value.Value); + } + break; + case BsonType.Null: + case BsonType.Undefined: + break; + case BsonType.Date: + { + BsonValue value = (BsonValue)t; + + long ticks = 0; + + if (value.Value is DateTime) + { + DateTime dateTime = (DateTime)value.Value; + if (DateTimeKindHandling == DateTimeKind.Utc) + { + dateTime = dateTime.ToUniversalTime(); + } + else if (DateTimeKindHandling == DateTimeKind.Local) + { + dateTime = dateTime.ToLocalTime(); + } + + ticks = DateTimeUtils.ConvertDateTimeToJavaScriptTicks(dateTime, false); + } +#if !NET20 + else + { + DateTimeOffset dateTimeOffset = (DateTimeOffset)value.Value; + ticks = DateTimeUtils.ConvertDateTimeToJavaScriptTicks(dateTimeOffset.UtcDateTime, dateTimeOffset.Offset); + } +#endif + + _writer.Write(ticks); + } + break; + case BsonType.Binary: + { + BsonBinary value = (BsonBinary)t; + + byte[] data = (byte[])value.Value; + _writer.Write(data.Length); + _writer.Write((byte)value.BinaryType); + _writer.Write(data); + } + break; + case BsonType.Oid: + { + BsonValue value = (BsonValue)t; + + byte[] data = (byte[])value.Value; + _writer.Write(data); + } + break; + case BsonType.Regex: + { + BsonRegex value = (BsonRegex)t; + + WriteString((string)value.Pattern.Value, value.Pattern.ByteCount, null); + WriteString((string)value.Options.Value, value.Options.ByteCount, null); + } + break; + default: + throw new ArgumentOutOfRangeException(nameof(t), "Unexpected token when writing BSON: {0}".FormatWith(CultureInfo.InvariantCulture, t.Type)); + } + } + + private void WriteString(string s, int byteCount, int? calculatedlengthPrefix) + { + if (calculatedlengthPrefix != null) + { + _writer.Write(calculatedlengthPrefix.GetValueOrDefault()); + } + + WriteUtf8Bytes(s, byteCount); + + _writer.Write((byte)0); + } + + public void WriteUtf8Bytes(string s, int byteCount) + { + if (s != null) + { + if (_largeByteBuffer == null) + { + _largeByteBuffer = new byte[256]; + } + if (byteCount <= 256) + { + Encoding.GetBytes(s, 0, s.Length, _largeByteBuffer, 0); + _writer.Write(_largeByteBuffer, 0, byteCount); + } + else + { + byte[] bytes = Encoding.GetBytes(s); + _writer.Write(bytes); + } + } + } + + private int CalculateSize(int stringByteCount) + { + return stringByteCount + 1; + } + + private int CalculateSizeWithLength(int stringByteCount, bool includeSize) + { + int baseSize = (includeSize) + ? 5 // size bytes + terminator + : 1; // terminator + + return baseSize + stringByteCount; + } + + private int CalculateSize(BsonToken t) + { + switch (t.Type) + { + case BsonType.Object: + { + BsonObject value = (BsonObject)t; + + int bases = 4; + foreach (BsonProperty p in value) + { + int size = 1; + size += CalculateSize(p.Name); + size += CalculateSize(p.Value); + + bases += size; + } + bases += 1; + value.CalculatedSize = bases; + return bases; + } + case BsonType.Array: + { + BsonArray value = (BsonArray)t; + + int size = 4; + ulong index = 0; + foreach (BsonToken c in value) + { + size += 1; + size += CalculateSize(MathUtils.IntLength(index)); + size += CalculateSize(c); + index++; + } + size += 1; + value.CalculatedSize = size; + + return value.CalculatedSize; + } + case BsonType.Integer: + return 4; + case BsonType.Long: + return 8; + case BsonType.Number: + return 8; + case BsonType.String: + { + BsonString value = (BsonString)t; + string s = (string)value.Value; + value.ByteCount = (s != null) ? Encoding.GetByteCount(s) : 0; + value.CalculatedSize = CalculateSizeWithLength(value.ByteCount, value.IncludeLength); + + return value.CalculatedSize; + } + case BsonType.Boolean: + return 1; + case BsonType.Null: + case BsonType.Undefined: + return 0; + case BsonType.Date: + return 8; + case BsonType.Binary: + { + BsonBinary value = (BsonBinary)t; + + byte[] data = (byte[])value.Value; + value.CalculatedSize = 4 + 1 + data.Length; + + return value.CalculatedSize; + } + case BsonType.Oid: + return 12; + case BsonType.Regex: + { + BsonRegex value = (BsonRegex)t; + int size = 0; + size += CalculateSize(value.Pattern); + size += CalculateSize(value.Options); + value.CalculatedSize = size; + + return value.CalculatedSize; + } + default: + throw new ArgumentOutOfRangeException(nameof(t), "Unexpected token when writing BSON: {0}".FormatWith(CultureInfo.InvariantCulture, t.Type)); + } + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Bson/BsonObjectId.cs b/Common/00-1Json8.3/Json8.3/Bson/BsonObjectId.cs new file mode 100644 index 0000000..0bb603e --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Bson/BsonObjectId.cs @@ -0,0 +1,57 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using Newtonsoft.Json.Utilities; + +namespace Newtonsoft.Json.Bson +{ + /// + /// Represents a BSON Oid (object id). + /// + public class BsonObjectId + { + /// + /// Gets or sets the value of the Oid. + /// + /// The value of the Oid. + public byte[] Value { get; private set; } + + /// + /// Initializes a new instance of the class. + /// + /// The Oid value. + public BsonObjectId(byte[] value) + { + ValidationUtils.ArgumentNotNull(value, nameof(value)); + if (value.Length != 12) + { + throw new ArgumentException("An ObjectId must be 12 bytes", nameof(value)); + } + + Value = value; + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Bson/BsonReader.cs b/Common/00-1Json8.3/Json8.3/Bson/BsonReader.cs new file mode 100644 index 0000000..0ea895a --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Bson/BsonReader.cs @@ -0,0 +1,827 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Text; +using System.IO; +using Newtonsoft.Json.Serialization; +using Newtonsoft.Json.Utilities; +using Newtonsoft.Json.Linq; + +namespace Newtonsoft.Json.Bson +{ + /// + /// Represents a reader that provides fast, non-cached, forward-only access to serialized JSON data. + /// + public class BsonReader : JsonReader + { + private const int MaxCharBytesSize = 128; + private static readonly byte[] SeqRange1 = new byte[] { 0, 127 }; // range of 1-byte sequence + private static readonly byte[] SeqRange2 = new byte[] { 194, 223 }; // range of 2-byte sequence + private static readonly byte[] SeqRange3 = new byte[] { 224, 239 }; // range of 3-byte sequence + private static readonly byte[] SeqRange4 = new byte[] { 240, 244 }; // range of 4-byte sequence + + private readonly BinaryReader _reader; + private readonly List _stack; + + private byte[] _byteBuffer; + private char[] _charBuffer; + + private BsonType _currentElementType; + private BsonReaderState _bsonReaderState; + private ContainerContext _currentContext; + + private bool _readRootValueAsArray; + private bool _jsonNet35BinaryCompatibility; + private DateTimeKind _dateTimeKindHandling; + + private enum BsonReaderState + { + Normal = 0, + ReferenceStart = 1, + ReferenceRef = 2, + ReferenceId = 3, + CodeWScopeStart = 4, + CodeWScopeCode = 5, + CodeWScopeScope = 6, + CodeWScopeScopeObject = 7, + CodeWScopeScopeEnd = 8 + } + + private class ContainerContext + { + public readonly BsonType Type; + public int Length; + public int Position; + + public ContainerContext(BsonType type) + { + Type = type; + } + } + + /// + /// Gets or sets a value indicating whether binary data reading should compatible with incorrect Json.NET 3.5 written binary. + /// + /// + /// true if binary data reading will be compatible with incorrect Json.NET 3.5 written binary; otherwise, false. + /// + [Obsolete("JsonNet35BinaryCompatibility will be removed in a future version of Json.NET.")] + public bool JsonNet35BinaryCompatibility + { + get { return _jsonNet35BinaryCompatibility; } + set { _jsonNet35BinaryCompatibility = value; } + } + + /// + /// Gets or sets a value indicating whether the root object will be read as a JSON array. + /// + /// + /// true if the root object will be read as a JSON array; otherwise, false. + /// + public bool ReadRootValueAsArray + { + get { return _readRootValueAsArray; } + set { _readRootValueAsArray = value; } + } + + /// + /// Gets or sets the used when reading values from BSON. + /// + /// The used when reading values from BSON. + public DateTimeKind DateTimeKindHandling + { + get { return _dateTimeKindHandling; } + set { _dateTimeKindHandling = value; } + } + + /// + /// Initializes a new instance of the class. + /// + /// The stream. + public BsonReader(Stream stream) + : this(stream, false, DateTimeKind.Local) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The reader. + public BsonReader(BinaryReader reader) + : this(reader, false, DateTimeKind.Local) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The stream. + /// if set to true the root object will be read as a JSON array. + /// The used when reading values from BSON. + public BsonReader(Stream stream, bool readRootValueAsArray, DateTimeKind dateTimeKindHandling) + { + ValidationUtils.ArgumentNotNull(stream, nameof(stream)); + _reader = new BinaryReader(stream); + _stack = new List(); + _readRootValueAsArray = readRootValueAsArray; + _dateTimeKindHandling = dateTimeKindHandling; + } + + /// + /// Initializes a new instance of the class. + /// + /// The reader. + /// if set to true the root object will be read as a JSON array. + /// The used when reading values from BSON. + public BsonReader(BinaryReader reader, bool readRootValueAsArray, DateTimeKind dateTimeKindHandling) + { + ValidationUtils.ArgumentNotNull(reader, nameof(reader)); + _reader = reader; + _stack = new List(); + _readRootValueAsArray = readRootValueAsArray; + _dateTimeKindHandling = dateTimeKindHandling; + } + + private string ReadElement() + { + _currentElementType = ReadType(); + string elementName = ReadString(); + return elementName; + } + + /// + /// Reads the next JSON token from the stream. + /// + /// + /// true if the next token was read successfully; false if there are no more tokens to read. + /// + public override bool Read() + { + try + { + bool success; + + switch (_bsonReaderState) + { + case BsonReaderState.Normal: + success = ReadNormal(); + break; + case BsonReaderState.ReferenceStart: + case BsonReaderState.ReferenceRef: + case BsonReaderState.ReferenceId: + success = ReadReference(); + break; + case BsonReaderState.CodeWScopeStart: + case BsonReaderState.CodeWScopeCode: + case BsonReaderState.CodeWScopeScope: + case BsonReaderState.CodeWScopeScopeObject: + case BsonReaderState.CodeWScopeScopeEnd: + success = ReadCodeWScope(); + break; + default: + throw JsonReaderException.Create(this, "Unexpected state: {0}".FormatWith(CultureInfo.InvariantCulture, _bsonReaderState)); + } + + if (!success) + { + SetToken(JsonToken.None); + return false; + } + + return true; + } + catch (EndOfStreamException) + { + SetToken(JsonToken.None); + return false; + } + } + + /// + /// Changes the to Closed. + /// + public override void Close() + { + base.Close(); + + if (CloseInput && _reader != null) + { +#if !(DOTNET || PORTABLE40 || PORTABLE) + _reader.Close(); +#else + _reader.Dispose(); +#endif + } + } + + private bool ReadCodeWScope() + { + switch (_bsonReaderState) + { + case BsonReaderState.CodeWScopeStart: + SetToken(JsonToken.PropertyName, "$code"); + _bsonReaderState = BsonReaderState.CodeWScopeCode; + return true; + case BsonReaderState.CodeWScopeCode: + // total CodeWScope size - not used + ReadInt32(); + + SetToken(JsonToken.String, ReadLengthString()); + _bsonReaderState = BsonReaderState.CodeWScopeScope; + return true; + case BsonReaderState.CodeWScopeScope: + if (CurrentState == State.PostValue) + { + SetToken(JsonToken.PropertyName, "$scope"); + return true; + } + else + { + SetToken(JsonToken.StartObject); + _bsonReaderState = BsonReaderState.CodeWScopeScopeObject; + + ContainerContext newContext = new ContainerContext(BsonType.Object); + PushContext(newContext); + newContext.Length = ReadInt32(); + + return true; + } + case BsonReaderState.CodeWScopeScopeObject: + bool result = ReadNormal(); + if (result && TokenType == JsonToken.EndObject) + { + _bsonReaderState = BsonReaderState.CodeWScopeScopeEnd; + } + + return result; + case BsonReaderState.CodeWScopeScopeEnd: + SetToken(JsonToken.EndObject); + _bsonReaderState = BsonReaderState.Normal; + return true; + default: + throw new ArgumentOutOfRangeException(); + } + } + + private bool ReadReference() + { + switch (CurrentState) + { + case State.ObjectStart: + { + SetToken(JsonToken.PropertyName, JsonTypeReflector.RefPropertyName); + _bsonReaderState = BsonReaderState.ReferenceRef; + return true; + } + case State.Property: + { + if (_bsonReaderState == BsonReaderState.ReferenceRef) + { + SetToken(JsonToken.String, ReadLengthString()); + return true; + } + else if (_bsonReaderState == BsonReaderState.ReferenceId) + { + SetToken(JsonToken.Bytes, ReadBytes(12)); + return true; + } + else + { + throw JsonReaderException.Create(this, "Unexpected state when reading BSON reference: " + _bsonReaderState); + } + } + case State.PostValue: + { + if (_bsonReaderState == BsonReaderState.ReferenceRef) + { + SetToken(JsonToken.PropertyName, JsonTypeReflector.IdPropertyName); + _bsonReaderState = BsonReaderState.ReferenceId; + return true; + } + else if (_bsonReaderState == BsonReaderState.ReferenceId) + { + SetToken(JsonToken.EndObject); + _bsonReaderState = BsonReaderState.Normal; + return true; + } + else + { + throw JsonReaderException.Create(this, "Unexpected state when reading BSON reference: " + _bsonReaderState); + } + } + default: + throw JsonReaderException.Create(this, "Unexpected state when reading BSON reference: " + CurrentState); + } + } + + private bool ReadNormal() + { + switch (CurrentState) + { + case State.Start: + { + JsonToken token = (!_readRootValueAsArray) ? JsonToken.StartObject : JsonToken.StartArray; + BsonType type = (!_readRootValueAsArray) ? BsonType.Object : BsonType.Array; + + SetToken(token); + ContainerContext newContext = new ContainerContext(type); + PushContext(newContext); + newContext.Length = ReadInt32(); + return true; + } + case State.Complete: + case State.Closed: + return false; + case State.Property: + { + ReadType(_currentElementType); + return true; + } + case State.ObjectStart: + case State.ArrayStart: + case State.PostValue: + ContainerContext context = _currentContext; + if (context == null) + { + return false; + } + + int lengthMinusEnd = context.Length - 1; + + if (context.Position < lengthMinusEnd) + { + if (context.Type == BsonType.Array) + { + ReadElement(); + ReadType(_currentElementType); + return true; + } + else + { + SetToken(JsonToken.PropertyName, ReadElement()); + return true; + } + } + else if (context.Position == lengthMinusEnd) + { + if (ReadByte() != 0) + { + throw JsonReaderException.Create(this, "Unexpected end of object byte value."); + } + + PopContext(); + if (_currentContext != null) + { + MovePosition(context.Length); + } + + JsonToken endToken = (context.Type == BsonType.Object) ? JsonToken.EndObject : JsonToken.EndArray; + SetToken(endToken); + return true; + } + else + { + throw JsonReaderException.Create(this, "Read past end of current container context."); + } + case State.ConstructorStart: + break; + case State.Constructor: + break; + case State.Error: + break; + case State.Finished: + break; + default: + throw new ArgumentOutOfRangeException(); + } + + return false; + } + + private void PopContext() + { + _stack.RemoveAt(_stack.Count - 1); + if (_stack.Count == 0) + { + _currentContext = null; + } + else + { + _currentContext = _stack[_stack.Count - 1]; + } + } + + private void PushContext(ContainerContext newContext) + { + _stack.Add(newContext); + _currentContext = newContext; + } + + private byte ReadByte() + { + MovePosition(1); + return _reader.ReadByte(); + } + + private void ReadType(BsonType type) + { + switch (type) + { + case BsonType.Number: + double d = ReadDouble(); + + if (_floatParseHandling == FloatParseHandling.Decimal) + { + SetToken(JsonToken.Float, Convert.ToDecimal(d, CultureInfo.InvariantCulture)); + } + else + { + SetToken(JsonToken.Float, d); + } + break; + case BsonType.String: + case BsonType.Symbol: + SetToken(JsonToken.String, ReadLengthString()); + break; + case BsonType.Object: + { + SetToken(JsonToken.StartObject); + + ContainerContext newContext = new ContainerContext(BsonType.Object); + PushContext(newContext); + newContext.Length = ReadInt32(); + break; + } + case BsonType.Array: + { + SetToken(JsonToken.StartArray); + + ContainerContext newContext = new ContainerContext(BsonType.Array); + PushContext(newContext); + newContext.Length = ReadInt32(); + break; + } + case BsonType.Binary: + BsonBinaryType binaryType; + byte[] data = ReadBinary(out binaryType); + + object value = (binaryType != BsonBinaryType.Uuid) + ? data + : (object)new Guid(data); + + SetToken(JsonToken.Bytes, value); + break; + case BsonType.Undefined: + SetToken(JsonToken.Undefined); + break; + case BsonType.Oid: + byte[] oid = ReadBytes(12); + SetToken(JsonToken.Bytes, oid); + break; + case BsonType.Boolean: + bool b = Convert.ToBoolean(ReadByte()); + SetToken(JsonToken.Boolean, b); + break; + case BsonType.Date: + long ticks = ReadInt64(); + DateTime utcDateTime = DateTimeUtils.ConvertJavaScriptTicksToDateTime(ticks); + + DateTime dateTime; + switch (DateTimeKindHandling) + { + case DateTimeKind.Unspecified: + dateTime = DateTime.SpecifyKind(utcDateTime, DateTimeKind.Unspecified); + break; + case DateTimeKind.Local: + dateTime = utcDateTime.ToLocalTime(); + break; + default: + dateTime = utcDateTime; + break; + } + + SetToken(JsonToken.Date, dateTime); + break; + case BsonType.Null: + SetToken(JsonToken.Null); + break; + case BsonType.Regex: + string expression = ReadString(); + string modifiers = ReadString(); + + string regex = @"/" + expression + @"/" + modifiers; + SetToken(JsonToken.String, regex); + break; + case BsonType.Reference: + SetToken(JsonToken.StartObject); + _bsonReaderState = BsonReaderState.ReferenceStart; + break; + case BsonType.Code: + SetToken(JsonToken.String, ReadLengthString()); + break; + case BsonType.CodeWScope: + SetToken(JsonToken.StartObject); + _bsonReaderState = BsonReaderState.CodeWScopeStart; + break; + case BsonType.Integer: + SetToken(JsonToken.Integer, (long)ReadInt32()); + break; + case BsonType.TimeStamp: + case BsonType.Long: + SetToken(JsonToken.Integer, ReadInt64()); + break; + default: + throw new ArgumentOutOfRangeException(nameof(type), "Unexpected BsonType value: " + type); + } + } + + private byte[] ReadBinary(out BsonBinaryType binaryType) + { + int dataLength = ReadInt32(); + + binaryType = (BsonBinaryType)ReadByte(); + +#pragma warning disable 612,618 + // the old binary type has the data length repeated in the data for some reason + if (binaryType == BsonBinaryType.BinaryOld && !_jsonNet35BinaryCompatibility) + { + dataLength = ReadInt32(); + } +#pragma warning restore 612,618 + + return ReadBytes(dataLength); + } + + private string ReadString() + { + EnsureBuffers(); + + StringBuilder builder = null; + + int totalBytesRead = 0; + // used in case of left over multibyte characters in the buffer + int offset = 0; + while (true) + { + int count = offset; + byte b; + while (count < MaxCharBytesSize && (b = _reader.ReadByte()) > 0) + { + _byteBuffer[count++] = b; + } + int byteCount = count - offset; + totalBytesRead += byteCount; + + if (count < MaxCharBytesSize && builder == null) + { + // pref optimization to avoid reading into a string builder + // if string is smaller than the buffer then return it directly + int length = Encoding.UTF8.GetChars(_byteBuffer, 0, byteCount, _charBuffer, 0); + + MovePosition(totalBytesRead + 1); + return new string(_charBuffer, 0, length); + } + else + { + // calculate the index of the end of the last full character in the buffer + int lastFullCharStop = GetLastFullCharStop(count - 1); + + int charCount = Encoding.UTF8.GetChars(_byteBuffer, 0, lastFullCharStop + 1, _charBuffer, 0); + + if (builder == null) + { + builder = new StringBuilder(MaxCharBytesSize * 2); + } + + builder.Append(_charBuffer, 0, charCount); + + if (lastFullCharStop < byteCount - 1) + { + offset = byteCount - lastFullCharStop - 1; + // copy left over multi byte characters to beginning of buffer for next iteration + Array.Copy(_byteBuffer, lastFullCharStop + 1, _byteBuffer, 0, offset); + } + else + { + // reached end of string + if (count < MaxCharBytesSize) + { + MovePosition(totalBytesRead + 1); + return builder.ToString(); + } + + offset = 0; + } + } + } + } + + private string ReadLengthString() + { + int length = ReadInt32(); + + MovePosition(length); + + string s = GetString(length - 1); + _reader.ReadByte(); + + return s; + } + + private string GetString(int length) + { + if (length == 0) + { + return string.Empty; + } + + EnsureBuffers(); + + StringBuilder builder = null; + + int totalBytesRead = 0; + + // used in case of left over multibyte characters in the buffer + int offset = 0; + do + { + int count = ((length - totalBytesRead) > MaxCharBytesSize - offset) + ? MaxCharBytesSize - offset + : length - totalBytesRead; + + int byteCount = _reader.Read(_byteBuffer, offset, count); + + if (byteCount == 0) + { + throw new EndOfStreamException("Unable to read beyond the end of the stream."); + } + + totalBytesRead += byteCount; + + // Above, byteCount is how many bytes we read this time. + // Below, byteCount is how many bytes are in the _byteBuffer. + byteCount += offset; + + if (byteCount == length) + { + // pref optimization to avoid reading into a string builder + // first iteration and all bytes read then return string directly + int charCount = Encoding.UTF8.GetChars(_byteBuffer, 0, byteCount, _charBuffer, 0); + return new string(_charBuffer, 0, charCount); + } + else + { + int lastFullCharStop = GetLastFullCharStop(byteCount - 1); + + if (builder == null) + { + builder = new StringBuilder(length); + } + + int charCount = Encoding.UTF8.GetChars(_byteBuffer, 0, lastFullCharStop + 1, _charBuffer, 0); + builder.Append(_charBuffer, 0, charCount); + + if (lastFullCharStop < byteCount - 1) + { + offset = byteCount - lastFullCharStop - 1; + // copy left over multi byte characters to beginning of buffer for next iteration + Array.Copy(_byteBuffer, lastFullCharStop + 1, _byteBuffer, 0, offset); + } + else + { + offset = 0; + } + } + } while (totalBytesRead < length); + + return builder.ToString(); + } + + private int GetLastFullCharStop(int start) + { + int lookbackPos = start; + int bis = 0; + while (lookbackPos >= 0) + { + bis = BytesInSequence(_byteBuffer[lookbackPos]); + if (bis == 0) + { + lookbackPos--; + continue; + } + else if (bis == 1) + { + break; + } + else + { + lookbackPos--; + break; + } + } + if (bis == start - lookbackPos) + { + //Full character. + return start; + } + else + { + return lookbackPos; + } + } + + private int BytesInSequence(byte b) + { + if (b <= SeqRange1[1]) + { + return 1; + } + if (b >= SeqRange2[0] && b <= SeqRange2[1]) + { + return 2; + } + if (b >= SeqRange3[0] && b <= SeqRange3[1]) + { + return 3; + } + if (b >= SeqRange4[0] && b <= SeqRange4[1]) + { + return 4; + } + return 0; + } + + private void EnsureBuffers() + { + if (_byteBuffer == null) + { + _byteBuffer = new byte[MaxCharBytesSize]; + } + if (_charBuffer == null) + { + int charBufferSize = Encoding.UTF8.GetMaxCharCount(MaxCharBytesSize); + _charBuffer = new char[charBufferSize]; + } + } + + private double ReadDouble() + { + MovePosition(8); + return _reader.ReadDouble(); + } + + private int ReadInt32() + { + MovePosition(4); + return _reader.ReadInt32(); + } + + private long ReadInt64() + { + MovePosition(8); + return _reader.ReadInt64(); + } + + private BsonType ReadType() + { + MovePosition(1); + return (BsonType)_reader.ReadSByte(); + } + + private void MovePosition(int count) + { + _currentContext.Position += count; + } + + private byte[] ReadBytes(int count) + { + MovePosition(count); + return _reader.ReadBytes(count); + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Bson/BsonToken.cs b/Common/00-1Json8.3/Json8.3/Bson/BsonToken.cs new file mode 100644 index 0000000..06927a4 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Bson/BsonToken.cs @@ -0,0 +1,157 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System.Collections; +using System.Collections.Generic; + +namespace Newtonsoft.Json.Bson +{ + internal abstract class BsonToken + { + public abstract BsonType Type { get; } + public BsonToken Parent { get; set; } + public int CalculatedSize { get; set; } + } + + internal class BsonObject : BsonToken, IEnumerable + { + private readonly List _children = new List(); + + public void Add(string name, BsonToken token) + { + _children.Add(new BsonProperty { Name = new BsonString(name, false), Value = token }); + token.Parent = this; + } + + public override BsonType Type + { + get { return BsonType.Object; } + } + + public IEnumerator GetEnumerator() + { + return _children.GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + } + + internal class BsonArray : BsonToken, IEnumerable + { + private readonly List _children = new List(); + + public void Add(BsonToken token) + { + _children.Add(token); + token.Parent = this; + } + + public override BsonType Type + { + get { return BsonType.Array; } + } + + public IEnumerator GetEnumerator() + { + return _children.GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + } + + internal class BsonValue : BsonToken + { + private readonly object _value; + private readonly BsonType _type; + + public BsonValue(object value, BsonType type) + { + _value = value; + _type = type; + } + + public object Value + { + get { return _value; } + } + + public override BsonType Type + { + get { return _type; } + } + } + + internal class BsonString : BsonValue + { + public int ByteCount { get; set; } + public bool IncludeLength { get; set; } + + public BsonString(object value, bool includeLength) + : base(value, BsonType.String) + { + IncludeLength = includeLength; + } + } + + internal class BsonBinary : BsonValue + { + public BsonBinaryType BinaryType { get; set; } + + public BsonBinary(byte[] value, BsonBinaryType binaryType) + : base(value, BsonType.Binary) + { + BinaryType = binaryType; + } + } + + internal class BsonRegex : BsonToken + { + public BsonString Pattern { get; set; } + public BsonString Options { get; set; } + + public BsonRegex(string pattern, string options) + { + Pattern = new BsonString(pattern, false); + Options = new BsonString(options, false); + } + + public override BsonType Type + { + get { return BsonType.Regex; } + } + } + + internal class BsonProperty + { + public BsonString Name { get; set; } + public BsonToken Value { get; set; } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Bson/BsonType.cs b/Common/00-1Json8.3/Json8.3/Bson/BsonType.cs new file mode 100644 index 0000000..e119298 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Bson/BsonType.cs @@ -0,0 +1,51 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +namespace Newtonsoft.Json.Bson +{ + internal enum BsonType : sbyte + { + Number = 1, + String = 2, + Object = 3, + Array = 4, + Binary = 5, + Undefined = 6, + Oid = 7, + Boolean = 8, + Date = 9, + Null = 10, + Regex = 11, + Reference = 12, + Code = 13, + Symbol = 14, + CodeWScope = 15, + Integer = 16, + TimeStamp = 17, + Long = 18, + MinKey = -1, + MaxKey = 127 + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Bson/BsonWriter.cs b/Common/00-1Json8.3/Json8.3/Bson/BsonWriter.cs new file mode 100644 index 0000000..2c0c2ff --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Bson/BsonWriter.cs @@ -0,0 +1,531 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) +using System.Numerics; +#endif +using System.Text; +using Newtonsoft.Json.Utilities; +using Newtonsoft.Json.Linq; +using System.Globalization; + +namespace Newtonsoft.Json.Bson +{ + /// + /// Represents a writer that provides a fast, non-cached, forward-only way of generating JSON data. + /// + public class BsonWriter : JsonWriter + { + private readonly BsonBinaryWriter _writer; + + private BsonToken _root; + private BsonToken _parent; + private string _propertyName; + + /// + /// Gets or sets the used when writing values to BSON. + /// When set to no conversion will occur. + /// + /// The used when writing values to BSON. + public DateTimeKind DateTimeKindHandling + { + get { return _writer.DateTimeKindHandling; } + set { _writer.DateTimeKindHandling = value; } + } + + /// + /// Initializes a new instance of the class. + /// + /// The stream. + public BsonWriter(Stream stream) + { + ValidationUtils.ArgumentNotNull(stream, nameof(stream)); + _writer = new BsonBinaryWriter(new BinaryWriter(stream)); + } + + /// + /// Initializes a new instance of the class. + /// + /// The writer. + public BsonWriter(BinaryWriter writer) + { + ValidationUtils.ArgumentNotNull(writer, nameof(writer)); + _writer = new BsonBinaryWriter(writer); + } + + /// + /// Flushes whatever is in the buffer to the underlying streams and also flushes the underlying stream. + /// + public override void Flush() + { + _writer.Flush(); + } + + /// + /// Writes the end. + /// + /// The token. + protected override void WriteEnd(JsonToken token) + { + base.WriteEnd(token); + RemoveParent(); + + if (Top == 0) + { + _writer.WriteToken(_root); + } + } + + /// + /// Writes out a comment /*...*/ containing the specified text. + /// + /// Text to place inside the comment. + public override void WriteComment(string text) + { + throw JsonWriterException.Create(this, "Cannot write JSON comment as BSON.", null); + } + + /// + /// Writes the start of a constructor with the given name. + /// + /// The name of the constructor. + public override void WriteStartConstructor(string name) + { + throw JsonWriterException.Create(this, "Cannot write JSON constructor as BSON.", null); + } + + /// + /// Writes raw JSON. + /// + /// The raw JSON to write. + public override void WriteRaw(string json) + { + throw JsonWriterException.Create(this, "Cannot write raw JSON as BSON.", null); + } + + /// + /// Writes raw JSON where a value is expected and updates the writer's state. + /// + /// The raw JSON to write. + public override void WriteRawValue(string json) + { + throw JsonWriterException.Create(this, "Cannot write raw JSON as BSON.", null); + } + + /// + /// Writes the beginning of a JSON array. + /// + public override void WriteStartArray() + { + base.WriteStartArray(); + + AddParent(new BsonArray()); + } + + /// + /// Writes the beginning of a JSON object. + /// + public override void WriteStartObject() + { + base.WriteStartObject(); + + AddParent(new BsonObject()); + } + + /// + /// Writes the property name of a name/value pair on a JSON object. + /// + /// The name of the property. + public override void WritePropertyName(string name) + { + base.WritePropertyName(name); + + _propertyName = name; + } + + /// + /// Closes this stream and the underlying stream. + /// + public override void Close() + { + base.Close(); + + if (CloseOutput && _writer != null) + { + _writer.Close(); + } + } + + private void AddParent(BsonToken container) + { + AddToken(container); + _parent = container; + } + + private void RemoveParent() + { + _parent = _parent.Parent; + } + + private void AddValue(object value, BsonType type) + { + AddToken(new BsonValue(value, type)); + } + + internal void AddToken(BsonToken token) + { + if (_parent != null) + { + if (_parent is BsonObject) + { + ((BsonObject)_parent).Add(_propertyName, token); + _propertyName = null; + } + else + { + ((BsonArray)_parent).Add(token); + } + } + else + { + if (token.Type != BsonType.Object && token.Type != BsonType.Array) + { + throw JsonWriterException.Create(this, "Error writing {0} value. BSON must start with an Object or Array.".FormatWith(CultureInfo.InvariantCulture, token.Type), null); + } + + _parent = token; + _root = token; + } + } + + #region WriteValue methods + /// + /// Writes a value. + /// An error will raised if the value cannot be written as a single JSON token. + /// + /// The value to write. + public override void WriteValue(object value) + { +#if !(NET20 || NET35 || PORTABLE || PORTABLE40) + if (value is BigInteger) + { + InternalWriteValue(JsonToken.Integer); + AddToken(new BsonBinary(((BigInteger)value).ToByteArray(), BsonBinaryType.Binary)); + } + else +#endif + { + base.WriteValue(value); + } + } + + /// + /// Writes a null value. + /// + public override void WriteNull() + { + base.WriteNull(); + AddValue(null, BsonType.Null); + } + + /// + /// Writes an undefined value. + /// + public override void WriteUndefined() + { + base.WriteUndefined(); + AddValue(null, BsonType.Undefined); + } + + /// + /// Writes a value. + /// + /// The value to write. + public override void WriteValue(string value) + { + base.WriteValue(value); + if (value == null) + { + AddValue(null, BsonType.Null); + } + else + { + AddToken(new BsonString(value, true)); + } + } + + /// + /// Writes a value. + /// + /// The value to write. + public override void WriteValue(int value) + { + base.WriteValue(value); + AddValue(value, BsonType.Integer); + } + + /// + /// Writes a value. + /// + /// The value to write. + [CLSCompliant(false)] + public override void WriteValue(uint value) + { + if (value > int.MaxValue) + { + throw JsonWriterException.Create(this, "Value is too large to fit in a signed 32 bit integer. BSON does not support unsigned values.", null); + } + + base.WriteValue(value); + AddValue(value, BsonType.Integer); + } + + /// + /// Writes a value. + /// + /// The value to write. + public override void WriteValue(long value) + { + base.WriteValue(value); + AddValue(value, BsonType.Long); + } + + /// + /// Writes a value. + /// + /// The value to write. + [CLSCompliant(false)] + public override void WriteValue(ulong value) + { + if (value > long.MaxValue) + { + throw JsonWriterException.Create(this, "Value is too large to fit in a signed 64 bit integer. BSON does not support unsigned values.", null); + } + + base.WriteValue(value); + AddValue(value, BsonType.Long); + } + + /// + /// Writes a value. + /// + /// The value to write. + public override void WriteValue(float value) + { + base.WriteValue(value); + AddValue(value, BsonType.Number); + } + + /// + /// Writes a value. + /// + /// The value to write. + public override void WriteValue(double value) + { + base.WriteValue(value); + AddValue(value, BsonType.Number); + } + + /// + /// Writes a value. + /// + /// The value to write. + public override void WriteValue(bool value) + { + base.WriteValue(value); + AddValue(value, BsonType.Boolean); + } + + /// + /// Writes a value. + /// + /// The value to write. + public override void WriteValue(short value) + { + base.WriteValue(value); + AddValue(value, BsonType.Integer); + } + + /// + /// Writes a value. + /// + /// The value to write. + [CLSCompliant(false)] + public override void WriteValue(ushort value) + { + base.WriteValue(value); + AddValue(value, BsonType.Integer); + } + + /// + /// Writes a value. + /// + /// The value to write. + public override void WriteValue(char value) + { + base.WriteValue(value); + string s = null; +#if !(DOTNET || PORTABLE40 || PORTABLE) + s = value.ToString(CultureInfo.InvariantCulture); +#else + s = value.ToString(); +#endif + AddToken(new BsonString(s, true)); + } + + /// + /// Writes a value. + /// + /// The value to write. + public override void WriteValue(byte value) + { + base.WriteValue(value); + AddValue(value, BsonType.Integer); + } + + /// + /// Writes a value. + /// + /// The value to write. + [CLSCompliant(false)] + public override void WriteValue(sbyte value) + { + base.WriteValue(value); + AddValue(value, BsonType.Integer); + } + + /// + /// Writes a value. + /// + /// The value to write. + public override void WriteValue(decimal value) + { + base.WriteValue(value); + AddValue(value, BsonType.Number); + } + + /// + /// Writes a value. + /// + /// The value to write. + public override void WriteValue(DateTime value) + { + base.WriteValue(value); + value = DateTimeUtils.EnsureDateTime(value, DateTimeZoneHandling); + AddValue(value, BsonType.Date); + } + +#if !NET20 + /// + /// Writes a value. + /// + /// The value to write. + public override void WriteValue(DateTimeOffset value) + { + base.WriteValue(value); + AddValue(value, BsonType.Date); + } +#endif + + /// + /// Writes a [] value. + /// + /// The [] value to write. + public override void WriteValue(byte[] value) + { + base.WriteValue(value); + AddToken(new BsonBinary(value, BsonBinaryType.Binary)); + } + + /// + /// Writes a value. + /// + /// The value to write. + public override void WriteValue(Guid value) + { + base.WriteValue(value); + AddToken(new BsonBinary(value.ToByteArray(), BsonBinaryType.Uuid)); + } + + /// + /// Writes a value. + /// + /// The value to write. + public override void WriteValue(TimeSpan value) + { + base.WriteValue(value); + AddToken(new BsonString(value.ToString(), true)); + } + + /// + /// Writes a value. + /// + /// The value to write. + public override void WriteValue(Uri value) + { + base.WriteValue(value); + AddToken(new BsonString(value.ToString(), true)); + } + #endregion + + /// + /// Writes a [] value that represents a BSON object id. + /// + /// The Object ID value to write. + public void WriteObjectId(byte[] value) + { + ValidationUtils.ArgumentNotNull(value, nameof(value)); + + if (value.Length != 12) + { + throw JsonWriterException.Create(this, "An object id must be 12 bytes", null); + } + + // hack to update the writer state + UpdateScopeWithFinishedValue(); + AutoComplete(JsonToken.Undefined); + AddValue(value, BsonType.Oid); + } + + /// + /// Writes a BSON regex. + /// + /// The regex pattern. + /// The regex options. + public void WriteRegex(string pattern, string options) + { + ValidationUtils.ArgumentNotNull(pattern, nameof(pattern)); + + // hack to update the writer state + UpdateScopeWithFinishedValue(); + AutoComplete(JsonToken.Undefined); + AddToken(new BsonRegex(pattern, options)); + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Class1.cs b/Common/00-1Json8.3/Json8.3/Class1.cs new file mode 100644 index 0000000..52cef5f --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Class1.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Json8._3 +{ + public class Class1 + { + } +} diff --git a/Common/00-1Json8.3/Json8.3/ConstructorHandling.cs b/Common/00-1Json8.3/Json8.3/ConstructorHandling.cs new file mode 100644 index 0000000..e403f1e --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/ConstructorHandling.cs @@ -0,0 +1,43 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +namespace Newtonsoft.Json +{ + /// + /// Specifies how constructors are used when initializing objects during deserialization by the . + /// + public enum ConstructorHandling + { + /// + /// First attempt to use the public default constructor, then fall back to single paramatized constructor, then the non-public default constructor. + /// + Default = 0, + + /// + /// Json.NET will use a non-public default constructor before falling back to a paramatized constructor. + /// + AllowNonPublicDefaultConstructor = 1 + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Converters/BinaryConverter.cs b/Common/00-1Json8.3/Json8.3/Converters/BinaryConverter.cs new file mode 100644 index 0000000..34b878b --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Converters/BinaryConverter.cs @@ -0,0 +1,201 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +#if !(DOTNET || PORTABLE40 || PORTABLE) +using System; +using System.Data.SqlTypes; +using System.Globalization; +using Newtonsoft.Json.Utilities; +using System.Collections.Generic; + +namespace Newtonsoft.Json.Converters +{ + /// + /// Converts a binary value to and from a base 64 string value. + /// + public class BinaryConverter : JsonConverter + { +#if !NET20 + private const string BinaryTypeName = "System.Data.Linq.Binary"; + private const string BinaryToArrayName = "ToArray"; + private ReflectionObject _reflectionObject; +#endif + + /// + /// Writes the JSON representation of the object. + /// + /// The to write to. + /// The value. + /// The calling serializer. + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + if (value == null) + { + writer.WriteNull(); + return; + } + + byte[] data = GetByteArray(value); + + writer.WriteValue(data); + } + + private byte[] GetByteArray(object value) + { +#if !(NET20) + if (value.GetType().AssignableToTypeName(BinaryTypeName)) + { + EnsureReflectionObject(value.GetType()); + return (byte[])_reflectionObject.GetValue(value, BinaryToArrayName); + } +#endif + if (value is SqlBinary) + { + return ((SqlBinary)value).Value; + } + + throw new JsonSerializationException("Unexpected value type when writing binary: {0}".FormatWith(CultureInfo.InvariantCulture, value.GetType())); + } + +#if !NET20 + private void EnsureReflectionObject(Type t) + { + if (_reflectionObject == null) + { + _reflectionObject = ReflectionObject.Create(t, t.GetConstructor(new[] { typeof(byte[]) }), BinaryToArrayName); + } + } +#endif + + /// + /// Reads the JSON representation of the object. + /// + /// The to read from. + /// Type of the object. + /// The existing value of object being read. + /// The calling serializer. + /// The object value. + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + { + if (reader.TokenType == JsonToken.Null) + { + if (!ReflectionUtils.IsNullable(objectType)) + { + throw JsonSerializationException.Create(reader, "Cannot convert null value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType)); + } + + return null; + } + + byte[] data; + + if (reader.TokenType == JsonToken.StartArray) + { + data = ReadByteArray(reader); + } + else if (reader.TokenType == JsonToken.String) + { + // current token is already at base64 string + // unable to call ReadAsBytes so do it the old fashion way + string encodedData = reader.Value.ToString(); + data = Convert.FromBase64String(encodedData); + } + else + { + throw JsonSerializationException.Create(reader, "Unexpected token parsing binary. Expected String or StartArray, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); + } + + Type t = (ReflectionUtils.IsNullableType(objectType)) + ? Nullable.GetUnderlyingType(objectType) + : objectType; + +#if !NET20 + if (t.AssignableToTypeName(BinaryTypeName)) + { + EnsureReflectionObject(t); + + return _reflectionObject.Creator(data); + } +#endif + + if (t == typeof(SqlBinary)) + { + return new SqlBinary(data); + } + + throw JsonSerializationException.Create(reader, "Unexpected object type when writing binary: {0}".FormatWith(CultureInfo.InvariantCulture, objectType)); + } + + private byte[] ReadByteArray(JsonReader reader) + { + List byteList = new List(); + + while (reader.Read()) + { + switch (reader.TokenType) + { + case JsonToken.Integer: + byteList.Add(Convert.ToByte(reader.Value, CultureInfo.InvariantCulture)); + break; + case JsonToken.EndArray: + return byteList.ToArray(); + case JsonToken.Comment: + // skip + break; + default: + throw JsonSerializationException.Create(reader, "Unexpected token when reading bytes: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); + } + } + + throw JsonSerializationException.Create(reader, "Unexpected end when reading bytes."); + } + + /// + /// Determines whether this instance can convert the specified object type. + /// + /// Type of the object. + /// + /// true if this instance can convert the specified object type; otherwise, false. + /// + public override bool CanConvert(Type objectType) + { +#if !NET20 + if (objectType.AssignableToTypeName(BinaryTypeName)) + { + return true; + } +#endif + + if (objectType == typeof(SqlBinary) || objectType == typeof(SqlBinary?)) + { + return true; + } + + return false; + } + } +} + +#endif \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Converters/BsonObjectIdConverter.cs b/Common/00-1Json8.3/Json8.3/Converters/BsonObjectIdConverter.cs new file mode 100644 index 0000000..c0a30ba --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Converters/BsonObjectIdConverter.cs @@ -0,0 +1,91 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using Newtonsoft.Json.Bson; +using System.Globalization; +using Newtonsoft.Json.Utilities; + +namespace Newtonsoft.Json.Converters +{ + /// + /// Converts a to and from JSON and BSON. + /// + public class BsonObjectIdConverter : JsonConverter + { + /// + /// Writes the JSON representation of the object. + /// + /// The to write to. + /// The value. + /// The calling serializer. + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + BsonObjectId objectId = (BsonObjectId)value; + + BsonWriter bsonWriter = writer as BsonWriter; + if (bsonWriter != null) + { + bsonWriter.WriteObjectId(objectId.Value); + } + else + { + writer.WriteValue(objectId.Value); + } + } + + /// + /// Reads the JSON representation of the object. + /// + /// The to read from. + /// Type of the object. + /// The existing value of object being read. + /// The calling serializer. + /// The object value. + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + { + if (reader.TokenType != JsonToken.Bytes) + { + throw new JsonSerializationException("Expected Bytes but got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); + } + + byte[] value = (byte[])reader.Value; + + return new BsonObjectId(value); + } + + /// + /// Determines whether this instance can convert the specified object type. + /// + /// Type of the object. + /// + /// true if this instance can convert the specified object type; otherwise, false. + /// + public override bool CanConvert(Type objectType) + { + return (objectType == typeof(BsonObjectId)); + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Converters/CustomCreationConverter.cs b/Common/00-1Json8.3/Json8.3/Converters/CustomCreationConverter.cs new file mode 100644 index 0000000..c373b0c --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Converters/CustomCreationConverter.cs @@ -0,0 +1,104 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Reflection; +using Newtonsoft.Json.Utilities; + +namespace Newtonsoft.Json.Converters +{ + /// + /// Create a custom object + /// + /// The object type to convert. + public abstract class CustomCreationConverter : JsonConverter + { + /// + /// Writes the JSON representation of the object. + /// + /// The to write to. + /// The value. + /// The calling serializer. + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + throw new NotSupportedException("CustomCreationConverter should only be used while deserializing."); + } + + /// + /// Reads the JSON representation of the object. + /// + /// The to read from. + /// Type of the object. + /// The existing value of object being read. + /// The calling serializer. + /// The object value. + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + { + if (reader.TokenType == JsonToken.Null) + { + return null; + } + + T value = Create(objectType); + if (value == null) + { + throw new JsonSerializationException("No object created."); + } + + serializer.Populate(reader, value); + return value; + } + + /// + /// Creates an object which will then be populated by the serializer. + /// + /// Type of the object. + /// The created object. + public abstract T Create(Type objectType); + + /// + /// Determines whether this instance can convert the specified object type. + /// + /// Type of the object. + /// + /// true if this instance can convert the specified object type; otherwise, false. + /// + public override bool CanConvert(Type objectType) + { + return typeof(T).IsAssignableFrom(objectType); + } + + /// + /// Gets a value indicating whether this can write JSON. + /// + /// + /// true if this can write JSON; otherwise, false. + /// + public override bool CanWrite + { + get { return false; } + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Converters/DataSetConverter.cs b/Common/00-1Json8.3/Json8.3/Converters/DataSetConverter.cs new file mode 100644 index 0000000..5c86e82 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Converters/DataSetConverter.cs @@ -0,0 +1,119 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +#if !(DOTNET || PORTABLE40 || PORTABLE) +using System; +using System.Data; +using Newtonsoft.Json.Serialization; + +namespace Newtonsoft.Json.Converters +{ + /// + /// Converts a to and from JSON. + /// + public class DataSetConverter : JsonConverter + { + /// + /// Writes the JSON representation of the object. + /// + /// The to write to. + /// The value. + /// The calling serializer. + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + DataSet dataSet = (DataSet)value; + DefaultContractResolver resolver = serializer.ContractResolver as DefaultContractResolver; + + DataTableConverter converter = new DataTableConverter(); + + writer.WriteStartObject(); + + foreach (DataTable table in dataSet.Tables) + { + writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(table.TableName) : table.TableName); + + converter.WriteJson(writer, table, serializer); + } + + writer.WriteEndObject(); + } + + /// + /// Reads the JSON representation of the object. + /// + /// The to read from. + /// Type of the object. + /// The existing value of object being read. + /// The calling serializer. + /// The object value. + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + { + if (reader.TokenType == JsonToken.Null) + { + return null; + } + + // handle typed datasets + DataSet ds = (objectType == typeof(DataSet)) + ? new DataSet() + : (DataSet)Activator.CreateInstance(objectType); + + DataTableConverter converter = new DataTableConverter(); + + reader.ReadAndAssert(); + + while (reader.TokenType == JsonToken.PropertyName) + { + DataTable dt = ds.Tables[(string)reader.Value]; + bool exists = (dt != null); + + dt = (DataTable)converter.ReadJson(reader, typeof(DataTable), dt, serializer); + + if (!exists) + { + ds.Tables.Add(dt); + } + + reader.ReadAndAssert(); + } + + return ds; + } + + /// + /// Determines whether this instance can convert the specified value type. + /// + /// Type of the value. + /// + /// true if this instance can convert the specified value type; otherwise, false. + /// + public override bool CanConvert(Type valueType) + { + return typeof(DataSet).IsAssignableFrom(valueType); + } + } +} + +#endif \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Converters/DataTableConverter.cs b/Common/00-1Json8.3/Json8.3/Converters/DataTableConverter.cs new file mode 100644 index 0000000..b2f775a --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Converters/DataTableConverter.cs @@ -0,0 +1,244 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +#if !(DOTNET || PORTABLE40 || PORTABLE) +using System.Collections.Generic; +using System.Globalization; +using Newtonsoft.Json.Utilities; +using System; +using System.Data; +using Newtonsoft.Json.Serialization; + +namespace Newtonsoft.Json.Converters +{ + /// + /// Converts a to and from JSON. + /// + public class DataTableConverter : JsonConverter + { + /// + /// Writes the JSON representation of the object. + /// + /// The to write to. + /// The value. + /// The calling serializer. + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + DataTable table = (DataTable)value; + DefaultContractResolver resolver = serializer.ContractResolver as DefaultContractResolver; + + writer.WriteStartArray(); + + foreach (DataRow row in table.Rows) + { + writer.WriteStartObject(); + foreach (DataColumn column in row.Table.Columns) + { + object columnValue = row[column]; + + if (serializer.NullValueHandling == NullValueHandling.Ignore && (columnValue == null || columnValue == DBNull.Value)) + { + continue; + } + + writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(column.ColumnName) : column.ColumnName); + serializer.Serialize(writer, columnValue); + } + writer.WriteEndObject(); + } + + writer.WriteEndArray(); + } + + /// + /// Reads the JSON representation of the object. + /// + /// The to read from. + /// Type of the object. + /// The existing value of object being read. + /// The calling serializer. + /// The object value. + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + { + if (reader.TokenType == JsonToken.Null) + { + return null; + } + + DataTable dt = existingValue as DataTable; + + if (dt == null) + { + // handle typed datasets + dt = (objectType == typeof(DataTable)) + ? new DataTable() + : (DataTable)Activator.CreateInstance(objectType); + } + + // DataTable is inside a DataSet + // populate the name from the property name + if (reader.TokenType == JsonToken.PropertyName) + { + dt.TableName = (string)reader.Value; + + reader.ReadAndAssert(); + + if (reader.TokenType == JsonToken.Null) + { + return dt; + } + } + + if (reader.TokenType != JsonToken.StartArray) + { + throw JsonSerializationException.Create(reader, "Unexpected JSON token when reading DataTable. Expected StartArray, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); + } + + reader.ReadAndAssert(); + + while (reader.TokenType != JsonToken.EndArray) + { + CreateRow(reader, dt, serializer); + + reader.ReadAndAssert(); + } + + return dt; + } + + private static void CreateRow(JsonReader reader, DataTable dt, JsonSerializer serializer) + { + DataRow dr = dt.NewRow(); + reader.ReadAndAssert(); + + while (reader.TokenType == JsonToken.PropertyName) + { + string columnName = (string)reader.Value; + + reader.ReadAndAssert(); + + DataColumn column = dt.Columns[columnName]; + if (column == null) + { + Type columnType = GetColumnDataType(reader); + column = new DataColumn(columnName, columnType); + dt.Columns.Add(column); + } + + if (column.DataType == typeof(DataTable)) + { + if (reader.TokenType == JsonToken.StartArray) + { + reader.ReadAndAssert(); + } + + DataTable nestedDt = new DataTable(); + + while (reader.TokenType != JsonToken.EndArray) + { + CreateRow(reader, nestedDt, serializer); + + reader.ReadAndAssert(); + } + + dr[columnName] = nestedDt; + } + else if (column.DataType.IsArray && column.DataType != typeof(byte[])) + { + if (reader.TokenType == JsonToken.StartArray) + { + reader.ReadAndAssert(); + } + + List o = new List(); + + while (reader.TokenType != JsonToken.EndArray) + { + o.Add(reader.Value); + reader.ReadAndAssert(); + } + + Array destinationArray = Array.CreateInstance(column.DataType.GetElementType(), o.Count); + Array.Copy(o.ToArray(), destinationArray, o.Count); + + dr[columnName] = destinationArray; + } + else + { + dr[columnName] = (reader.Value != null) ? serializer.Deserialize(reader, column.DataType) : DBNull.Value; + } + + reader.ReadAndAssert(); + } + + dr.EndEdit(); + dt.Rows.Add(dr); + } + + private static Type GetColumnDataType(JsonReader reader) + { + JsonToken tokenType = reader.TokenType; + + switch (tokenType) + { + case JsonToken.Integer: + case JsonToken.Boolean: + case JsonToken.Float: + case JsonToken.String: + case JsonToken.Date: + case JsonToken.Bytes: + return reader.ValueType; + case JsonToken.Null: + case JsonToken.Undefined: + return typeof(string); + case JsonToken.StartArray: + reader.ReadAndAssert(); + if (reader.TokenType == JsonToken.StartObject) + { + return typeof(DataTable); // nested datatable + } + + Type arrayType = GetColumnDataType(reader); + return arrayType.MakeArrayType(); + default: + throw JsonSerializationException.Create(reader, "Unexpected JSON token when reading DataTable: {0}".FormatWith(CultureInfo.InvariantCulture, tokenType)); + } + } + + /// + /// Determines whether this instance can convert the specified value type. + /// + /// Type of the value. + /// + /// true if this instance can convert the specified value type; otherwise, false. + /// + public override bool CanConvert(Type valueType) + { + return typeof(DataTable).IsAssignableFrom(valueType); + } + } +} + +#endif \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Converters/DateTimeConverterBase.cs b/Common/00-1Json8.3/Json8.3/Converters/DateTimeConverterBase.cs new file mode 100644 index 0000000..5e0ed29 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Converters/DateTimeConverterBase.cs @@ -0,0 +1,58 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; + +namespace Newtonsoft.Json.Converters +{ + /// + /// Provides a base class for converting a to and from JSON. + /// + public abstract class DateTimeConverterBase : JsonConverter + { + /// + /// Determines whether this instance can convert the specified object type. + /// + /// Type of the object. + /// + /// true if this instance can convert the specified object type; otherwise, false. + /// + public override bool CanConvert(Type objectType) + { + if (objectType == typeof(DateTime) || objectType == typeof(DateTime?)) + { + return true; + } +#if !NET20 + if (objectType == typeof(DateTimeOffset) || objectType == typeof(DateTimeOffset?)) + { + return true; + } +#endif + + return false; + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Converters/DiscriminatedUnionConverter.cs b/Common/00-1Json8.3/Json8.3/Converters/DiscriminatedUnionConverter.cs new file mode 100644 index 0000000..679a832 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Converters/DiscriminatedUnionConverter.cs @@ -0,0 +1,280 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +#if !(NET35 || NET20) +using Newtonsoft.Json.Linq; +using System; +using System.Collections; +using System.Collections.Generic; +#if NET20 +using Newtonsoft.Json.Utilities.LinqBridge; +#else +using System.Linq; +#endif +using System.Reflection; +using Newtonsoft.Json.Serialization; +using System.Globalization; +using Newtonsoft.Json.Utilities; + +namespace Newtonsoft.Json.Converters +{ + /// + /// Converts a F# discriminated union type to and from JSON. + /// + public class DiscriminatedUnionConverter : JsonConverter + { + #region UnionDefinition + internal class Union + { + public List Cases; + public FSharpFunction TagReader { get; set; } + } + + internal class UnionCase + { + public int Tag; + public string Name; + public PropertyInfo[] Fields; + public FSharpFunction FieldReader; + public FSharpFunction Constructor; + } + #endregion + + private const string CasePropertyName = "Case"; + private const string FieldsPropertyName = "Fields"; + + private static readonly ThreadSafeStore UnionCache = new ThreadSafeStore(CreateUnion); + private static readonly ThreadSafeStore UnionTypeLookupCache = new ThreadSafeStore(CreateUnionTypeLookup); + + private static Type CreateUnionTypeLookup(Type t) + { + // this lookup is because cases with fields are derived from union type + // need to get declaring type to avoid duplicate Unions in cache + + // hacky but I can't find an API to get the declaring type without GetUnionCases + object[] cases = (object[])FSharpUtils.GetUnionCases(null, t, null); + + object caseInfo = cases.First(); + + Type unionType = (Type)FSharpUtils.GetUnionCaseInfoDeclaringType(caseInfo); + return unionType; + } + + private static Union CreateUnion(Type t) + { + Union u = new Union(); + + u.TagReader = (FSharpFunction)FSharpUtils.PreComputeUnionTagReader(null, t, null); + u.Cases = new List(); + + object[] cases = (object[])FSharpUtils.GetUnionCases(null, t, null); + + foreach (object unionCaseInfo in cases) + { + UnionCase unionCase = new UnionCase(); + unionCase.Tag = (int)FSharpUtils.GetUnionCaseInfoTag(unionCaseInfo); + unionCase.Name = (string)FSharpUtils.GetUnionCaseInfoName(unionCaseInfo); + unionCase.Fields = (PropertyInfo[])FSharpUtils.GetUnionCaseInfoFields(unionCaseInfo); + unionCase.FieldReader = (FSharpFunction)FSharpUtils.PreComputeUnionReader(null, unionCaseInfo, null); + unionCase.Constructor = (FSharpFunction)FSharpUtils.PreComputeUnionConstructor(null, unionCaseInfo, null); + + u.Cases.Add(unionCase); + } + + return u; + } + + /// + /// Writes the JSON representation of the object. + /// + /// The to write to. + /// The value. + /// The calling serializer. + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + DefaultContractResolver resolver = serializer.ContractResolver as DefaultContractResolver; + + Type unionType = UnionTypeLookupCache.Get(value.GetType()); + Union union = UnionCache.Get(unionType); + + int tag = (int)union.TagReader.Invoke(value); + UnionCase caseInfo = union.Cases.Single(c => c.Tag == tag); + + writer.WriteStartObject(); + writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(CasePropertyName) : CasePropertyName); + writer.WriteValue(caseInfo.Name); + if (caseInfo.Fields != null && caseInfo.Fields.Length > 0) + { + object[] fields = (object[])caseInfo.FieldReader.Invoke(value); + + writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(FieldsPropertyName) : FieldsPropertyName); + writer.WriteStartArray(); + foreach (object field in fields) + { + serializer.Serialize(writer, field); + } + writer.WriteEndArray(); + } + writer.WriteEndObject(); + } + + /// + /// Reads the JSON representation of the object. + /// + /// The to read from. + /// Type of the object. + /// The existing value of object being read. + /// The calling serializer. + /// The object value. + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + { + if (reader.TokenType == JsonToken.Null) + { + return null; + } + + UnionCase caseInfo = null; + string caseName = null; + JArray fields = null; + + // start object + reader.ReadAndAssert(); + + while (reader.TokenType == JsonToken.PropertyName) + { + string propertyName = reader.Value.ToString(); + if (string.Equals(propertyName, CasePropertyName, StringComparison.OrdinalIgnoreCase)) + { + reader.ReadAndAssert(); + + Union union = UnionCache.Get(objectType); + + caseName = reader.Value.ToString(); + + caseInfo = union.Cases.SingleOrDefault(c => c.Name == caseName); + + if (caseInfo == null) + { + throw JsonSerializationException.Create(reader, "No union type found with the name '{0}'.".FormatWith(CultureInfo.InvariantCulture, caseName)); + } + } + else if (string.Equals(propertyName, FieldsPropertyName, StringComparison.OrdinalIgnoreCase)) + { + reader.ReadAndAssert(); + if (reader.TokenType != JsonToken.StartArray) + { + throw JsonSerializationException.Create(reader, "Union fields must been an array."); + } + + fields = (JArray)JToken.ReadFrom(reader); + } + else + { + throw JsonSerializationException.Create(reader, "Unexpected property '{0}' found when reading union.".FormatWith(CultureInfo.InvariantCulture, propertyName)); + } + + reader.ReadAndAssert(); + } + + if (caseInfo == null) + { + throw JsonSerializationException.Create(reader, "No '{0}' property with union name found.".FormatWith(CultureInfo.InvariantCulture, CasePropertyName)); + } + + object[] typedFieldValues = new object[caseInfo.Fields.Length]; + + if (caseInfo.Fields.Length > 0 && fields == null) + { + throw JsonSerializationException.Create(reader, "No '{0}' property with union fields found.".FormatWith(CultureInfo.InvariantCulture, FieldsPropertyName)); + } + + if (fields != null) + { + if (caseInfo.Fields.Length != fields.Count) + { + throw JsonSerializationException.Create(reader, "The number of field values does not match the number of properties defined by union '{0}'.".FormatWith(CultureInfo.InvariantCulture, caseName)); + } + + for (int i = 0; i < fields.Count; i++) + { + JToken t = fields[i]; + PropertyInfo fieldProperty = caseInfo.Fields[i]; + + typedFieldValues[i] = t.ToObject(fieldProperty.PropertyType, serializer); + } + } + + object[] args = { typedFieldValues }; + + return caseInfo.Constructor.Invoke(args); + } + + /// + /// Determines whether this instance can convert the specified object type. + /// + /// Type of the object. + /// + /// true if this instance can convert the specified object type; otherwise, false. + /// + public override bool CanConvert(Type objectType) + { + if (typeof(IEnumerable).IsAssignableFrom(objectType)) + { + return false; + } + + // all fsharp objects have CompilationMappingAttribute + // get the fsharp assembly from the attribute and initialize latebound methods + object[] attributes; +#if !(DOTNET || PORTABLE) + attributes = objectType.GetCustomAttributes(true); +#else + attributes = objectType.GetTypeInfo().GetCustomAttributes(true).ToArray(); +#endif + + bool isFSharpType = false; + foreach (object attribute in attributes) + { + Type attributeType = attribute.GetType(); + if (attributeType.FullName == "Microsoft.FSharp.Core.CompilationMappingAttribute") + { + FSharpUtils.EnsureInitialized(attributeType.Assembly()); + + isFSharpType = true; + break; + } + } + + if (!isFSharpType) + { + return false; + } + + return (bool)FSharpUtils.IsUnion(null, objectType, null); + } + } +} + +#endif \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Converters/EntityKeyMemberConverter.cs b/Common/00-1Json8.3/Json8.3/Converters/EntityKeyMemberConverter.cs new file mode 100644 index 0000000..87250d8 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Converters/EntityKeyMemberConverter.cs @@ -0,0 +1,157 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +#if !(NET20 || DOTNET || PORTABLE40 || PORTABLE) +using System; +using Newtonsoft.Json.Serialization; +using System.Globalization; +using Newtonsoft.Json.Utilities; + +namespace Newtonsoft.Json.Converters +{ + /// + /// Converts an Entity Framework EntityKey to and from JSON. + /// + public class EntityKeyMemberConverter : JsonConverter + { + private const string EntityKeyMemberFullTypeName = "System.Data.EntityKeyMember"; + + private const string KeyPropertyName = "Key"; + private const string TypePropertyName = "Type"; + private const string ValuePropertyName = "Value"; + + private static ReflectionObject _reflectionObject; + + /// + /// Writes the JSON representation of the object. + /// + /// The to write to. + /// The value. + /// The calling serializer. + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + EnsureReflectionObject(value.GetType()); + + DefaultContractResolver resolver = serializer.ContractResolver as DefaultContractResolver; + + string keyName = (string)_reflectionObject.GetValue(value, KeyPropertyName); + object keyValue = _reflectionObject.GetValue(value, ValuePropertyName); + + Type keyValueType = (keyValue != null) ? keyValue.GetType() : null; + + writer.WriteStartObject(); + writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(KeyPropertyName) : KeyPropertyName); + writer.WriteValue(keyName); + writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(TypePropertyName) : TypePropertyName); + writer.WriteValue((keyValueType != null) ? keyValueType.FullName : null); + + writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(ValuePropertyName) : ValuePropertyName); + + if (keyValueType != null) + { + string valueJson; + if (JsonSerializerInternalWriter.TryConvertToString(keyValue, keyValueType, out valueJson)) + { + writer.WriteValue(valueJson); + } + else + { + writer.WriteValue(keyValue); + } + } + else + { + writer.WriteNull(); + } + + writer.WriteEndObject(); + } + + private static void ReadAndAssertProperty(JsonReader reader, string propertyName) + { + reader.ReadAndAssert(); + + if (reader.TokenType != JsonToken.PropertyName || !string.Equals(reader.Value.ToString(), propertyName, StringComparison.OrdinalIgnoreCase)) + { + throw new JsonSerializationException("Expected JSON property '{0}'.".FormatWith(CultureInfo.InvariantCulture, propertyName)); + } + } + + /// + /// Reads the JSON representation of the object. + /// + /// The to read from. + /// Type of the object. + /// The existing value of object being read. + /// The calling serializer. + /// The object value. + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + { + EnsureReflectionObject(objectType); + + object entityKeyMember = _reflectionObject.Creator(); + + ReadAndAssertProperty(reader, KeyPropertyName); + reader.ReadAndAssert(); + _reflectionObject.SetValue(entityKeyMember, KeyPropertyName, reader.Value.ToString()); + + ReadAndAssertProperty(reader, TypePropertyName); + reader.ReadAndAssert(); + string type = reader.Value.ToString(); + + Type t = Type.GetType(type); + + ReadAndAssertProperty(reader, ValuePropertyName); + reader.ReadAndAssert(); + _reflectionObject.SetValue(entityKeyMember, ValuePropertyName, serializer.Deserialize(reader, t)); + + reader.ReadAndAssert(); + + return entityKeyMember; + } + + private static void EnsureReflectionObject(Type objectType) + { + if (_reflectionObject == null) + { + _reflectionObject = ReflectionObject.Create(objectType, KeyPropertyName, ValuePropertyName); + } + } + + /// + /// Determines whether this instance can convert the specified object type. + /// + /// Type of the object. + /// + /// true if this instance can convert the specified object type; otherwise, false. + /// + public override bool CanConvert(Type objectType) + { + return objectType.AssignableToTypeName(EntityKeyMemberFullTypeName); + } + } +} + +#endif \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Converters/ExpandoObjectConverter.cs b/Common/00-1Json8.3/Json8.3/Converters/ExpandoObjectConverter.cs new file mode 100644 index 0000000..4ca6a61 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Converters/ExpandoObjectConverter.cs @@ -0,0 +1,168 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +#if !(NET35 || NET20 || PORTABLE40) + +using System; +using System.Collections.Generic; +using System.Dynamic; +using System.Globalization; +using System.Linq; +using System.Text; +using Newtonsoft.Json.Utilities; + +namespace Newtonsoft.Json.Converters +{ + /// + /// Converts an ExpandoObject to and from JSON. + /// + public class ExpandoObjectConverter : JsonConverter + { + /// + /// Writes the JSON representation of the object. + /// + /// The to write to. + /// The value. + /// The calling serializer. + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + // can write is set to false + } + + /// + /// Reads the JSON representation of the object. + /// + /// The to read from. + /// Type of the object. + /// The existing value of object being read. + /// The calling serializer. + /// The object value. + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + { + return ReadValue(reader); + } + + private object ReadValue(JsonReader reader) + { + if (!reader.MoveToContent()) + { + throw JsonSerializationException.Create(reader, "Unexpected end when reading ExpandoObject."); + } + + switch (reader.TokenType) + { + case JsonToken.StartObject: + return ReadObject(reader); + case JsonToken.StartArray: + return ReadList(reader); + default: + if (JsonTokenUtils.IsPrimitiveToken(reader.TokenType)) + { + return reader.Value; + } + + throw JsonSerializationException.Create(reader, "Unexpected token when converting ExpandoObject: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); + } + } + + private object ReadList(JsonReader reader) + { + IList list = new List(); + + while (reader.Read()) + { + switch (reader.TokenType) + { + case JsonToken.Comment: + break; + default: + object v = ReadValue(reader); + + list.Add(v); + break; + case JsonToken.EndArray: + return list; + } + } + + throw JsonSerializationException.Create(reader, "Unexpected end when reading ExpandoObject."); + } + + private object ReadObject(JsonReader reader) + { + IDictionary expandoObject = new ExpandoObject(); + + while (reader.Read()) + { + switch (reader.TokenType) + { + case JsonToken.PropertyName: + string propertyName = reader.Value.ToString(); + + if (!reader.Read()) + { + throw JsonSerializationException.Create(reader, "Unexpected end when reading ExpandoObject."); + } + + object v = ReadValue(reader); + + expandoObject[propertyName] = v; + break; + case JsonToken.Comment: + break; + case JsonToken.EndObject: + return expandoObject; + } + } + + throw JsonSerializationException.Create(reader, "Unexpected end when reading ExpandoObject."); + } + + /// + /// Determines whether this instance can convert the specified object type. + /// + /// Type of the object. + /// + /// true if this instance can convert the specified object type; otherwise, false. + /// + public override bool CanConvert(Type objectType) + { + return (objectType == typeof(ExpandoObject)); + } + + /// + /// Gets a value indicating whether this can write JSON. + /// + /// + /// true if this can write JSON; otherwise, false. + /// + public override bool CanWrite + { + get { return false; } + } + } +} + +#endif \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Converters/IsoDateTimeConverter.cs b/Common/00-1Json8.3/Json8.3/Converters/IsoDateTimeConverter.cs new file mode 100644 index 0000000..9d2f822 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Converters/IsoDateTimeConverter.cs @@ -0,0 +1,197 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Globalization; +using Newtonsoft.Json.Utilities; + +namespace Newtonsoft.Json.Converters +{ + /// + /// Converts a to and from the ISO 8601 date format (e.g. 2008-04-12T12:53Z). + /// + public class IsoDateTimeConverter : DateTimeConverterBase + { + private const string DefaultDateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK"; + + private DateTimeStyles _dateTimeStyles = DateTimeStyles.RoundtripKind; + private string _dateTimeFormat; + private CultureInfo _culture; + + /// + /// Gets or sets the date time styles used when converting a date to and from JSON. + /// + /// The date time styles used when converting a date to and from JSON. + public DateTimeStyles DateTimeStyles + { + get { return _dateTimeStyles; } + set { _dateTimeStyles = value; } + } + + /// + /// Gets or sets the date time format used when converting a date to and from JSON. + /// + /// The date time format used when converting a date to and from JSON. + public string DateTimeFormat + { + get { return _dateTimeFormat ?? string.Empty; } + set { _dateTimeFormat = StringUtils.NullEmptyString(value); } + } + + /// + /// Gets or sets the culture used when converting a date to and from JSON. + /// + /// The culture used when converting a date to and from JSON. + public CultureInfo Culture + { + get { return _culture ?? CultureInfo.CurrentCulture; } + set { _culture = value; } + } + + /// + /// Writes the JSON representation of the object. + /// + /// The to write to. + /// The value. + /// The calling serializer. + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + string text; + + if (value is DateTime) + { + DateTime dateTime = (DateTime)value; + + if ((_dateTimeStyles & DateTimeStyles.AdjustToUniversal) == DateTimeStyles.AdjustToUniversal + || (_dateTimeStyles & DateTimeStyles.AssumeUniversal) == DateTimeStyles.AssumeUniversal) + { + dateTime = dateTime.ToUniversalTime(); + } + + text = dateTime.ToString(_dateTimeFormat ?? DefaultDateTimeFormat, Culture); + } +#if !NET20 + else if (value is DateTimeOffset) + { + DateTimeOffset dateTimeOffset = (DateTimeOffset)value; + if ((_dateTimeStyles & DateTimeStyles.AdjustToUniversal) == DateTimeStyles.AdjustToUniversal + || (_dateTimeStyles & DateTimeStyles.AssumeUniversal) == DateTimeStyles.AssumeUniversal) + { + dateTimeOffset = dateTimeOffset.ToUniversalTime(); + } + + text = dateTimeOffset.ToString(_dateTimeFormat ?? DefaultDateTimeFormat, Culture); + } +#endif + else + { + throw new JsonSerializationException("Unexpected value when converting date. Expected DateTime or DateTimeOffset, got {0}.".FormatWith(CultureInfo.InvariantCulture, ReflectionUtils.GetObjectType(value))); + } + + writer.WriteValue(text); + } + + /// + /// Reads the JSON representation of the object. + /// + /// The to read from. + /// Type of the object. + /// The existing value of object being read. + /// The calling serializer. + /// The object value. + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + { + bool nullable = ReflectionUtils.IsNullableType(objectType); +#if !NET20 + Type t = (nullable) + ? Nullable.GetUnderlyingType(objectType) + : objectType; +#endif + + if (reader.TokenType == JsonToken.Null) + { + if (!ReflectionUtils.IsNullableType(objectType)) + { + throw JsonSerializationException.Create(reader, "Cannot convert null value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType)); + } + + return null; + } + + if (reader.TokenType == JsonToken.Date) + { +#if !NET20 + if (t == typeof(DateTimeOffset)) + { + return (reader.Value is DateTimeOffset) ? reader.Value : new DateTimeOffset((DateTime)reader.Value); + } + + // converter is expected to return a DateTime + if (reader.Value is DateTimeOffset) + { + return ((DateTimeOffset)reader.Value).DateTime; + } +#endif + + return reader.Value; + } + + if (reader.TokenType != JsonToken.String) + { + throw JsonSerializationException.Create(reader, "Unexpected token parsing date. Expected String, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); + } + + string dateText = reader.Value.ToString(); + + if (string.IsNullOrEmpty(dateText) && nullable) + { + return null; + } + +#if !NET20 + if (t == typeof(DateTimeOffset)) + { + if (!string.IsNullOrEmpty(_dateTimeFormat)) + { + return DateTimeOffset.ParseExact(dateText, _dateTimeFormat, Culture, _dateTimeStyles); + } + else + { + return DateTimeOffset.Parse(dateText, Culture, _dateTimeStyles); + } + } +#endif + + if (!string.IsNullOrEmpty(_dateTimeFormat)) + { + return DateTime.ParseExact(dateText, _dateTimeFormat, Culture, _dateTimeStyles); + } + else + { + return DateTime.Parse(dateText, Culture, _dateTimeStyles); + } + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Converters/JavaScriptDateTimeConverter.cs b/Common/00-1Json8.3/Json8.3/Converters/JavaScriptDateTimeConverter.cs new file mode 100644 index 0000000..0f0e7ff --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Converters/JavaScriptDateTimeConverter.cs @@ -0,0 +1,127 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Globalization; +using Newtonsoft.Json.Utilities; + +namespace Newtonsoft.Json.Converters +{ + /// + /// Converts a to and from a JavaScript date constructor (e.g. new Date(52231943)). + /// + public class JavaScriptDateTimeConverter : DateTimeConverterBase + { + /// + /// Writes the JSON representation of the object. + /// + /// The to write to. + /// The value. + /// The calling serializer. + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + long ticks; + + if (value is DateTime) + { + DateTime dateTime = (DateTime)value; + DateTime utcDateTime = dateTime.ToUniversalTime(); + ticks = DateTimeUtils.ConvertDateTimeToJavaScriptTicks(utcDateTime); + } +#if !NET20 + else if (value is DateTimeOffset) + { + DateTimeOffset dateTimeOffset = (DateTimeOffset)value; + DateTimeOffset utcDateTimeOffset = dateTimeOffset.ToUniversalTime(); + ticks = DateTimeUtils.ConvertDateTimeToJavaScriptTicks(utcDateTimeOffset.UtcDateTime); + } +#endif + else + { + throw new JsonSerializationException("Expected date object value."); + } + + writer.WriteStartConstructor("Date"); + writer.WriteValue(ticks); + writer.WriteEndConstructor(); + } + + /// + /// Reads the JSON representation of the object. + /// + /// The to read from. + /// Type of the object. + /// The existing property value of the JSON that is being converted. + /// The calling serializer. + /// The object value. + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + { + if (reader.TokenType == JsonToken.Null) + { + if (!ReflectionUtils.IsNullable(objectType)) + { + throw JsonSerializationException.Create(reader, "Cannot convert null value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType)); + } + + return null; + } + + if (reader.TokenType != JsonToken.StartConstructor || !string.Equals(reader.Value.ToString(), "Date", StringComparison.Ordinal)) + { + throw JsonSerializationException.Create(reader, "Unexpected token or value when parsing date. Token: {0}, Value: {1}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType, reader.Value)); + } + + reader.Read(); + + if (reader.TokenType != JsonToken.Integer) + { + throw JsonSerializationException.Create(reader, "Unexpected token parsing date. Expected Integer, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); + } + + long ticks = (long)reader.Value; + + DateTime d = DateTimeUtils.ConvertJavaScriptTicksToDateTime(ticks); + + reader.Read(); + + if (reader.TokenType != JsonToken.EndConstructor) + { + throw JsonSerializationException.Create(reader, "Unexpected token parsing date. Expected EndConstructor, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); + } + +#if !NET20 + Type t = (ReflectionUtils.IsNullableType(objectType)) + ? Nullable.GetUnderlyingType(objectType) + : objectType; + if (t == typeof(DateTimeOffset)) + { + return new DateTimeOffset(d); + } +#endif + + return d; + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Converters/JsonValueConverter.cs b/Common/00-1Json8.3/Json8.3/Converters/JsonValueConverter.cs new file mode 100644 index 0000000..25f979f --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Converters/JsonValueConverter.cs @@ -0,0 +1,225 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + + +#if NETFX_CORE +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Security; +using Newtonsoft.Json.Utilities; +using Windows.Data.Json; + +namespace Newtonsoft.Json.Converters +{ + /// + /// Converts a to and from JSON. + /// + public class JsonValueConverter : JsonConverter + { + /// + /// Writes the JSON representation of the object. + /// + /// The to write to. + /// The value. + /// The calling serializer. + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + WriteJsonValue(writer, (IJsonValue)value); + } + + private void WriteJsonValue(JsonWriter writer, IJsonValue value) + { + switch (value.ValueType) + { + case JsonValueType.Array: + { + JsonArray a = value.GetArray(); + writer.WriteStartArray(); + for (int i = 0; i < a.Count; i++) + { + WriteJsonValue(writer, a[i]); + } + writer.WriteEndArray(); + } + break; + case JsonValueType.Boolean: + { + writer.WriteValue(value.GetBoolean()); + } + break; + case JsonValueType.Null: + { + writer.WriteNull(); + } + break; + case JsonValueType.Number: + { + // JsonValue doesn't support integers + // serialize whole numbers without a decimal point + double d = value.GetNumber(); + bool isInteger = (d % 1 == 0); + if (isInteger && d <= long.MaxValue && d >= long.MinValue) + writer.WriteValue(Convert.ToInt64(d)); + else + writer.WriteValue(d); + } + break; + case JsonValueType.Object: + { + JsonObject o = value.GetObject(); + writer.WriteStartObject(); + foreach (KeyValuePair v in o) + { + writer.WritePropertyName(v.Key); + WriteJsonValue(writer, v.Value); + } + writer.WriteEndObject(); + } + break; + case JsonValueType.String: + { + writer.WriteValue(value.GetString()); + } + break; + default: + throw new ArgumentOutOfRangeException("ValueType"); + } + } + + /// + /// Reads the JSON representation of the object. + /// + /// The to read from. + /// Type of the object. + /// The existing value of object being read. + /// The calling serializer. + /// The object value. + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + { + if (reader.TokenType == JsonToken.None) + reader.Read(); + + IJsonValue value = CreateJsonValue(reader); + + if (!objectType.IsAssignableFrom(value.GetType())) + throw JsonSerializationException.Create(reader, "Could not convert '{0}' to '{1}'.".FormatWith(CultureInfo.InvariantCulture, value.GetType(), objectType)); + + return value; + } + + private IJsonValue CreateJsonValue(JsonReader reader) + { + while (reader.TokenType == JsonToken.Comment) + { + if (!reader.Read()) + throw JsonSerializationException.Create(reader, "Unexpected end."); + } + + switch (reader.TokenType) + { + case JsonToken.StartObject: + { + return CreateJsonObject(reader); + } + case JsonToken.StartArray: + { + JsonArray a = new JsonArray(); + + while (reader.Read()) + { + switch (reader.TokenType) + { + case JsonToken.EndArray: + return a; + default: + IJsonValue value = CreateJsonValue(reader); + a.Add(value); + break; + } + } + } + break; + case JsonToken.Integer: + case JsonToken.Float: + return JsonValue.CreateNumberValue(Convert.ToDouble(reader.Value, CultureInfo.InvariantCulture)); + case JsonToken.String: + return JsonValue.CreateStringValue(reader.Value.ToString()); + case JsonToken.Boolean: + return JsonValue.CreateBooleanValue(Convert.ToBoolean(reader.Value, CultureInfo.InvariantCulture)); + case JsonToken.Null: + // surely there is a better way to create a null value than this? + return JsonValue.Parse("null"); + case JsonToken.Date: + return JsonValue.CreateStringValue(reader.Value.ToString()); + case JsonToken.Bytes: + return JsonValue.CreateStringValue(reader.Value.ToString()); + default: + throw JsonSerializationException.Create(reader, "Unexpected or unsupported token: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); + } + + throw JsonSerializationException.Create(reader, "Unexpected end."); + } + + private JsonObject CreateJsonObject(JsonReader reader) + { + JsonObject o = new JsonObject(); + string propertyName = null; + + while (reader.Read()) + { + switch (reader.TokenType) + { + case JsonToken.PropertyName: + propertyName = (string)reader.Value; + break; + case JsonToken.EndObject: + return o; + case JsonToken.Comment: + break; + default: + IJsonValue propertyValue = CreateJsonValue(reader); + o.Add(propertyName, propertyValue); + break; + } + } + + throw JsonSerializationException.Create(reader, "Unexpected end."); + } + + /// + /// Determines whether this instance can convert the specified object type. + /// + /// Type of the object. + /// + /// true if this instance can convert the specified object type; otherwise, false. + /// + public override bool CanConvert(Type objectType) + { + return typeof(IJsonValue).IsAssignableFrom(objectType); + } + } +} +#endif \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Converters/KeyValuePairConverter.cs b/Common/00-1Json8.3/Json8.3/Converters/KeyValuePairConverter.cs new file mode 100644 index 0000000..71f5fbb --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Converters/KeyValuePairConverter.cs @@ -0,0 +1,149 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Collections.Generic; +using Newtonsoft.Json.Serialization; +using Newtonsoft.Json.Utilities; +using System.Reflection; + +namespace Newtonsoft.Json.Converters +{ + /// + /// Converts a to and from JSON. + /// + public class KeyValuePairConverter : JsonConverter + { + private const string KeyName = "Key"; + private const string ValueName = "Value"; + + private static readonly ThreadSafeStore ReflectionObjectPerType = new ThreadSafeStore(InitializeReflectionObject); + + private static ReflectionObject InitializeReflectionObject(Type t) + { + IList genericArguments = t.GetGenericArguments(); + Type keyType = genericArguments[0]; + Type valueType = genericArguments[1]; + + return ReflectionObject.Create(t, t.GetConstructor(new[] { keyType, valueType }), KeyName, ValueName); + } + + /// + /// Writes the JSON representation of the object. + /// + /// The to write to. + /// The value. + /// The calling serializer. + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + ReflectionObject reflectionObject = ReflectionObjectPerType.Get(value.GetType()); + + DefaultContractResolver resolver = serializer.ContractResolver as DefaultContractResolver; + + writer.WriteStartObject(); + writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(KeyName) : KeyName); + serializer.Serialize(writer, reflectionObject.GetValue(value, KeyName), reflectionObject.GetType(KeyName)); + writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(ValueName) : ValueName); + serializer.Serialize(writer, reflectionObject.GetValue(value, ValueName), reflectionObject.GetType(ValueName)); + writer.WriteEndObject(); + } + + /// + /// Reads the JSON representation of the object. + /// + /// The to read from. + /// Type of the object. + /// The existing value of object being read. + /// The calling serializer. + /// The object value. + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + { + if (reader.TokenType == JsonToken.Null) + { + if (!ReflectionUtils.IsNullableType(objectType)) + { + throw JsonSerializationException.Create(reader, "Cannot convert null value to KeyValuePair."); + } + + return null; + } + + object key = null; + object value = null; + + reader.ReadAndAssert(); + + Type t = ReflectionUtils.IsNullableType(objectType) + ? Nullable.GetUnderlyingType(objectType) + : objectType; + + ReflectionObject reflectionObject = ReflectionObjectPerType.Get(t); + + while (reader.TokenType == JsonToken.PropertyName) + { + string propertyName = reader.Value.ToString(); + if (string.Equals(propertyName, KeyName, StringComparison.OrdinalIgnoreCase)) + { + reader.ReadAndAssert(); + key = serializer.Deserialize(reader, reflectionObject.GetType(KeyName)); + } + else if (string.Equals(propertyName, ValueName, StringComparison.OrdinalIgnoreCase)) + { + reader.ReadAndAssert(); + value = serializer.Deserialize(reader, reflectionObject.GetType(ValueName)); + } + else + { + reader.Skip(); + } + + reader.ReadAndAssert(); + } + + return reflectionObject.Creator(key, value); + } + + /// + /// Determines whether this instance can convert the specified object type. + /// + /// Type of the object. + /// + /// true if this instance can convert the specified object type; otherwise, false. + /// + public override bool CanConvert(Type objectType) + { + Type t = (ReflectionUtils.IsNullableType(objectType)) + ? Nullable.GetUnderlyingType(objectType) + : objectType; + + if (t.IsValueType() && t.IsGenericType()) + { + return (t.GetGenericTypeDefinition() == typeof(KeyValuePair<,>)); + } + + return false; + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Converters/RegexConverter.cs b/Common/00-1Json8.3/Json8.3/Converters/RegexConverter.cs new file mode 100644 index 0000000..1d6de62 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Converters/RegexConverter.cs @@ -0,0 +1,227 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Text.RegularExpressions; +using Newtonsoft.Json.Bson; +using System.Globalization; +using Newtonsoft.Json.Serialization; + +namespace Newtonsoft.Json.Converters +{ + /// + /// Converts a to and from JSON and BSON. + /// + public class RegexConverter : JsonConverter + { + private const string PatternName = "Pattern"; + private const string OptionsName = "Options"; + + /// + /// Writes the JSON representation of the object. + /// + /// The to write to. + /// The value. + /// The calling serializer. + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + Regex regex = (Regex)value; + + BsonWriter bsonWriter = writer as BsonWriter; + if (bsonWriter != null) + { + WriteBson(bsonWriter, regex); + } + else + { + WriteJson(writer, regex, serializer); + } + } + + private bool HasFlag(RegexOptions options, RegexOptions flag) + { + return ((options & flag) == flag); + } + + private void WriteBson(BsonWriter writer, Regex regex) + { + // Regular expression - The first cstring is the regex pattern, the second + // is the regex options string. Options are identified by characters, which + // must be stored in alphabetical order. Valid options are 'i' for case + // insensitive matching, 'm' for multiline matching, 'x' for verbose mode, + // 'l' to make \w, \W, etc. locale dependent, 's' for dotall mode + // ('.' matches everything), and 'u' to make \w, \W, etc. match unicode. + + string options = null; + + if (HasFlag(regex.Options, RegexOptions.IgnoreCase)) + { + options += "i"; + } + + if (HasFlag(regex.Options, RegexOptions.Multiline)) + { + options += "m"; + } + + if (HasFlag(regex.Options, RegexOptions.Singleline)) + { + options += "s"; + } + + options += "u"; + + if (HasFlag(regex.Options, RegexOptions.ExplicitCapture)) + { + options += "x"; + } + + writer.WriteRegex(regex.ToString(), options); + } + + private void WriteJson(JsonWriter writer, Regex regex, JsonSerializer serializer) + { + DefaultContractResolver resolver = serializer.ContractResolver as DefaultContractResolver; + + writer.WriteStartObject(); + writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(PatternName) : PatternName); + writer.WriteValue(regex.ToString()); + writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(OptionsName) : OptionsName); + serializer.Serialize(writer, regex.Options); + writer.WriteEndObject(); + } + + /// + /// Reads the JSON representation of the object. + /// + /// The to read from. + /// Type of the object. + /// The existing value of object being read. + /// The calling serializer. + /// The object value. + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + { + if (reader.TokenType == JsonToken.StartObject) + { + return ReadRegexObject(reader, serializer); + } + + if (reader.TokenType == JsonToken.String) + { + return ReadRegexString(reader); + } + + throw JsonSerializationException.Create(reader, "Unexpected token when reading Regex."); + } + + private object ReadRegexString(JsonReader reader) + { + string regexText = (string)reader.Value; + int patternOptionDelimiterIndex = regexText.LastIndexOf('/'); + + string patternText = regexText.Substring(1, patternOptionDelimiterIndex - 1); + string optionsText = regexText.Substring(patternOptionDelimiterIndex + 1); + + RegexOptions options = RegexOptions.None; + foreach (char c in optionsText) + { + switch (c) + { + case 'i': + options |= RegexOptions.IgnoreCase; + break; + case 'm': + options |= RegexOptions.Multiline; + break; + case 's': + options |= RegexOptions.Singleline; + break; + case 'x': + options |= RegexOptions.ExplicitCapture; + break; + } + } + + return new Regex(patternText, options); + } + + private Regex ReadRegexObject(JsonReader reader, JsonSerializer serializer) + { + string pattern = null; + RegexOptions? options = null; + + while (reader.Read()) + { + switch (reader.TokenType) + { + case JsonToken.PropertyName: + string propertyName = reader.Value.ToString(); + + if (!reader.Read()) + { + throw JsonSerializationException.Create(reader, "Unexpected end when reading Regex."); + } + + if (string.Equals(propertyName, PatternName, StringComparison.OrdinalIgnoreCase)) + { + pattern = (string)reader.Value; + } + else if (string.Equals(propertyName, OptionsName, StringComparison.OrdinalIgnoreCase)) + { + options = serializer.Deserialize(reader); + } + else + { + reader.Skip(); + } + break; + case JsonToken.Comment: + break; + case JsonToken.EndObject: + if (pattern == null) + { + throw JsonSerializationException.Create(reader, "Error deserializing Regex. No pattern found."); + } + + return new Regex(pattern, options ?? RegexOptions.None); + } + } + + throw JsonSerializationException.Create(reader, "Unexpected end when reading Regex."); + } + + /// + /// Determines whether this instance can convert the specified object type. + /// + /// Type of the object. + /// + /// true if this instance can convert the specified object type; otherwise, false. + /// + public override bool CanConvert(Type objectType) + { + return (objectType == typeof(Regex)); + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Converters/StringEnumConverter.cs b/Common/00-1Json8.3/Json8.3/Converters/StringEnumConverter.cs new file mode 100644 index 0000000..cb97ea9 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Converters/StringEnumConverter.cs @@ -0,0 +1,175 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Reflection; +using System.Runtime.Serialization; +using Newtonsoft.Json.Utilities; +#if NET20 +using Newtonsoft.Json.Utilities.LinqBridge; +#else +using System.Linq; + +#endif + +namespace Newtonsoft.Json.Converters +{ + /// + /// Converts an to and from its name string value. + /// + public class StringEnumConverter : JsonConverter + { + /// + /// Gets or sets a value indicating whether the written enum text should be camel case. + /// + /// true if the written enum text will be camel case; otherwise, false. + public bool CamelCaseText { get; set; } + + /// + /// Gets or sets a value indicating whether integer values are allowed. + /// + /// true if integers are allowed; otherwise, false. + public bool AllowIntegerValues { get; set; } + + /// + /// Initializes a new instance of the class. + /// + public StringEnumConverter() + { + AllowIntegerValues = true; + } + + /// + /// Initializes a new instance of the class. + /// + /// true if the written enum text will be camel case; otherwise, false. + public StringEnumConverter(bool camelCaseText) + : this() + { + CamelCaseText = camelCaseText; + } + + /// + /// Writes the JSON representation of the object. + /// + /// The to write to. + /// The value. + /// The calling serializer. + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + if (value == null) + { + writer.WriteNull(); + return; + } + + Enum e = (Enum)value; + + string enumName = e.ToString("G"); + + if (char.IsNumber(enumName[0]) || enumName[0] == '-') + { + // enum value has no name so write number + writer.WriteValue(value); + } + else + { + Type enumType = e.GetType(); + + string finalName = EnumUtils.ToEnumName(enumType, enumName, CamelCaseText); + + writer.WriteValue(finalName); + } + } + + /// + /// Reads the JSON representation of the object. + /// + /// The to read from. + /// Type of the object. + /// The existing value of object being read. + /// The calling serializer. + /// The object value. + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + { + if (reader.TokenType == JsonToken.Null) + { + if (!ReflectionUtils.IsNullableType(objectType)) + { + throw JsonSerializationException.Create(reader, "Cannot convert null value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType)); + } + + return null; + } + + bool isNullable = ReflectionUtils.IsNullableType(objectType); + Type t = isNullable ? Nullable.GetUnderlyingType(objectType) : objectType; + + try + { + if (reader.TokenType == JsonToken.String) + { + string enumText = reader.Value.ToString(); + return EnumUtils.ParseEnumName(enumText, isNullable, t); + } + + if (reader.TokenType == JsonToken.Integer) + { + if (!AllowIntegerValues) + { + throw JsonSerializationException.Create(reader, "Integer value {0} is not allowed.".FormatWith(CultureInfo.InvariantCulture, reader.Value)); + } + + return ConvertUtils.ConvertOrCast(reader.Value, CultureInfo.InvariantCulture, t); + } + } + catch (Exception ex) + { + throw JsonSerializationException.Create(reader, "Error converting value {0} to type '{1}'.".FormatWith(CultureInfo.InvariantCulture, MiscellaneousUtils.FormatValueForPrint(reader.Value), objectType), ex); + } + + // we don't actually expect to get here. + throw JsonSerializationException.Create(reader, "Unexpected token {0} when parsing enum.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); + } + + /// + /// Determines whether this instance can convert the specified object type. + /// + /// Type of the object. + /// + /// true if this instance can convert the specified object type; otherwise, false. + /// + public override bool CanConvert(Type objectType) + { + Type t = (ReflectionUtils.IsNullableType(objectType)) + ? Nullable.GetUnderlyingType(objectType) + : objectType; + + return t.IsEnum(); + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Converters/VersionConverter.cs b/Common/00-1Json8.3/Json8.3/Converters/VersionConverter.cs new file mode 100644 index 0000000..3f512e4 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Converters/VersionConverter.cs @@ -0,0 +1,106 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Globalization; +using Newtonsoft.Json.Utilities; + +namespace Newtonsoft.Json.Converters +{ + /// + /// Converts a to and from a string (e.g. "1.2.3.4"). + /// + public class VersionConverter : JsonConverter + { + /// + /// Writes the JSON representation of the object. + /// + /// The to write to. + /// The value. + /// The calling serializer. + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + if (value == null) + { + writer.WriteNull(); + } + else if (value is Version) + { + writer.WriteValue(value.ToString()); + } + else + { + throw new JsonSerializationException("Expected Version object value"); + } + } + + /// + /// Reads the JSON representation of the object. + /// + /// The to read from. + /// Type of the object. + /// The existing property value of the JSON that is being converted. + /// The calling serializer. + /// The object value. + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + { + if (reader.TokenType == JsonToken.Null) + { + return null; + } + else + { + if (reader.TokenType == JsonToken.String) + { + try + { + Version v = new Version((string)reader.Value); + return v; + } + catch (Exception ex) + { + throw JsonSerializationException.Create(reader, "Error parsing version string: {0}".FormatWith(CultureInfo.InvariantCulture, reader.Value), ex); + } + } + else + { + throw JsonSerializationException.Create(reader, "Unexpected token or value when parsing version. Token: {0}, Value: {1}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType, reader.Value)); + } + } + } + + /// + /// Determines whether this instance can convert the specified object type. + /// + /// Type of the object. + /// + /// true if this instance can convert the specified object type; otherwise, false. + /// + public override bool CanConvert(Type objectType) + { + return objectType == typeof(Version); + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Converters/XmlNodeConverter.cs b/Common/00-1Json8.3/Json8.3/Converters/XmlNodeConverter.cs new file mode 100644 index 0000000..051f676 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Converters/XmlNodeConverter.cs @@ -0,0 +1,1949 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +#if !PORTABLE40 +#if !(PORTABLE || NET20 || NET35) +using System.Numerics; +#endif +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Xml; +using System.Reflection; +using Newtonsoft.Json.Serialization; +#if !(NET20 || PORTABLE40) +using System.Xml.Linq; +#endif +using Newtonsoft.Json.Utilities; +#if NET20 +using Newtonsoft.Json.Utilities.LinqBridge; +#else +using System.Linq; + +#endif + +namespace Newtonsoft.Json.Converters +{ + + #region XmlNodeWrappers +#if !DOTNET && !PORTABLE && !PORTABLE40 + internal class XmlDocumentWrapper : XmlNodeWrapper, IXmlDocument + { + private readonly XmlDocument _document; + + public XmlDocumentWrapper(XmlDocument document) + : base(document) + { + _document = document; + } + + public IXmlNode CreateComment(string data) + { + return new XmlNodeWrapper(_document.CreateComment(data)); + } + + public IXmlNode CreateTextNode(string text) + { + return new XmlNodeWrapper(_document.CreateTextNode(text)); + } + + public IXmlNode CreateCDataSection(string data) + { + return new XmlNodeWrapper(_document.CreateCDataSection(data)); + } + + public IXmlNode CreateWhitespace(string text) + { + return new XmlNodeWrapper(_document.CreateWhitespace(text)); + } + + public IXmlNode CreateSignificantWhitespace(string text) + { + return new XmlNodeWrapper(_document.CreateSignificantWhitespace(text)); + } + + public IXmlNode CreateXmlDeclaration(string version, string encoding, string standalone) + { + return new XmlDeclarationWrapper(_document.CreateXmlDeclaration(version, encoding, standalone)); + } + + public IXmlNode CreateXmlDocumentType(string name, string publicId, string systemId, string internalSubset) + { + return new XmlDocumentTypeWrapper(_document.CreateDocumentType(name, publicId, systemId, null)); + } + + public IXmlNode CreateProcessingInstruction(string target, string data) + { + return new XmlNodeWrapper(_document.CreateProcessingInstruction(target, data)); + } + + public IXmlElement CreateElement(string elementName) + { + return new XmlElementWrapper(_document.CreateElement(elementName)); + } + + public IXmlElement CreateElement(string qualifiedName, string namespaceUri) + { + return new XmlElementWrapper(_document.CreateElement(qualifiedName, namespaceUri)); + } + + public IXmlNode CreateAttribute(string name, string value) + { + XmlNodeWrapper attribute = new XmlNodeWrapper(_document.CreateAttribute(name)); + attribute.Value = value; + + return attribute; + } + + public IXmlNode CreateAttribute(string qualifiedName, string namespaceUri, string value) + { + XmlNodeWrapper attribute = new XmlNodeWrapper(_document.CreateAttribute(qualifiedName, namespaceUri)); + attribute.Value = value; + + return attribute; + } + + public IXmlElement DocumentElement + { + get + { + if (_document.DocumentElement == null) + { + return null; + } + + return new XmlElementWrapper(_document.DocumentElement); + } + } + } + + internal class XmlElementWrapper : XmlNodeWrapper, IXmlElement + { + private readonly XmlElement _element; + + public XmlElementWrapper(XmlElement element) + : base(element) + { + _element = element; + } + + public void SetAttributeNode(IXmlNode attribute) + { + XmlNodeWrapper xmlAttributeWrapper = (XmlNodeWrapper)attribute; + + _element.SetAttributeNode((XmlAttribute)xmlAttributeWrapper.WrappedNode); + } + + public string GetPrefixOfNamespace(string namespaceUri) + { + return _element.GetPrefixOfNamespace(namespaceUri); + } + + public bool IsEmpty + { + get { return _element.IsEmpty; } + } + } + + internal class XmlDeclarationWrapper : XmlNodeWrapper, IXmlDeclaration + { + private readonly XmlDeclaration _declaration; + + public XmlDeclarationWrapper(XmlDeclaration declaration) + : base(declaration) + { + _declaration = declaration; + } + + public string Version + { + get { return _declaration.Version; } + } + + public string Encoding + { + get { return _declaration.Encoding; } + set { _declaration.Encoding = value; } + } + + public string Standalone + { + get { return _declaration.Standalone; } + set { _declaration.Standalone = value; } + } + } + + internal class XmlDocumentTypeWrapper : XmlNodeWrapper, IXmlDocumentType + { + private readonly XmlDocumentType _documentType; + + public XmlDocumentTypeWrapper(XmlDocumentType documentType) + : base(documentType) + { + _documentType = documentType; + } + + public string Name + { + get { return _documentType.Name; } + } + + public string System + { + get { return _documentType.SystemId; } + } + + public string Public + { + get { return _documentType.PublicId; } + } + + public string InternalSubset + { + get { return _documentType.InternalSubset; } + } + + public override string LocalName + { + get { return "DOCTYPE"; } + } + } + + internal class XmlNodeWrapper : IXmlNode + { + private readonly XmlNode _node; + private IList _childNodes; + + public XmlNodeWrapper(XmlNode node) + { + _node = node; + } + + public object WrappedNode + { + get { return _node; } + } + + public XmlNodeType NodeType + { + get { return _node.NodeType; } + } + + public virtual string LocalName + { + get { return _node.LocalName; } + } + + public IList ChildNodes + { + get + { + // childnodes is read multiple times + // cache results to prevent multiple reads which kills perf in large documents + if (_childNodes == null) + { + _childNodes = _node.ChildNodes.Cast().Select(WrapNode).ToList(); + } + + return _childNodes; + } + } + + internal static IXmlNode WrapNode(XmlNode node) + { + switch (node.NodeType) + { + case XmlNodeType.Element: + return new XmlElementWrapper((XmlElement)node); + case XmlNodeType.XmlDeclaration: + return new XmlDeclarationWrapper((XmlDeclaration)node); + case XmlNodeType.DocumentType: + return new XmlDocumentTypeWrapper((XmlDocumentType)node); + default: + return new XmlNodeWrapper(node); + } + } + + public IList Attributes + { + get + { + if (_node.Attributes == null) + { + return null; + } + + return _node.Attributes.Cast().Select(WrapNode).ToList(); + } + } + + public IXmlNode ParentNode + { + get + { + XmlNode node = (_node is XmlAttribute) + ? ((XmlAttribute)_node).OwnerElement + : _node.ParentNode; + + if (node == null) + { + return null; + } + + return WrapNode(node); + } + } + + public string Value + { + get { return _node.Value; } + set { _node.Value = value; } + } + + public IXmlNode AppendChild(IXmlNode newChild) + { + XmlNodeWrapper xmlNodeWrapper = (XmlNodeWrapper)newChild; + _node.AppendChild(xmlNodeWrapper._node); + _childNodes = null; + + return newChild; + } + + public string NamespaceUri + { + get { return _node.NamespaceURI; } + } + } +#endif + #endregion + + #region Interfaces + internal interface IXmlDocument : IXmlNode + { + IXmlNode CreateComment(string text); + IXmlNode CreateTextNode(string text); + IXmlNode CreateCDataSection(string data); + IXmlNode CreateWhitespace(string text); + IXmlNode CreateSignificantWhitespace(string text); + IXmlNode CreateXmlDeclaration(string version, string encoding, string standalone); + IXmlNode CreateXmlDocumentType(string name, string publicId, string systemId, string internalSubset); + IXmlNode CreateProcessingInstruction(string target, string data); + IXmlElement CreateElement(string elementName); + IXmlElement CreateElement(string qualifiedName, string namespaceUri); + IXmlNode CreateAttribute(string name, string value); + IXmlNode CreateAttribute(string qualifiedName, string namespaceUri, string value); + + IXmlElement DocumentElement { get; } + } + + internal interface IXmlDeclaration : IXmlNode + { + string Version { get; } + string Encoding { get; set; } + string Standalone { get; set; } + } + + internal interface IXmlDocumentType : IXmlNode + { + string Name { get; } + string System { get; } + string Public { get; } + string InternalSubset { get; } + } + + internal interface IXmlElement : IXmlNode + { + void SetAttributeNode(IXmlNode attribute); + string GetPrefixOfNamespace(string namespaceUri); + bool IsEmpty { get; } + } + + internal interface IXmlNode + { + XmlNodeType NodeType { get; } + string LocalName { get; } + IList ChildNodes { get; } + IList Attributes { get; } + IXmlNode ParentNode { get; } + string Value { get; set; } + IXmlNode AppendChild(IXmlNode newChild); + string NamespaceUri { get; } + object WrappedNode { get; } + } + #endregion + + #region XNodeWrappers +#if !NET20 + internal class XDeclarationWrapper : XObjectWrapper, IXmlDeclaration + { + internal XDeclaration Declaration { get; private set; } + + public XDeclarationWrapper(XDeclaration declaration) + : base(null) + { + Declaration = declaration; + } + + public override XmlNodeType NodeType + { + get { return XmlNodeType.XmlDeclaration; } + } + + public string Version + { + get { return Declaration.Version; } + } + + public string Encoding + { + get { return Declaration.Encoding; } + set { Declaration.Encoding = value; } + } + + public string Standalone + { + get { return Declaration.Standalone; } + set { Declaration.Standalone = value; } + } + } + + internal class XDocumentTypeWrapper : XObjectWrapper, IXmlDocumentType + { + private readonly XDocumentType _documentType; + + public XDocumentTypeWrapper(XDocumentType documentType) + : base(documentType) + { + _documentType = documentType; + } + + public string Name + { + get { return _documentType.Name; } + } + + public string System + { + get { return _documentType.SystemId; } + } + + public string Public + { + get { return _documentType.PublicId; } + } + + public string InternalSubset + { + get { return _documentType.InternalSubset; } + } + + public override string LocalName + { + get { return "DOCTYPE"; } + } + } + + internal class XDocumentWrapper : XContainerWrapper, IXmlDocument + { + private XDocument Document + { + get { return (XDocument)WrappedNode; } + } + + public XDocumentWrapper(XDocument document) + : base(document) + { + } + + public override IList ChildNodes + { + get + { + IList childNodes = base.ChildNodes; + + if (Document.Declaration != null && childNodes[0].NodeType != XmlNodeType.XmlDeclaration) + { + childNodes.Insert(0, new XDeclarationWrapper(Document.Declaration)); + } + + return childNodes; + } + } + + public IXmlNode CreateComment(string text) + { + return new XObjectWrapper(new XComment(text)); + } + + public IXmlNode CreateTextNode(string text) + { + return new XObjectWrapper(new XText(text)); + } + + public IXmlNode CreateCDataSection(string data) + { + return new XObjectWrapper(new XCData(data)); + } + + public IXmlNode CreateWhitespace(string text) + { + return new XObjectWrapper(new XText(text)); + } + + public IXmlNode CreateSignificantWhitespace(string text) + { + return new XObjectWrapper(new XText(text)); + } + + public IXmlNode CreateXmlDeclaration(string version, string encoding, string standalone) + { + return new XDeclarationWrapper(new XDeclaration(version, encoding, standalone)); + } + + public IXmlNode CreateXmlDocumentType(string name, string publicId, string systemId, string internalSubset) + { + return new XDocumentTypeWrapper(new XDocumentType(name, publicId, systemId, internalSubset)); + } + + public IXmlNode CreateProcessingInstruction(string target, string data) + { + return new XProcessingInstructionWrapper(new XProcessingInstruction(target, data)); + } + + public IXmlElement CreateElement(string elementName) + { + return new XElementWrapper(new XElement(elementName)); + } + + public IXmlElement CreateElement(string qualifiedName, string namespaceUri) + { + string localName = MiscellaneousUtils.GetLocalName(qualifiedName); + return new XElementWrapper(new XElement(XName.Get(localName, namespaceUri))); + } + + public IXmlNode CreateAttribute(string name, string value) + { + return new XAttributeWrapper(new XAttribute(name, value)); + } + + public IXmlNode CreateAttribute(string qualifiedName, string namespaceUri, string value) + { + string localName = MiscellaneousUtils.GetLocalName(qualifiedName); + return new XAttributeWrapper(new XAttribute(XName.Get(localName, namespaceUri), value)); + } + + public IXmlElement DocumentElement + { + get + { + if (Document.Root == null) + { + return null; + } + + return new XElementWrapper(Document.Root); + } + } + + public override IXmlNode AppendChild(IXmlNode newChild) + { + XDeclarationWrapper declarationWrapper = newChild as XDeclarationWrapper; + if (declarationWrapper != null) + { + Document.Declaration = declarationWrapper.Declaration; + return declarationWrapper; + } + else + { + return base.AppendChild(newChild); + } + } + } + + internal class XTextWrapper : XObjectWrapper + { + private XText Text + { + get { return (XText)WrappedNode; } + } + + public XTextWrapper(XText text) + : base(text) + { + } + + public override string Value + { + get { return Text.Value; } + set { Text.Value = value; } + } + + public override IXmlNode ParentNode + { + get + { + if (Text.Parent == null) + { + return null; + } + + return XContainerWrapper.WrapNode(Text.Parent); + } + } + } + + internal class XCommentWrapper : XObjectWrapper + { + private XComment Text + { + get { return (XComment)WrappedNode; } + } + + public XCommentWrapper(XComment text) + : base(text) + { + } + + public override string Value + { + get { return Text.Value; } + set { Text.Value = value; } + } + + public override IXmlNode ParentNode + { + get + { + if (Text.Parent == null) + { + return null; + } + + return XContainerWrapper.WrapNode(Text.Parent); + } + } + } + + internal class XProcessingInstructionWrapper : XObjectWrapper + { + private XProcessingInstruction ProcessingInstruction + { + get { return (XProcessingInstruction)WrappedNode; } + } + + public XProcessingInstructionWrapper(XProcessingInstruction processingInstruction) + : base(processingInstruction) + { + } + + public override string LocalName + { + get { return ProcessingInstruction.Target; } + } + + public override string Value + { + get { return ProcessingInstruction.Data; } + set { ProcessingInstruction.Data = value; } + } + } + + internal class XContainerWrapper : XObjectWrapper + { + private IList _childNodes; + + private XContainer Container + { + get { return (XContainer)WrappedNode; } + } + + public XContainerWrapper(XContainer container) + : base(container) + { + } + + public override IList ChildNodes + { + get + { + // childnodes is read multiple times + // cache results to prevent multiple reads which kills perf in large documents + if (_childNodes == null) + { + _childNodes = Container.Nodes().Select(WrapNode).ToList(); + } + + return _childNodes; + } + } + + public override IXmlNode ParentNode + { + get + { + if (Container.Parent == null) + { + return null; + } + + return WrapNode(Container.Parent); + } + } + + internal static IXmlNode WrapNode(XObject node) + { + if (node is XDocument) + { + return new XDocumentWrapper((XDocument)node); + } + else if (node is XElement) + { + return new XElementWrapper((XElement)node); + } + else if (node is XContainer) + { + return new XContainerWrapper((XContainer)node); + } + else if (node is XProcessingInstruction) + { + return new XProcessingInstructionWrapper((XProcessingInstruction)node); + } + else if (node is XText) + { + return new XTextWrapper((XText)node); + } + else if (node is XComment) + { + return new XCommentWrapper((XComment)node); + } + else if (node is XAttribute) + { + return new XAttributeWrapper((XAttribute)node); + } + else if (node is XDocumentType) + { + return new XDocumentTypeWrapper((XDocumentType)node); + } + else + { + return new XObjectWrapper(node); + } + } + + public override IXmlNode AppendChild(IXmlNode newChild) + { + Container.Add(newChild.WrappedNode); + _childNodes = null; + + return newChild; + } + } + + internal class XObjectWrapper : IXmlNode + { + private readonly XObject _xmlObject; + + public XObjectWrapper(XObject xmlObject) + { + _xmlObject = xmlObject; + } + + public object WrappedNode + { + get { return _xmlObject; } + } + + public virtual XmlNodeType NodeType + { + get { return _xmlObject.NodeType; } + } + + public virtual string LocalName + { + get { return null; } + } + + public virtual IList ChildNodes + { + get { return new List(); } + } + + public virtual IList Attributes + { + get { return null; } + } + + public virtual IXmlNode ParentNode + { + get { return null; } + } + + public virtual string Value + { + get { return null; } + set { throw new InvalidOperationException(); } + } + + public virtual IXmlNode AppendChild(IXmlNode newChild) + { + throw new InvalidOperationException(); + } + + public virtual string NamespaceUri + { + get { return null; } + } + } + + internal class XAttributeWrapper : XObjectWrapper + { + private XAttribute Attribute + { + get { return (XAttribute)WrappedNode; } + } + + public XAttributeWrapper(XAttribute attribute) + : base(attribute) + { + } + + public override string Value + { + get { return Attribute.Value; } + set { Attribute.Value = value; } + } + + public override string LocalName + { + get { return Attribute.Name.LocalName; } + } + + public override string NamespaceUri + { + get { return Attribute.Name.NamespaceName; } + } + + public override IXmlNode ParentNode + { + get + { + if (Attribute.Parent == null) + { + return null; + } + + return XContainerWrapper.WrapNode(Attribute.Parent); + } + } + } + + internal class XElementWrapper : XContainerWrapper, IXmlElement + { + private XElement Element + { + get { return (XElement)WrappedNode; } + } + + public XElementWrapper(XElement element) + : base(element) + { + } + + public void SetAttributeNode(IXmlNode attribute) + { + XObjectWrapper wrapper = (XObjectWrapper)attribute; + Element.Add(wrapper.WrappedNode); + } + + public override IList Attributes + { + get { return Element.Attributes().Select(a => new XAttributeWrapper(a)).Cast().ToList(); } + } + + public override string Value + { + get { return Element.Value; } + set { Element.Value = value; } + } + + public override string LocalName + { + get { return Element.Name.LocalName; } + } + + public override string NamespaceUri + { + get { return Element.Name.NamespaceName; } + } + + public string GetPrefixOfNamespace(string namespaceUri) + { + return Element.GetPrefixOfNamespace(namespaceUri); + } + + public bool IsEmpty + { + get { return Element.IsEmpty; } + } + } +#endif + #endregion + + /// + /// Converts XML to and from JSON. + /// + public class XmlNodeConverter : JsonConverter + { + private const string TextName = "#text"; + private const string CommentName = "#comment"; + private const string CDataName = "#cdata-section"; + private const string WhitespaceName = "#whitespace"; + private const string SignificantWhitespaceName = "#significant-whitespace"; + private const string DeclarationName = "?xml"; + private const string JsonNamespaceUri = "http://james.newtonking.com/projects/json"; + + /// + /// Gets or sets the name of the root element to insert when deserializing to XML if the JSON structure has produces multiple root elements. + /// + /// The name of the deserialize root element. + public string DeserializeRootElementName { get; set; } + + /// + /// Gets or sets a flag to indicate whether to write the Json.NET array attribute. + /// This attribute helps preserve arrays when converting the written XML back to JSON. + /// + /// true if the array attibute is written to the XML; otherwise, false. + public bool WriteArrayAttribute { get; set; } + + /// + /// Gets or sets a value indicating whether to write the root JSON object. + /// + /// true if the JSON root object is omitted; otherwise, false. + public bool OmitRootObject { get; set; } + + #region Writing + /// + /// Writes the JSON representation of the object. + /// + /// The to write to. + /// The calling serializer. + /// The value. + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + IXmlNode node = WrapXml(value); + + XmlNamespaceManager manager = new XmlNamespaceManager(new NameTable()); + PushParentNamespaces(node, manager); + + if (!OmitRootObject) + { + writer.WriteStartObject(); + } + + SerializeNode(writer, node, manager, !OmitRootObject); + + if (!OmitRootObject) + { + writer.WriteEndObject(); + } + } + + private IXmlNode WrapXml(object value) + { +#if !NET20 + if (value is XObject) + { + return XContainerWrapper.WrapNode((XObject)value); + } +#endif +#if !(DOTNET || PORTABLE) + if (value is XmlNode) + { + return XmlNodeWrapper.WrapNode((XmlNode)value); + } +#endif + + throw new ArgumentException("Value must be an XML object.", nameof(value)); + } + + private void PushParentNamespaces(IXmlNode node, XmlNamespaceManager manager) + { + List parentElements = null; + + IXmlNode parent = node; + while ((parent = parent.ParentNode) != null) + { + if (parent.NodeType == XmlNodeType.Element) + { + if (parentElements == null) + { + parentElements = new List(); + } + + parentElements.Add(parent); + } + } + + if (parentElements != null) + { + parentElements.Reverse(); + + foreach (IXmlNode parentElement in parentElements) + { + manager.PushScope(); + foreach (IXmlNode attribute in parentElement.Attributes) + { + if (attribute.NamespaceUri == "http://www.w3.org/2000/xmlns/" && attribute.LocalName != "xmlns") + { + manager.AddNamespace(attribute.LocalName, attribute.Value); + } + } + } + } + } + + private string ResolveFullName(IXmlNode node, XmlNamespaceManager manager) + { + string prefix = (node.NamespaceUri == null || (node.LocalName == "xmlns" && node.NamespaceUri == "http://www.w3.org/2000/xmlns/")) + ? null + : manager.LookupPrefix(node.NamespaceUri); + + if (!string.IsNullOrEmpty(prefix)) + { + return prefix + ":" + XmlConvert.DecodeName(node.LocalName); + } + else + { + return XmlConvert.DecodeName(node.LocalName); + } + } + + private string GetPropertyName(IXmlNode node, XmlNamespaceManager manager) + { + switch (node.NodeType) + { + case XmlNodeType.Attribute: + if (node.NamespaceUri == JsonNamespaceUri) + { + return "$" + node.LocalName; + } + else + { + return "@" + ResolveFullName(node, manager); + } + case XmlNodeType.CDATA: + return CDataName; + case XmlNodeType.Comment: + return CommentName; + case XmlNodeType.Element: + if (node.NamespaceUri == JsonNamespaceUri) + { + return "$" + node.LocalName; + } + else + { + return ResolveFullName(node, manager); + } + case XmlNodeType.ProcessingInstruction: + return "?" + ResolveFullName(node, manager); + case XmlNodeType.DocumentType: + return "!" + ResolveFullName(node, manager); + case XmlNodeType.XmlDeclaration: + return DeclarationName; + case XmlNodeType.SignificantWhitespace: + return SignificantWhitespaceName; + case XmlNodeType.Text: + return TextName; + case XmlNodeType.Whitespace: + return WhitespaceName; + default: + throw new JsonSerializationException("Unexpected XmlNodeType when getting node name: " + node.NodeType); + } + } + + private bool IsArray(IXmlNode node) + { + IXmlNode jsonArrayAttribute = (node.Attributes != null) + ? node.Attributes.SingleOrDefault(a => a.LocalName == "Array" && a.NamespaceUri == JsonNamespaceUri) + : null; + + return (jsonArrayAttribute != null && XmlConvert.ToBoolean(jsonArrayAttribute.Value)); + } + + private void SerializeGroupedNodes(JsonWriter writer, IXmlNode node, XmlNamespaceManager manager, bool writePropertyName) + { + // group nodes together by name + Dictionary> nodesGroupedByName = new Dictionary>(); + + for (int i = 0; i < node.ChildNodes.Count; i++) + { + IXmlNode childNode = node.ChildNodes[i]; + string nodeName = GetPropertyName(childNode, manager); + + List nodes; + if (!nodesGroupedByName.TryGetValue(nodeName, out nodes)) + { + nodes = new List(); + nodesGroupedByName.Add(nodeName, nodes); + } + + nodes.Add(childNode); + } + + // loop through grouped nodes. write single name instances as normal, + // write multiple names together in an array + foreach (KeyValuePair> nodeNameGroup in nodesGroupedByName) + { + List groupedNodes = nodeNameGroup.Value; + bool writeArray; + + if (groupedNodes.Count == 1) + { + writeArray = IsArray(groupedNodes[0]); + } + else + { + writeArray = true; + } + + if (!writeArray) + { + SerializeNode(writer, groupedNodes[0], manager, writePropertyName); + } + else + { + string elementNames = nodeNameGroup.Key; + + if (writePropertyName) + { + writer.WritePropertyName(elementNames); + } + + writer.WriteStartArray(); + + for (int i = 0; i < groupedNodes.Count; i++) + { + SerializeNode(writer, groupedNodes[i], manager, false); + } + + writer.WriteEndArray(); + } + } + } + + private void SerializeNode(JsonWriter writer, IXmlNode node, XmlNamespaceManager manager, bool writePropertyName) + { + switch (node.NodeType) + { + case XmlNodeType.Document: + case XmlNodeType.DocumentFragment: + SerializeGroupedNodes(writer, node, manager, writePropertyName); + break; + case XmlNodeType.Element: + if (IsArray(node) && node.ChildNodes.All(n => n.LocalName == node.LocalName) && node.ChildNodes.Count > 0) + { + SerializeGroupedNodes(writer, node, manager, false); + } + else + { + manager.PushScope(); + + foreach (IXmlNode attribute in node.Attributes) + { + if (attribute.NamespaceUri == "http://www.w3.org/2000/xmlns/") + { + string namespacePrefix = (attribute.LocalName != "xmlns") + ? XmlConvert.DecodeName(attribute.LocalName) + : string.Empty; + string namespaceUri = attribute.Value; + + manager.AddNamespace(namespacePrefix, namespaceUri); + } + } + + if (writePropertyName) + { + writer.WritePropertyName(GetPropertyName(node, manager)); + } + + if (!ValueAttributes(node.Attributes).Any() && node.ChildNodes.Count == 1 + && node.ChildNodes[0].NodeType == XmlNodeType.Text) + { + // write elements with a single text child as a name value pair + writer.WriteValue(node.ChildNodes[0].Value); + } + else if (node.ChildNodes.Count == 0 && CollectionUtils.IsNullOrEmpty(node.Attributes)) + { + IXmlElement element = (IXmlElement)node; + + // empty element + if (element.IsEmpty) + { + writer.WriteNull(); + } + else + { + writer.WriteValue(string.Empty); + } + } + else + { + writer.WriteStartObject(); + + for (int i = 0; i < node.Attributes.Count; i++) + { + SerializeNode(writer, node.Attributes[i], manager, true); + } + + SerializeGroupedNodes(writer, node, manager, true); + + writer.WriteEndObject(); + } + + manager.PopScope(); + } + + break; + case XmlNodeType.Comment: + if (writePropertyName) + { + writer.WriteComment(node.Value); + } + break; + case XmlNodeType.Attribute: + case XmlNodeType.Text: + case XmlNodeType.CDATA: + case XmlNodeType.ProcessingInstruction: + case XmlNodeType.Whitespace: + case XmlNodeType.SignificantWhitespace: + if (node.NamespaceUri == "http://www.w3.org/2000/xmlns/" && node.Value == JsonNamespaceUri) + { + return; + } + + if (node.NamespaceUri == JsonNamespaceUri) + { + if (node.LocalName == "Array") + { + return; + } + } + + if (writePropertyName) + { + writer.WritePropertyName(GetPropertyName(node, manager)); + } + writer.WriteValue(node.Value); + break; + case XmlNodeType.XmlDeclaration: + IXmlDeclaration declaration = (IXmlDeclaration)node; + writer.WritePropertyName(GetPropertyName(node, manager)); + writer.WriteStartObject(); + + if (!string.IsNullOrEmpty(declaration.Version)) + { + writer.WritePropertyName("@version"); + writer.WriteValue(declaration.Version); + } + if (!string.IsNullOrEmpty(declaration.Encoding)) + { + writer.WritePropertyName("@encoding"); + writer.WriteValue(declaration.Encoding); + } + if (!string.IsNullOrEmpty(declaration.Standalone)) + { + writer.WritePropertyName("@standalone"); + writer.WriteValue(declaration.Standalone); + } + + writer.WriteEndObject(); + break; + case XmlNodeType.DocumentType: + IXmlDocumentType documentType = (IXmlDocumentType)node; + writer.WritePropertyName(GetPropertyName(node, manager)); + writer.WriteStartObject(); + + if (!string.IsNullOrEmpty(documentType.Name)) + { + writer.WritePropertyName("@name"); + writer.WriteValue(documentType.Name); + } + if (!string.IsNullOrEmpty(documentType.Public)) + { + writer.WritePropertyName("@public"); + writer.WriteValue(documentType.Public); + } + if (!string.IsNullOrEmpty(documentType.System)) + { + writer.WritePropertyName("@system"); + writer.WriteValue(documentType.System); + } + if (!string.IsNullOrEmpty(documentType.InternalSubset)) + { + writer.WritePropertyName("@internalSubset"); + writer.WriteValue(documentType.InternalSubset); + } + + writer.WriteEndObject(); + break; + default: + throw new JsonSerializationException("Unexpected XmlNodeType when serializing nodes: " + node.NodeType); + } + } + #endregion + + #region Reading + /// + /// Reads the JSON representation of the object. + /// + /// The to read from. + /// Type of the object. + /// The existing value of object being read. + /// The calling serializer. + /// The object value. + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + { + if (reader.TokenType == JsonToken.Null) + { + return null; + } + + XmlNamespaceManager manager = new XmlNamespaceManager(new NameTable()); + IXmlDocument document = null; + IXmlNode rootNode = null; + +#if !NET20 + if (typeof(XObject).IsAssignableFrom(objectType)) + { + if (objectType != typeof(XDocument) && objectType != typeof(XElement)) + { + throw new JsonSerializationException("XmlNodeConverter only supports deserializing XDocument or XElement."); + } + + XDocument d = new XDocument(); + document = new XDocumentWrapper(d); + rootNode = document; + } +#endif +#if !(DOTNET || PORTABLE) + if (typeof(XmlNode).IsAssignableFrom(objectType)) + { + if (objectType != typeof(XmlDocument)) + { + throw new JsonSerializationException("XmlNodeConverter only supports deserializing XmlDocuments"); + } + + XmlDocument d = new XmlDocument(); + // prevent http request when resolving any DTD references + d.XmlResolver = null; + + document = new XmlDocumentWrapper(d); + rootNode = document; + } +#endif + + if (document == null || rootNode == null) + { + throw new JsonSerializationException("Unexpected type when converting XML: " + objectType); + } + + if (reader.TokenType != JsonToken.StartObject) + { + throw new JsonSerializationException("XmlNodeConverter can only convert JSON that begins with an object."); + } + + if (!string.IsNullOrEmpty(DeserializeRootElementName)) + { + //rootNode = document.CreateElement(DeserializeRootElementName); + //document.AppendChild(rootNode); + ReadElement(reader, document, rootNode, DeserializeRootElementName, manager); + } + else + { + reader.Read(); + DeserializeNode(reader, document, manager, rootNode); + } + +#if !NET20 + if (objectType == typeof(XElement)) + { + XElement element = (XElement)document.DocumentElement.WrappedNode; + element.Remove(); + + return element; + } +#endif + + return document.WrappedNode; + } + + private void DeserializeValue(JsonReader reader, IXmlDocument document, XmlNamespaceManager manager, string propertyName, IXmlNode currentNode) + { + switch (propertyName) + { + case TextName: + currentNode.AppendChild(document.CreateTextNode(reader.Value.ToString())); + break; + case CDataName: + currentNode.AppendChild(document.CreateCDataSection(reader.Value.ToString())); + break; + case WhitespaceName: + currentNode.AppendChild(document.CreateWhitespace(reader.Value.ToString())); + break; + case SignificantWhitespaceName: + currentNode.AppendChild(document.CreateSignificantWhitespace(reader.Value.ToString())); + break; + default: + // processing instructions and the xml declaration start with ? + if (!string.IsNullOrEmpty(propertyName) && propertyName[0] == '?') + { + CreateInstruction(reader, document, currentNode, propertyName); + } + else if (string.Equals(propertyName, "!DOCTYPE", StringComparison.OrdinalIgnoreCase)) + { + CreateDocumentType(reader, document, currentNode); + } + else + { + if (reader.TokenType == JsonToken.StartArray) + { + // handle nested arrays + ReadArrayElements(reader, document, propertyName, currentNode, manager); + return; + } + + // have to wait until attributes have been parsed before creating element + // attributes may contain namespace info used by the element + ReadElement(reader, document, currentNode, propertyName, manager); + } + break; + } + } + + private void ReadElement(JsonReader reader, IXmlDocument document, IXmlNode currentNode, string propertyName, XmlNamespaceManager manager) + { + if (string.IsNullOrEmpty(propertyName)) + { + throw JsonSerializationException.Create(reader, "XmlNodeConverter cannot convert JSON with an empty property name to XML."); + } + + Dictionary attributeNameValues = ReadAttributeElements(reader, manager); + + string elementPrefix = MiscellaneousUtils.GetPrefix(propertyName); + + if (propertyName.StartsWith('@')) + { + string attributeName = propertyName.Substring(1); + string attributePrefix = MiscellaneousUtils.GetPrefix(attributeName); + + AddAttribute(reader, document, currentNode, attributeName, manager, attributePrefix); + } + else if (propertyName.StartsWith('$')) + { + if (propertyName == JsonTypeReflector.ArrayValuesPropertyName) + { + propertyName = propertyName.Substring(1); + elementPrefix = manager.LookupPrefix(JsonNamespaceUri); + CreateElement(reader, document, currentNode, propertyName, manager, elementPrefix, attributeNameValues); + } + else + { + string attributeName = propertyName.Substring(1); + string attributePrefix = manager.LookupPrefix(JsonNamespaceUri); + AddAttribute(reader, document, currentNode, attributeName, manager, attributePrefix); + } + } + else + { + CreateElement(reader, document, currentNode, propertyName, manager, elementPrefix, attributeNameValues); + } + } + + private void CreateElement(JsonReader reader, IXmlDocument document, IXmlNode currentNode, string elementName, XmlNamespaceManager manager, string elementPrefix, Dictionary attributeNameValues) + { + IXmlElement element = CreateElement(elementName, document, elementPrefix, manager); + + currentNode.AppendChild(element); + + // add attributes to newly created element + foreach (KeyValuePair nameValue in attributeNameValues) + { + string encodedName = XmlConvert.EncodeName(nameValue.Key); + string attributePrefix = MiscellaneousUtils.GetPrefix(nameValue.Key); + + IXmlNode attribute = (!string.IsNullOrEmpty(attributePrefix)) + ? document.CreateAttribute(encodedName, manager.LookupNamespace(attributePrefix) ?? string.Empty, nameValue.Value) + : document.CreateAttribute(encodedName, nameValue.Value); + + element.SetAttributeNode(attribute); + } + + if (reader.TokenType == JsonToken.String + || reader.TokenType == JsonToken.Integer + || reader.TokenType == JsonToken.Float + || reader.TokenType == JsonToken.Boolean + || reader.TokenType == JsonToken.Date) + { + string text = ConvertTokenToXmlValue(reader); + if (text != null) + { + element.AppendChild(document.CreateTextNode(text)); + } + } + else if (reader.TokenType == JsonToken.Null) + { + // empty element. do nothing + } + else + { + // finished element will have no children to deserialize + if (reader.TokenType != JsonToken.EndObject) + { + manager.PushScope(); + DeserializeNode(reader, document, manager, element); + manager.PopScope(); + } + + manager.RemoveNamespace(string.Empty, manager.DefaultNamespace); + } + } + + private static void AddAttribute(JsonReader reader, IXmlDocument document, IXmlNode currentNode, string attributeName, XmlNamespaceManager manager, string attributePrefix) + { + string encodedName = XmlConvert.EncodeName(attributeName); + string attributeValue = reader.Value.ToString(); + + IXmlNode attribute = (!string.IsNullOrEmpty(attributePrefix)) + ? document.CreateAttribute(encodedName, manager.LookupNamespace(attributePrefix), attributeValue) + : document.CreateAttribute(encodedName, attributeValue); + + ((IXmlElement)currentNode).SetAttributeNode(attribute); + } + + private string ConvertTokenToXmlValue(JsonReader reader) + { + if (reader.TokenType == JsonToken.String) + { + return (reader.Value != null) ? reader.Value.ToString() : null; + } + else if (reader.TokenType == JsonToken.Integer) + { +#if !(NET20 || NET35 || PORTABLE || PORTABLE40) + if (reader.Value is BigInteger) + { + return ((BigInteger)reader.Value).ToString(CultureInfo.InvariantCulture); + } +#endif + + return XmlConvert.ToString(Convert.ToInt64(reader.Value, CultureInfo.InvariantCulture)); + } + else if (reader.TokenType == JsonToken.Float) + { + if (reader.Value is decimal) + { + return XmlConvert.ToString((decimal)reader.Value); + } + if (reader.Value is float) + { + return XmlConvert.ToString((float)reader.Value); + } + + return XmlConvert.ToString(Convert.ToDouble(reader.Value, CultureInfo.InvariantCulture)); + } + else if (reader.TokenType == JsonToken.Boolean) + { + return XmlConvert.ToString(Convert.ToBoolean(reader.Value, CultureInfo.InvariantCulture)); + } + else if (reader.TokenType == JsonToken.Date) + { +#if !NET20 + if (reader.Value is DateTimeOffset) + { + return XmlConvert.ToString((DateTimeOffset)reader.Value); + } +#endif + + DateTime d = Convert.ToDateTime(reader.Value, CultureInfo.InvariantCulture); +#if !PORTABLE + return XmlConvert.ToString(d, DateTimeUtils.ToSerializationMode(d.Kind)); +#else + return XmlConvert.ToString(d); +#endif + } + else if (reader.TokenType == JsonToken.Null) + { + return null; + } + else + { + throw JsonSerializationException.Create(reader, "Cannot get an XML string value from token type '{0}'.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); + } + } + + private void ReadArrayElements(JsonReader reader, IXmlDocument document, string propertyName, IXmlNode currentNode, XmlNamespaceManager manager) + { + string elementPrefix = MiscellaneousUtils.GetPrefix(propertyName); + + IXmlElement nestedArrayElement = CreateElement(propertyName, document, elementPrefix, manager); + + currentNode.AppendChild(nestedArrayElement); + + int count = 0; + while (reader.Read() && reader.TokenType != JsonToken.EndArray) + { + DeserializeValue(reader, document, manager, propertyName, nestedArrayElement); + count++; + } + + if (WriteArrayAttribute) + { + AddJsonArrayAttribute(nestedArrayElement, document); + } + + if (count == 1 && WriteArrayAttribute) + { + IXmlElement arrayElement = nestedArrayElement.ChildNodes.OfType().Single(n => n.LocalName == propertyName); + AddJsonArrayAttribute(arrayElement, document); + } + } + + private void AddJsonArrayAttribute(IXmlElement element, IXmlDocument document) + { + element.SetAttributeNode(document.CreateAttribute("json:Array", JsonNamespaceUri, "true")); + +#if !NET20 + // linq to xml doesn't automatically include prefixes via the namespace manager + if (element is XElementWrapper) + { + if (element.GetPrefixOfNamespace(JsonNamespaceUri) == null) + { + element.SetAttributeNode(document.CreateAttribute("xmlns:json", "http://www.w3.org/2000/xmlns/", JsonNamespaceUri)); + } + } +#endif + } + + private Dictionary ReadAttributeElements(JsonReader reader, XmlNamespaceManager manager) + { + Dictionary attributeNameValues = new Dictionary(); + bool finishedAttributes = false; + bool finishedElement = false; + + // a string token means the element only has a single text child + if (reader.TokenType != JsonToken.String + && reader.TokenType != JsonToken.Null + && reader.TokenType != JsonToken.Boolean + && reader.TokenType != JsonToken.Integer + && reader.TokenType != JsonToken.Float + && reader.TokenType != JsonToken.Date + && reader.TokenType != JsonToken.StartConstructor) + { + // read properties until first non-attribute is encountered + while (!finishedAttributes && !finishedElement && reader.Read()) + { + switch (reader.TokenType) + { + case JsonToken.PropertyName: + string attributeName = reader.Value.ToString(); + + if (!string.IsNullOrEmpty(attributeName)) + { + char firstChar = attributeName[0]; + string attributeValue; + + switch (firstChar) + { + case '@': + attributeName = attributeName.Substring(1); + reader.Read(); + attributeValue = ConvertTokenToXmlValue(reader); + attributeNameValues.Add(attributeName, attributeValue); + + string namespacePrefix; + if (IsNamespaceAttribute(attributeName, out namespacePrefix)) + { + manager.AddNamespace(namespacePrefix, attributeValue); + } + break; + case '$': + // check that JsonNamespaceUri is in scope + // if it isn't then add it to document and namespace manager + string jsonPrefix = manager.LookupPrefix(JsonNamespaceUri); + if (jsonPrefix == null) + { + // ensure that the prefix used is free + int? i = null; + while (manager.LookupNamespace("json" + i) != null) + { + i = i.GetValueOrDefault() + 1; + } + jsonPrefix = "json" + i; + + attributeNameValues.Add("xmlns:" + jsonPrefix, JsonNamespaceUri); + manager.AddNamespace(jsonPrefix, JsonNamespaceUri); + } + + // special case $values, it will have a non-primitive value + if (attributeName == JsonTypeReflector.ArrayValuesPropertyName) + { + finishedAttributes = true; + break; + } + + attributeName = attributeName.Substring(1); + reader.Read(); + + if (!JsonTokenUtils.IsPrimitiveToken(reader.TokenType)) + { + throw JsonSerializationException.Create(reader, "Unexpected JsonToken: " + reader.TokenType); + } + + attributeValue = (reader.Value != null) ? reader.Value.ToString() : null; + attributeNameValues.Add(jsonPrefix + ":" + attributeName, attributeValue); + break; + default: + finishedAttributes = true; + break; + } + } + else + { + finishedAttributes = true; + } + + break; + case JsonToken.EndObject: + finishedElement = true; + break; + case JsonToken.Comment: + finishedElement = true; + break; + default: + throw JsonSerializationException.Create(reader, "Unexpected JsonToken: " + reader.TokenType); + } + } + } + + return attributeNameValues; + } + + private void CreateInstruction(JsonReader reader, IXmlDocument document, IXmlNode currentNode, string propertyName) + { + if (propertyName == DeclarationName) + { + string version = null; + string encoding = null; + string standalone = null; + while (reader.Read() && reader.TokenType != JsonToken.EndObject) + { + switch (reader.Value.ToString()) + { + case "@version": + reader.Read(); + version = reader.Value.ToString(); + break; + case "@encoding": + reader.Read(); + encoding = reader.Value.ToString(); + break; + case "@standalone": + reader.Read(); + standalone = reader.Value.ToString(); + break; + default: + throw JsonSerializationException.Create(reader, "Unexpected property name encountered while deserializing XmlDeclaration: " + reader.Value); + } + } + + IXmlNode declaration = document.CreateXmlDeclaration(version, encoding, standalone); + currentNode.AppendChild(declaration); + } + else + { + IXmlNode instruction = document.CreateProcessingInstruction(propertyName.Substring(1), reader.Value.ToString()); + currentNode.AppendChild(instruction); + } + } + + private void CreateDocumentType(JsonReader reader, IXmlDocument document, IXmlNode currentNode) + { + string name = null; + string publicId = null; + string systemId = null; + string internalSubset = null; + while (reader.Read() && reader.TokenType != JsonToken.EndObject) + { + switch (reader.Value.ToString()) + { + case "@name": + reader.Read(); + name = reader.Value.ToString(); + break; + case "@public": + reader.Read(); + publicId = reader.Value.ToString(); + break; + case "@system": + reader.Read(); + systemId = reader.Value.ToString(); + break; + case "@internalSubset": + reader.Read(); + internalSubset = reader.Value.ToString(); + break; + default: + throw JsonSerializationException.Create(reader, "Unexpected property name encountered while deserializing XmlDeclaration: " + reader.Value); + } + } + + IXmlNode documentType = document.CreateXmlDocumentType(name, publicId, systemId, internalSubset); + currentNode.AppendChild(documentType); + } + + private IXmlElement CreateElement(string elementName, IXmlDocument document, string elementPrefix, XmlNamespaceManager manager) + { + string encodeName = XmlConvert.EncodeName(elementName); + string ns = string.IsNullOrEmpty(elementPrefix) ? manager.DefaultNamespace : manager.LookupNamespace(elementPrefix); + + IXmlElement element = (!string.IsNullOrEmpty(ns)) ? document.CreateElement(encodeName, ns) : document.CreateElement(encodeName); + + return element; + } + + private void DeserializeNode(JsonReader reader, IXmlDocument document, XmlNamespaceManager manager, IXmlNode currentNode) + { + do + { + switch (reader.TokenType) + { + case JsonToken.PropertyName: + if (currentNode.NodeType == XmlNodeType.Document && document.DocumentElement != null) + { + throw JsonSerializationException.Create(reader, "JSON root object has multiple properties. The root object must have a single property in order to create a valid XML document. Consider specifing a DeserializeRootElementName."); + } + + string propertyName = reader.Value.ToString(); + reader.Read(); + + if (reader.TokenType == JsonToken.StartArray) + { + int count = 0; + while (reader.Read() && reader.TokenType != JsonToken.EndArray) + { + DeserializeValue(reader, document, manager, propertyName, currentNode); + count++; + } + + if (count == 1 && WriteArrayAttribute) + { + IXmlElement arrayElement = currentNode.ChildNodes.OfType().Single(n => n.LocalName == propertyName); + AddJsonArrayAttribute(arrayElement, document); + } + } + else + { + DeserializeValue(reader, document, manager, propertyName, currentNode); + } + break; + case JsonToken.StartConstructor: + string constructorName = reader.Value.ToString(); + + while (reader.Read() && reader.TokenType != JsonToken.EndConstructor) + { + DeserializeValue(reader, document, manager, constructorName, currentNode); + } + break; + case JsonToken.Comment: + currentNode.AppendChild(document.CreateComment((string)reader.Value)); + break; + case JsonToken.EndObject: + case JsonToken.EndArray: + return; + default: + throw JsonSerializationException.Create(reader, "Unexpected JsonToken when deserializing node: " + reader.TokenType); + } + } while (reader.TokenType == JsonToken.PropertyName || reader.Read()); + // don't read if current token is a property. token was already read when parsing element attributes + } + + /// + /// Checks if the attributeName is a namespace attribute. + /// + /// Attribute name to test. + /// The attribute name prefix if it has one, otherwise an empty string. + /// True if attribute name is for a namespace attribute, otherwise false. + private bool IsNamespaceAttribute(string attributeName, out string prefix) + { + if (attributeName.StartsWith("xmlns", StringComparison.Ordinal)) + { + if (attributeName.Length == 5) + { + prefix = string.Empty; + return true; + } + else if (attributeName[5] == ':') + { + prefix = attributeName.Substring(6, attributeName.Length - 6); + return true; + } + } + prefix = null; + return false; + } + + private IEnumerable ValueAttributes(IEnumerable c) + { + return c.Where(a => a.NamespaceUri != JsonNamespaceUri); + } + #endregion + + /// + /// Determines whether this instance can convert the specified value type. + /// + /// Type of the value. + /// + /// true if this instance can convert the specified value type; otherwise, false. + /// + public override bool CanConvert(Type valueType) + { +#if !NET20 + if (typeof(XObject).IsAssignableFrom(valueType)) + { + return true; + } +#endif +#if !(DOTNET || PORTABLE) + if (typeof(XmlNode).IsAssignableFrom(valueType)) + { + return true; + } +#endif + + return false; + } + } +} + +#endif \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/DateFormatHandling.cs b/Common/00-1Json8.3/Json8.3/DateFormatHandling.cs new file mode 100644 index 0000000..e26feec --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/DateFormatHandling.cs @@ -0,0 +1,43 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +namespace Newtonsoft.Json +{ + /// + /// Specifies how dates are formatted when writing JSON text. + /// + public enum DateFormatHandling + { + /// + /// Dates are written in the ISO 8601 format, e.g. "2012-03-21T05:40Z". + /// + IsoDateFormat, + + /// + /// Dates are written in the Microsoft JSON format, e.g. "\/Date(1198908717056)\/". + /// + MicrosoftDateFormat + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/DateParseHandling.cs b/Common/00-1Json8.3/Json8.3/DateParseHandling.cs new file mode 100644 index 0000000..359ac35 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/DateParseHandling.cs @@ -0,0 +1,49 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +namespace Newtonsoft.Json +{ + /// + /// Specifies how date formatted strings, e.g. "\/Date(1198908717056)\/" and "2012-03-21T05:40Z", are parsed when reading JSON text. + /// + public enum DateParseHandling + { + /// + /// Date formatted strings are not parsed to a date type and are read as strings. + /// + None = 0, + + /// + /// Date formatted strings, e.g. "\/Date(1198908717056)\/" and "2012-03-21T05:40Z", are parsed to . + /// + DateTime = 1, +#if !NET20 + /// + /// Date formatted strings, e.g. "\/Date(1198908717056)\/" and "2012-03-21T05:40Z", are parsed to . + /// + DateTimeOffset = 2 +#endif + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/DateTimeZoneHandling.cs b/Common/00-1Json8.3/Json8.3/DateTimeZoneHandling.cs new file mode 100644 index 0000000..9877d6e --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/DateTimeZoneHandling.cs @@ -0,0 +1,56 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; + +namespace Newtonsoft.Json +{ + /// + /// Specifies how to treat the time value when converting between string and . + /// + public enum DateTimeZoneHandling + { + /// + /// Treat as local time. If the object represents a Coordinated Universal Time (UTC), it is converted to the local time. + /// + Local = 0, + + /// + /// Treat as a UTC. If the object represents a local time, it is converted to a UTC. + /// + Utc = 1, + + /// + /// Treat as a local time if a is being converted to a string. + /// If a string is being converted to , convert to a local time if a time zone is specified. + /// + Unspecified = 2, + + /// + /// Time zone information should be preserved when converting. + /// + RoundtripKind = 3 + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/DefaultValueHandling.cs b/Common/00-1Json8.3/Json8.3/DefaultValueHandling.cs new file mode 100644 index 0000000..a63adf9 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/DefaultValueHandling.cs @@ -0,0 +1,67 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.ComponentModel; + +namespace Newtonsoft.Json +{ + /// + /// Specifies default value handling options for the . + /// + /// + /// + /// + /// + [Flags] + public enum DefaultValueHandling + { + /// + /// Include members where the member value is the same as the member's default value when serializing objects. + /// Included members are written to JSON. Has no effect when deserializing. + /// + Include = 0, + + /// + /// Ignore members where the member value is the same as the member's default value when serializing objects + /// so that is is not written to JSON. + /// This option will ignore all default values (e.g. null for objects and nullable types; 0 for integers, + /// decimals and floating point numbers; and false for booleans). The default value ignored can be changed by + /// placing the on the property. + /// + Ignore = 1, + + /// + /// Members with a default value but no JSON will be set to their default value when deserializing. + /// + Populate = 2, + + /// + /// Ignore members where the member value is the same as the member's default value when serializing objects + /// and sets members to their default value when deserializing. + /// + IgnoreAndPopulate = Ignore | Populate + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/FloatFormatHandling.cs b/Common/00-1Json8.3/Json8.3/FloatFormatHandling.cs new file mode 100644 index 0000000..1c7f424 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/FloatFormatHandling.cs @@ -0,0 +1,50 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +namespace Newtonsoft.Json +{ + /// + /// Specifies float format handling options when writing special floating point numbers, e.g. , + /// and with . + /// + public enum FloatFormatHandling + { + /// + /// Write special floating point values as strings in JSON, e.g. "NaN", "Infinity", "-Infinity". + /// + String = 0, + + /// + /// Write special floating point values as symbols in JSON, e.g. NaN, Infinity, -Infinity. + /// Note that this will produce non-valid JSON. + /// + Symbol = 1, + + /// + /// Write special floating point values as the property's default value in JSON, e.g. 0.0 for a property, null for a property. + /// + DefaultValue = 2 + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/FloatParseHandling.cs b/Common/00-1Json8.3/Json8.3/FloatParseHandling.cs new file mode 100644 index 0000000..3058394 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/FloatParseHandling.cs @@ -0,0 +1,43 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +namespace Newtonsoft.Json +{ + /// + /// Specifies how floating point numbers, e.g. 1.0 and 9.9, are parsed when reading JSON text. + /// + public enum FloatParseHandling + { + /// + /// Floating point numbers are parsed to . + /// + Double = 0, + + /// + /// Floating point numbers are parsed to . + /// + Decimal = 1 + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Formatting.cs b/Common/00-1Json8.3/Json8.3/Formatting.cs new file mode 100644 index 0000000..9438e63 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Formatting.cs @@ -0,0 +1,43 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +namespace Newtonsoft.Json +{ + /// + /// Specifies formatting options for the . + /// + public enum Formatting + { + /// + /// No special formatting is applied. This is the default. + /// + None = 0, + + /// + /// Causes child objects to be indented according to the and settings. + /// + Indented = 1 + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/IArrayPool.cs b/Common/00-1Json8.3/Json8.3/IArrayPool.cs new file mode 100644 index 0000000..3d5037e --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/IArrayPool.cs @@ -0,0 +1,22 @@ +namespace Newtonsoft.Json +{ + /// + /// Provides an interface for using pooled arrays. + /// + /// The array type content. + public interface IArrayPool + { + /// + /// Rent a array from the pool. This array must be returned when it is no longer needed. + /// + /// The minimum required length of the array. The returned array may be longer. + /// The rented array from the pool. This array must be returned when it is no longer needed. + T[] Rent(int minimumLength); + + /// + /// Return an array to the pool. + /// + /// The array that is being returned. + void Return(T[] array); + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/IJsonLineInfo.cs b/Common/00-1Json8.3/Json8.3/IJsonLineInfo.cs new file mode 100644 index 0000000..b71aedf --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/IJsonLineInfo.cs @@ -0,0 +1,53 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +namespace Newtonsoft.Json +{ + /// + /// Provides an interface to enable a class to return line and position information. + /// + public interface IJsonLineInfo + { + /// + /// Gets a value indicating whether the class can return line information. + /// + /// + /// true if LineNumber and LinePosition can be provided; otherwise, false. + /// + bool HasLineInfo(); + + /// + /// Gets the current line number. + /// + /// The current line number or 0 if no line information is available (for example, HasLineInfo returns false). + int LineNumber { get; } + + /// + /// Gets the current line position. + /// + /// The current line position or 0 if no line information is available (for example, HasLineInfo returns false). + int LinePosition { get; } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/JsonArrayAttribute.cs b/Common/00-1Json8.3/Json8.3/JsonArrayAttribute.cs new file mode 100644 index 0000000..bbfc90d --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/JsonArrayAttribute.cs @@ -0,0 +1,73 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; + +namespace Newtonsoft.Json +{ + /// + /// Instructs the how to serialize the collection. + /// + [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false)] + public sealed class JsonArrayAttribute : JsonContainerAttribute + { + private bool _allowNullItems; + + /// + /// Gets or sets a value indicating whether null items are allowed in the collection. + /// + /// true if null items are allowed in the collection; otherwise, false. + public bool AllowNullItems + { + get { return _allowNullItems; } + set { _allowNullItems = value; } + } + + /// + /// Initializes a new instance of the class. + /// + public JsonArrayAttribute() + { + } + + /// + /// Initializes a new instance of the class with a flag indicating whether the array can contain null items + /// + /// A flag indicating whether the array can contain null items. + public JsonArrayAttribute(bool allowNullItems) + { + _allowNullItems = allowNullItems; + } + + /// + /// Initializes a new instance of the class with the specified container Id. + /// + /// The container Id. + public JsonArrayAttribute(string id) + : base(id) + { + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/JsonConstructorAttribute.cs b/Common/00-1Json8.3/Json8.3/JsonConstructorAttribute.cs new file mode 100644 index 0000000..cd5d1bb --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/JsonConstructorAttribute.cs @@ -0,0 +1,37 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; + +namespace Newtonsoft.Json +{ + /// + /// Instructs the to use the specified constructor when deserializing that object. + /// + [AttributeUsage(AttributeTargets.Constructor, AllowMultiple = false)] + public sealed class JsonConstructorAttribute : Attribute + { + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/JsonContainerAttribute.cs b/Common/00-1Json8.3/Json8.3/JsonContainerAttribute.cs new file mode 100644 index 0000000..cfc1b58 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/JsonContainerAttribute.cs @@ -0,0 +1,138 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; + +namespace Newtonsoft.Json +{ + /// + /// Instructs the how to serialize the object. + /// + [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false)] + public abstract class JsonContainerAttribute : Attribute + { + /// + /// Gets or sets the id. + /// + /// The id. + public string Id { get; set; } + + /// + /// Gets or sets the title. + /// + /// The title. + public string Title { get; set; } + + /// + /// Gets or sets the description. + /// + /// The description. + public string Description { get; set; } + + /// + /// Gets the collection's items converter. + /// + /// The collection's items converter. + public Type ItemConverterType { get; set; } + + /// + /// The parameter list to use when constructing the JsonConverter described by ItemConverterType. + /// If null, the default constructor is used. + /// When non-null, there must be a constructor defined in the JsonConverter that exactly matches the number, + /// order, and type of these parameters. + /// + /// + /// [JsonContainer(ItemConverterType = typeof(MyContainerConverter), ItemConverterParameters = new object[] { 123, "Four" })] + /// + public object[] ItemConverterParameters { get; set; } + + // yuck. can't set nullable properties on an attribute in C# + // have to use this approach to get an unset default state + internal bool? _isReference; + internal bool? _itemIsReference; + internal ReferenceLoopHandling? _itemReferenceLoopHandling; + internal TypeNameHandling? _itemTypeNameHandling; + + /// + /// Gets or sets a value that indicates whether to preserve object references. + /// + /// + /// true to keep object reference; otherwise, false. The default is false. + /// + public bool IsReference + { + get { return _isReference ?? default(bool); } + set { _isReference = value; } + } + + /// + /// Gets or sets a value that indicates whether to preserve collection's items references. + /// + /// + /// true to keep collection's items object references; otherwise, false. The default is false. + /// + public bool ItemIsReference + { + get { return _itemIsReference ?? default(bool); } + set { _itemIsReference = value; } + } + + /// + /// Gets or sets the reference loop handling used when serializing the collection's items. + /// + /// The reference loop handling. + public ReferenceLoopHandling ItemReferenceLoopHandling + { + get { return _itemReferenceLoopHandling ?? default(ReferenceLoopHandling); } + set { _itemReferenceLoopHandling = value; } + } + + /// + /// Gets or sets the type name handling used when serializing the collection's items. + /// + /// The type name handling. + public TypeNameHandling ItemTypeNameHandling + { + get { return _itemTypeNameHandling ?? default(TypeNameHandling); } + set { _itemTypeNameHandling = value; } + } + + /// + /// Initializes a new instance of the class. + /// + protected JsonContainerAttribute() + { + } + + /// + /// Initializes a new instance of the class with the specified container Id. + /// + /// The container Id. + protected JsonContainerAttribute(string id) + { + Id = id; + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/JsonConvert.cs b/Common/00-1Json8.3/Json8.3/JsonConvert.cs new file mode 100644 index 0000000..e1021b4 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/JsonConvert.cs @@ -0,0 +1,1153 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.IO; +using System.Globalization; +#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) +using System.Numerics; +#endif +#if !(NET20 || NET35 || PORTABLE40) +using System.Threading.Tasks; +#endif +using Newtonsoft.Json.Linq; +using Newtonsoft.Json.Utilities; +using System.Xml; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Serialization; +using System.Text; +#if !(NET20 || PORTABLE40) +using System.Xml.Linq; + +#endif + +namespace Newtonsoft.Json +{ + /// + /// Provides methods for converting between common language runtime types and JSON types. + /// + /// + /// + /// + public static class JsonConvert + { + /// + /// Gets or sets a function that creates default . + /// Default settings are automatically used by serialization methods on , + /// and and on . + /// To serialize without using any default settings create a with + /// . + /// + public static Func DefaultSettings { get; set; } + + /// + /// Represents JavaScript's boolean value true as a string. This field is read-only. + /// + public static readonly string True = "true"; + + /// + /// Represents JavaScript's boolean value false as a string. This field is read-only. + /// + public static readonly string False = "false"; + + /// + /// Represents JavaScript's null as a string. This field is read-only. + /// + public static readonly string Null = "null"; + + /// + /// Represents JavaScript's undefined as a string. This field is read-only. + /// + public static readonly string Undefined = "undefined"; + + /// + /// Represents JavaScript's positive infinity as a string. This field is read-only. + /// + public static readonly string PositiveInfinity = "Infinity"; + + /// + /// Represents JavaScript's negative infinity as a string. This field is read-only. + /// + public static readonly string NegativeInfinity = "-Infinity"; + + /// + /// Represents JavaScript's NaN as a string. This field is read-only. + /// + public static readonly string NaN = "NaN"; + + /// + /// Converts the to its JSON string representation. + /// + /// The value to convert. + /// A JSON string representation of the . + public static string ToString(DateTime value) + { + return ToString(value, DateFormatHandling.IsoDateFormat, DateTimeZoneHandling.RoundtripKind); + } + + /// + /// Converts the to its JSON string representation using the specified. + /// + /// The value to convert. + /// The format the date will be converted to. + /// The time zone handling when the date is converted to a string. + /// A JSON string representation of the . + public static string ToString(DateTime value, DateFormatHandling format, DateTimeZoneHandling timeZoneHandling) + { + DateTime updatedDateTime = DateTimeUtils.EnsureDateTime(value, timeZoneHandling); + + using (StringWriter writer = StringUtils.CreateStringWriter(64)) + { + writer.Write('"'); + DateTimeUtils.WriteDateTimeString(writer, updatedDateTime, format, null, CultureInfo.InvariantCulture); + writer.Write('"'); + return writer.ToString(); + } + } + +#if !NET20 + /// + /// Converts the to its JSON string representation. + /// + /// The value to convert. + /// A JSON string representation of the . + public static string ToString(DateTimeOffset value) + { + return ToString(value, DateFormatHandling.IsoDateFormat); + } + + /// + /// Converts the to its JSON string representation using the specified. + /// + /// The value to convert. + /// The format the date will be converted to. + /// A JSON string representation of the . + public static string ToString(DateTimeOffset value, DateFormatHandling format) + { + using (StringWriter writer = StringUtils.CreateStringWriter(64)) + { + writer.Write('"'); + DateTimeUtils.WriteDateTimeOffsetString(writer, value, format, null, CultureInfo.InvariantCulture); + writer.Write('"'); + return writer.ToString(); + } + } +#endif + + /// + /// Converts the to its JSON string representation. + /// + /// The value to convert. + /// A JSON string representation of the . + public static string ToString(bool value) + { + return (value) ? True : False; + } + + /// + /// Converts the to its JSON string representation. + /// + /// The value to convert. + /// A JSON string representation of the . + public static string ToString(char value) + { + return ToString(char.ToString(value)); + } + + /// + /// Converts the to its JSON string representation. + /// + /// The value to convert. + /// A JSON string representation of the . + public static string ToString(Enum value) + { + return value.ToString("D"); + } + + /// + /// Converts the to its JSON string representation. + /// + /// The value to convert. + /// A JSON string representation of the . + public static string ToString(int value) + { + return value.ToString(null, CultureInfo.InvariantCulture); + } + + /// + /// Converts the to its JSON string representation. + /// + /// The value to convert. + /// A JSON string representation of the . + public static string ToString(short value) + { + return value.ToString(null, CultureInfo.InvariantCulture); + } + + /// + /// Converts the to its JSON string representation. + /// + /// The value to convert. + /// A JSON string representation of the . + [CLSCompliant(false)] + public static string ToString(ushort value) + { + return value.ToString(null, CultureInfo.InvariantCulture); + } + + /// + /// Converts the to its JSON string representation. + /// + /// The value to convert. + /// A JSON string representation of the . + [CLSCompliant(false)] + public static string ToString(uint value) + { + return value.ToString(null, CultureInfo.InvariantCulture); + } + + /// + /// Converts the to its JSON string representation. + /// + /// The value to convert. + /// A JSON string representation of the . + public static string ToString(long value) + { + return value.ToString(null, CultureInfo.InvariantCulture); + } + +#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) + private static string ToStringInternal(BigInteger value) + { + return value.ToString(null, CultureInfo.InvariantCulture); + } +#endif + + /// + /// Converts the to its JSON string representation. + /// + /// The value to convert. + /// A JSON string representation of the . + [CLSCompliant(false)] + public static string ToString(ulong value) + { + return value.ToString(null, CultureInfo.InvariantCulture); + } + + /// + /// Converts the to its JSON string representation. + /// + /// The value to convert. + /// A JSON string representation of the . + public static string ToString(float value) + { + return EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture)); + } + + internal static string ToString(float value, FloatFormatHandling floatFormatHandling, char quoteChar, bool nullable) + { + return EnsureFloatFormat(value, EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture)), floatFormatHandling, quoteChar, nullable); + } + + private static string EnsureFloatFormat(double value, string text, FloatFormatHandling floatFormatHandling, char quoteChar, bool nullable) + { + if (floatFormatHandling == FloatFormatHandling.Symbol || !(double.IsInfinity(value) || double.IsNaN(value))) + { + return text; + } + + if (floatFormatHandling == FloatFormatHandling.DefaultValue) + { + return (!nullable) ? "0.0" : Null; + } + + return quoteChar + text + quoteChar; + } + + /// + /// Converts the to its JSON string representation. + /// + /// The value to convert. + /// A JSON string representation of the . + public static string ToString(double value) + { + return EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture)); + } + + internal static string ToString(double value, FloatFormatHandling floatFormatHandling, char quoteChar, bool nullable) + { + return EnsureFloatFormat(value, EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture)), floatFormatHandling, quoteChar, nullable); + } + + private static string EnsureDecimalPlace(double value, string text) + { + if (double.IsNaN(value) || double.IsInfinity(value) || text.IndexOf('.') != -1 || text.IndexOf('E') != -1 || text.IndexOf('e') != -1) + { + return text; + } + + return text + ".0"; + } + + private static string EnsureDecimalPlace(string text) + { + if (text.IndexOf('.') != -1) + { + return text; + } + + return text + ".0"; + } + + /// + /// Converts the to its JSON string representation. + /// + /// The value to convert. + /// A JSON string representation of the . + public static string ToString(byte value) + { + return value.ToString(null, CultureInfo.InvariantCulture); + } + + /// + /// Converts the to its JSON string representation. + /// + /// The value to convert. + /// A JSON string representation of the . + [CLSCompliant(false)] + public static string ToString(sbyte value) + { + return value.ToString(null, CultureInfo.InvariantCulture); + } + + /// + /// Converts the to its JSON string representation. + /// + /// The value to convert. + /// A JSON string representation of the . + public static string ToString(decimal value) + { + return EnsureDecimalPlace(value.ToString(null, CultureInfo.InvariantCulture)); + } + + /// + /// Converts the to its JSON string representation. + /// + /// The value to convert. + /// A JSON string representation of the . + public static string ToString(Guid value) + { + return ToString(value, '"'); + } + + internal static string ToString(Guid value, char quoteChar) + { + string text; + string qc; +#if !(DOTNET || PORTABLE40 || PORTABLE) + text = value.ToString("D", CultureInfo.InvariantCulture); + qc = quoteChar.ToString(CultureInfo.InvariantCulture); +#else + text = value.ToString("D"); + qc = quoteChar.ToString(); +#endif + + return qc + text + qc; + } + + /// + /// Converts the to its JSON string representation. + /// + /// The value to convert. + /// A JSON string representation of the . + public static string ToString(TimeSpan value) + { + return ToString(value, '"'); + } + + internal static string ToString(TimeSpan value, char quoteChar) + { + return ToString(value.ToString(), quoteChar); + } + + /// + /// Converts the to its JSON string representation. + /// + /// The value to convert. + /// A JSON string representation of the . + public static string ToString(Uri value) + { + if (value == null) + { + return Null; + } + + return ToString(value, '"'); + } + + internal static string ToString(Uri value, char quoteChar) + { + return ToString(value.OriginalString, quoteChar); + } + + /// + /// Converts the to its JSON string representation. + /// + /// The value to convert. + /// A JSON string representation of the . + public static string ToString(string value) + { + return ToString(value, '"'); + } + + /// + /// Converts the to its JSON string representation. + /// + /// The value to convert. + /// The string delimiter character. + /// A JSON string representation of the . + public static string ToString(string value, char delimiter) + { + return ToString(value, delimiter, StringEscapeHandling.Default); + } + + /// + /// Converts the to its JSON string representation. + /// + /// The value to convert. + /// The string delimiter character. + /// The string escape handling. + /// A JSON string representation of the . + public static string ToString(string value, char delimiter, StringEscapeHandling stringEscapeHandling) + { + if (delimiter != '"' && delimiter != '\'') + { + throw new ArgumentException("Delimiter must be a single or double quote.", nameof(delimiter)); + } + + return JavaScriptUtils.ToEscapedJavaScriptString(value, delimiter, true, stringEscapeHandling); + } + + /// + /// Converts the to its JSON string representation. + /// + /// The value to convert. + /// A JSON string representation of the . + public static string ToString(object value) + { + if (value == null) + { + return Null; + } + + PrimitiveTypeCode typeCode = ConvertUtils.GetTypeCode(value.GetType()); + + switch (typeCode) + { + case PrimitiveTypeCode.String: + return ToString((string)value); + case PrimitiveTypeCode.Char: + return ToString((char)value); + case PrimitiveTypeCode.Boolean: + return ToString((bool)value); + case PrimitiveTypeCode.SByte: + return ToString((sbyte)value); + case PrimitiveTypeCode.Int16: + return ToString((short)value); + case PrimitiveTypeCode.UInt16: + return ToString((ushort)value); + case PrimitiveTypeCode.Int32: + return ToString((int)value); + case PrimitiveTypeCode.Byte: + return ToString((byte)value); + case PrimitiveTypeCode.UInt32: + return ToString((uint)value); + case PrimitiveTypeCode.Int64: + return ToString((long)value); + case PrimitiveTypeCode.UInt64: + return ToString((ulong)value); + case PrimitiveTypeCode.Single: + return ToString((float)value); + case PrimitiveTypeCode.Double: + return ToString((double)value); + case PrimitiveTypeCode.DateTime: + return ToString((DateTime)value); + case PrimitiveTypeCode.Decimal: + return ToString((decimal)value); +#if !(DOTNET || PORTABLE) + case PrimitiveTypeCode.DBNull: + return Null; +#endif +#if !NET20 + case PrimitiveTypeCode.DateTimeOffset: + return ToString((DateTimeOffset)value); +#endif + case PrimitiveTypeCode.Guid: + return ToString((Guid)value); + case PrimitiveTypeCode.Uri: + return ToString((Uri)value); + case PrimitiveTypeCode.TimeSpan: + return ToString((TimeSpan)value); +#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) + case PrimitiveTypeCode.BigInteger: + return ToStringInternal((BigInteger)value); +#endif + } + + throw new ArgumentException("Unsupported type: {0}. Use the JsonSerializer class to get the object's JSON representation.".FormatWith(CultureInfo.InvariantCulture, value.GetType())); + } + + #region Serialize + /// + /// Serializes the specified object to a JSON string. + /// + /// The object to serialize. + /// A JSON string representation of the object. + public static string SerializeObject(object value) + { + return SerializeObject(value, null, (JsonSerializerSettings)null); + } + + /// + /// Serializes the specified object to a JSON string using formatting. + /// + /// The object to serialize. + /// Indicates how the output is formatted. + /// + /// A JSON string representation of the object. + /// + public static string SerializeObject(object value, Formatting formatting) + { + return SerializeObject(value, formatting, (JsonSerializerSettings)null); + } + + /// + /// Serializes the specified object to a JSON string using a collection of . + /// + /// The object to serialize. + /// A collection converters used while serializing. + /// A JSON string representation of the object. + public static string SerializeObject(object value, params JsonConverter[] converters) + { + JsonSerializerSettings settings = (converters != null && converters.Length > 0) + ? new JsonSerializerSettings { Converters = converters } + : null; + + return SerializeObject(value, null, settings); + } + + /// + /// Serializes the specified object to a JSON string using formatting and a collection of . + /// + /// The object to serialize. + /// Indicates how the output is formatted. + /// A collection converters used while serializing. + /// A JSON string representation of the object. + public static string SerializeObject(object value, Formatting formatting, params JsonConverter[] converters) + { + JsonSerializerSettings settings = (converters != null && converters.Length > 0) + ? new JsonSerializerSettings { Converters = converters } + : null; + + return SerializeObject(value, null, formatting, settings); + } + + /// + /// Serializes the specified object to a JSON string using . + /// + /// The object to serialize. + /// The used to serialize the object. + /// If this is null, default serialization settings will be used. + /// + /// A JSON string representation of the object. + /// + public static string SerializeObject(object value, JsonSerializerSettings settings) + { + return SerializeObject(value, null, settings); + } + + /// + /// Serializes the specified object to a JSON string using a type, formatting and . + /// + /// The object to serialize. + /// The used to serialize the object. + /// If this is null, default serialization settings will be used. + /// + /// The type of the value being serialized. + /// This parameter is used when is Auto to write out the type name if the type of the value does not match. + /// Specifing the type is optional. + /// + /// + /// A JSON string representation of the object. + /// + public static string SerializeObject(object value, Type type, JsonSerializerSettings settings) + { + JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings); + + return SerializeObjectInternal(value, type, jsonSerializer); + } + + /// + /// Serializes the specified object to a JSON string using formatting and . + /// + /// The object to serialize. + /// Indicates how the output is formatted. + /// The used to serialize the object. + /// If this is null, default serialization settings will be used. + /// + /// A JSON string representation of the object. + /// + public static string SerializeObject(object value, Formatting formatting, JsonSerializerSettings settings) + { + return SerializeObject(value, null, formatting, settings); + } + + /// + /// Serializes the specified object to a JSON string using a type, formatting and . + /// + /// The object to serialize. + /// Indicates how the output is formatted. + /// The used to serialize the object. + /// If this is null, default serialization settings will be used. + /// + /// The type of the value being serialized. + /// This parameter is used when is Auto to write out the type name if the type of the value does not match. + /// Specifing the type is optional. + /// + /// + /// A JSON string representation of the object. + /// + public static string SerializeObject(object value, Type type, Formatting formatting, JsonSerializerSettings settings) + { + JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings); + jsonSerializer.Formatting = formatting; + + return SerializeObjectInternal(value, type, jsonSerializer); + } + + private static string SerializeObjectInternal(object value, Type type, JsonSerializer jsonSerializer) + { + StringBuilder sb = new StringBuilder(256); + StringWriter sw = new StringWriter(sb, CultureInfo.InvariantCulture); + using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) + { + jsonWriter.Formatting = jsonSerializer.Formatting; + + jsonSerializer.Serialize(jsonWriter, value, type); + } + + return sw.ToString(); + } + +#if !(NET20 || NET35 || PORTABLE40) + /// + /// Asynchronously serializes the specified object to a JSON string. + /// Serialization will happen on a new thread. + /// + /// The object to serialize. + /// + /// A task that represents the asynchronous serialize operation. The value of the TResult parameter contains a JSON string representation of the object. + /// + [ObsoleteAttribute("SerializeObjectAsync is obsolete. Use the Task.Factory.StartNew method to serialize JSON asynchronously: Task.Factory.StartNew(() => JsonConvert.SerializeObject(value))")] + public static Task SerializeObjectAsync(object value) + { + return SerializeObjectAsync(value, Formatting.None, null); + } + + /// + /// Asynchronously serializes the specified object to a JSON string using formatting. + /// Serialization will happen on a new thread. + /// + /// The object to serialize. + /// Indicates how the output is formatted. + /// + /// A task that represents the asynchronous serialize operation. The value of the TResult parameter contains a JSON string representation of the object. + /// + [ObsoleteAttribute("SerializeObjectAsync is obsolete. Use the Task.Factory.StartNew method to serialize JSON asynchronously: Task.Factory.StartNew(() => JsonConvert.SerializeObject(value, formatting))")] + public static Task SerializeObjectAsync(object value, Formatting formatting) + { + return SerializeObjectAsync(value, formatting, null); + } + + /// + /// Asynchronously serializes the specified object to a JSON string using formatting and a collection of . + /// Serialization will happen on a new thread. + /// + /// The object to serialize. + /// Indicates how the output is formatted. + /// The used to serialize the object. + /// If this is null, default serialization settings will be used. + /// + /// A task that represents the asynchronous serialize operation. The value of the TResult parameter contains a JSON string representation of the object. + /// + [ObsoleteAttribute("SerializeObjectAsync is obsolete. Use the Task.Factory.StartNew method to serialize JSON asynchronously: Task.Factory.StartNew(() => JsonConvert.SerializeObject(value, formatting, settings))")] + public static Task SerializeObjectAsync(object value, Formatting formatting, JsonSerializerSettings settings) + { + return Task.Factory.StartNew(() => SerializeObject(value, formatting, settings)); + } +#endif + #endregion + + #region Deserialize + /// + /// Deserializes the JSON to a .NET object. + /// + /// The JSON to deserialize. + /// The deserialized object from the JSON string. + public static object DeserializeObject(string value) + { + return DeserializeObject(value, null, (JsonSerializerSettings)null); + } + + /// + /// Deserializes the JSON to a .NET object using . + /// + /// The JSON to deserialize. + /// + /// The used to deserialize the object. + /// If this is null, default serialization settings will be used. + /// + /// The deserialized object from the JSON string. + public static object DeserializeObject(string value, JsonSerializerSettings settings) + { + return DeserializeObject(value, null, settings); + } + + /// + /// Deserializes the JSON to the specified .NET type. + /// + /// The JSON to deserialize. + /// The of object being deserialized. + /// The deserialized object from the JSON string. + public static object DeserializeObject(string value, Type type) + { + return DeserializeObject(value, type, (JsonSerializerSettings)null); + } + + /// + /// Deserializes the JSON to the specified .NET type. + /// + /// The type of the object to deserialize to. + /// The JSON to deserialize. + /// The deserialized object from the JSON string. + public static T DeserializeObject(string value) + { + return DeserializeObject(value, (JsonSerializerSettings)null); + } + + /// + /// Deserializes the JSON to the given anonymous type. + /// + /// + /// The anonymous type to deserialize to. This can't be specified + /// traditionally and must be infered from the anonymous type passed + /// as a parameter. + /// + /// The JSON to deserialize. + /// The anonymous type object. + /// The deserialized anonymous type from the JSON string. + public static T DeserializeAnonymousType(string value, T anonymousTypeObject) + { + return DeserializeObject(value); + } + + /// + /// Deserializes the JSON to the given anonymous type using . + /// + /// + /// The anonymous type to deserialize to. This can't be specified + /// traditionally and must be infered from the anonymous type passed + /// as a parameter. + /// + /// The JSON to deserialize. + /// The anonymous type object. + /// + /// The used to deserialize the object. + /// If this is null, default serialization settings will be used. + /// + /// The deserialized anonymous type from the JSON string. + public static T DeserializeAnonymousType(string value, T anonymousTypeObject, JsonSerializerSettings settings) + { + return DeserializeObject(value, settings); + } + + /// + /// Deserializes the JSON to the specified .NET type using a collection of . + /// + /// The type of the object to deserialize to. + /// The JSON to deserialize. + /// Converters to use while deserializing. + /// The deserialized object from the JSON string. + public static T DeserializeObject(string value, params JsonConverter[] converters) + { + return (T)DeserializeObject(value, typeof(T), converters); + } + + /// + /// Deserializes the JSON to the specified .NET type using . + /// + /// The type of the object to deserialize to. + /// The object to deserialize. + /// + /// The used to deserialize the object. + /// If this is null, default serialization settings will be used. + /// + /// The deserialized object from the JSON string. + public static T DeserializeObject(string value, JsonSerializerSettings settings) + { + return (T)DeserializeObject(value, typeof(T), settings); + } + + /// + /// Deserializes the JSON to the specified .NET type using a collection of . + /// + /// The JSON to deserialize. + /// The type of the object to deserialize. + /// Converters to use while deserializing. + /// The deserialized object from the JSON string. + public static object DeserializeObject(string value, Type type, params JsonConverter[] converters) + { + JsonSerializerSettings settings = (converters != null && converters.Length > 0) + ? new JsonSerializerSettings { Converters = converters } + : null; + + return DeserializeObject(value, type, settings); + } + + /// + /// Deserializes the JSON to the specified .NET type using . + /// + /// The JSON to deserialize. + /// The type of the object to deserialize to. + /// + /// The used to deserialize the object. + /// If this is null, default serialization settings will be used. + /// + /// The deserialized object from the JSON string. + public static object DeserializeObject(string value, Type type, JsonSerializerSettings settings) + { + ValidationUtils.ArgumentNotNull(value, nameof(value)); + + JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings); + + // by default DeserializeObject should check for additional content + if (!jsonSerializer.IsCheckAdditionalContentSet()) + { + jsonSerializer.CheckAdditionalContent = true; + } + + using (var reader = new JsonTextReader(new StringReader(value))) + { + return jsonSerializer.Deserialize(reader, type); + } + } + +#if !(NET20 || NET35 || PORTABLE40) + /// + /// Asynchronously deserializes the JSON to the specified .NET type. + /// Deserialization will happen on a new thread. + /// + /// The type of the object to deserialize to. + /// The JSON to deserialize. + /// + /// A task that represents the asynchronous deserialize operation. The value of the TResult parameter contains the deserialized object from the JSON string. + /// + [ObsoleteAttribute("DeserializeObjectAsync is obsolete. Use the Task.Factory.StartNew method to deserialize JSON asynchronously: Task.Factory.StartNew(() => JsonConvert.DeserializeObject(value))")] + public static Task DeserializeObjectAsync(string value) + { + return DeserializeObjectAsync(value, null); + } + + /// + /// Asynchronously deserializes the JSON to the specified .NET type using . + /// Deserialization will happen on a new thread. + /// + /// The type of the object to deserialize to. + /// The JSON to deserialize. + /// + /// The used to deserialize the object. + /// If this is null, default serialization settings will be used. + /// + /// + /// A task that represents the asynchronous deserialize operation. The value of the TResult parameter contains the deserialized object from the JSON string. + /// + [ObsoleteAttribute("DeserializeObjectAsync is obsolete. Use the Task.Factory.StartNew method to deserialize JSON asynchronously: Task.Factory.StartNew(() => JsonConvert.DeserializeObject(value, settings))")] + public static Task DeserializeObjectAsync(string value, JsonSerializerSettings settings) + { + return Task.Factory.StartNew(() => DeserializeObject(value, settings)); + } + + /// + /// Asynchronously deserializes the JSON to the specified .NET type. + /// Deserialization will happen on a new thread. + /// + /// The JSON to deserialize. + /// + /// A task that represents the asynchronous deserialize operation. The value of the TResult parameter contains the deserialized object from the JSON string. + /// + [ObsoleteAttribute("DeserializeObjectAsync is obsolete. Use the Task.Factory.StartNew method to deserialize JSON asynchronously: Task.Factory.StartNew(() => JsonConvert.DeserializeObject(value))")] + public static Task DeserializeObjectAsync(string value) + { + return DeserializeObjectAsync(value, null, null); + } + + /// + /// Asynchronously deserializes the JSON to the specified .NET type using . + /// Deserialization will happen on a new thread. + /// + /// The JSON to deserialize. + /// The type of the object to deserialize to. + /// + /// The used to deserialize the object. + /// If this is null, default serialization settings will be used. + /// + /// + /// A task that represents the asynchronous deserialize operation. The value of the TResult parameter contains the deserialized object from the JSON string. + /// + [ObsoleteAttribute("DeserializeObjectAsync is obsolete. Use the Task.Factory.StartNew method to deserialize JSON asynchronously: Task.Factory.StartNew(() => JsonConvert.DeserializeObject(value, type, settings))")] + public static Task DeserializeObjectAsync(string value, Type type, JsonSerializerSettings settings) + { + return Task.Factory.StartNew(() => DeserializeObject(value, type, settings)); + } +#endif + #endregion + + #region Populate + /// + /// Populates the object with values from the JSON string. + /// + /// The JSON to populate values from. + /// The target object to populate values onto. + public static void PopulateObject(string value, object target) + { + PopulateObject(value, target, null); + } + + /// + /// Populates the object with values from the JSON string using . + /// + /// The JSON to populate values from. + /// The target object to populate values onto. + /// + /// The used to deserialize the object. + /// If this is null, default serialization settings will be used. + /// + public static void PopulateObject(string value, object target, JsonSerializerSettings settings) + { + JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings); + + using (JsonReader jsonReader = new JsonTextReader(new StringReader(value))) + { + jsonSerializer.Populate(jsonReader, target); + + if (jsonReader.Read() && jsonReader.TokenType != JsonToken.Comment) + { + throw new JsonSerializationException("Additional text found in JSON string after finishing deserializing object."); + } + } + } + +#if !(NET20 || NET35 || PORTABLE40) + /// + /// Asynchronously populates the object with values from the JSON string using . + /// + /// The JSON to populate values from. + /// The target object to populate values onto. + /// + /// The used to deserialize the object. + /// If this is null, default serialization settings will be used. + /// + /// + /// A task that represents the asynchronous populate operation. + /// + [ObsoleteAttribute("PopulateObjectAsync is obsolete. Use the Task.Factory.StartNew method to populate an object with JSON values asynchronously: Task.Factory.StartNew(() => JsonConvert.PopulateObject(value, target, settings))")] + public static Task PopulateObjectAsync(string value, object target, JsonSerializerSettings settings) + { + return Task.Factory.StartNew(() => PopulateObject(value, target, settings)); + } +#endif + #endregion + + #region Xml +#if !(PORTABLE40 || PORTABLE || DOTNET) + /// + /// Serializes the XML node to a JSON string. + /// + /// The node to serialize. + /// A JSON string of the XmlNode. + public static string SerializeXmlNode(XmlNode node) + { + return SerializeXmlNode(node, Formatting.None); + } + + /// + /// Serializes the XML node to a JSON string using formatting. + /// + /// The node to serialize. + /// Indicates how the output is formatted. + /// A JSON string of the XmlNode. + public static string SerializeXmlNode(XmlNode node, Formatting formatting) + { + XmlNodeConverter converter = new XmlNodeConverter(); + + return SerializeObject(node, formatting, converter); + } + + /// + /// Serializes the XML node to a JSON string using formatting and omits the root object if is true. + /// + /// The node to serialize. + /// Indicates how the output is formatted. + /// Omits writing the root object. + /// A JSON string of the XmlNode. + public static string SerializeXmlNode(XmlNode node, Formatting formatting, bool omitRootObject) + { + XmlNodeConverter converter = new XmlNodeConverter { OmitRootObject = omitRootObject }; + + return SerializeObject(node, formatting, converter); + } + + /// + /// Deserializes the XmlNode from a JSON string. + /// + /// The JSON string. + /// The deserialized XmlNode + public static XmlDocument DeserializeXmlNode(string value) + { + return DeserializeXmlNode(value, null); + } + + /// + /// Deserializes the XmlNode from a JSON string nested in a root elment specified by . + /// + /// The JSON string. + /// The name of the root element to append when deserializing. + /// The deserialized XmlNode + public static XmlDocument DeserializeXmlNode(string value, string deserializeRootElementName) + { + return DeserializeXmlNode(value, deserializeRootElementName, false); + } + + /// + /// Deserializes the XmlNode from a JSON string nested in a root elment specified by + /// and writes a .NET array attribute for collections. + /// + /// The JSON string. + /// The name of the root element to append when deserializing. + /// + /// A flag to indicate whether to write the Json.NET array attribute. + /// This attribute helps preserve arrays when converting the written XML back to JSON. + /// + /// The deserialized XmlNode + public static XmlDocument DeserializeXmlNode(string value, string deserializeRootElementName, bool writeArrayAttribute) + { + XmlNodeConverter converter = new XmlNodeConverter(); + converter.DeserializeRootElementName = deserializeRootElementName; + converter.WriteArrayAttribute = writeArrayAttribute; + + return (XmlDocument)DeserializeObject(value, typeof(XmlDocument), converter); + } +#endif + +#if !NET20 && !PORTABLE40 + /// + /// Serializes the to a JSON string. + /// + /// The node to convert to JSON. + /// A JSON string of the XNode. + public static string SerializeXNode(XObject node) + { + return SerializeXNode(node, Formatting.None); + } + + /// + /// Serializes the to a JSON string using formatting. + /// + /// The node to convert to JSON. + /// Indicates how the output is formatted. + /// A JSON string of the XNode. + public static string SerializeXNode(XObject node, Formatting formatting) + { + return SerializeXNode(node, formatting, false); + } + + /// + /// Serializes the to a JSON string using formatting and omits the root object if is true. + /// + /// The node to serialize. + /// Indicates how the output is formatted. + /// Omits writing the root object. + /// A JSON string of the XNode. + public static string SerializeXNode(XObject node, Formatting formatting, bool omitRootObject) + { + XmlNodeConverter converter = new XmlNodeConverter { OmitRootObject = omitRootObject }; + + return SerializeObject(node, formatting, converter); + } + + /// + /// Deserializes the from a JSON string. + /// + /// The JSON string. + /// The deserialized XNode + public static XDocument DeserializeXNode(string value) + { + return DeserializeXNode(value, null); + } + + /// + /// Deserializes the from a JSON string nested in a root elment specified by . + /// + /// The JSON string. + /// The name of the root element to append when deserializing. + /// The deserialized XNode + public static XDocument DeserializeXNode(string value, string deserializeRootElementName) + { + return DeserializeXNode(value, deserializeRootElementName, false); + } + + /// + /// Deserializes the from a JSON string nested in a root elment specified by + /// and writes a .NET array attribute for collections. + /// + /// The JSON string. + /// The name of the root element to append when deserializing. + /// + /// A flag to indicate whether to write the Json.NET array attribute. + /// This attribute helps preserve arrays when converting the written XML back to JSON. + /// + /// The deserialized XNode + public static XDocument DeserializeXNode(string value, string deserializeRootElementName, bool writeArrayAttribute) + { + XmlNodeConverter converter = new XmlNodeConverter(); + converter.DeserializeRootElementName = deserializeRootElementName; + converter.WriteArrayAttribute = writeArrayAttribute; + + return (XDocument)DeserializeObject(value, typeof(XDocument), converter); + } +#endif + #endregion + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/JsonConverter.cs b/Common/00-1Json8.3/Json8.3/JsonConverter.cs new file mode 100644 index 0000000..a973d38 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/JsonConverter.cs @@ -0,0 +1,99 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Collections.Generic; +using System.Text; +using Newtonsoft.Json.Utilities; +using Newtonsoft.Json.Schema; + +namespace Newtonsoft.Json +{ + /// + /// Converts an object to and from JSON. + /// + public abstract class JsonConverter + { + /// + /// Writes the JSON representation of the object. + /// + /// The to write to. + /// The value. + /// The calling serializer. + public abstract void WriteJson(JsonWriter writer, object value, JsonSerializer serializer); + + /// + /// Reads the JSON representation of the object. + /// + /// The to read from. + /// Type of the object. + /// The existing value of object being read. + /// The calling serializer. + /// The object value. + public abstract object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer); + + /// + /// Determines whether this instance can convert the specified object type. + /// + /// Type of the object. + /// + /// true if this instance can convert the specified object type; otherwise, false. + /// + public abstract bool CanConvert(Type objectType); + + /// + /// + /// Gets the of the JSON produced by the JsonConverter. + /// + /// + /// JSON Schema validation has been moved to its own package. See http://www.newtonsoft.com/jsonschema for more details. + /// + /// + /// The of the JSON produced by the JsonConverter. + [Obsolete("JSON Schema validation has been moved to its own package. It is strongly recommended that you do not override GetSchema() in your own converter. It is not used by Json.NET and will be removed at some point in the future. Converter's that override GetSchema() will stop working when it is removed.")] + public virtual JsonSchema GetSchema() + { + return null; + } + + /// + /// Gets a value indicating whether this can read JSON. + /// + /// true if this can read JSON; otherwise, false. + public virtual bool CanRead + { + get { return true; } + } + + /// + /// Gets a value indicating whether this can write JSON. + /// + /// true if this can write JSON; otherwise, false. + public virtual bool CanWrite + { + get { return true; } + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/JsonConverterAttribute.cs b/Common/00-1Json8.3/Json8.3/JsonConverterAttribute.cs new file mode 100644 index 0000000..fdafb3a --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/JsonConverterAttribute.cs @@ -0,0 +1,80 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using Newtonsoft.Json.Utilities; +using System.Globalization; + +namespace Newtonsoft.Json +{ + /// + /// Instructs the to use the specified when serializing the member or class. + /// + [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface | AttributeTargets.Enum | AttributeTargets.Parameter, AllowMultiple = false)] + public sealed class JsonConverterAttribute : Attribute + { + private readonly Type _converterType; + + /// + /// Gets the of the converter. + /// + /// The of the converter. + public Type ConverterType + { + get { return _converterType; } + } + + /// + /// The parameter list to use when constructing the JsonConverter described by ConverterType. + /// If null, the default constructor is used. + /// + public object[] ConverterParameters { get; private set; } + + /// + /// Initializes a new instance of the class. + /// + /// Type of the converter. + public JsonConverterAttribute(Type converterType) + { + if (converterType == null) + { + throw new ArgumentNullException(nameof(converterType)); + } + + _converterType = converterType; + } + + /// + /// Initializes a new instance of the class. + /// + /// Type of the converter. + /// Parameter list to use when constructing the JsonConverter. Can be null. + public JsonConverterAttribute(Type converterType, params object[] converterParameters) + : this(converterType) + { + ConverterParameters = converterParameters; + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/JsonConverterCollection.cs b/Common/00-1Json8.3/Json8.3/JsonConverterCollection.cs new file mode 100644 index 0000000..b2c0492 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/JsonConverterCollection.cs @@ -0,0 +1,39 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Collections.Generic; +using System.Text; +using System.Collections.ObjectModel; + +namespace Newtonsoft.Json +{ + /// + /// Represents a collection of . + /// + public class JsonConverterCollection : Collection + { + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/JsonDictionaryAttribute.cs b/Common/00-1Json8.3/Json8.3/JsonDictionaryAttribute.cs new file mode 100644 index 0000000..7ddf411 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/JsonDictionaryAttribute.cs @@ -0,0 +1,52 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; + +namespace Newtonsoft.Json +{ + /// + /// Instructs the how to serialize the collection. + /// + [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false)] + public sealed class JsonDictionaryAttribute : JsonContainerAttribute + { + /// + /// Initializes a new instance of the class. + /// + public JsonDictionaryAttribute() + { + } + + /// + /// Initializes a new instance of the class with the specified container Id. + /// + /// The container Id. + public JsonDictionaryAttribute(string id) + : base(id) + { + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/JsonException.cs b/Common/00-1Json8.3/Json8.3/JsonException.cs new file mode 100644 index 0000000..97ea724 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/JsonException.cs @@ -0,0 +1,92 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Runtime.Serialization; +using System.Text; +using Newtonsoft.Json.Utilities; + +namespace Newtonsoft.Json +{ + /// + /// The exception thrown when an error occurs during JSON serialization or deserialization. + /// +#if !(DOTNET || PORTABLE40 || PORTABLE) + [Serializable] +#endif + public class JsonException : Exception + { + /// + /// Initializes a new instance of the class. + /// + public JsonException() + { + } + + /// + /// Initializes a new instance of the class + /// with a specified error message. + /// + /// The error message that explains the reason for the exception. + public JsonException(string message) + : base(message) + { + } + + /// + /// Initializes a new instance of the class + /// with a specified error message and a reference to the inner exception that is the cause of this exception. + /// + /// The error message that explains the reason for the exception. + /// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no inner exception is specified. + public JsonException(string message, Exception innerException) + : base(message, innerException) + { + } + +#if !(DOTNET || PORTABLE40 || PORTABLE) + /// + /// Initializes a new instance of the class. + /// + /// The that holds the serialized object data about the exception being thrown. + /// The that contains contextual information about the source or destination. + /// The parameter is null. + /// The class name is null or is zero (0). + public JsonException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } +#endif + + internal static JsonException Create(IJsonLineInfo lineInfo, string path, string message) + { + message = JsonPosition.FormatMessage(lineInfo, path, message); + + return new JsonException(message); + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/JsonExtensionDataAttribute.cs b/Common/00-1Json8.3/Json8.3/JsonExtensionDataAttribute.cs new file mode 100644 index 0000000..6bc15b7 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/JsonExtensionDataAttribute.cs @@ -0,0 +1,37 @@ +using System; + +namespace Newtonsoft.Json +{ + /// + /// Instructs the to deserialize properties with no matching class member into the specified collection + /// and write values during serialization. + /// + [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false)] + public class JsonExtensionDataAttribute : Attribute + { + /// + /// Gets or sets a value that indicates whether to write extension data when serializing the object. + /// + /// + /// true to write extension data when serializing the object; otherwise, false. The default is true. + /// + public bool WriteData { get; set; } + + /// + /// Gets or sets a value that indicates whether to read extension data when deserializing the object. + /// + /// + /// true to read extension data when deserializing the object; otherwise, false. The default is true. + /// + public bool ReadData { get; set; } + + /// + /// Initializes a new instance of the class. + /// + public JsonExtensionDataAttribute() + { + WriteData = true; + ReadData = true; + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/JsonIgnoreAttribute.cs b/Common/00-1Json8.3/Json8.3/JsonIgnoreAttribute.cs new file mode 100644 index 0000000..8229299 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/JsonIgnoreAttribute.cs @@ -0,0 +1,39 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Collections.Generic; +using System.Text; + +namespace Newtonsoft.Json +{ + /// + /// Instructs the not to serialize the public field or public read/write property value. + /// + [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false)] + public sealed class JsonIgnoreAttribute : Attribute + { + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/JsonObjectAttribute.cs b/Common/00-1Json8.3/Json8.3/JsonObjectAttribute.cs new file mode 100644 index 0000000..61fad92 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/JsonObjectAttribute.cs @@ -0,0 +1,89 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; + +namespace Newtonsoft.Json +{ + /// + /// Instructs the how to serialize the object. + /// + [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface, AllowMultiple = false)] + public sealed class JsonObjectAttribute : JsonContainerAttribute + { + private MemberSerialization _memberSerialization = MemberSerialization.OptOut; + + // yuck. can't set nullable properties on an attribute in C# + // have to use this approach to get an unset default state + internal Required? _itemRequired; + + /// + /// Gets or sets the member serialization. + /// + /// The member serialization. + public MemberSerialization MemberSerialization + { + get { return _memberSerialization; } + set { _memberSerialization = value; } + } + + /// + /// Gets or sets a value that indicates whether the object's properties are required. + /// + /// + /// A value indicating whether the object's properties are required. + /// + public Required ItemRequired + { + get { return _itemRequired ?? default(Required); } + set { _itemRequired = value; } + } + + /// + /// Initializes a new instance of the class. + /// + public JsonObjectAttribute() + { + } + + /// + /// Initializes a new instance of the class with the specified member serialization. + /// + /// The member serialization. + public JsonObjectAttribute(MemberSerialization memberSerialization) + { + MemberSerialization = memberSerialization; + } + + /// + /// Initializes a new instance of the class with the specified container Id. + /// + /// The container Id. + public JsonObjectAttribute(string id) + : base(id) + { + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/JsonPosition.cs b/Common/00-1Json8.3/Json8.3/JsonPosition.cs new file mode 100644 index 0000000..f478cc1 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/JsonPosition.cs @@ -0,0 +1,167 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Text; +using Newtonsoft.Json.Utilities; + +namespace Newtonsoft.Json +{ + internal enum JsonContainerType + { + None = 0, + Object = 1, + Array = 2, + Constructor = 3 + } + + internal struct JsonPosition + { + private static readonly char[] SpecialCharacters = { '.', ' ', '[', ']', '(', ')' }; + + internal JsonContainerType Type; + internal int Position; + internal string PropertyName; + internal bool HasIndex; + + public JsonPosition(JsonContainerType type) + { + Type = type; + HasIndex = TypeHasIndex(type); + Position = -1; + PropertyName = null; + } + + internal int CalculateLength() + { + switch (Type) + { + case JsonContainerType.Object: + return PropertyName.Length + 5; + case JsonContainerType.Array: + case JsonContainerType.Constructor: + return MathUtils.IntLength((ulong)Position) + 2; + default: + throw new ArgumentOutOfRangeException("Type"); + } + } + + internal void WriteTo(StringBuilder sb) + { + switch (Type) + { + case JsonContainerType.Object: + string propertyName = PropertyName; + if (propertyName.IndexOfAny(SpecialCharacters) != -1) + { + sb.Append(@"['"); + sb.Append(propertyName); + sb.Append(@"']"); + } + else + { + if (sb.Length > 0) + { + sb.Append('.'); + } + + sb.Append(propertyName); + } + break; + case JsonContainerType.Array: + case JsonContainerType.Constructor: + sb.Append('['); + sb.Append(Position); + sb.Append(']'); + break; + } + } + + internal static bool TypeHasIndex(JsonContainerType type) + { + return (type == JsonContainerType.Array || type == JsonContainerType.Constructor); + } + + internal static string BuildPath(List positions, JsonPosition? currentPosition) + { + int capacity = 0; + if (positions != null) + { + for (int i = 0; i < positions.Count; i++) + { + capacity += positions[i].CalculateLength(); + } + } + if (currentPosition != null) + { + capacity += currentPosition.GetValueOrDefault().CalculateLength(); + } + + StringBuilder sb = new StringBuilder(capacity); + if (positions != null) + { + foreach (JsonPosition state in positions) + { + state.WriteTo(sb); + } + } + if (currentPosition != null) + { + currentPosition.GetValueOrDefault().WriteTo(sb); + } + + return sb.ToString(); + } + + internal static string FormatMessage(IJsonLineInfo lineInfo, string path, string message) + { + // don't add a fullstop and space when message ends with a new line + if (!message.EndsWith(Environment.NewLine, StringComparison.Ordinal)) + { + message = message.Trim(); + + if (!message.EndsWith('.')) + { + message += "."; + } + + message += " "; + } + + message += "Path '{0}'".FormatWith(CultureInfo.InvariantCulture, path); + + if (lineInfo != null && lineInfo.HasLineInfo()) + { + message += ", line {0}, position {1}".FormatWith(CultureInfo.InvariantCulture, lineInfo.LineNumber, lineInfo.LinePosition); + } + + message += "."; + + return message; + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/JsonPropertyAttribute.cs b/Common/00-1Json8.3/Json8.3/JsonPropertyAttribute.cs new file mode 100644 index 0000000..6efe0ed --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/JsonPropertyAttribute.cs @@ -0,0 +1,201 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; + +namespace Newtonsoft.Json +{ + /// + /// Instructs the to always serialize the member with the specified name. + /// + [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Parameter, AllowMultiple = false)] + public sealed class JsonPropertyAttribute : Attribute + { + // yuck. can't set nullable properties on an attribute in C# + // have to use this approach to get an unset default state + internal NullValueHandling? _nullValueHandling; + internal DefaultValueHandling? _defaultValueHandling; + internal ReferenceLoopHandling? _referenceLoopHandling; + internal ObjectCreationHandling? _objectCreationHandling; + internal TypeNameHandling? _typeNameHandling; + internal bool? _isReference; + internal int? _order; + internal Required? _required; + internal bool? _itemIsReference; + internal ReferenceLoopHandling? _itemReferenceLoopHandling; + internal TypeNameHandling? _itemTypeNameHandling; + + /// + /// Gets or sets the converter used when serializing the property's collection items. + /// + /// The collection's items converter. + public Type ItemConverterType { get; set; } + + /// + /// The parameter list to use when constructing the JsonConverter described by ItemConverterType. + /// If null, the default constructor is used. + /// When non-null, there must be a constructor defined in the JsonConverter that exactly matches the number, + /// order, and type of these parameters. + /// + /// + /// [JsonProperty(ItemConverterType = typeof(MyContainerConverter), ItemConverterParameters = new object[] { 123, "Four" })] + /// + public object[] ItemConverterParameters { get; set; } + + /// + /// Gets or sets the null value handling used when serializing this property. + /// + /// The null value handling. + public NullValueHandling NullValueHandling + { + get { return _nullValueHandling ?? default(NullValueHandling); } + set { _nullValueHandling = value; } + } + + /// + /// Gets or sets the default value handling used when serializing this property. + /// + /// The default value handling. + public DefaultValueHandling DefaultValueHandling + { + get { return _defaultValueHandling ?? default(DefaultValueHandling); } + set { _defaultValueHandling = value; } + } + + /// + /// Gets or sets the reference loop handling used when serializing this property. + /// + /// The reference loop handling. + public ReferenceLoopHandling ReferenceLoopHandling + { + get { return _referenceLoopHandling ?? default(ReferenceLoopHandling); } + set { _referenceLoopHandling = value; } + } + + /// + /// Gets or sets the object creation handling used when deserializing this property. + /// + /// The object creation handling. + public ObjectCreationHandling ObjectCreationHandling + { + get { return _objectCreationHandling ?? default(ObjectCreationHandling); } + set { _objectCreationHandling = value; } + } + + /// + /// Gets or sets the type name handling used when serializing this property. + /// + /// The type name handling. + public TypeNameHandling TypeNameHandling + { + get { return _typeNameHandling ?? default(TypeNameHandling); } + set { _typeNameHandling = value; } + } + + /// + /// Gets or sets whether this property's value is serialized as a reference. + /// + /// Whether this property's value is serialized as a reference. + public bool IsReference + { + get { return _isReference ?? default(bool); } + set { _isReference = value; } + } + + /// + /// Gets or sets the order of serialization of a member. + /// + /// The numeric order of serialization. + public int Order + { + get { return _order ?? default(int); } + set { _order = value; } + } + + /// + /// Gets or sets a value indicating whether this property is required. + /// + /// + /// A value indicating whether this property is required. + /// + public Required Required + { + get { return _required ?? Required.Default; } + set { _required = value; } + } + + /// + /// Gets or sets the name of the property. + /// + /// The name of the property. + public string PropertyName { get; set; } + + /// + /// Gets or sets the the reference loop handling used when serializing the property's collection items. + /// + /// The collection's items reference loop handling. + public ReferenceLoopHandling ItemReferenceLoopHandling + { + get { return _itemReferenceLoopHandling ?? default(ReferenceLoopHandling); } + set { _itemReferenceLoopHandling = value; } + } + + /// + /// Gets or sets the the type name handling used when serializing the property's collection items. + /// + /// The collection's items type name handling. + public TypeNameHandling ItemTypeNameHandling + { + get { return _itemTypeNameHandling ?? default(TypeNameHandling); } + set { _itemTypeNameHandling = value; } + } + + /// + /// Gets or sets whether this property's collection items are serialized as a reference. + /// + /// Whether this property's collection items are serialized as a reference. + public bool ItemIsReference + { + get { return _itemIsReference ?? default(bool); } + set { _itemIsReference = value; } + } + + /// + /// Initializes a new instance of the class. + /// + public JsonPropertyAttribute() + { + } + + /// + /// Initializes a new instance of the class with the specified name. + /// + /// Name of the property. + public JsonPropertyAttribute(string propertyName) + { + PropertyName = propertyName; + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/JsonReader.cs b/Common/00-1Json8.3/Json8.3/JsonReader.cs new file mode 100644 index 0000000..ce71c23 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/JsonReader.cs @@ -0,0 +1,1173 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Collections.Generic; +using System.IO; +using System.Globalization; +#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) +using System.Numerics; +#endif +using Newtonsoft.Json.Serialization; +using Newtonsoft.Json.Utilities; +#if NET20 +using Newtonsoft.Json.Utilities.LinqBridge; +#else +using System.Linq; +#endif + +namespace Newtonsoft.Json +{ + /// + /// Represents a reader that provides fast, non-cached, forward-only access to serialized JSON data. + /// + public abstract class JsonReader : IDisposable + { + /// + /// Specifies the state of the reader. + /// + protected internal enum State + { + /// + /// The Read method has not been called. + /// + Start, + + /// + /// The end of the file has been reached successfully. + /// + Complete, + + /// + /// Reader is at a property. + /// + Property, + + /// + /// Reader is at the start of an object. + /// + ObjectStart, + + /// + /// Reader is in an object. + /// + Object, + + /// + /// Reader is at the start of an array. + /// + ArrayStart, + + /// + /// Reader is in an array. + /// + Array, + + /// + /// The Close method has been called. + /// + Closed, + + /// + /// Reader has just read a value. + /// + PostValue, + + /// + /// Reader is at the start of a constructor. + /// + ConstructorStart, + + /// + /// Reader in a constructor. + /// + Constructor, + + /// + /// An error occurred that prevents the read operation from continuing. + /// + Error, + + /// + /// The end of the file has been reached successfully. + /// + Finished + } + + // current Token data + private JsonToken _tokenType; + private object _value; + internal char _quoteChar; + internal State _currentState; + private JsonPosition _currentPosition; + private CultureInfo _culture; + private DateTimeZoneHandling _dateTimeZoneHandling; + private int? _maxDepth; + private bool _hasExceededMaxDepth; + internal DateParseHandling _dateParseHandling; + internal FloatParseHandling _floatParseHandling; + private string _dateFormatString; + private List _stack; + + /// + /// Gets the current reader state. + /// + /// The current reader state. + protected State CurrentState + { + get { return _currentState; } + } + + /// + /// Gets or sets a value indicating whether the underlying stream or + /// should be closed when the reader is closed. + /// + /// + /// true to close the underlying stream or when + /// the reader is closed; otherwise false. The default is true. + /// + public bool CloseInput { get; set; } + + /// + /// Gets or sets a value indicating whether multiple pieces of JSON content can + /// be read from a continuous stream without erroring. + /// + /// + /// true to support reading multiple pieces of JSON content; otherwise false. The default is false. + /// + public bool SupportMultipleContent { get; set; } + + /// + /// Gets the quotation mark character used to enclose the value of a string. + /// + public virtual char QuoteChar + { + get { return _quoteChar; } + protected internal set { _quoteChar = value; } + } + + /// + /// Get or set how time zones are handling when reading JSON. + /// + public DateTimeZoneHandling DateTimeZoneHandling + { + get { return _dateTimeZoneHandling; } + set + { + if (value < DateTimeZoneHandling.Local || value > DateTimeZoneHandling.RoundtripKind) + { + throw new ArgumentOutOfRangeException(nameof(value)); + } + + _dateTimeZoneHandling = value; + } + } + + /// + /// Get or set how date formatted strings, e.g. "\/Date(1198908717056)\/" and "2012-03-21T05:40Z", are parsed when reading JSON. + /// + public DateParseHandling DateParseHandling + { + get { return _dateParseHandling; } + set + { + if (value < DateParseHandling.None || +#if !NET20 + value > DateParseHandling.DateTimeOffset +#else + value > DateParseHandling.DateTime +#endif + ) + { + throw new ArgumentOutOfRangeException(nameof(value)); + } + + _dateParseHandling = value; + } + } + + /// + /// Get or set how floating point numbers, e.g. 1.0 and 9.9, are parsed when reading JSON text. + /// + public FloatParseHandling FloatParseHandling + { + get { return _floatParseHandling; } + set + { + if (value < FloatParseHandling.Double || value > FloatParseHandling.Decimal) + { + throw new ArgumentOutOfRangeException(nameof(value)); + } + + _floatParseHandling = value; + } + } + + /// + /// Get or set how custom date formatted strings are parsed when reading JSON. + /// + public string DateFormatString + { + get { return _dateFormatString; } + set { _dateFormatString = value; } + } + + /// + /// Gets or sets the maximum depth allowed when reading JSON. Reading past this depth will throw a . + /// + public int? MaxDepth + { + get { return _maxDepth; } + set + { + if (value <= 0) + { + throw new ArgumentException("Value must be positive.", nameof(value)); + } + + _maxDepth = value; + } + } + + /// + /// Gets the type of the current JSON token. + /// + public virtual JsonToken TokenType + { + get { return _tokenType; } + } + + /// + /// Gets the text value of the current JSON token. + /// + public virtual object Value + { + get { return _value; } + } + + /// + /// Gets The Common Language Runtime (CLR) type for the current JSON token. + /// + public virtual Type ValueType + { + get { return (_value != null) ? _value.GetType() : null; } + } + + /// + /// Gets the depth of the current token in the JSON document. + /// + /// The depth of the current token in the JSON document. + public virtual int Depth + { + get + { + int depth = (_stack != null) ? _stack.Count : 0; + if (JsonTokenUtils.IsStartToken(TokenType) || _currentPosition.Type == JsonContainerType.None) + { + return depth; + } + else + { + return depth + 1; + } + } + } + + /// + /// Gets the path of the current JSON token. + /// + public virtual string Path + { + get + { + if (_currentPosition.Type == JsonContainerType.None) + { + return string.Empty; + } + + bool insideContainer = (_currentState != State.ArrayStart + && _currentState != State.ConstructorStart + && _currentState != State.ObjectStart); + + JsonPosition? current = insideContainer ? (JsonPosition?)_currentPosition : null; + + return JsonPosition.BuildPath(_stack, current); + } + } + + /// + /// Gets or sets the culture used when reading JSON. Defaults to . + /// + public CultureInfo Culture + { + get { return _culture ?? CultureInfo.InvariantCulture; } + set { _culture = value; } + } + + internal JsonPosition GetPosition(int depth) + { + if (_stack != null && depth < _stack.Count) + { + return _stack[depth]; + } + + return _currentPosition; + } + + /// + /// Initializes a new instance of the class with the specified . + /// + protected JsonReader() + { + _currentState = State.Start; + _dateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind; + _dateParseHandling = DateParseHandling.DateTime; + _floatParseHandling = FloatParseHandling.Double; + + CloseInput = true; + } + + private void Push(JsonContainerType value) + { + UpdateScopeWithFinishedValue(); + + if (_currentPosition.Type == JsonContainerType.None) + { + _currentPosition = new JsonPosition(value); + } + else + { + if (_stack == null) + { + _stack = new List(); + } + + _stack.Add(_currentPosition); + _currentPosition = new JsonPosition(value); + + // this is a little hacky because Depth increases when first property/value is written but only testing here is faster/simpler + if (_maxDepth != null && Depth + 1 > _maxDepth && !_hasExceededMaxDepth) + { + _hasExceededMaxDepth = true; + throw JsonReaderException.Create(this, "The reader's MaxDepth of {0} has been exceeded.".FormatWith(CultureInfo.InvariantCulture, _maxDepth)); + } + } + } + + private JsonContainerType Pop() + { + JsonPosition oldPosition; + if (_stack != null && _stack.Count > 0) + { + oldPosition = _currentPosition; + _currentPosition = _stack[_stack.Count - 1]; + _stack.RemoveAt(_stack.Count - 1); + } + else + { + oldPosition = _currentPosition; + _currentPosition = new JsonPosition(); + } + + if (_maxDepth != null && Depth <= _maxDepth) + { + _hasExceededMaxDepth = false; + } + + return oldPosition.Type; + } + + private JsonContainerType Peek() + { + return _currentPosition.Type; + } + + /// + /// Reads the next JSON token from the stream. + /// + /// true if the next token was read successfully; false if there are no more tokens to read. + public abstract bool Read(); + + /// + /// Reads the next JSON token from the stream as a . + /// + /// A . This method will return null at the end of an array. + public virtual int? ReadAsInt32() + { + JsonToken t = GetContentToken(); + + switch (t) + { + case JsonToken.None: + case JsonToken.Null: + case JsonToken.EndArray: + return null; + case JsonToken.Integer: + case JsonToken.Float: + if (!(Value is int)) + { + SetToken(JsonToken.Integer, Convert.ToInt32(Value, CultureInfo.InvariantCulture), false); + } + + return (int)Value; + case JsonToken.String: + string s = (string)Value; + return ReadInt32String(s); + } + + throw JsonReaderException.Create(this, "Error reading integer. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t)); + } + + internal int? ReadInt32String(string s) + { + if (string.IsNullOrEmpty(s)) + { + SetToken(JsonToken.Null, null, false); + return null; + } + + int i; + if (int.TryParse(s, NumberStyles.Integer, Culture, out i)) + { + SetToken(JsonToken.Integer, i, false); + return i; + } + else + { + SetToken(JsonToken.String, s, false); + throw JsonReaderException.Create(this, "Could not convert string to integer: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); + } + } + + /// + /// Reads the next JSON token from the stream as a . + /// + /// A . This method will return null at the end of an array. + public virtual string ReadAsString() + { + JsonToken t = GetContentToken(); + + switch (t) + { + case JsonToken.None: + case JsonToken.Null: + case JsonToken.EndArray: + return null; + case JsonToken.String: + return (string)Value; + } + + if (JsonTokenUtils.IsPrimitiveToken(t)) + { + if (Value != null) + { + string s; + if (Value is IFormattable) + { + s = ((IFormattable)Value).ToString(null, Culture); + } + else if (Value is Uri) + { + s = ((Uri)Value).OriginalString; + } + else + { + s = Value.ToString(); + } + + SetToken(JsonToken.String, s, false); + return s; + } + } + + throw JsonReaderException.Create(this, "Error reading string. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t)); + } + + /// + /// Reads the next JSON token from the stream as a []. + /// + /// A [] or a null reference if the next JSON token is null. This method will return null at the end of an array. + public virtual byte[] ReadAsBytes() + { + JsonToken t = GetContentToken(); + + if (t == JsonToken.None) + { + return null; + } + + if (TokenType == JsonToken.StartObject) + { + ReadIntoWrappedTypeObject(); + + byte[] data = ReadAsBytes(); + ReaderReadAndAssert(); + + if (TokenType != JsonToken.EndObject) + { + throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); + } + + SetToken(JsonToken.Bytes, data, false); + return data; + } + + switch (t) + { + case JsonToken.String: + { + // attempt to convert possible base 64 or GUID string to bytes + // GUID has to have format 00000000-0000-0000-0000-000000000000 + string s = (string)Value; + + byte[] data; + + Guid g; + if (s.Length == 0) + { + data = new byte[0]; + } + else if (ConvertUtils.TryConvertGuid(s, out g)) + { + data = g.ToByteArray(); + } + else + { + data = Convert.FromBase64String(s); + } + + SetToken(JsonToken.Bytes, data, false); + return data; + } + case JsonToken.Null: + case JsonToken.EndArray: + return null; + case JsonToken.Bytes: + if (ValueType == typeof(Guid)) + { + byte[] data = ((Guid)Value).ToByteArray(); + SetToken(JsonToken.Bytes, data, false); + return data; + } + + return (byte[])Value; + case JsonToken.StartArray: + return ReadArrayIntoByteArray(); + } + + throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t)); + } + + internal byte[] ReadArrayIntoByteArray() + { + List buffer = new List(); + + while (true) + { + JsonToken t = GetContentToken(); + switch (t) + { + case JsonToken.None: + throw JsonReaderException.Create(this, "Unexpected end when reading bytes."); + case JsonToken.Integer: + buffer.Add(Convert.ToByte(Value, CultureInfo.InvariantCulture)); + break; + case JsonToken.EndArray: + byte[] d = buffer.ToArray(); + SetToken(JsonToken.Bytes, d, false); + return d; + default: + throw JsonReaderException.Create(this, "Unexpected token when reading bytes: {0}.".FormatWith(CultureInfo.InvariantCulture, t)); + } + } + } + + /// + /// Reads the next JSON token from the stream as a . + /// + /// A . This method will return null at the end of an array. + public virtual double? ReadAsDouble() + { + JsonToken t = GetContentToken(); + + switch (t) + { + case JsonToken.None: + case JsonToken.Null: + case JsonToken.EndArray: + return null; + case JsonToken.Integer: + case JsonToken.Float: + if (!(Value is double)) + { + SetToken(JsonToken.Float, Convert.ToDouble(Value, CultureInfo.InvariantCulture), false); + } + + return (double) Value; + case JsonToken.String: + return ReadDoubleString((string) Value); + } + + throw JsonReaderException.Create(this, "Error reading double. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t)); + } + + internal double? ReadDoubleString(string s) + { + if (string.IsNullOrEmpty(s)) + { + SetToken(JsonToken.Null, null, false); + return null; + } + + double d; + if (double.TryParse(s, NumberStyles.Float | NumberStyles.AllowThousands, Culture, out d)) + { + SetToken(JsonToken.Float, d, false); + return d; + } + else + { + SetToken(JsonToken.String, s, false); + throw JsonReaderException.Create(this, "Could not convert string to double: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); + } + } + + /// + /// Reads the next JSON token from the stream as a . + /// + /// A . This method will return null at the end of an array. + public virtual bool? ReadAsBoolean() + { + JsonToken t = GetContentToken(); + + switch (t) + { + case JsonToken.None: + case JsonToken.Null: + case JsonToken.EndArray: + return null; + case JsonToken.Integer: + case JsonToken.Float: + bool b; +#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) + if (Value is BigInteger) + { + b = (BigInteger)Value != 0; + } + else +#endif + { + b = Convert.ToBoolean(Value, CultureInfo.InvariantCulture); + } + + SetToken(JsonToken.Boolean, b, false); + + return b; + case JsonToken.String: + return ReadBooleanString((string)Value); + case JsonToken.Boolean: + return (bool)Value; + } + + throw JsonReaderException.Create(this, "Error reading boolean. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t)); + } + + internal bool? ReadBooleanString(string s) + { + if (string.IsNullOrEmpty(s)) + { + SetToken(JsonToken.Null, null, false); + return null; + } + + bool b; + if (bool.TryParse(s, out b)) + { + SetToken(JsonToken.Boolean, b, false); + return b; + } + else + { + SetToken(JsonToken.String, s, false); + throw JsonReaderException.Create(this, "Could not convert string to boolean: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); + } + } + + /// + /// Reads the next JSON token from the stream as a . + /// + /// A . This method will return null at the end of an array. + public virtual decimal? ReadAsDecimal() + { + JsonToken t = GetContentToken(); + + switch (t) + { + case JsonToken.None: + case JsonToken.Null: + case JsonToken.EndArray: + return null; + case JsonToken.Integer: + case JsonToken.Float: + if (!(Value is decimal)) + { + SetToken(JsonToken.Float, Convert.ToDecimal(Value, CultureInfo.InvariantCulture), false); + } + + return (decimal)Value; + case JsonToken.String: + return ReadDecimalString((string)Value); + } + + throw JsonReaderException.Create(this, "Error reading decimal. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t)); + } + + internal decimal? ReadDecimalString(string s) + { + if (string.IsNullOrEmpty(s)) + { + SetToken(JsonToken.Null, null, false); + return null; + } + + decimal d; + if (decimal.TryParse(s, NumberStyles.Number, Culture, out d)) + { + SetToken(JsonToken.Float, d, false); + return d; + } + else + { + SetToken(JsonToken.String, s, false); + throw JsonReaderException.Create(this, "Could not convert string to decimal: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); + } + } + + /// + /// Reads the next JSON token from the stream as a . + /// + /// A . This method will return null at the end of an array. + public virtual DateTime? ReadAsDateTime() + { + switch (GetContentToken()) + { + case JsonToken.None: + case JsonToken.Null: + case JsonToken.EndArray: + return null; + case JsonToken.Date: +#if !NET20 + if (Value is DateTimeOffset) + { + SetToken(JsonToken.Date, ((DateTimeOffset)Value).DateTime, false); + } +#endif + + return (DateTime)Value; + case JsonToken.String: + string s = (string)Value; + return ReadDateTimeString(s); + } + + throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); + } + + internal DateTime? ReadDateTimeString(string s) + { + if (string.IsNullOrEmpty(s)) + { + SetToken(JsonToken.Null, null, false); + return null; + } + + DateTime dt; + if (DateTimeUtils.TryParseDateTime(s, DateTimeZoneHandling, _dateFormatString, Culture, out dt)) + { + dt = DateTimeUtils.EnsureDateTime(dt, DateTimeZoneHandling); + SetToken(JsonToken.Date, dt, false); + return dt; + } + + if (DateTime.TryParse(s, Culture, DateTimeStyles.RoundtripKind, out dt)) + { + dt = DateTimeUtils.EnsureDateTime(dt, DateTimeZoneHandling); + SetToken(JsonToken.Date, dt, false); + return dt; + } + + throw JsonReaderException.Create(this, "Could not convert string to DateTime: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); + } + +#if !NET20 + /// + /// Reads the next JSON token from the stream as a . + /// + /// A . This method will return null at the end of an array. + public virtual DateTimeOffset? ReadAsDateTimeOffset() + { + JsonToken t = GetContentToken(); + + switch (t) + { + case JsonToken.None: + case JsonToken.Null: + case JsonToken.EndArray: + return null; + case JsonToken.Date: + if (Value is DateTime) + { + SetToken(JsonToken.Date, new DateTimeOffset((DateTime)Value), false); + } + + return (DateTimeOffset)Value; + case JsonToken.String: + string s = (string)Value; + return ReadDateTimeOffsetString(s); + default: + throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t)); + } + } + + internal DateTimeOffset? ReadDateTimeOffsetString(string s) + { + if (string.IsNullOrEmpty(s)) + { + SetToken(JsonToken.Null, null, false); + return null; + } + + DateTimeOffset dt; + if (DateTimeUtils.TryParseDateTimeOffset(s, _dateFormatString, Culture, out dt)) + { + SetToken(JsonToken.Date, dt, false); + return dt; + } + + if (DateTimeOffset.TryParse(s, Culture, DateTimeStyles.RoundtripKind, out dt)) + { + SetToken(JsonToken.Date, dt, false); + return dt; + } + + SetToken(JsonToken.String, s, false); + throw JsonReaderException.Create(this, "Could not convert string to DateTimeOffset: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); + } +#endif + + internal void ReaderReadAndAssert() + { + if (!Read()) + { + throw CreateUnexpectedEndException(); + } + } + + internal JsonReaderException CreateUnexpectedEndException() + { + return JsonReaderException.Create(this, "Unexpected end when reading JSON."); + } + + internal void ReadIntoWrappedTypeObject() + { + ReaderReadAndAssert(); + if (Value.ToString() == JsonTypeReflector.TypePropertyName) + { + ReaderReadAndAssert(); + if (Value != null && Value.ToString().StartsWith("System.Byte[]", StringComparison.Ordinal)) + { + ReaderReadAndAssert(); + if (Value.ToString() == JsonTypeReflector.ValuePropertyName) + { + return; + } + } + } + + throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, JsonToken.StartObject)); + } + + /// + /// Skips the children of the current token. + /// + public void Skip() + { + if (TokenType == JsonToken.PropertyName) + { + Read(); + } + + if (JsonTokenUtils.IsStartToken(TokenType)) + { + int depth = Depth; + + while (Read() && (depth < Depth)) + { + } + } + } + + /// + /// Sets the current token. + /// + /// The new token. + protected void SetToken(JsonToken newToken) + { + SetToken(newToken, null, true); + } + + /// + /// Sets the current token and value. + /// + /// The new token. + /// The value. + protected void SetToken(JsonToken newToken, object value) + { + SetToken(newToken, value, true); + } + + internal void SetToken(JsonToken newToken, object value, bool updateIndex) + { + _tokenType = newToken; + _value = value; + + switch (newToken) + { + case JsonToken.StartObject: + _currentState = State.ObjectStart; + Push(JsonContainerType.Object); + break; + case JsonToken.StartArray: + _currentState = State.ArrayStart; + Push(JsonContainerType.Array); + break; + case JsonToken.StartConstructor: + _currentState = State.ConstructorStart; + Push(JsonContainerType.Constructor); + break; + case JsonToken.EndObject: + ValidateEnd(JsonToken.EndObject); + break; + case JsonToken.EndArray: + ValidateEnd(JsonToken.EndArray); + break; + case JsonToken.EndConstructor: + ValidateEnd(JsonToken.EndConstructor); + break; + case JsonToken.PropertyName: + _currentState = State.Property; + + _currentPosition.PropertyName = (string)value; + break; + case JsonToken.Undefined: + case JsonToken.Integer: + case JsonToken.Float: + case JsonToken.Boolean: + case JsonToken.Null: + case JsonToken.Date: + case JsonToken.String: + case JsonToken.Raw: + case JsonToken.Bytes: + SetPostValueState(updateIndex); + break; + } + } + + internal void SetPostValueState(bool updateIndex) + { + if (Peek() != JsonContainerType.None) + { + _currentState = State.PostValue; + } + else + { + SetFinished(); + } + + if (updateIndex) + { + UpdateScopeWithFinishedValue(); + } + } + + private void UpdateScopeWithFinishedValue() + { + if (_currentPosition.HasIndex) + { + _currentPosition.Position++; + } + } + + private void ValidateEnd(JsonToken endToken) + { + JsonContainerType currentObject = Pop(); + + if (GetTypeForCloseToken(endToken) != currentObject) + { + throw JsonReaderException.Create(this, "JsonToken {0} is not valid for closing JsonType {1}.".FormatWith(CultureInfo.InvariantCulture, endToken, currentObject)); + } + + if (Peek() != JsonContainerType.None) + { + _currentState = State.PostValue; + } + else + { + SetFinished(); + } + } + + /// + /// Sets the state based on current token type. + /// + protected void SetStateBasedOnCurrent() + { + JsonContainerType currentObject = Peek(); + + switch (currentObject) + { + case JsonContainerType.Object: + _currentState = State.Object; + break; + case JsonContainerType.Array: + _currentState = State.Array; + break; + case JsonContainerType.Constructor: + _currentState = State.Constructor; + break; + case JsonContainerType.None: + SetFinished(); + break; + default: + throw JsonReaderException.Create(this, "While setting the reader state back to current object an unexpected JsonType was encountered: {0}".FormatWith(CultureInfo.InvariantCulture, currentObject)); + } + } + + private void SetFinished() + { + if (SupportMultipleContent) + { + _currentState = State.Start; + } + else + { + _currentState = State.Finished; + } + } + + private JsonContainerType GetTypeForCloseToken(JsonToken token) + { + switch (token) + { + case JsonToken.EndObject: + return JsonContainerType.Object; + case JsonToken.EndArray: + return JsonContainerType.Array; + case JsonToken.EndConstructor: + return JsonContainerType.Constructor; + default: + throw JsonReaderException.Create(this, "Not a valid close JsonToken: {0}".FormatWith(CultureInfo.InvariantCulture, token)); + } + } + + /// + /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. + /// + void IDisposable.Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + /// + /// Releases unmanaged and - optionally - managed resources + /// + /// true to release both managed and unmanaged resources; false to release only unmanaged resources. + protected virtual void Dispose(bool disposing) + { + if (_currentState != State.Closed && disposing) + { + Close(); + } + } + + /// + /// Changes the to Closed. + /// + public virtual void Close() + { + _currentState = State.Closed; + _tokenType = JsonToken.None; + _value = null; + } + + internal void ReadAndAssert() + { + if (!Read()) + { + throw JsonSerializationException.Create(this, "Unexpected end when reading JSON."); + } + } + + internal bool ReadAndMoveToContent() + { + return Read() && MoveToContent(); + } + + internal bool MoveToContent() + { + JsonToken t = TokenType; + while (t == JsonToken.None || t == JsonToken.Comment) + { + if (!Read()) + { + return false; + } + + t = TokenType; + } + + return true; + } + + private JsonToken GetContentToken() + { + JsonToken t; + do + { + if (!Read()) + { + SetToken(JsonToken.None); + return JsonToken.None; + } + else + { + t = TokenType; + } + } while (t == JsonToken.Comment); + + return t; + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/JsonReaderException.cs b/Common/00-1Json8.3/Json8.3/JsonReaderException.cs new file mode 100644 index 0000000..9f448c4 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/JsonReaderException.cs @@ -0,0 +1,139 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Globalization; +using System.Runtime.Serialization; +using Newtonsoft.Json.Utilities; + +namespace Newtonsoft.Json +{ + /// + /// The exception thrown when an error occurs while reading JSON text. + /// +#if !(DOTNET || PORTABLE || PORTABLE40) + [Serializable] +#endif + public class JsonReaderException : JsonException + { + /// + /// Gets the line number indicating where the error occurred. + /// + /// The line number indicating where the error occurred. + public int LineNumber { get; private set; } + + /// + /// Gets the line position indicating where the error occurred. + /// + /// The line position indicating where the error occurred. + public int LinePosition { get; private set; } + + /// + /// Gets the path to the JSON where the error occurred. + /// + /// The path to the JSON where the error occurred. + public string Path { get; private set; } + + /// + /// Initializes a new instance of the class. + /// + public JsonReaderException() + { + } + + /// + /// Initializes a new instance of the class + /// with a specified error message. + /// + /// The error message that explains the reason for the exception. + public JsonReaderException(string message) + : base(message) + { + } + + /// + /// Initializes a new instance of the class + /// with a specified error message and a reference to the inner exception that is the cause of this exception. + /// + /// The error message that explains the reason for the exception. + /// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no inner exception is specified. + public JsonReaderException(string message, Exception innerException) + : base(message, innerException) + { + } + +#if !(DOTNET || PORTABLE40 || PORTABLE) + /// + /// Initializes a new instance of the class. + /// + /// The that holds the serialized object data about the exception being thrown. + /// The that contains contextual information about the source or destination. + /// The parameter is null. + /// The class name is null or is zero (0). + public JsonReaderException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } +#endif + + internal JsonReaderException(string message, Exception innerException, string path, int lineNumber, int linePosition) + : base(message, innerException) + { + Path = path; + LineNumber = lineNumber; + LinePosition = linePosition; + } + + internal static JsonReaderException Create(JsonReader reader, string message) + { + return Create(reader, message, null); + } + + internal static JsonReaderException Create(JsonReader reader, string message, Exception ex) + { + return Create(reader as IJsonLineInfo, reader.Path, message, ex); + } + + internal static JsonReaderException Create(IJsonLineInfo lineInfo, string path, string message, Exception ex) + { + message = JsonPosition.FormatMessage(lineInfo, path, message); + + int lineNumber; + int linePosition; + if (lineInfo != null && lineInfo.HasLineInfo()) + { + lineNumber = lineInfo.LineNumber; + linePosition = lineInfo.LinePosition; + } + else + { + lineNumber = 0; + linePosition = 0; + } + + return new JsonReaderException(message, ex, path, lineNumber, linePosition); + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/JsonRequiredAttribute.cs b/Common/00-1Json8.3/Json8.3/JsonRequiredAttribute.cs new file mode 100644 index 0000000..625a23a --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/JsonRequiredAttribute.cs @@ -0,0 +1,39 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Collections.Generic; +using System.Text; + +namespace Newtonsoft.Json +{ + /// + /// Instructs the to always serialize the member, and require the member has a value. + /// + [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false)] + public sealed class JsonRequiredAttribute : Attribute + { + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/JsonSerializationException.cs b/Common/00-1Json8.3/Json8.3/JsonSerializationException.cs new file mode 100644 index 0000000..1c872c7 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/JsonSerializationException.cs @@ -0,0 +1,100 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Collections.Generic; +using System.Runtime.Serialization; +using System.Text; + +namespace Newtonsoft.Json +{ + /// + /// The exception thrown when an error occurs during JSON serialization or deserialization. + /// +#if !(DOTNET || PORTABLE40 || PORTABLE) + [Serializable] +#endif + public class JsonSerializationException : JsonException + { + /// + /// Initializes a new instance of the class. + /// + public JsonSerializationException() + { + } + + /// + /// Initializes a new instance of the class + /// with a specified error message. + /// + /// The error message that explains the reason for the exception. + public JsonSerializationException(string message) + : base(message) + { + } + + /// + /// Initializes a new instance of the class + /// with a specified error message and a reference to the inner exception that is the cause of this exception. + /// + /// The error message that explains the reason for the exception. + /// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no inner exception is specified. + public JsonSerializationException(string message, Exception innerException) + : base(message, innerException) + { + } + +#if !(DOTNET || PORTABLE40 || PORTABLE) + /// + /// Initializes a new instance of the class. + /// + /// The that holds the serialized object data about the exception being thrown. + /// The that contains contextual information about the source or destination. + /// The parameter is null. + /// The class name is null or is zero (0). + public JsonSerializationException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } +#endif + + internal static JsonSerializationException Create(JsonReader reader, string message) + { + return Create(reader, message, null); + } + + internal static JsonSerializationException Create(JsonReader reader, string message, Exception ex) + { + return Create(reader as IJsonLineInfo, reader.Path, message, ex); + } + + internal static JsonSerializationException Create(IJsonLineInfo lineInfo, string path, string message, Exception ex) + { + message = JsonPosition.FormatMessage(lineInfo, path, message); + + return new JsonSerializationException(message, ex); + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/JsonSerializer.cs b/Common/00-1Json8.3/Json8.3/JsonSerializer.cs new file mode 100644 index 0000000..7540116 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/JsonSerializer.cs @@ -0,0 +1,1140 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Diagnostics; +using System.Globalization; +using System.IO; +using System.Runtime.Serialization.Formatters; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Serialization; +using Newtonsoft.Json.Utilities; +using System.Runtime.Serialization; +using ErrorEventArgs = Newtonsoft.Json.Serialization.ErrorEventArgs; + +namespace Newtonsoft.Json +{ + /// + /// Serializes and deserializes objects into and from the JSON format. + /// The enables you to control how objects are encoded into JSON. + /// + public class JsonSerializer + { + internal TypeNameHandling _typeNameHandling; + internal FormatterAssemblyStyle _typeNameAssemblyFormat; + internal PreserveReferencesHandling _preserveReferencesHandling; + internal ReferenceLoopHandling _referenceLoopHandling; + internal MissingMemberHandling _missingMemberHandling; + internal ObjectCreationHandling _objectCreationHandling; + internal NullValueHandling _nullValueHandling; + internal DefaultValueHandling _defaultValueHandling; + internal ConstructorHandling _constructorHandling; + internal MetadataPropertyHandling _metadataPropertyHandling; + internal JsonConverterCollection _converters; + internal IContractResolver _contractResolver; + internal ITraceWriter _traceWriter; + internal IEqualityComparer _equalityComparer; + internal SerializationBinder _binder; + internal StreamingContext _context; + private IReferenceResolver _referenceResolver; + + private Formatting? _formatting; + private DateFormatHandling? _dateFormatHandling; + private DateTimeZoneHandling? _dateTimeZoneHandling; + private DateParseHandling? _dateParseHandling; + private FloatFormatHandling? _floatFormatHandling; + private FloatParseHandling? _floatParseHandling; + private StringEscapeHandling? _stringEscapeHandling; + private CultureInfo _culture; + private int? _maxDepth; + private bool _maxDepthSet; + private bool? _checkAdditionalContent; + private string _dateFormatString; + private bool _dateFormatStringSet; + + /// + /// Occurs when the errors during serialization and deserialization. + /// + public virtual event EventHandler Error; + + /// + /// Gets or sets the used by the serializer when resolving references. + /// + public virtual IReferenceResolver ReferenceResolver + { + get { return GetReferenceResolver(); } + set + { + if (value == null) + { + throw new ArgumentNullException(nameof(value), "Reference resolver cannot be null."); + } + + _referenceResolver = value; + } + } + + /// + /// Gets or sets the used by the serializer when resolving type names. + /// + public virtual SerializationBinder Binder + { + get { return _binder; } + set + { + if (value == null) + { + throw new ArgumentNullException(nameof(value), "Serialization binder cannot be null."); + } + + _binder = value; + } + } + + /// + /// Gets or sets the used by the serializer when writing trace messages. + /// + /// The trace writer. + public virtual ITraceWriter TraceWriter + { + get { return _traceWriter; } + set { _traceWriter = value; } + } + + /// + /// Gets or sets the equality comparer used by the serializer when comparing references. + /// + /// The equality comparer. + public virtual IEqualityComparer EqualityComparer + { + get { return _equalityComparer; } + set { _equalityComparer = value; } + } + + /// + /// Gets or sets how type name writing and reading is handled by the serializer. + /// + /// + /// should be used with caution when your application deserializes JSON from an external source. + /// Incoming types should be validated with a custom + /// when deserializing with a value other than TypeNameHandling.None. + /// + public virtual TypeNameHandling TypeNameHandling + { + get { return _typeNameHandling; } + set + { + if (value < TypeNameHandling.None || value > TypeNameHandling.Auto) + { + throw new ArgumentOutOfRangeException(nameof(value)); + } + + _typeNameHandling = value; + } + } + + /// + /// Gets or sets how a type name assembly is written and resolved by the serializer. + /// + /// The type name assembly format. + public virtual FormatterAssemblyStyle TypeNameAssemblyFormat + { + get { return _typeNameAssemblyFormat; } + set + { + if (value < FormatterAssemblyStyle.Simple || value > FormatterAssemblyStyle.Full) + { + throw new ArgumentOutOfRangeException(nameof(value)); + } + + _typeNameAssemblyFormat = value; + } + } + + /// + /// Gets or sets how object references are preserved by the serializer. + /// + public virtual PreserveReferencesHandling PreserveReferencesHandling + { + get { return _preserveReferencesHandling; } + set + { + if (value < PreserveReferencesHandling.None || value > PreserveReferencesHandling.All) + { + throw new ArgumentOutOfRangeException(nameof(value)); + } + + _preserveReferencesHandling = value; + } + } + + /// + /// Get or set how reference loops (e.g. a class referencing itself) is handled. + /// + public virtual ReferenceLoopHandling ReferenceLoopHandling + { + get { return _referenceLoopHandling; } + set + { + if (value < ReferenceLoopHandling.Error || value > ReferenceLoopHandling.Serialize) + { + throw new ArgumentOutOfRangeException(nameof(value)); + } + + _referenceLoopHandling = value; + } + } + + /// + /// Get or set how missing members (e.g. JSON contains a property that isn't a member on the object) are handled during deserialization. + /// + public virtual MissingMemberHandling MissingMemberHandling + { + get { return _missingMemberHandling; } + set + { + if (value < MissingMemberHandling.Ignore || value > MissingMemberHandling.Error) + { + throw new ArgumentOutOfRangeException(nameof(value)); + } + + _missingMemberHandling = value; + } + } + + /// + /// Get or set how null values are handled during serialization and deserialization. + /// + public virtual NullValueHandling NullValueHandling + { + get { return _nullValueHandling; } + set + { + if (value < NullValueHandling.Include || value > NullValueHandling.Ignore) + { + throw new ArgumentOutOfRangeException(nameof(value)); + } + + _nullValueHandling = value; + } + } + + /// + /// Get or set how null default are handled during serialization and deserialization. + /// + public virtual DefaultValueHandling DefaultValueHandling + { + get { return _defaultValueHandling; } + set + { + if (value < DefaultValueHandling.Include || value > DefaultValueHandling.IgnoreAndPopulate) + { + throw new ArgumentOutOfRangeException(nameof(value)); + } + + _defaultValueHandling = value; + } + } + + /// + /// Gets or sets how objects are created during deserialization. + /// + /// The object creation handling. + public virtual ObjectCreationHandling ObjectCreationHandling + { + get { return _objectCreationHandling; } + set + { + if (value < ObjectCreationHandling.Auto || value > ObjectCreationHandling.Replace) + { + throw new ArgumentOutOfRangeException(nameof(value)); + } + + _objectCreationHandling = value; + } + } + + /// + /// Gets or sets how constructors are used during deserialization. + /// + /// The constructor handling. + public virtual ConstructorHandling ConstructorHandling + { + get { return _constructorHandling; } + set + { + if (value < ConstructorHandling.Default || value > ConstructorHandling.AllowNonPublicDefaultConstructor) + { + throw new ArgumentOutOfRangeException(nameof(value)); + } + + _constructorHandling = value; + } + } + + /// + /// Gets or sets how metadata properties are used during deserialization. + /// + /// The metadata properties handling. + public virtual MetadataPropertyHandling MetadataPropertyHandling + { + get { return _metadataPropertyHandling; } + set + { + if (value < MetadataPropertyHandling.Default || value > MetadataPropertyHandling.Ignore) + { + throw new ArgumentOutOfRangeException(nameof(value)); + } + + _metadataPropertyHandling = value; + } + } + + /// + /// Gets a collection that will be used during serialization. + /// + /// Collection that will be used during serialization. + public virtual JsonConverterCollection Converters + { + get + { + if (_converters == null) + { + _converters = new JsonConverterCollection(); + } + + return _converters; + } + } + + /// + /// Gets or sets the contract resolver used by the serializer when + /// serializing .NET objects to JSON and vice versa. + /// + public virtual IContractResolver ContractResolver + { + get { return _contractResolver; } + set { _contractResolver = value ?? DefaultContractResolver.Instance; } + } + + /// + /// Gets or sets the used by the serializer when invoking serialization callback methods. + /// + /// The context. + public virtual StreamingContext Context + { + get { return _context; } + set { _context = value; } + } + + /// + /// Indicates how JSON text output is formatted. + /// + public virtual Formatting Formatting + { + get { return _formatting ?? JsonSerializerSettings.DefaultFormatting; } + set { _formatting = value; } + } + + /// + /// Get or set how dates are written to JSON text. + /// + public virtual DateFormatHandling DateFormatHandling + { + get { return _dateFormatHandling ?? JsonSerializerSettings.DefaultDateFormatHandling; } + set { _dateFormatHandling = value; } + } + + /// + /// Get or set how time zones are handling during serialization and deserialization. + /// + public virtual DateTimeZoneHandling DateTimeZoneHandling + { + get { return _dateTimeZoneHandling ?? JsonSerializerSettings.DefaultDateTimeZoneHandling; } + set { _dateTimeZoneHandling = value; } + } + + /// + /// Get or set how date formatted strings, e.g. "\/Date(1198908717056)\/" and "2012-03-21T05:40Z", are parsed when reading JSON. + /// + public virtual DateParseHandling DateParseHandling + { + get { return _dateParseHandling ?? JsonSerializerSettings.DefaultDateParseHandling; } + set { _dateParseHandling = value; } + } + + /// + /// Get or set how floating point numbers, e.g. 1.0 and 9.9, are parsed when reading JSON text. + /// + public virtual FloatParseHandling FloatParseHandling + { + get { return _floatParseHandling ?? JsonSerializerSettings.DefaultFloatParseHandling; } + set { _floatParseHandling = value; } + } + + /// + /// Get or set how special floating point numbers, e.g. , + /// and , + /// are written as JSON text. + /// + public virtual FloatFormatHandling FloatFormatHandling + { + get { return _floatFormatHandling ?? JsonSerializerSettings.DefaultFloatFormatHandling; } + set { _floatFormatHandling = value; } + } + + /// + /// Get or set how strings are escaped when writing JSON text. + /// + public virtual StringEscapeHandling StringEscapeHandling + { + get { return _stringEscapeHandling ?? JsonSerializerSettings.DefaultStringEscapeHandling; } + set { _stringEscapeHandling = value; } + } + + /// + /// Get or set how and values are formatted when writing JSON text, and the expected date format when reading JSON text. + /// + public virtual string DateFormatString + { + get { return _dateFormatString ?? JsonSerializerSettings.DefaultDateFormatString; } + set + { + _dateFormatString = value; + _dateFormatStringSet = true; + } + } + + /// + /// Gets or sets the culture used when reading JSON. Defaults to . + /// + public virtual CultureInfo Culture + { + get { return _culture ?? JsonSerializerSettings.DefaultCulture; } + set { _culture = value; } + } + + /// + /// Gets or sets the maximum depth allowed when reading JSON. Reading past this depth will throw a . + /// + public virtual int? MaxDepth + { + get { return _maxDepth; } + set + { + if (value <= 0) + { + throw new ArgumentException("Value must be positive.", nameof(value)); + } + + _maxDepth = value; + _maxDepthSet = true; + } + } + + /// + /// Gets a value indicating whether there will be a check for additional JSON content after deserializing an object. + /// + /// + /// true if there will be a check for additional JSON content after deserializing an object; otherwise, false. + /// + public virtual bool CheckAdditionalContent + { + get { return _checkAdditionalContent ?? JsonSerializerSettings.DefaultCheckAdditionalContent; } + set { _checkAdditionalContent = value; } + } + + internal bool IsCheckAdditionalContentSet() + { + return (_checkAdditionalContent != null); + } + + /// + /// Initializes a new instance of the class. + /// + public JsonSerializer() + { + _referenceLoopHandling = JsonSerializerSettings.DefaultReferenceLoopHandling; + _missingMemberHandling = JsonSerializerSettings.DefaultMissingMemberHandling; + _nullValueHandling = JsonSerializerSettings.DefaultNullValueHandling; + _defaultValueHandling = JsonSerializerSettings.DefaultDefaultValueHandling; + _objectCreationHandling = JsonSerializerSettings.DefaultObjectCreationHandling; + _preserveReferencesHandling = JsonSerializerSettings.DefaultPreserveReferencesHandling; + _constructorHandling = JsonSerializerSettings.DefaultConstructorHandling; + _typeNameHandling = JsonSerializerSettings.DefaultTypeNameHandling; + _metadataPropertyHandling = JsonSerializerSettings.DefaultMetadataPropertyHandling; + _context = JsonSerializerSettings.DefaultContext; + _binder = DefaultSerializationBinder.Instance; + + _culture = JsonSerializerSettings.DefaultCulture; + _contractResolver = DefaultContractResolver.Instance; + } + + /// + /// Creates a new instance. + /// The will not use default settings + /// from . + /// + /// + /// A new instance. + /// The will not use default settings + /// from . + /// + public static JsonSerializer Create() + { + return new JsonSerializer(); + } + + /// + /// Creates a new instance using the specified . + /// The will not use default settings + /// from . + /// + /// The settings to be applied to the . + /// + /// A new instance using the specified . + /// The will not use default settings + /// from . + /// + public static JsonSerializer Create(JsonSerializerSettings settings) + { + JsonSerializer serializer = Create(); + + if (settings != null) + { + ApplySerializerSettings(serializer, settings); + } + + return serializer; + } + + /// + /// Creates a new instance. + /// The will use default settings + /// from . + /// + /// + /// A new instance. + /// The will use default settings + /// from . + /// + public static JsonSerializer CreateDefault() + { + // copy static to local variable to avoid concurrency issues + Func defaultSettingsCreator = JsonConvert.DefaultSettings; + JsonSerializerSettings defaultSettings = (defaultSettingsCreator != null) ? defaultSettingsCreator() : null; + + return Create(defaultSettings); + } + + /// + /// Creates a new instance using the specified . + /// The will use default settings + /// from as well as the specified . + /// + /// The settings to be applied to the . + /// + /// A new instance using the specified . + /// The will use default settings + /// from as well as the specified . + /// + public static JsonSerializer CreateDefault(JsonSerializerSettings settings) + { + JsonSerializer serializer = CreateDefault(); + if (settings != null) + { + ApplySerializerSettings(serializer, settings); + } + + return serializer; + } + + private static void ApplySerializerSettings(JsonSerializer serializer, JsonSerializerSettings settings) + { + if (!CollectionUtils.IsNullOrEmpty(settings.Converters)) + { + // insert settings converters at the beginning so they take precedence + // if user wants to remove one of the default converters they will have to do it manually + for (int i = 0; i < settings.Converters.Count; i++) + { + serializer.Converters.Insert(i, settings.Converters[i]); + } + } + + // serializer specific + if (settings._typeNameHandling != null) + { + serializer.TypeNameHandling = settings.TypeNameHandling; + } + if (settings._metadataPropertyHandling != null) + { + serializer.MetadataPropertyHandling = settings.MetadataPropertyHandling; + } + if (settings._typeNameAssemblyFormat != null) + { + serializer.TypeNameAssemblyFormat = settings.TypeNameAssemblyFormat; + } + if (settings._preserveReferencesHandling != null) + { + serializer.PreserveReferencesHandling = settings.PreserveReferencesHandling; + } + if (settings._referenceLoopHandling != null) + { + serializer.ReferenceLoopHandling = settings.ReferenceLoopHandling; + } + if (settings._missingMemberHandling != null) + { + serializer.MissingMemberHandling = settings.MissingMemberHandling; + } + if (settings._objectCreationHandling != null) + { + serializer.ObjectCreationHandling = settings.ObjectCreationHandling; + } + if (settings._nullValueHandling != null) + { + serializer.NullValueHandling = settings.NullValueHandling; + } + if (settings._defaultValueHandling != null) + { + serializer.DefaultValueHandling = settings.DefaultValueHandling; + } + if (settings._constructorHandling != null) + { + serializer.ConstructorHandling = settings.ConstructorHandling; + } + if (settings._context != null) + { + serializer.Context = settings.Context; + } + if (settings._checkAdditionalContent != null) + { + serializer._checkAdditionalContent = settings._checkAdditionalContent; + } + + if (settings.Error != null) + { + serializer.Error += settings.Error; + } + + if (settings.ContractResolver != null) + { + serializer.ContractResolver = settings.ContractResolver; + } + if (settings.ReferenceResolverProvider != null) + { + serializer.ReferenceResolver = settings.ReferenceResolverProvider(); + } + if (settings.TraceWriter != null) + { + serializer.TraceWriter = settings.TraceWriter; + } + if (settings.EqualityComparer != null) + { + serializer.EqualityComparer = settings.EqualityComparer; + } + if (settings.Binder != null) + { + serializer.Binder = settings.Binder; + } + + // reader/writer specific + // unset values won't override reader/writer set values + if (settings._formatting != null) + { + serializer._formatting = settings._formatting; + } + if (settings._dateFormatHandling != null) + { + serializer._dateFormatHandling = settings._dateFormatHandling; + } + if (settings._dateTimeZoneHandling != null) + { + serializer._dateTimeZoneHandling = settings._dateTimeZoneHandling; + } + if (settings._dateParseHandling != null) + { + serializer._dateParseHandling = settings._dateParseHandling; + } + if (settings._dateFormatStringSet) + { + serializer._dateFormatString = settings._dateFormatString; + serializer._dateFormatStringSet = settings._dateFormatStringSet; + } + if (settings._floatFormatHandling != null) + { + serializer._floatFormatHandling = settings._floatFormatHandling; + } + if (settings._floatParseHandling != null) + { + serializer._floatParseHandling = settings._floatParseHandling; + } + if (settings._stringEscapeHandling != null) + { + serializer._stringEscapeHandling = settings._stringEscapeHandling; + } + if (settings._culture != null) + { + serializer._culture = settings._culture; + } + if (settings._maxDepthSet) + { + serializer._maxDepth = settings._maxDepth; + serializer._maxDepthSet = settings._maxDepthSet; + } + } + + /// + /// Populates the JSON values onto the target object. + /// + /// The that contains the JSON structure to reader values from. + /// The target object to populate values onto. + public void Populate(TextReader reader, object target) + { + Populate(new JsonTextReader(reader), target); + } + + /// + /// Populates the JSON values onto the target object. + /// + /// The that contains the JSON structure to reader values from. + /// The target object to populate values onto. + public void Populate(JsonReader reader, object target) + { + PopulateInternal(reader, target); + } + + internal virtual void PopulateInternal(JsonReader reader, object target) + { + ValidationUtils.ArgumentNotNull(reader, nameof(reader)); + ValidationUtils.ArgumentNotNull(target, nameof(target)); + + // set serialization options onto reader + CultureInfo previousCulture; + DateTimeZoneHandling? previousDateTimeZoneHandling; + DateParseHandling? previousDateParseHandling; + FloatParseHandling? previousFloatParseHandling; + int? previousMaxDepth; + string previousDateFormatString; + SetupReader(reader, out previousCulture, out previousDateTimeZoneHandling, out previousDateParseHandling, out previousFloatParseHandling, out previousMaxDepth, out previousDateFormatString); + + TraceJsonReader traceJsonReader = (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) + ? new TraceJsonReader(reader) + : null; + + JsonSerializerInternalReader serializerReader = new JsonSerializerInternalReader(this); + serializerReader.Populate(traceJsonReader ?? reader, target); + + if (traceJsonReader != null) + { + TraceWriter.Trace(TraceLevel.Verbose, traceJsonReader.GetDeserializedJsonMessage(), null); + } + + ResetReader(reader, previousCulture, previousDateTimeZoneHandling, previousDateParseHandling, previousFloatParseHandling, previousMaxDepth, previousDateFormatString); + } + + /// + /// Deserializes the JSON structure contained by the specified . + /// + /// The that contains the JSON structure to deserialize. + /// The being deserialized. + public object Deserialize(JsonReader reader) + { + return Deserialize(reader, null); + } + + /// + /// Deserializes the JSON structure contained by the specified + /// into an instance of the specified type. + /// + /// The containing the object. + /// The of object being deserialized. + /// The instance of being deserialized. + public object Deserialize(TextReader reader, Type objectType) + { + return Deserialize(new JsonTextReader(reader), objectType); + } + + /// + /// Deserializes the JSON structure contained by the specified + /// into an instance of the specified type. + /// + /// The containing the object. + /// The type of the object to deserialize. + /// The instance of being deserialized. + public T Deserialize(JsonReader reader) + { + return (T)Deserialize(reader, typeof(T)); + } + + /// + /// Deserializes the JSON structure contained by the specified + /// into an instance of the specified type. + /// + /// The containing the object. + /// The of object being deserialized. + /// The instance of being deserialized. + public object Deserialize(JsonReader reader, Type objectType) + { + return DeserializeInternal(reader, objectType); + } + + internal virtual object DeserializeInternal(JsonReader reader, Type objectType) + { + ValidationUtils.ArgumentNotNull(reader, nameof(reader)); + + // set serialization options onto reader + CultureInfo previousCulture; + DateTimeZoneHandling? previousDateTimeZoneHandling; + DateParseHandling? previousDateParseHandling; + FloatParseHandling? previousFloatParseHandling; + int? previousMaxDepth; + string previousDateFormatString; + SetupReader(reader, out previousCulture, out previousDateTimeZoneHandling, out previousDateParseHandling, out previousFloatParseHandling, out previousMaxDepth, out previousDateFormatString); + + TraceJsonReader traceJsonReader = (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) + ? new TraceJsonReader(reader) + : null; + + JsonSerializerInternalReader serializerReader = new JsonSerializerInternalReader(this); + object value = serializerReader.Deserialize(traceJsonReader ?? reader, objectType, CheckAdditionalContent); + + if (traceJsonReader != null) + { + TraceWriter.Trace(TraceLevel.Verbose, traceJsonReader.GetDeserializedJsonMessage(), null); + } + + ResetReader(reader, previousCulture, previousDateTimeZoneHandling, previousDateParseHandling, previousFloatParseHandling, previousMaxDepth, previousDateFormatString); + + return value; + } + + private void SetupReader(JsonReader reader, out CultureInfo previousCulture, out DateTimeZoneHandling? previousDateTimeZoneHandling, out DateParseHandling? previousDateParseHandling, out FloatParseHandling? previousFloatParseHandling, out int? previousMaxDepth, out string previousDateFormatString) + { + if (_culture != null && !_culture.Equals(reader.Culture)) + { + previousCulture = reader.Culture; + reader.Culture = _culture; + } + else + { + previousCulture = null; + } + + if (_dateTimeZoneHandling != null && reader.DateTimeZoneHandling != _dateTimeZoneHandling) + { + previousDateTimeZoneHandling = reader.DateTimeZoneHandling; + reader.DateTimeZoneHandling = _dateTimeZoneHandling.GetValueOrDefault(); + } + else + { + previousDateTimeZoneHandling = null; + } + + if (_dateParseHandling != null && reader.DateParseHandling != _dateParseHandling) + { + previousDateParseHandling = reader.DateParseHandling; + reader.DateParseHandling = _dateParseHandling.GetValueOrDefault(); + } + else + { + previousDateParseHandling = null; + } + + if (_floatParseHandling != null && reader.FloatParseHandling != _floatParseHandling) + { + previousFloatParseHandling = reader.FloatParseHandling; + reader.FloatParseHandling = _floatParseHandling.GetValueOrDefault(); + } + else + { + previousFloatParseHandling = null; + } + + if (_maxDepthSet && reader.MaxDepth != _maxDepth) + { + previousMaxDepth = reader.MaxDepth; + reader.MaxDepth = _maxDepth; + } + else + { + previousMaxDepth = null; + } + + if (_dateFormatStringSet && reader.DateFormatString != _dateFormatString) + { + previousDateFormatString = reader.DateFormatString; + reader.DateFormatString = _dateFormatString; + } + else + { + previousDateFormatString = null; + } + + JsonTextReader textReader = reader as JsonTextReader; + if (textReader != null) + { + DefaultContractResolver resolver = _contractResolver as DefaultContractResolver; + if (resolver != null) + { + textReader.NameTable = resolver.GetState().NameTable; + } + } + } + + private void ResetReader(JsonReader reader, CultureInfo previousCulture, DateTimeZoneHandling? previousDateTimeZoneHandling, DateParseHandling? previousDateParseHandling, FloatParseHandling? previousFloatParseHandling, int? previousMaxDepth, string previousDateFormatString) + { + // reset reader back to previous options + if (previousCulture != null) + { + reader.Culture = previousCulture; + } + if (previousDateTimeZoneHandling != null) + { + reader.DateTimeZoneHandling = previousDateTimeZoneHandling.GetValueOrDefault(); + } + if (previousDateParseHandling != null) + { + reader.DateParseHandling = previousDateParseHandling.GetValueOrDefault(); + } + if (previousFloatParseHandling != null) + { + reader.FloatParseHandling = previousFloatParseHandling.GetValueOrDefault(); + } + if (_maxDepthSet) + { + reader.MaxDepth = previousMaxDepth; + } + if (_dateFormatStringSet) + { + reader.DateFormatString = previousDateFormatString; + } + + JsonTextReader textReader = reader as JsonTextReader; + if (textReader != null) + { + textReader.NameTable = null; + } + } + + /// + /// Serializes the specified and writes the JSON structure + /// to a Stream using the specified . + /// + /// The used to write the JSON structure. + /// The to serialize. + public void Serialize(TextWriter textWriter, object value) + { + Serialize(new JsonTextWriter(textWriter), value); + } + + /// + /// Serializes the specified and writes the JSON structure + /// to a Stream using the specified . + /// + /// The used to write the JSON structure. + /// The to serialize. + /// + /// The type of the value being serialized. + /// This parameter is used when is Auto to write out the type name if the type of the value does not match. + /// Specifing the type is optional. + /// + public void Serialize(JsonWriter jsonWriter, object value, Type objectType) + { + SerializeInternal(jsonWriter, value, objectType); + } + + /// + /// Serializes the specified and writes the JSON structure + /// to a Stream using the specified . + /// + /// The used to write the JSON structure. + /// The to serialize. + /// + /// The type of the value being serialized. + /// This parameter is used when is Auto to write out the type name if the type of the value does not match. + /// Specifing the type is optional. + /// + public void Serialize(TextWriter textWriter, object value, Type objectType) + { + Serialize(new JsonTextWriter(textWriter), value, objectType); + } + + /// + /// Serializes the specified and writes the JSON structure + /// to a Stream using the specified . + /// + /// The used to write the JSON structure. + /// The to serialize. + public void Serialize(JsonWriter jsonWriter, object value) + { + SerializeInternal(jsonWriter, value, null); + } + + internal virtual void SerializeInternal(JsonWriter jsonWriter, object value, Type objectType) + { + ValidationUtils.ArgumentNotNull(jsonWriter, nameof(jsonWriter)); + + // set serialization options onto writer + Formatting? previousFormatting = null; + if (_formatting != null && jsonWriter.Formatting != _formatting) + { + previousFormatting = jsonWriter.Formatting; + jsonWriter.Formatting = _formatting.GetValueOrDefault(); + } + + DateFormatHandling? previousDateFormatHandling = null; + if (_dateFormatHandling != null && jsonWriter.DateFormatHandling != _dateFormatHandling) + { + previousDateFormatHandling = jsonWriter.DateFormatHandling; + jsonWriter.DateFormatHandling = _dateFormatHandling.GetValueOrDefault(); + } + + DateTimeZoneHandling? previousDateTimeZoneHandling = null; + if (_dateTimeZoneHandling != null && jsonWriter.DateTimeZoneHandling != _dateTimeZoneHandling) + { + previousDateTimeZoneHandling = jsonWriter.DateTimeZoneHandling; + jsonWriter.DateTimeZoneHandling = _dateTimeZoneHandling.GetValueOrDefault(); + } + + FloatFormatHandling? previousFloatFormatHandling = null; + if (_floatFormatHandling != null && jsonWriter.FloatFormatHandling != _floatFormatHandling) + { + previousFloatFormatHandling = jsonWriter.FloatFormatHandling; + jsonWriter.FloatFormatHandling = _floatFormatHandling.GetValueOrDefault(); + } + + StringEscapeHandling? previousStringEscapeHandling = null; + if (_stringEscapeHandling != null && jsonWriter.StringEscapeHandling != _stringEscapeHandling) + { + previousStringEscapeHandling = jsonWriter.StringEscapeHandling; + jsonWriter.StringEscapeHandling = _stringEscapeHandling.GetValueOrDefault(); + } + + CultureInfo previousCulture = null; + if (_culture != null && !_culture.Equals(jsonWriter.Culture)) + { + previousCulture = jsonWriter.Culture; + jsonWriter.Culture = _culture; + } + + string previousDateFormatString = null; + if (_dateFormatStringSet && jsonWriter.DateFormatString != _dateFormatString) + { + previousDateFormatString = jsonWriter.DateFormatString; + jsonWriter.DateFormatString = _dateFormatString; + } + + TraceJsonWriter traceJsonWriter = (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) + ? new TraceJsonWriter(jsonWriter) + : null; + + JsonSerializerInternalWriter serializerWriter = new JsonSerializerInternalWriter(this); + serializerWriter.Serialize(traceJsonWriter ?? jsonWriter, value, objectType); + + if (traceJsonWriter != null) + { + TraceWriter.Trace(TraceLevel.Verbose, traceJsonWriter.GetSerializedJsonMessage(), null); + } + + // reset writer back to previous options + if (previousFormatting != null) + { + jsonWriter.Formatting = previousFormatting.GetValueOrDefault(); + } + if (previousDateFormatHandling != null) + { + jsonWriter.DateFormatHandling = previousDateFormatHandling.GetValueOrDefault(); + } + if (previousDateTimeZoneHandling != null) + { + jsonWriter.DateTimeZoneHandling = previousDateTimeZoneHandling.GetValueOrDefault(); + } + if (previousFloatFormatHandling != null) + { + jsonWriter.FloatFormatHandling = previousFloatFormatHandling.GetValueOrDefault(); + } + if (previousStringEscapeHandling != null) + { + jsonWriter.StringEscapeHandling = previousStringEscapeHandling.GetValueOrDefault(); + } + if (_dateFormatStringSet) + { + jsonWriter.DateFormatString = previousDateFormatString; + } + if (previousCulture != null) + { + jsonWriter.Culture = previousCulture; + } + } + + internal IReferenceResolver GetReferenceResolver() + { + if (_referenceResolver == null) + { + _referenceResolver = new DefaultReferenceResolver(); + } + + return _referenceResolver; + } + + internal JsonConverter GetMatchingConverter(Type type) + { + return GetMatchingConverter(_converters, type); + } + + internal static JsonConverter GetMatchingConverter(IList converters, Type objectType) + { +#if DEBUG + ValidationUtils.ArgumentNotNull(objectType, nameof(objectType)); +#endif + + if (converters != null) + { + for (int i = 0; i < converters.Count; i++) + { + JsonConverter converter = converters[i]; + + if (converter.CanConvert(objectType)) + { + return converter; + } + } + } + + return null; + } + + internal void OnError(ErrorEventArgs e) + { + EventHandler error = Error; + if (error != null) + { + error(this, e); + } + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/JsonSerializerSettings.cs b/Common/00-1Json8.3/Json8.3/JsonSerializerSettings.cs new file mode 100644 index 0000000..d3b9b49 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/JsonSerializerSettings.cs @@ -0,0 +1,403 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Globalization; +using System.Runtime.Serialization.Formatters; +using Newtonsoft.Json.Serialization; +using System.Runtime.Serialization; + +namespace Newtonsoft.Json +{ + /// + /// Specifies the settings on a object. + /// + public class JsonSerializerSettings + { + internal const ReferenceLoopHandling DefaultReferenceLoopHandling = ReferenceLoopHandling.Error; + internal const MissingMemberHandling DefaultMissingMemberHandling = MissingMemberHandling.Ignore; + internal const NullValueHandling DefaultNullValueHandling = NullValueHandling.Include; + internal const DefaultValueHandling DefaultDefaultValueHandling = DefaultValueHandling.Include; + internal const ObjectCreationHandling DefaultObjectCreationHandling = ObjectCreationHandling.Auto; + internal const PreserveReferencesHandling DefaultPreserveReferencesHandling = PreserveReferencesHandling.None; + internal const ConstructorHandling DefaultConstructorHandling = ConstructorHandling.Default; + internal const TypeNameHandling DefaultTypeNameHandling = TypeNameHandling.None; + internal const MetadataPropertyHandling DefaultMetadataPropertyHandling = MetadataPropertyHandling.Default; + internal const FormatterAssemblyStyle DefaultTypeNameAssemblyFormat = FormatterAssemblyStyle.Simple; + internal static readonly StreamingContext DefaultContext; + + internal const Formatting DefaultFormatting = Formatting.None; + internal const DateFormatHandling DefaultDateFormatHandling = DateFormatHandling.IsoDateFormat; + internal const DateTimeZoneHandling DefaultDateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind; + internal const DateParseHandling DefaultDateParseHandling = DateParseHandling.DateTime; + internal const FloatParseHandling DefaultFloatParseHandling = FloatParseHandling.Double; + internal const FloatFormatHandling DefaultFloatFormatHandling = FloatFormatHandling.String; + internal const StringEscapeHandling DefaultStringEscapeHandling = StringEscapeHandling.Default; + internal const FormatterAssemblyStyle DefaultFormatterAssemblyStyle = FormatterAssemblyStyle.Simple; + internal static readonly CultureInfo DefaultCulture; + internal const bool DefaultCheckAdditionalContent = false; + internal const string DefaultDateFormatString = @"yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK"; + + internal Formatting? _formatting; + internal DateFormatHandling? _dateFormatHandling; + internal DateTimeZoneHandling? _dateTimeZoneHandling; + internal DateParseHandling? _dateParseHandling; + internal FloatFormatHandling? _floatFormatHandling; + internal FloatParseHandling? _floatParseHandling; + internal StringEscapeHandling? _stringEscapeHandling; + internal CultureInfo _culture; + internal bool? _checkAdditionalContent; + internal int? _maxDepth; + internal bool _maxDepthSet; + internal string _dateFormatString; + internal bool _dateFormatStringSet; + internal FormatterAssemblyStyle? _typeNameAssemblyFormat; + internal DefaultValueHandling? _defaultValueHandling; + internal PreserveReferencesHandling? _preserveReferencesHandling; + internal NullValueHandling? _nullValueHandling; + internal ObjectCreationHandling? _objectCreationHandling; + internal MissingMemberHandling? _missingMemberHandling; + internal ReferenceLoopHandling? _referenceLoopHandling; + internal StreamingContext? _context; + internal ConstructorHandling? _constructorHandling; + internal TypeNameHandling? _typeNameHandling; + internal MetadataPropertyHandling? _metadataPropertyHandling; + + /// + /// Gets or sets how reference loops (e.g. a class referencing itself) is handled. + /// + /// Reference loop handling. + public ReferenceLoopHandling ReferenceLoopHandling + { + get { return _referenceLoopHandling ?? DefaultReferenceLoopHandling; } + set { _referenceLoopHandling = value; } + } + + /// + /// Gets or sets how missing members (e.g. JSON contains a property that isn't a member on the object) are handled during deserialization. + /// + /// Missing member handling. + public MissingMemberHandling MissingMemberHandling + { + get { return _missingMemberHandling ?? DefaultMissingMemberHandling; } + set { _missingMemberHandling = value; } + } + + /// + /// Gets or sets how objects are created during deserialization. + /// + /// The object creation handling. + public ObjectCreationHandling ObjectCreationHandling + { + get { return _objectCreationHandling ?? DefaultObjectCreationHandling; } + set { _objectCreationHandling = value; } + } + + /// + /// Gets or sets how null values are handled during serialization and deserialization. + /// + /// Null value handling. + public NullValueHandling NullValueHandling + { + get { return _nullValueHandling ?? DefaultNullValueHandling; } + set { _nullValueHandling = value; } + } + + /// + /// Gets or sets how null default are handled during serialization and deserialization. + /// + /// The default value handling. + public DefaultValueHandling DefaultValueHandling + { + get { return _defaultValueHandling ?? DefaultDefaultValueHandling; } + set { _defaultValueHandling = value; } + } + + /// + /// Gets or sets a collection that will be used during serialization. + /// + /// The converters. + public IList Converters { get; set; } + + /// + /// Gets or sets how object references are preserved by the serializer. + /// + /// The preserve references handling. + public PreserveReferencesHandling PreserveReferencesHandling + { + get { return _preserveReferencesHandling ?? DefaultPreserveReferencesHandling; } + set { _preserveReferencesHandling = value; } + } + + /// + /// Gets or sets how type name writing and reading is handled by the serializer. + /// + /// + /// should be used with caution when your application deserializes JSON from an external source. + /// Incoming types should be validated with a custom + /// when deserializing with a value other than TypeNameHandling.None. + /// + /// The type name handling. + public TypeNameHandling TypeNameHandling + { + get { return _typeNameHandling ?? DefaultTypeNameHandling; } + set { _typeNameHandling = value; } + } + + /// + /// Gets or sets how metadata properties are used during deserialization. + /// + /// The metadata properties handling. + public MetadataPropertyHandling MetadataPropertyHandling + { + get { return _metadataPropertyHandling ?? DefaultMetadataPropertyHandling; } + set { _metadataPropertyHandling = value; } + } + + /// + /// Gets or sets how a type name assembly is written and resolved by the serializer. + /// + /// The type name assembly format. + public FormatterAssemblyStyle TypeNameAssemblyFormat + { + get { return _typeNameAssemblyFormat ?? DefaultFormatterAssemblyStyle; } + set { _typeNameAssemblyFormat = value; } + } + + /// + /// Gets or sets how constructors are used during deserialization. + /// + /// The constructor handling. + public ConstructorHandling ConstructorHandling + { + get { return _constructorHandling ?? DefaultConstructorHandling; } + set { _constructorHandling = value; } + } + + /// + /// Gets or sets the contract resolver used by the serializer when + /// serializing .NET objects to JSON and vice versa. + /// + /// The contract resolver. + public IContractResolver ContractResolver { get; set; } + + /// + /// Gets or sets the equality comparer used by the serializer when comparing references. + /// + /// The equality comparer. + public IEqualityComparer EqualityComparer { get; set; } + + /// + /// Gets or sets the used by the serializer when resolving references. + /// + /// The reference resolver. + [ObsoleteAttribute("ReferenceResolver property is obsolete. Use the ReferenceResolverProvider property to set the IReferenceResolver: settings.ReferenceResolverProvider = () => resolver")] + public IReferenceResolver ReferenceResolver + { + get + { + if (ReferenceResolverProvider == null) + { + return null; + } + + return ReferenceResolverProvider(); + } + set + { + ReferenceResolverProvider = (value != null) + ? () => value + : (Func)null; + } + } + + /// + /// Gets or sets a function that creates the used by the serializer when resolving references. + /// + /// A function that creates the used by the serializer when resolving references. + public Func ReferenceResolverProvider { get; set; } + + /// + /// Gets or sets the used by the serializer when writing trace messages. + /// + /// The trace writer. + public ITraceWriter TraceWriter { get; set; } + + /// + /// Gets or sets the used by the serializer when resolving type names. + /// + /// The binder. + public SerializationBinder Binder { get; set; } + + /// + /// Gets or sets the error handler called during serialization and deserialization. + /// + /// The error handler called during serialization and deserialization. + public EventHandler Error { get; set; } + + /// + /// Gets or sets the used by the serializer when invoking serialization callback methods. + /// + /// The context. + public StreamingContext Context + { + get { return _context ?? DefaultContext; } + set { _context = value; } + } + + /// + /// Get or set how and values are formatted when writing JSON text, and the expected date format when reading JSON text. + /// + public string DateFormatString + { + get { return _dateFormatString ?? DefaultDateFormatString; } + set + { + _dateFormatString = value; + _dateFormatStringSet = true; + } + } + + /// + /// Gets or sets the maximum depth allowed when reading JSON. Reading past this depth will throw a . + /// + public int? MaxDepth + { + get { return _maxDepth; } + set + { + if (value <= 0) + { + throw new ArgumentException("Value must be positive.", nameof(value)); + } + + _maxDepth = value; + _maxDepthSet = true; + } + } + + /// + /// Indicates how JSON text output is formatted. + /// + public Formatting Formatting + { + get { return _formatting ?? DefaultFormatting; } + set { _formatting = value; } + } + + /// + /// Get or set how dates are written to JSON text. + /// + public DateFormatHandling DateFormatHandling + { + get { return _dateFormatHandling ?? DefaultDateFormatHandling; } + set { _dateFormatHandling = value; } + } + + /// + /// Get or set how time zones are handling during serialization and deserialization. + /// + public DateTimeZoneHandling DateTimeZoneHandling + { + get { return _dateTimeZoneHandling ?? DefaultDateTimeZoneHandling; } + set { _dateTimeZoneHandling = value; } + } + + /// + /// Get or set how date formatted strings, e.g. "\/Date(1198908717056)\/" and "2012-03-21T05:40Z", are parsed when reading JSON. + /// + public DateParseHandling DateParseHandling + { + get { return _dateParseHandling ?? DefaultDateParseHandling; } + set { _dateParseHandling = value; } + } + + /// + /// Get or set how special floating point numbers, e.g. , + /// and , + /// are written as JSON. + /// + public FloatFormatHandling FloatFormatHandling + { + get { return _floatFormatHandling ?? DefaultFloatFormatHandling; } + set { _floatFormatHandling = value; } + } + + /// + /// Get or set how floating point numbers, e.g. 1.0 and 9.9, are parsed when reading JSON text. + /// + public FloatParseHandling FloatParseHandling + { + get { return _floatParseHandling ?? DefaultFloatParseHandling; } + set { _floatParseHandling = value; } + } + + /// + /// Get or set how strings are escaped when writing JSON text. + /// + public StringEscapeHandling StringEscapeHandling + { + get { return _stringEscapeHandling ?? DefaultStringEscapeHandling; } + set { _stringEscapeHandling = value; } + } + + /// + /// Gets or sets the culture used when reading JSON. Defaults to . + /// + public CultureInfo Culture + { + get { return _culture ?? DefaultCulture; } + set { _culture = value; } + } + + /// + /// Gets a value indicating whether there will be a check for additional content after deserializing an object. + /// + /// + /// true if there will be a check for additional content after deserializing an object; otherwise, false. + /// + public bool CheckAdditionalContent + { + get { return _checkAdditionalContent ?? DefaultCheckAdditionalContent; } + set { _checkAdditionalContent = value; } + } + + static JsonSerializerSettings() + { + DefaultContext = new StreamingContext(); + DefaultCulture = CultureInfo.InvariantCulture; + } + + /// + /// Initializes a new instance of the class. + /// + public JsonSerializerSettings() + { + Converters = new List(); + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/JsonTextReader.cs b/Common/00-1Json8.3/Json8.3/JsonTextReader.cs new file mode 100644 index 0000000..96a3ee8 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/JsonTextReader.cs @@ -0,0 +1,2380 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Text; +using System.IO; +using System.Globalization; +#if !(PORTABLE || PORTABLE40 || NET35 || NET20) +using System.Numerics; +#endif +using Newtonsoft.Json.Utilities; + +namespace Newtonsoft.Json +{ + internal enum ReadType + { + Read, + ReadAsInt32, + ReadAsBytes, + ReadAsString, + ReadAsDecimal, + ReadAsDateTime, +#if !NET20 + ReadAsDateTimeOffset, +#endif + ReadAsDouble, + ReadAsBoolean + } + + /// + /// Represents a reader that provides fast, non-cached, forward-only access to JSON text data. + /// + public class JsonTextReader : JsonReader, IJsonLineInfo + { + private const char UnicodeReplacementChar = '\uFFFD'; + private const int MaximumJavascriptIntegerCharacterLength = 380; + + private readonly TextReader _reader; + private char[] _chars; + private int _charsUsed; + private int _charPos; + private int _lineStartPos; + private int _lineNumber; + private bool _isEndOfFile; + private StringBuffer _stringBuffer; + private StringReference _stringReference; + private IArrayPool _arrayPool; + internal PropertyNameTable NameTable; + + /// + /// Initializes a new instance of the class with the specified . + /// + /// The TextReader containing the XML data to read. + public JsonTextReader(TextReader reader) + { + if (reader == null) + { + throw new ArgumentNullException(nameof(reader)); + } + + _reader = reader; + _lineNumber = 1; + } + +#if DEBUG + internal void SetCharBuffer(char[] chars) + { + _chars = chars; + } +#endif + + /// + /// Gets or sets the reader's character buffer pool. + /// + public IArrayPool ArrayPool + { + get { return _arrayPool; } + set + { + if (value == null) + { + throw new ArgumentNullException(nameof(value)); + } + + _arrayPool = value; + } + } + + private void EnsureBufferNotEmpty() + { + if (_stringBuffer.IsEmpty) + { + _stringBuffer = new StringBuffer(_arrayPool, 1024); + } + } + + private void OnNewLine(int pos) + { + _lineNumber++; + _lineStartPos = pos; + } + + private void ParseString(char quote, ReadType readType) + { + _charPos++; + + ShiftBufferIfNeeded(); + ReadStringIntoBuffer(quote); + SetPostValueState(true); + + switch (readType) + { + case ReadType.ReadAsBytes: + Guid g; + byte[] data; + if (_stringReference.Length == 0) + { + data = new byte[0]; + } + else if (_stringReference.Length == 36 && ConvertUtils.TryConvertGuid(_stringReference.ToString(), out g)) + { + data = g.ToByteArray(); + } + else + { + data = Convert.FromBase64CharArray(_stringReference.Chars, _stringReference.StartIndex, _stringReference.Length); + } + + SetToken(JsonToken.Bytes, data, false); + break; + case ReadType.ReadAsString: + string text = _stringReference.ToString(); + + SetToken(JsonToken.String, text, false); + _quoteChar = quote; + break; + case ReadType.ReadAsInt32: + case ReadType.ReadAsDecimal: + case ReadType.ReadAsBoolean: + // caller will convert result + break; + default: + if (_dateParseHandling != DateParseHandling.None) + { + DateParseHandling dateParseHandling; + if (readType == ReadType.ReadAsDateTime) + { + dateParseHandling = DateParseHandling.DateTime; + } +#if !NET20 + else if (readType == ReadType.ReadAsDateTimeOffset) + { + dateParseHandling = DateParseHandling.DateTimeOffset; + } +#endif + else + { + dateParseHandling = _dateParseHandling; + } + + if (dateParseHandling == DateParseHandling.DateTime) + { + DateTime dt; + if (DateTimeUtils.TryParseDateTime(_stringReference, DateTimeZoneHandling, DateFormatString, Culture, out dt)) + { + SetToken(JsonToken.Date, dt, false); + return; + } + } +#if !NET20 + else + { + DateTimeOffset dt; + if (DateTimeUtils.TryParseDateTimeOffset(_stringReference, DateFormatString, Culture, out dt)) + { + SetToken(JsonToken.Date, dt, false); + return; + } + } +#endif + } + + SetToken(JsonToken.String, _stringReference.ToString(), false); + _quoteChar = quote; + break; + } + } + + private static void BlockCopyChars(char[] src, int srcOffset, char[] dst, int dstOffset, int count) + { + const int charByteCount = 2; + + Buffer.BlockCopy(src, srcOffset * charByteCount, dst, dstOffset * charByteCount, count * charByteCount); + } + + private void ShiftBufferIfNeeded() + { + // once in the last 10% of the buffer shift the remaining content to the start to avoid + // unnessesarly increasing the buffer size when reading numbers/strings + int length = _chars.Length; + if (length - _charPos <= length * 0.1) + { + int count = _charsUsed - _charPos; + if (count > 0) + { + BlockCopyChars(_chars, _charPos, _chars, 0, count); + } + + _lineStartPos -= _charPos; + _charPos = 0; + _charsUsed = count; + _chars[_charsUsed] = '\0'; + } + } + + private int ReadData(bool append) + { + return ReadData(append, 0); + } + + private int ReadData(bool append, int charsRequired) + { + if (_isEndOfFile) + { + return 0; + } + + // char buffer is full + if (_charsUsed + charsRequired >= _chars.Length - 1) + { + if (append) + { + // copy to new array either double the size of the current or big enough to fit required content + int newArrayLength = Math.Max(_chars.Length * 2, _charsUsed + charsRequired + 1); + + // increase the size of the buffer + char[] dst = BufferUtils.RentBuffer(_arrayPool, newArrayLength); + + BlockCopyChars(_chars, 0, dst, 0, _chars.Length); + + BufferUtils.ReturnBuffer(_arrayPool, _chars); + + _chars = dst; + } + else + { + int remainingCharCount = _charsUsed - _charPos; + + if (remainingCharCount + charsRequired + 1 >= _chars.Length) + { + // the remaining count plus the required is bigger than the current buffer size + char[] dst = BufferUtils.RentBuffer(_arrayPool, remainingCharCount + charsRequired + 1); + + if (remainingCharCount > 0) + { + BlockCopyChars(_chars, _charPos, dst, 0, remainingCharCount); + } + + BufferUtils.ReturnBuffer(_arrayPool, _chars); + + _chars = dst; + } + else + { + // copy any remaining data to the beginning of the buffer if needed and reset positions + if (remainingCharCount > 0) + { + BlockCopyChars(_chars, _charPos, _chars, 0, remainingCharCount); + } + } + + _lineStartPos -= _charPos; + _charPos = 0; + _charsUsed = remainingCharCount; + } + } + + int attemptCharReadCount = _chars.Length - _charsUsed - 1; + + int charsRead = _reader.Read(_chars, _charsUsed, attemptCharReadCount); + + _charsUsed += charsRead; + + if (charsRead == 0) + { + _isEndOfFile = true; + } + + _chars[_charsUsed] = '\0'; + return charsRead; + } + + private bool EnsureChars(int relativePosition, bool append) + { + if (_charPos + relativePosition >= _charsUsed) + { + return ReadChars(relativePosition, append); + } + + return true; + } + + private bool ReadChars(int relativePosition, bool append) + { + if (_isEndOfFile) + { + return false; + } + + int charsRequired = _charPos + relativePosition - _charsUsed + 1; + + int totalCharsRead = 0; + + // it is possible that the TextReader doesn't return all data at once + // repeat read until the required text is returned or the reader is out of content + do + { + int charsRead = ReadData(append, charsRequired - totalCharsRead); + + // no more content + if (charsRead == 0) + { + break; + } + + totalCharsRead += charsRead; + } while (totalCharsRead < charsRequired); + + if (totalCharsRead < charsRequired) + { + return false; + } + return true; + } + + /// + /// Reads the next JSON token from the stream. + /// + /// + /// true if the next token was read successfully; false if there are no more tokens to read. + /// + public override bool Read() + { + EnsureBuffer(); + + while (true) + { + switch (_currentState) + { + case State.Start: + case State.Property: + case State.Array: + case State.ArrayStart: + case State.Constructor: + case State.ConstructorStart: + return ParseValue(); + case State.Object: + case State.ObjectStart: + return ParseObject(); + case State.PostValue: + // returns true if it hits + // end of object or array + if (ParsePostValue()) + { + return true; + } + break; + case State.Finished: + if (EnsureChars(0, false)) + { + EatWhitespace(false); + if (_isEndOfFile) + { + SetToken(JsonToken.None); + return false; + } + if (_chars[_charPos] == '/') + { + ParseComment(true); + return true; + } + + throw JsonReaderException.Create(this, "Additional text encountered after finished reading JSON content: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos])); + } + SetToken(JsonToken.None); + return false; + default: + throw JsonReaderException.Create(this, "Unexpected state: {0}.".FormatWith(CultureInfo.InvariantCulture, CurrentState)); + } + } + } + + /// + /// Reads the next JSON token from the stream as a . + /// + /// A . This method will return null at the end of an array. + public override int? ReadAsInt32() + { + return (int?)ReadNumberValue(ReadType.ReadAsInt32); + } + + /// + /// Reads the next JSON token from the stream as a . + /// + /// A . This method will return null at the end of an array. + public override DateTime? ReadAsDateTime() + { + return (DateTime?)ReadStringValue(ReadType.ReadAsDateTime); + } + + /// + /// Reads the next JSON token from the stream as a . + /// + /// A . This method will return null at the end of an array. + public override string ReadAsString() + { + return (string)ReadStringValue(ReadType.ReadAsString); + } + + /// + /// Reads the next JSON token from the stream as a []. + /// + /// A [] or a null reference if the next JSON token is null. This method will return null at the end of an array. + public override byte[] ReadAsBytes() + { + EnsureBuffer(); + bool isWrapped = false; + + switch (_currentState) + { + case State.Start: + case State.Property: + case State.Array: + case State.ArrayStart: + case State.Constructor: + case State.ConstructorStart: + case State.PostValue: + while (true) + { + char currentChar = _chars[_charPos]; + + switch (currentChar) + { + case '\0': + if (ReadNullChar()) + { + SetToken(JsonToken.None, null, false); + return null; + } + break; + case '"': + case '\'': + ParseString(currentChar, ReadType.ReadAsBytes); + byte[] data = (byte[])Value; + if (isWrapped) + { + ReaderReadAndAssert(); + if (TokenType != JsonToken.EndObject) + { + throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); + } + SetToken(JsonToken.Bytes, data, false); + } + return data; + case '{': + _charPos++; + SetToken(JsonToken.StartObject); + ReadIntoWrappedTypeObject(); + isWrapped = true; + break; + case '[': + _charPos++; + SetToken(JsonToken.StartArray); + return ReadArrayIntoByteArray(); + case 'n': + HandleNull(); + return null; + case '/': + ParseComment(false); + break; + case ',': + ProcessValueComma(); + break; + case ']': + _charPos++; + if (_currentState == State.Array || _currentState == State.ArrayStart || _currentState == State.PostValue) + { + SetToken(JsonToken.EndArray); + return null; + } + throw CreateUnexpectedCharacterException(currentChar); + case StringUtils.CarriageReturn: + ProcessCarriageReturn(false); + break; + case StringUtils.LineFeed: + ProcessLineFeed(); + break; + case ' ': + case StringUtils.Tab: + // eat + _charPos++; + break; + default: + _charPos++; + + if (!char.IsWhiteSpace(currentChar)) + { + throw CreateUnexpectedCharacterException(currentChar); + } + + // eat + break; + } + } + case State.Finished: + ReadFinished(); + return null; + default: + throw JsonReaderException.Create(this, "Unexpected state: {0}.".FormatWith(CultureInfo.InvariantCulture, CurrentState)); + } + } + + private object ReadStringValue(ReadType readType) + { + EnsureBuffer(); + + switch (_currentState) + { + case State.Start: + case State.Property: + case State.Array: + case State.ArrayStart: + case State.Constructor: + case State.ConstructorStart: + case State.PostValue: + while (true) + { + char currentChar = _chars[_charPos]; + + switch (currentChar) + { + case '\0': + if (ReadNullChar()) + { + SetToken(JsonToken.None, null, false); + return null; + } + break; + case '"': + case '\'': + ParseString(currentChar, readType); + switch (readType) + { + case ReadType.ReadAsBytes: + return Value; + case ReadType.ReadAsString: + return Value; + case ReadType.ReadAsDateTime: + if (Value is DateTime) + { + return (DateTime)Value; + } + return ReadDateTimeString((string)Value); +#if !NET20 + case ReadType.ReadAsDateTimeOffset: + if (Value is DateTimeOffset) + { + return (DateTimeOffset)Value; + } + return ReadDateTimeOffsetString((string)Value); +#endif + default: + throw new ArgumentOutOfRangeException(nameof(readType)); + } + case '-': + case '.': + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + if (readType != ReadType.ReadAsString) + { + _charPos++; + throw CreateUnexpectedCharacterException(currentChar); + } + ParseNumber(ReadType.Read); + string s = ((IFormattable)Value).ToString(null, CultureInfo.InvariantCulture); + SetToken(JsonToken.String, s); + return s; + case 't': + case 'f': + if (readType != ReadType.ReadAsString) + { + _charPos++; + throw CreateUnexpectedCharacterException(currentChar); + } + string expected = currentChar == 't' ? JsonConvert.True : JsonConvert.False; + if (!MatchValueWithTrailingSeparator(expected)) + { + throw CreateUnexpectedCharacterException(_chars[_charPos]); + } + SetToken(JsonToken.String, expected); + return expected; + case 'n': + HandleNull(); + return null; + case '/': + ParseComment(false); + break; + case ',': + ProcessValueComma(); + break; + case ']': + _charPos++; + if (_currentState == State.Array || _currentState == State.ArrayStart || _currentState == State.PostValue) + { + SetToken(JsonToken.EndArray); + return null; + } + throw CreateUnexpectedCharacterException(currentChar); + case StringUtils.CarriageReturn: + ProcessCarriageReturn(false); + break; + case StringUtils.LineFeed: + ProcessLineFeed(); + break; + case ' ': + case StringUtils.Tab: + // eat + _charPos++; + break; + default: + _charPos++; + + if (!char.IsWhiteSpace(currentChar)) + { + throw CreateUnexpectedCharacterException(currentChar); + } + + // eat + break; + } + } + case State.Finished: + ReadFinished(); + return null; + default: + throw JsonReaderException.Create(this, "Unexpected state: {0}.".FormatWith(CultureInfo.InvariantCulture, CurrentState)); + } + } + + private JsonReaderException CreateUnexpectedCharacterException(char c) + { + return JsonReaderException.Create(this, "Unexpected character encountered while parsing value: {0}.".FormatWith(CultureInfo.InvariantCulture, c)); + } + + /// + /// Reads the next JSON token from the stream as a . + /// + /// A . This method will return null at the end of an array. + public override bool? ReadAsBoolean() + { + EnsureBuffer(); + + switch (_currentState) + { + case State.Start: + case State.Property: + case State.Array: + case State.ArrayStart: + case State.Constructor: + case State.ConstructorStart: + case State.PostValue: + while (true) + { + char currentChar = _chars[_charPos]; + + switch (currentChar) + { + case '\0': + if (ReadNullChar()) + { + SetToken(JsonToken.None, null, false); + return null; + } + break; + case '"': + case '\'': + ParseString(currentChar, ReadType.Read); + return ReadBooleanString(_stringReference.ToString()); + case 'n': + HandleNull(); + return null; + case '-': + case '.': + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + ParseNumber(ReadType.Read); + bool b; +#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) + if (Value is BigInteger) + { + b = (BigInteger)Value != 0; + } + else +#endif + { + b = Convert.ToBoolean(Value, CultureInfo.InvariantCulture); + } + SetToken(JsonToken.Boolean, b, false); + return b; + case 't': + case 'f': + bool isTrue = currentChar == 't'; + string expected = isTrue ? JsonConvert.True : JsonConvert.False; + + if (!MatchValueWithTrailingSeparator(expected)) + { + throw CreateUnexpectedCharacterException(_chars[_charPos]); + } + SetToken(JsonToken.Boolean, isTrue); + return isTrue; + case '/': + ParseComment(false); + break; + case ',': + ProcessValueComma(); + break; + case ']': + _charPos++; + if (_currentState == State.Array || _currentState == State.ArrayStart || _currentState == State.PostValue) + { + SetToken(JsonToken.EndArray); + return null; + } + throw CreateUnexpectedCharacterException(currentChar); + case StringUtils.CarriageReturn: + ProcessCarriageReturn(false); + break; + case StringUtils.LineFeed: + ProcessLineFeed(); + break; + case ' ': + case StringUtils.Tab: + // eat + _charPos++; + break; + default: + _charPos++; + + if (!char.IsWhiteSpace(currentChar)) + { + throw CreateUnexpectedCharacterException(currentChar); + } + + // eat + break; + } + } + case State.Finished: + ReadFinished(); + return null; + default: + throw JsonReaderException.Create(this, "Unexpected state: {0}.".FormatWith(CultureInfo.InvariantCulture, CurrentState)); + } + } + + private void ProcessValueComma() + { + _charPos++; + + if (_currentState != State.PostValue) + { + SetToken(JsonToken.Undefined); + throw CreateUnexpectedCharacterException(','); + } + + SetStateBasedOnCurrent(); + } + + private object ReadNumberValue(ReadType readType) + { + EnsureBuffer(); + + switch (_currentState) + { + case State.Start: + case State.Property: + case State.Array: + case State.ArrayStart: + case State.Constructor: + case State.ConstructorStart: + case State.PostValue: + while (true) + { + char currentChar = _chars[_charPos]; + + switch (currentChar) + { + case '\0': + if (ReadNullChar()) + { + SetToken(JsonToken.None, null, false); + return null; + } + break; + case '"': + case '\'': + ParseString(currentChar, readType); + switch (readType) + { + case ReadType.ReadAsInt32: + return ReadInt32String(_stringReference.ToString()); + case ReadType.ReadAsDecimal: + return ReadDecimalString(_stringReference.ToString()); + case ReadType.ReadAsDouble: + return ReadDoubleString(_stringReference.ToString()); + default: + throw new ArgumentOutOfRangeException(nameof(readType)); + } + case 'n': + HandleNull(); + return null; + case '-': + case '.': + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + ParseNumber(readType); + return Value; + case '/': + ParseComment(false); + break; + case ',': + ProcessValueComma(); + break; + case ']': + _charPos++; + if (_currentState == State.Array || _currentState == State.ArrayStart || _currentState == State.PostValue) + { + SetToken(JsonToken.EndArray); + return null; + } + throw CreateUnexpectedCharacterException(currentChar); + case StringUtils.CarriageReturn: + ProcessCarriageReturn(false); + break; + case StringUtils.LineFeed: + ProcessLineFeed(); + break; + case ' ': + case StringUtils.Tab: + // eat + _charPos++; + break; + default: + _charPos++; + + if (!char.IsWhiteSpace(currentChar)) + { + throw CreateUnexpectedCharacterException(currentChar); + } + + // eat + break; + } + } + case State.Finished: + ReadFinished(); + return null; + default: + throw JsonReaderException.Create(this, "Unexpected state: {0}.".FormatWith(CultureInfo.InvariantCulture, CurrentState)); + } + } + +#if !NET20 + /// + /// Reads the next JSON token from the stream as a . + /// + /// A . This method will return null at the end of an array. + public override DateTimeOffset? ReadAsDateTimeOffset() + { + return (DateTimeOffset?)ReadStringValue(ReadType.ReadAsDateTimeOffset); + } +#endif + + /// + /// Reads the next JSON token from the stream as a . + /// + /// A . This method will return null at the end of an array. + public override decimal? ReadAsDecimal() + { + return (decimal?)ReadNumberValue(ReadType.ReadAsDecimal); + } + + /// + /// Reads the next JSON token from the stream as a . + /// + /// A . This method will return null at the end of an array. + public override double? ReadAsDouble() + { + return (double?)ReadNumberValue(ReadType.ReadAsDouble); + } + + private void HandleNull() + { + if (EnsureChars(1, true)) + { + char next = _chars[_charPos + 1]; + + if (next == 'u') + { + ParseNull(); + return; + } + + _charPos += 2; + throw CreateUnexpectedCharacterException(_chars[_charPos - 1]); + } + + _charPos = _charsUsed; + throw CreateUnexpectedEndException(); + } + + private void ReadFinished() + { + if (EnsureChars(0, false)) + { + EatWhitespace(false); + if (_isEndOfFile) + { + return; + } + if (_chars[_charPos] == '/') + { + ParseComment(false); + } + else + { + throw JsonReaderException.Create(this, "Additional text encountered after finished reading JSON content: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos])); + } + } + + SetToken(JsonToken.None); + } + + private bool ReadNullChar() + { + if (_charsUsed == _charPos) + { + if (ReadData(false) == 0) + { + _isEndOfFile = true; + return true; + } + } + else + { + _charPos++; + } + + return false; + } + + private void EnsureBuffer() + { + if (_chars == null) + { + _chars = BufferUtils.RentBuffer(_arrayPool, 1024); + _chars[0] = '\0'; + } + } + + private void ReadStringIntoBuffer(char quote) + { + int charPos = _charPos; + int initialPosition = _charPos; + int lastWritePosition = _charPos; + _stringBuffer.Position = 0; + + while (true) + { + switch (_chars[charPos++]) + { + case '\0': + if (_charsUsed == charPos - 1) + { + charPos--; + + if (ReadData(true) == 0) + { + _charPos = charPos; + throw JsonReaderException.Create(this, "Unterminated string. Expected delimiter: {0}.".FormatWith(CultureInfo.InvariantCulture, quote)); + } + } + break; + case '\\': + _charPos = charPos; + if (!EnsureChars(0, true)) + { + throw JsonReaderException.Create(this, "Unterminated string. Expected delimiter: {0}.".FormatWith(CultureInfo.InvariantCulture, quote)); + } + + // start of escape sequence + int escapeStartPos = charPos - 1; + + char currentChar = _chars[charPos]; + charPos++; + + char writeChar; + + switch (currentChar) + { + case 'b': + writeChar = '\b'; + break; + case 't': + writeChar = '\t'; + break; + case 'n': + writeChar = '\n'; + break; + case 'f': + writeChar = '\f'; + break; + case 'r': + writeChar = '\r'; + break; + case '\\': + writeChar = '\\'; + break; + case '"': + case '\'': + case '/': + writeChar = currentChar; + break; + case 'u': + _charPos = charPos; + writeChar = ParseUnicode(); + + if (StringUtils.IsLowSurrogate(writeChar)) + { + // low surrogate with no preceding high surrogate; this char is replaced + writeChar = UnicodeReplacementChar; + } + else if (StringUtils.IsHighSurrogate(writeChar)) + { + bool anotherHighSurrogate; + + // loop for handling situations where there are multiple consecutive high surrogates + do + { + anotherHighSurrogate = false; + + // potential start of a surrogate pair + if (EnsureChars(2, true) && _chars[_charPos] == '\\' && _chars[_charPos + 1] == 'u') + { + char highSurrogate = writeChar; + + _charPos += 2; + writeChar = ParseUnicode(); + + if (StringUtils.IsLowSurrogate(writeChar)) + { + // a valid surrogate pair! + } + else if (StringUtils.IsHighSurrogate(writeChar)) + { + // another high surrogate; replace current and start check over + highSurrogate = UnicodeReplacementChar; + anotherHighSurrogate = true; + } + else + { + // high surrogate not followed by low surrogate; original char is replaced + highSurrogate = UnicodeReplacementChar; + } + + EnsureBufferNotEmpty(); + + WriteCharToBuffer(highSurrogate, lastWritePosition, escapeStartPos); + lastWritePosition = _charPos; + } + else + { + // there are not enough remaining chars for the low surrogate or is not follow by unicode sequence + // replace high surrogate and continue on as usual + writeChar = UnicodeReplacementChar; + } + } while (anotherHighSurrogate); + } + + charPos = _charPos; + break; + default: + _charPos = charPos; + throw JsonReaderException.Create(this, "Bad JSON escape sequence: {0}.".FormatWith(CultureInfo.InvariantCulture, @"\" + currentChar)); + } + + EnsureBufferNotEmpty(); + WriteCharToBuffer(writeChar, lastWritePosition, escapeStartPos); + + lastWritePosition = charPos; + break; + case StringUtils.CarriageReturn: + _charPos = charPos - 1; + ProcessCarriageReturn(true); + charPos = _charPos; + break; + case StringUtils.LineFeed: + _charPos = charPos - 1; + ProcessLineFeed(); + charPos = _charPos; + break; + case '"': + case '\'': + if (_chars[charPos - 1] == quote) + { + charPos--; + + if (initialPosition == lastWritePosition) + { + _stringReference = new StringReference(_chars, initialPosition, charPos - initialPosition); + } + else + { + EnsureBufferNotEmpty(); + + if (charPos > lastWritePosition) + { + _stringBuffer.Append(_arrayPool, _chars, lastWritePosition, charPos - lastWritePosition); + } + + _stringReference = new StringReference(_stringBuffer.InternalBuffer, 0, _stringBuffer.Position); + } + + charPos++; + _charPos = charPos; + return; + } + break; + } + } + } + + private void WriteCharToBuffer(char writeChar, int lastWritePosition, int writeToPosition) + { + if (writeToPosition > lastWritePosition) + { + _stringBuffer.Append(_arrayPool, _chars, lastWritePosition, writeToPosition - lastWritePosition); + } + + _stringBuffer.Append(_arrayPool, writeChar); + } + + private char ParseUnicode() + { + char writeChar; + if (EnsureChars(4, true)) + { + char hexChar = Convert.ToChar(ConvertUtils.HexTextToInt(_chars, _charPos, _charPos + 4)); + writeChar = hexChar; + + _charPos += 4; + } + else + { + throw JsonReaderException.Create(this, "Unexpected end while parsing unicode character."); + } + return writeChar; + } + + private void ReadNumberIntoBuffer() + { + int charPos = _charPos; + + while (true) + { + switch (_chars[charPos]) + { + case '\0': + _charPos = charPos; + + if (_charsUsed == charPos) + { + if (ReadData(true) == 0) + { + return; + } + } + else + { + return; + } + break; + case '-': + case '+': + case 'a': + case 'A': + case 'b': + case 'B': + case 'c': + case 'C': + case 'd': + case 'D': + case 'e': + case 'E': + case 'f': + case 'F': + case 'x': + case 'X': + case '.': + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + charPos++; + break; + default: + _charPos = charPos; + + char currentChar = _chars[_charPos]; + if (char.IsWhiteSpace(currentChar) || currentChar == ',' || currentChar == '}' || currentChar == ']' || currentChar == ')' || currentChar == '/') + { + return; + } + + throw JsonReaderException.Create(this, "Unexpected character encountered while parsing number: {0}.".FormatWith(CultureInfo.InvariantCulture, currentChar)); + } + } + } + + private void ClearRecentString() + { + _stringBuffer.Position = 0; + _stringReference = new StringReference(); + } + + private bool ParsePostValue() + { + while (true) + { + char currentChar = _chars[_charPos]; + + switch (currentChar) + { + case '\0': + if (_charsUsed == _charPos) + { + if (ReadData(false) == 0) + { + _currentState = State.Finished; + return false; + } + } + else + { + _charPos++; + } + break; + case '}': + _charPos++; + SetToken(JsonToken.EndObject); + return true; + case ']': + _charPos++; + SetToken(JsonToken.EndArray); + return true; + case ')': + _charPos++; + SetToken(JsonToken.EndConstructor); + return true; + case '/': + ParseComment(true); + return true; + case ',': + _charPos++; + + // finished parsing + SetStateBasedOnCurrent(); + return false; + case ' ': + case StringUtils.Tab: + // eat + _charPos++; + break; + case StringUtils.CarriageReturn: + ProcessCarriageReturn(false); + break; + case StringUtils.LineFeed: + ProcessLineFeed(); + break; + default: + if (char.IsWhiteSpace(currentChar)) + { + // eat + _charPos++; + } + else + { + throw JsonReaderException.Create(this, "After parsing a value an unexpected character was encountered: {0}.".FormatWith(CultureInfo.InvariantCulture, currentChar)); + } + break; + } + } + } + + private bool ParseObject() + { + while (true) + { + char currentChar = _chars[_charPos]; + + switch (currentChar) + { + case '\0': + if (_charsUsed == _charPos) + { + if (ReadData(false) == 0) + { + return false; + } + } + else + { + _charPos++; + } + break; + case '}': + SetToken(JsonToken.EndObject); + _charPos++; + return true; + case '/': + ParseComment(true); + return true; + case StringUtils.CarriageReturn: + ProcessCarriageReturn(false); + break; + case StringUtils.LineFeed: + ProcessLineFeed(); + break; + case ' ': + case StringUtils.Tab: + // eat + _charPos++; + break; + default: + if (char.IsWhiteSpace(currentChar)) + { + // eat + _charPos++; + } + else + { + return ParseProperty(); + } + break; + } + } + } + + private bool ParseProperty() + { + char firstChar = _chars[_charPos]; + char quoteChar; + + if (firstChar == '"' || firstChar == '\'') + { + _charPos++; + quoteChar = firstChar; + ShiftBufferIfNeeded(); + ReadStringIntoBuffer(quoteChar); + } + else if (ValidIdentifierChar(firstChar)) + { + quoteChar = '\0'; + ShiftBufferIfNeeded(); + ParseUnquotedProperty(); + } + else + { + throw JsonReaderException.Create(this, "Invalid property identifier character: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos])); + } + + string propertyName; + + if (NameTable != null) + { + propertyName = NameTable.Get(_stringReference.Chars, _stringReference.StartIndex, _stringReference.Length); + + // no match in name table + if (propertyName == null) + { + propertyName = _stringReference.ToString(); + } + } + else + { + propertyName = _stringReference.ToString(); + } + + EatWhitespace(false); + + if (_chars[_charPos] != ':') + { + throw JsonReaderException.Create(this, "Invalid character after parsing property name. Expected ':' but got: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos])); + } + + _charPos++; + + SetToken(JsonToken.PropertyName, propertyName); + _quoteChar = quoteChar; + ClearRecentString(); + + return true; + } + + private bool ValidIdentifierChar(char value) + { + return (char.IsLetterOrDigit(value) || value == '_' || value == '$'); + } + + private void ParseUnquotedProperty() + { + int initialPosition = _charPos; + + // parse unquoted property name until whitespace or colon + while (true) + { + switch (_chars[_charPos]) + { + case '\0': + if (_charsUsed == _charPos) + { + if (ReadData(true) == 0) + { + throw JsonReaderException.Create(this, "Unexpected end while parsing unquoted property name."); + } + + break; + } + + _stringReference = new StringReference(_chars, initialPosition, _charPos - initialPosition); + return; + default: + char currentChar = _chars[_charPos]; + + if (ValidIdentifierChar(currentChar)) + { + _charPos++; + break; + } + else if (char.IsWhiteSpace(currentChar) || currentChar == ':') + { + _stringReference = new StringReference(_chars, initialPosition, _charPos - initialPosition); + return; + } + + throw JsonReaderException.Create(this, "Invalid JavaScript property identifier character: {0}.".FormatWith(CultureInfo.InvariantCulture, currentChar)); + } + } + } + + private bool ParseValue() + { + while (true) + { + char currentChar = _chars[_charPos]; + + switch (currentChar) + { + case '\0': + if (_charsUsed == _charPos) + { + if (ReadData(false) == 0) + { + return false; + } + } + else + { + _charPos++; + } + break; + case '"': + case '\'': + ParseString(currentChar, ReadType.Read); + return true; + case 't': + ParseTrue(); + return true; + case 'f': + ParseFalse(); + return true; + case 'n': + if (EnsureChars(1, true)) + { + char next = _chars[_charPos + 1]; + + if (next == 'u') + { + ParseNull(); + } + else if (next == 'e') + { + ParseConstructor(); + } + else + { + throw CreateUnexpectedCharacterException(_chars[_charPos]); + } + } + else + { + _charPos++; + throw CreateUnexpectedEndException(); + } + return true; + case 'N': + ParseNumberNaN(); + return true; + case 'I': + ParseNumberPositiveInfinity(); + return true; + case '-': + if (EnsureChars(1, true) && _chars[_charPos + 1] == 'I') + { + ParseNumberNegativeInfinity(); + } + else + { + ParseNumber(ReadType.Read); + } + return true; + case '/': + ParseComment(true); + return true; + case 'u': + ParseUndefined(); + return true; + case '{': + _charPos++; + SetToken(JsonToken.StartObject); + return true; + case '[': + _charPos++; + SetToken(JsonToken.StartArray); + return true; + case ']': + _charPos++; + SetToken(JsonToken.EndArray); + return true; + case ',': + // don't increment position, the next call to read will handle comma + // this is done to handle multiple empty comma values + SetToken(JsonToken.Undefined); + return true; + case ')': + _charPos++; + SetToken(JsonToken.EndConstructor); + return true; + case StringUtils.CarriageReturn: + ProcessCarriageReturn(false); + break; + case StringUtils.LineFeed: + ProcessLineFeed(); + break; + case ' ': + case StringUtils.Tab: + // eat + _charPos++; + break; + default: + if (char.IsWhiteSpace(currentChar)) + { + // eat + _charPos++; + break; + } + if (char.IsNumber(currentChar) || currentChar == '-' || currentChar == '.') + { + ParseNumber(ReadType.Read); + return true; + } + + throw CreateUnexpectedCharacterException(currentChar); + } + } + } + + private void ProcessLineFeed() + { + _charPos++; + OnNewLine(_charPos); + } + + private void ProcessCarriageReturn(bool append) + { + _charPos++; + + if (EnsureChars(1, append) && _chars[_charPos] == StringUtils.LineFeed) + { + _charPos++; + } + + OnNewLine(_charPos); + } + + private bool EatWhitespace(bool oneOrMore) + { + bool finished = false; + bool ateWhitespace = false; + while (!finished) + { + char currentChar = _chars[_charPos]; + + switch (currentChar) + { + case '\0': + if (_charsUsed == _charPos) + { + if (ReadData(false) == 0) + { + finished = true; + } + } + else + { + _charPos++; + } + break; + case StringUtils.CarriageReturn: + ProcessCarriageReturn(false); + break; + case StringUtils.LineFeed: + ProcessLineFeed(); + break; + default: + if (currentChar == ' ' || char.IsWhiteSpace(currentChar)) + { + ateWhitespace = true; + _charPos++; + } + else + { + finished = true; + } + break; + } + } + + return (!oneOrMore || ateWhitespace); + } + + private void ParseConstructor() + { + if (MatchValueWithTrailingSeparator("new")) + { + EatWhitespace(false); + + int initialPosition = _charPos; + int endPosition; + + while (true) + { + char currentChar = _chars[_charPos]; + if (currentChar == '\0') + { + if (_charsUsed == _charPos) + { + if (ReadData(true) == 0) + { + throw JsonReaderException.Create(this, "Unexpected end while parsing constructor."); + } + } + else + { + endPosition = _charPos; + _charPos++; + break; + } + } + else if (char.IsLetterOrDigit(currentChar)) + { + _charPos++; + } + else if (currentChar == StringUtils.CarriageReturn) + { + endPosition = _charPos; + ProcessCarriageReturn(true); + break; + } + else if (currentChar == StringUtils.LineFeed) + { + endPosition = _charPos; + ProcessLineFeed(); + break; + } + else if (char.IsWhiteSpace(currentChar)) + { + endPosition = _charPos; + _charPos++; + break; + } + else if (currentChar == '(') + { + endPosition = _charPos; + break; + } + else + { + throw JsonReaderException.Create(this, "Unexpected character while parsing constructor: {0}.".FormatWith(CultureInfo.InvariantCulture, currentChar)); + } + } + + _stringReference = new StringReference(_chars, initialPosition, endPosition - initialPosition); + string constructorName = _stringReference.ToString(); + + EatWhitespace(false); + + if (_chars[_charPos] != '(') + { + throw JsonReaderException.Create(this, "Unexpected character while parsing constructor: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos])); + } + + _charPos++; + + ClearRecentString(); + + SetToken(JsonToken.StartConstructor, constructorName); + } + else + { + throw JsonReaderException.Create(this, "Unexpected content while parsing JSON."); + } + } + + private void ParseNumber(ReadType readType) + { + ShiftBufferIfNeeded(); + + char firstChar = _chars[_charPos]; + int initialPosition = _charPos; + + ReadNumberIntoBuffer(); + + // set state to PostValue now so that if there is an error parsing the number then the reader can continue + SetPostValueState(true); + + _stringReference = new StringReference(_chars, initialPosition, _charPos - initialPosition); + + object numberValue; + JsonToken numberType; + + bool singleDigit = (char.IsDigit(firstChar) && _stringReference.Length == 1); + bool nonBase10 = (firstChar == '0' && _stringReference.Length > 1 && _stringReference.Chars[_stringReference.StartIndex + 1] != '.' && _stringReference.Chars[_stringReference.StartIndex + 1] != 'e' && _stringReference.Chars[_stringReference.StartIndex + 1] != 'E'); + + if (readType == ReadType.ReadAsInt32) + { + if (singleDigit) + { + // digit char values start at 48 + numberValue = firstChar - 48; + } + else if (nonBase10) + { + string number = _stringReference.ToString(); + + try + { + int integer = number.StartsWith("0x", StringComparison.OrdinalIgnoreCase) ? Convert.ToInt32(number, 16) : Convert.ToInt32(number, 8); + + numberValue = integer; + } + catch (Exception ex) + { + throw JsonReaderException.Create(this, "Input string '{0}' is not a valid integer.".FormatWith(CultureInfo.InvariantCulture, number), ex); + } + } + else + { + int value; + ParseResult parseResult = ConvertUtils.Int32TryParse(_stringReference.Chars, _stringReference.StartIndex, _stringReference.Length, out value); + if (parseResult == ParseResult.Success) + { + numberValue = value; + } + else if (parseResult == ParseResult.Overflow) + { + throw JsonReaderException.Create(this, "JSON integer {0} is too large or small for an Int32.".FormatWith(CultureInfo.InvariantCulture, _stringReference.ToString())); + } + else + { + throw JsonReaderException.Create(this, "Input string '{0}' is not a valid integer.".FormatWith(CultureInfo.InvariantCulture, _stringReference.ToString())); + } + } + + numberType = JsonToken.Integer; + } + else if (readType == ReadType.ReadAsDecimal) + { + if (singleDigit) + { + // digit char values start at 48 + numberValue = (decimal)firstChar - 48; + } + else if (nonBase10) + { + string number = _stringReference.ToString(); + + try + { + // decimal.Parse doesn't support parsing hexadecimal values + long integer = number.StartsWith("0x", StringComparison.OrdinalIgnoreCase) ? Convert.ToInt64(number, 16) : Convert.ToInt64(number, 8); + + numberValue = Convert.ToDecimal(integer); + } + catch (Exception ex) + { + throw JsonReaderException.Create(this, "Input string '{0}' is not a valid decimal.".FormatWith(CultureInfo.InvariantCulture, number), ex); + } + } + else + { + string number = _stringReference.ToString(); + + decimal value; + if (decimal.TryParse(number, NumberStyles.Number | NumberStyles.AllowExponent, CultureInfo.InvariantCulture, out value)) + { + numberValue = value; + } + else + { + throw JsonReaderException.Create(this, "Input string '{0}' is not a valid decimal.".FormatWith(CultureInfo.InvariantCulture, _stringReference.ToString())); + } + } + + numberType = JsonToken.Float; + } + else if (readType == ReadType.ReadAsDouble) + { + if (singleDigit) + { + // digit char values start at 48 + numberValue = (double)firstChar - 48; + } + else if (nonBase10) + { + string number = _stringReference.ToString(); + + try + { + // double.Parse doesn't support parsing hexadecimal values + long integer = number.StartsWith("0x", StringComparison.OrdinalIgnoreCase) ? Convert.ToInt64(number, 16) : Convert.ToInt64(number, 8); + + numberValue = Convert.ToDouble(integer); + } + catch (Exception ex) + { + throw JsonReaderException.Create(this, "Input string '{0}' is not a valid double.".FormatWith(CultureInfo.InvariantCulture, number), ex); + } + } + else + { + string number = _stringReference.ToString(); + + double value; + if (double.TryParse(number, NumberStyles.Float, CultureInfo.InvariantCulture, out value)) + { + numberValue = value; + } + else + { + throw JsonReaderException.Create(this, "Input string '{0}' is not a valid double.".FormatWith(CultureInfo.InvariantCulture, _stringReference.ToString())); + } + } + + numberType = JsonToken.Float; + } + else + { + if (singleDigit) + { + // digit char values start at 48 + numberValue = (long)firstChar - 48; + numberType = JsonToken.Integer; + } + else if (nonBase10) + { + string number = _stringReference.ToString(); + + try + { + numberValue = number.StartsWith("0x", StringComparison.OrdinalIgnoreCase) ? Convert.ToInt64(number, 16) : Convert.ToInt64(number, 8); + } + catch (Exception ex) + { + throw JsonReaderException.Create(this, "Input string '{0}' is not a valid number.".FormatWith(CultureInfo.InvariantCulture, number), ex); + } + + numberType = JsonToken.Integer; + } + else + { + long value; + ParseResult parseResult = ConvertUtils.Int64TryParse(_stringReference.Chars, _stringReference.StartIndex, _stringReference.Length, out value); + if (parseResult == ParseResult.Success) + { + numberValue = value; + numberType = JsonToken.Integer; + } + else if (parseResult == ParseResult.Overflow) + { +#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) + string number = _stringReference.ToString(); + + if (number.Length > MaximumJavascriptIntegerCharacterLength) + { + throw JsonReaderException.Create(this, "JSON integer {0} is too large to parse.".FormatWith(CultureInfo.InvariantCulture, _stringReference.ToString())); + } + + numberValue = BigIntegerParse(number, CultureInfo.InvariantCulture); + numberType = JsonToken.Integer; +#else + throw JsonReaderException.Create(this, "JSON integer {0} is too large or small for an Int64.".FormatWith(CultureInfo.InvariantCulture, _stringReference.ToString())); +#endif + } + else + { + string number = _stringReference.ToString(); + + if (_floatParseHandling == FloatParseHandling.Decimal) + { + decimal d; + if (decimal.TryParse(number, NumberStyles.Number | NumberStyles.AllowExponent, CultureInfo.InvariantCulture, out d)) + { + numberValue = d; + } + else + { + throw JsonReaderException.Create(this, "Input string '{0}' is not a valid decimal.".FormatWith(CultureInfo.InvariantCulture, number)); + } + } + else + { + double d; + if (double.TryParse(number, NumberStyles.Float | NumberStyles.AllowThousands, CultureInfo.InvariantCulture, out d)) + { + numberValue = d; + } + else + { + throw JsonReaderException.Create(this, "Input string '{0}' is not a valid number.".FormatWith(CultureInfo.InvariantCulture, number)); + } + } + + numberType = JsonToken.Float; + } + } + } + + ClearRecentString(); + + // index has already been updated + SetToken(numberType, numberValue, false); + } + +#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) + // By using the BigInteger type in a separate method, + // the runtime can execute the ParseNumber even if + // the System.Numerics.BigInteger.Parse method is + // missing, which happens in some versions of Mono + [MethodImpl(MethodImplOptions.NoInlining)] + private static object BigIntegerParse(string number, CultureInfo culture) + { + return System.Numerics.BigInteger.Parse(number, culture); + } +#endif + + private void ParseComment(bool setToken) + { + // should have already parsed / character before reaching this method + _charPos++; + + if (!EnsureChars(1, false)) + { + throw JsonReaderException.Create(this, "Unexpected end while parsing comment."); + } + + bool singlelineComment; + + if (_chars[_charPos] == '*') + { + singlelineComment = false; + } + else if (_chars[_charPos] == '/') + { + singlelineComment = true; + } + else + { + throw JsonReaderException.Create(this, "Error parsing comment. Expected: *, got {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos])); + } + + _charPos++; + + int initialPosition = _charPos; + + while (true) + { + switch (_chars[_charPos]) + { + case '\0': + if (_charsUsed == _charPos) + { + if (ReadData(true) == 0) + { + if (!singlelineComment) + { + throw JsonReaderException.Create(this, "Unexpected end while parsing comment."); + } + + EndComment(setToken, initialPosition, _charPos); + return; + } + } + else + { + _charPos++; + } + break; + case '*': + _charPos++; + + if (!singlelineComment) + { + if (EnsureChars(0, true)) + { + if (_chars[_charPos] == '/') + { + EndComment(setToken, initialPosition, _charPos - 1); + + _charPos++; + return; + } + } + } + break; + case StringUtils.CarriageReturn: + if (singlelineComment) + { + EndComment(setToken, initialPosition, _charPos); + return; + } + ProcessCarriageReturn(true); + break; + case StringUtils.LineFeed: + if (singlelineComment) + { + EndComment(setToken, initialPosition, _charPos); + return; + } + ProcessLineFeed(); + break; + default: + _charPos++; + break; + } + } + } + + private void EndComment(bool setToken, int initialPosition, int endPosition) + { + if (setToken) + { + SetToken(JsonToken.Comment, new string(_chars, initialPosition, endPosition - initialPosition)); + } + } + + private bool MatchValue(string value) + { + if (!EnsureChars(value.Length - 1, true)) + { + _charPos = _charsUsed; + throw CreateUnexpectedEndException(); + } + + for (int i = 0; i < value.Length; i++) + { + if (_chars[_charPos + i] != value[i]) + { + _charPos += i; + return false; + } + } + + _charPos += value.Length; + + return true; + } + + private bool MatchValueWithTrailingSeparator(string value) + { + // will match value and then move to the next character, checking that it is a separator character + bool match = MatchValue(value); + + if (!match) + { + return false; + } + + if (!EnsureChars(0, false)) + { + return true; + } + + return IsSeparator(_chars[_charPos]) || _chars[_charPos] == '\0'; + } + + private bool IsSeparator(char c) + { + switch (c) + { + case '}': + case ']': + case ',': + return true; + case '/': + // check next character to see if start of a comment + if (!EnsureChars(1, false)) + { + return false; + } + + var nextChart = _chars[_charPos + 1]; + + return (nextChart == '*' || nextChart == '/'); + case ')': + if (CurrentState == State.Constructor || CurrentState == State.ConstructorStart) + { + return true; + } + break; + case ' ': + case StringUtils.Tab: + case StringUtils.LineFeed: + case StringUtils.CarriageReturn: + return true; + default: + if (char.IsWhiteSpace(c)) + { + return true; + } + break; + } + + return false; + } + + private void ParseTrue() + { + // check characters equal 'true' + // and that it is followed by either a separator character + // or the text ends + if (MatchValueWithTrailingSeparator(JsonConvert.True)) + { + SetToken(JsonToken.Boolean, true); + } + else + { + throw JsonReaderException.Create(this, "Error parsing boolean value."); + } + } + + private void ParseNull() + { + if (MatchValueWithTrailingSeparator(JsonConvert.Null)) + { + SetToken(JsonToken.Null); + } + else + { + throw JsonReaderException.Create(this, "Error parsing null value."); + } + } + + private void ParseUndefined() + { + if (MatchValueWithTrailingSeparator(JsonConvert.Undefined)) + { + SetToken(JsonToken.Undefined); + } + else + { + throw JsonReaderException.Create(this, "Error parsing undefined value."); + } + } + + private void ParseFalse() + { + if (MatchValueWithTrailingSeparator(JsonConvert.False)) + { + SetToken(JsonToken.Boolean, false); + } + else + { + throw JsonReaderException.Create(this, "Error parsing boolean value."); + } + } + + private void ParseNumberNegativeInfinity() + { + if (MatchValueWithTrailingSeparator(JsonConvert.NegativeInfinity)) + { + if (_floatParseHandling == FloatParseHandling.Decimal) + { + throw new JsonReaderException("Cannot read -Infinity as a decimal."); + } + + SetToken(JsonToken.Float, double.NegativeInfinity); + } + else + { + throw JsonReaderException.Create(this, "Error parsing negative infinity value."); + } + } + + private void ParseNumberPositiveInfinity() + { + if (MatchValueWithTrailingSeparator(JsonConvert.PositiveInfinity)) + { + if (_floatParseHandling == FloatParseHandling.Decimal) + { + throw new JsonReaderException("Cannot read Infinity as a decimal."); + } + + SetToken(JsonToken.Float, double.PositiveInfinity); + } + else + { + throw JsonReaderException.Create(this, "Error parsing positive infinity value."); + } + } + + private void ParseNumberNaN() + { + if (MatchValueWithTrailingSeparator(JsonConvert.NaN)) + { + if (_floatParseHandling == FloatParseHandling.Decimal) + { + throw new JsonReaderException("Cannot read NaN as a decimal."); + } + + SetToken(JsonToken.Float, double.NaN); + } + else + { + throw JsonReaderException.Create(this, "Error parsing NaN value."); + } + } + + /// + /// Changes the state to closed. + /// + public override void Close() + { + base.Close(); + + if (_chars != null) + { + BufferUtils.ReturnBuffer(_arrayPool, _chars); + _chars = null; + } + + if (CloseInput && _reader != null) + { +#if !(DOTNET || PORTABLE40 || PORTABLE) + _reader.Close(); +#else + _reader.Dispose(); +#endif + } + + _stringBuffer.Clear(_arrayPool); + } + + /// + /// Gets a value indicating whether the class can return line information. + /// + /// + /// true if LineNumber and LinePosition can be provided; otherwise, false. + /// + public bool HasLineInfo() + { + return true; + } + + /// + /// Gets the current line number. + /// + /// + /// The current line number or 0 if no line information is available (for example, HasLineInfo returns false). + /// + public int LineNumber + { + get + { + if (CurrentState == State.Start && LinePosition == 0 && TokenType != JsonToken.Comment) + { + return 0; + } + + return _lineNumber; + } + } + + /// + /// Gets the current line position. + /// + /// + /// The current line position or 0 if no line information is available (for example, HasLineInfo returns false). + /// + public int LinePosition + { + get { return _charPos - _lineStartPos; } + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/JsonTextWriter.cs b/Common/00-1Json8.3/Json8.3/JsonTextWriter.cs new file mode 100644 index 0000000..8367846 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/JsonTextWriter.cs @@ -0,0 +1,807 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Collections.Generic; +using System.Globalization; +#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) +using System.Numerics; +#endif +using System.Text; +using System.IO; +using System.Xml; +using Newtonsoft.Json.Utilities; + +namespace Newtonsoft.Json +{ + /// + /// Represents a writer that provides a fast, non-cached, forward-only way of generating JSON data. + /// + public class JsonTextWriter : JsonWriter + { + private readonly TextWriter _writer; + private Base64Encoder _base64Encoder; + private char _indentChar; + private int _indentation; + private char _quoteChar; + private bool _quoteName; + private bool[] _charEscapeFlags; + private char[] _writeBuffer; + private IArrayPool _arrayPool; + private char[] _indentChars; + + private Base64Encoder Base64Encoder + { + get + { + if (_base64Encoder == null) + { + _base64Encoder = new Base64Encoder(_writer); + } + + return _base64Encoder; + } + } + + /// + /// Gets or sets the writer's character array pool. + /// + public IArrayPool ArrayPool + { + get { return _arrayPool; } + set + { + if (value == null) + { + throw new ArgumentNullException(nameof(value)); + } + + _arrayPool = value; + } + } + + /// + /// Gets or sets how many IndentChars to write for each level in the hierarchy when is set to Formatting.Indented. + /// + public int Indentation + { + get { return _indentation; } + set + { + if (value < 0) + { + throw new ArgumentException("Indentation value must be greater than 0."); + } + + _indentation = value; + } + } + + /// + /// Gets or sets which character to use to quote attribute values. + /// + public char QuoteChar + { + get { return _quoteChar; } + set + { + if (value != '"' && value != '\'') + { + throw new ArgumentException(@"Invalid JavaScript string quote character. Valid quote characters are ' and ""."); + } + + _quoteChar = value; + UpdateCharEscapeFlags(); + } + } + + /// + /// Gets or sets which character to use for indenting when is set to Formatting.Indented. + /// + public char IndentChar + { + get { return _indentChar; } + set + { + if (value != _indentChar) + { + _indentChar = value; + _indentChars = null; + } + } + } + + /// + /// Gets or sets a value indicating whether object names will be surrounded with quotes. + /// + public bool QuoteName + { + get { return _quoteName; } + set { _quoteName = value; } + } + + /// + /// Creates an instance of the JsonWriter class using the specified . + /// + /// The TextWriter to write to. + public JsonTextWriter(TextWriter textWriter) + { + if (textWriter == null) + { + throw new ArgumentNullException(nameof(textWriter)); + } + + _writer = textWriter; + _quoteChar = '"'; + _quoteName = true; + _indentChar = ' '; + _indentation = 2; + + UpdateCharEscapeFlags(); + } + + /// + /// Flushes whatever is in the buffer to the underlying streams and also flushes the underlying stream. + /// + public override void Flush() + { + _writer.Flush(); + } + + /// + /// Closes this stream and the underlying stream. + /// + public override void Close() + { + base.Close(); + + if (_writeBuffer != null) + { + BufferUtils.ReturnBuffer(_arrayPool, _writeBuffer); + _writeBuffer = null; + } + + if (CloseOutput && _writer != null) + { +#if !(DOTNET || PORTABLE40 || PORTABLE) + _writer.Close(); +#else + _writer.Dispose(); +#endif + } + } + + /// + /// Writes the beginning of a JSON object. + /// + public override void WriteStartObject() + { + InternalWriteStart(JsonToken.StartObject, JsonContainerType.Object); + + _writer.Write('{'); + } + + /// + /// Writes the beginning of a JSON array. + /// + public override void WriteStartArray() + { + InternalWriteStart(JsonToken.StartArray, JsonContainerType.Array); + + _writer.Write('['); + } + + /// + /// Writes the start of a constructor with the given name. + /// + /// The name of the constructor. + public override void WriteStartConstructor(string name) + { + InternalWriteStart(JsonToken.StartConstructor, JsonContainerType.Constructor); + + _writer.Write("new "); + _writer.Write(name); + _writer.Write('('); + } + + /// + /// Writes the specified end token. + /// + /// The end token to write. + protected override void WriteEnd(JsonToken token) + { + switch (token) + { + case JsonToken.EndObject: + _writer.Write('}'); + break; + case JsonToken.EndArray: + _writer.Write(']'); + break; + case JsonToken.EndConstructor: + _writer.Write(')'); + break; + default: + throw JsonWriterException.Create(this, "Invalid JsonToken: " + token, null); + } + } + + /// + /// Writes the property name of a name/value pair on a JSON object. + /// + /// The name of the property. + public override void WritePropertyName(string name) + { + InternalWritePropertyName(name); + + WriteEscapedString(name, _quoteName); + + _writer.Write(':'); + } + + /// + /// Writes the property name of a name/value pair on a JSON object. + /// + /// The name of the property. + /// A flag to indicate whether the text should be escaped when it is written as a JSON property name. + public override void WritePropertyName(string name, bool escape) + { + InternalWritePropertyName(name); + + if (escape) + { + WriteEscapedString(name, _quoteName); + } + else + { + if (_quoteName) + { + _writer.Write(_quoteChar); + } + + _writer.Write(name); + + if (_quoteName) + { + _writer.Write(_quoteChar); + } + } + + _writer.Write(':'); + } + + internal override void OnStringEscapeHandlingChanged() + { + UpdateCharEscapeFlags(); + } + + private void UpdateCharEscapeFlags() + { + _charEscapeFlags = JavaScriptUtils.GetCharEscapeFlags(StringEscapeHandling, _quoteChar); + } + + /// + /// Writes indent characters. + /// + protected override void WriteIndent() + { + _writer.WriteLine(); + + // levels of indentation multiplied by the indent count + int currentIndentCount = Top * _indentation; + + if (currentIndentCount > 0) + { + if (_indentChars == null) + { + _indentChars = new string(_indentChar, 10).ToCharArray(); + } + + while (currentIndentCount > 0) + { + int writeCount = Math.Min(currentIndentCount, 10); + + _writer.Write(_indentChars, 0, writeCount); + + currentIndentCount -= writeCount; + } + } + } + + /// + /// Writes the JSON value delimiter. + /// + protected override void WriteValueDelimiter() + { + _writer.Write(','); + } + + /// + /// Writes an indent space. + /// + protected override void WriteIndentSpace() + { + _writer.Write(' '); + } + + private void WriteValueInternal(string value, JsonToken token) + { + _writer.Write(value); + } + + #region WriteValue methods + /// + /// Writes a value. + /// An error will raised if the value cannot be written as a single JSON token. + /// + /// The value to write. + public override void WriteValue(object value) + { +#if !(NET20 || NET35 || PORTABLE || PORTABLE40) + if (value is BigInteger) + { + InternalWriteValue(JsonToken.Integer); + WriteValueInternal(((BigInteger)value).ToString(CultureInfo.InvariantCulture), JsonToken.String); + } + else +#endif + { + base.WriteValue(value); + } + } + + /// + /// Writes a null value. + /// + public override void WriteNull() + { + InternalWriteValue(JsonToken.Null); + WriteValueInternal(JsonConvert.Null, JsonToken.Null); + } + + /// + /// Writes an undefined value. + /// + public override void WriteUndefined() + { + InternalWriteValue(JsonToken.Undefined); + WriteValueInternal(JsonConvert.Undefined, JsonToken.Undefined); + } + + /// + /// Writes raw JSON. + /// + /// The raw JSON to write. + public override void WriteRaw(string json) + { + InternalWriteRaw(); + + _writer.Write(json); + } + + /// + /// Writes a value. + /// + /// The value to write. + public override void WriteValue(string value) + { + InternalWriteValue(JsonToken.String); + + if (value == null) + { + WriteValueInternal(JsonConvert.Null, JsonToken.Null); + } + else + { + WriteEscapedString(value, true); + } + } + + private void WriteEscapedString(string value, bool quote) + { + EnsureWriteBuffer(); + JavaScriptUtils.WriteEscapedJavaScriptString(_writer, value, _quoteChar, quote, _charEscapeFlags, StringEscapeHandling, _arrayPool, ref _writeBuffer); + } + + /// + /// Writes a value. + /// + /// The value to write. + public override void WriteValue(int value) + { + InternalWriteValue(JsonToken.Integer); + WriteIntegerValue(value); + } + + /// + /// Writes a value. + /// + /// The value to write. + [CLSCompliant(false)] + public override void WriteValue(uint value) + { + InternalWriteValue(JsonToken.Integer); + WriteIntegerValue(value); + } + + /// + /// Writes a value. + /// + /// The value to write. + public override void WriteValue(long value) + { + InternalWriteValue(JsonToken.Integer); + WriteIntegerValue(value); + } + + /// + /// Writes a value. + /// + /// The value to write. + [CLSCompliant(false)] + public override void WriteValue(ulong value) + { + InternalWriteValue(JsonToken.Integer); + WriteIntegerValue(value); + } + + /// + /// Writes a value. + /// + /// The value to write. + public override void WriteValue(float value) + { + InternalWriteValue(JsonToken.Float); + WriteValueInternal(JsonConvert.ToString(value, FloatFormatHandling, QuoteChar, false), JsonToken.Float); + } + + /// + /// Writes a value. + /// + /// The value to write. + public override void WriteValue(float? value) + { + if (value == null) + { + WriteNull(); + } + else + { + InternalWriteValue(JsonToken.Float); + WriteValueInternal(JsonConvert.ToString(value.GetValueOrDefault(), FloatFormatHandling, QuoteChar, true), JsonToken.Float); + } + } + + /// + /// Writes a value. + /// + /// The value to write. + public override void WriteValue(double value) + { + InternalWriteValue(JsonToken.Float); + WriteValueInternal(JsonConvert.ToString(value, FloatFormatHandling, QuoteChar, false), JsonToken.Float); + } + + /// + /// Writes a value. + /// + /// The value to write. + public override void WriteValue(double? value) + { + if (value == null) + { + WriteNull(); + } + else + { + InternalWriteValue(JsonToken.Float); + WriteValueInternal(JsonConvert.ToString(value.GetValueOrDefault(), FloatFormatHandling, QuoteChar, true), JsonToken.Float); + } + } + + /// + /// Writes a value. + /// + /// The value to write. + public override void WriteValue(bool value) + { + InternalWriteValue(JsonToken.Boolean); + WriteValueInternal(JsonConvert.ToString(value), JsonToken.Boolean); + } + + /// + /// Writes a value. + /// + /// The value to write. + public override void WriteValue(short value) + { + InternalWriteValue(JsonToken.Integer); + WriteIntegerValue(value); + } + + /// + /// Writes a value. + /// + /// The value to write. + [CLSCompliant(false)] + public override void WriteValue(ushort value) + { + InternalWriteValue(JsonToken.Integer); + WriteIntegerValue(value); + } + + /// + /// Writes a value. + /// + /// The value to write. + public override void WriteValue(char value) + { + InternalWriteValue(JsonToken.String); + WriteValueInternal(JsonConvert.ToString(value), JsonToken.String); + } + + /// + /// Writes a value. + /// + /// The value to write. + public override void WriteValue(byte value) + { + InternalWriteValue(JsonToken.Integer); + WriteIntegerValue(value); + } + + /// + /// Writes a value. + /// + /// The value to write. + [CLSCompliant(false)] + public override void WriteValue(sbyte value) + { + InternalWriteValue(JsonToken.Integer); + WriteIntegerValue(value); + } + + /// + /// Writes a value. + /// + /// The value to write. + public override void WriteValue(decimal value) + { + InternalWriteValue(JsonToken.Float); + WriteValueInternal(JsonConvert.ToString(value), JsonToken.Float); + } + + /// + /// Writes a value. + /// + /// The value to write. + public override void WriteValue(DateTime value) + { + InternalWriteValue(JsonToken.Date); + value = DateTimeUtils.EnsureDateTime(value, DateTimeZoneHandling); + + if (string.IsNullOrEmpty(DateFormatString)) + { + EnsureWriteBuffer(); + + int pos = 0; + _writeBuffer[pos++] = _quoteChar; + pos = DateTimeUtils.WriteDateTimeString(_writeBuffer, pos, value, null, value.Kind, DateFormatHandling); + _writeBuffer[pos++] = _quoteChar; + + _writer.Write(_writeBuffer, 0, pos); + } + else + { + _writer.Write(_quoteChar); + _writer.Write(value.ToString(DateFormatString, Culture)); + _writer.Write(_quoteChar); + } + } + + /// + /// Writes a [] value. + /// + /// The [] value to write. + public override void WriteValue(byte[] value) + { + if (value == null) + { + WriteNull(); + } + else + { + InternalWriteValue(JsonToken.Bytes); + _writer.Write(_quoteChar); + Base64Encoder.Encode(value, 0, value.Length); + Base64Encoder.Flush(); + _writer.Write(_quoteChar); + } + } + +#if !NET20 + /// + /// Writes a value. + /// + /// The value to write. + public override void WriteValue(DateTimeOffset value) + { + InternalWriteValue(JsonToken.Date); + + if (string.IsNullOrEmpty(DateFormatString)) + { + EnsureWriteBuffer(); + + int pos = 0; + _writeBuffer[pos++] = _quoteChar; + pos = DateTimeUtils.WriteDateTimeString(_writeBuffer, pos, (DateFormatHandling == DateFormatHandling.IsoDateFormat) ? value.DateTime : value.UtcDateTime, value.Offset, DateTimeKind.Local, DateFormatHandling); + _writeBuffer[pos++] = _quoteChar; + + _writer.Write(_writeBuffer, 0, pos); + } + else + { + _writer.Write(_quoteChar); + _writer.Write(value.ToString(DateFormatString, Culture)); + _writer.Write(_quoteChar); + } + } +#endif + + /// + /// Writes a value. + /// + /// The value to write. + public override void WriteValue(Guid value) + { + InternalWriteValue(JsonToken.String); + + string text = null; + +#if !(DOTNET || PORTABLE40 || PORTABLE) + text = value.ToString("D", CultureInfo.InvariantCulture); +#else + text = value.ToString("D"); +#endif + + _writer.Write(_quoteChar); + _writer.Write(text); + _writer.Write(_quoteChar); + } + + /// + /// Writes a value. + /// + /// The value to write. + public override void WriteValue(TimeSpan value) + { + InternalWriteValue(JsonToken.String); + + string text; +#if (NET35 || NET20) + text = value.ToString(); +#else + text = value.ToString(null, CultureInfo.InvariantCulture); +#endif + + _writer.Write(_quoteChar); + _writer.Write(text); + _writer.Write(_quoteChar); + } + + /// + /// Writes a value. + /// + /// The value to write. + public override void WriteValue(Uri value) + { + if (value == null) + { + WriteNull(); + } + else + { + InternalWriteValue(JsonToken.String); + WriteEscapedString(value.OriginalString, true); + } + } + #endregion + + /// + /// Writes out a comment /*...*/ containing the specified text. + /// + /// Text to place inside the comment. + public override void WriteComment(string text) + { + InternalWriteComment(); + + _writer.Write("/*"); + _writer.Write(text); + _writer.Write("*/"); + } + + /// + /// Writes out the given white space. + /// + /// The string of white space characters. + public override void WriteWhitespace(string ws) + { + InternalWriteWhitespace(ws); + + _writer.Write(ws); + } + + private void EnsureWriteBuffer() + { + if (_writeBuffer == null) + { + // maximum buffer sized used when writing iso date + _writeBuffer = BufferUtils.RentBuffer(_arrayPool, 35); + } + } + + private void WriteIntegerValue(long value) + { + if (value >= 0 && value <= 9) + { + _writer.Write((char)('0' + value)); + } + else + { + ulong uvalue = (value < 0) ? (ulong)-value : (ulong)value; + + if (value < 0) + { + _writer.Write('-'); + } + + WriteIntegerValue(uvalue); + } + } + + private void WriteIntegerValue(ulong uvalue) + { + if (uvalue <= 9) + { + _writer.Write((char)('0' + uvalue)); + } + else + { + EnsureWriteBuffer(); + + int totalLength = MathUtils.IntLength(uvalue); + int length = 0; + + do + { + _writeBuffer[totalLength - ++length] = (char)('0' + (uvalue % 10)); + uvalue /= 10; + } while (uvalue != 0); + + _writer.Write(_writeBuffer, 0, length); + } + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/JsonToken.cs b/Common/00-1Json8.3/Json8.3/JsonToken.cs new file mode 100644 index 0000000..aa93ce2 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/JsonToken.cs @@ -0,0 +1,127 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Collections.Generic; +using System.Text; + +namespace Newtonsoft.Json +{ + /// + /// Specifies the type of JSON token. + /// + public enum JsonToken + { + /// + /// This is returned by the if a method has not been called. + /// + None = 0, + + /// + /// An object start token. + /// + StartObject = 1, + + /// + /// An array start token. + /// + StartArray = 2, + + /// + /// A constructor start token. + /// + StartConstructor = 3, + + /// + /// An object property name. + /// + PropertyName = 4, + + /// + /// A comment. + /// + Comment = 5, + + /// + /// Raw JSON. + /// + Raw = 6, + + /// + /// An integer. + /// + Integer = 7, + + /// + /// A float. + /// + Float = 8, + + /// + /// A string. + /// + String = 9, + + /// + /// A boolean. + /// + Boolean = 10, + + /// + /// A null token. + /// + Null = 11, + + /// + /// An undefined token. + /// + Undefined = 12, + + /// + /// An object end token. + /// + EndObject = 13, + + /// + /// An array end token. + /// + EndArray = 14, + + /// + /// A constructor end token. + /// + EndConstructor = 15, + + /// + /// A Date. + /// + Date = 16, + + /// + /// Byte data. + /// + Bytes = 17 + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/JsonValidatingReader.cs b/Common/00-1Json8.3/Json8.3/JsonValidatingReader.cs new file mode 100644 index 0000000..260791b --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/JsonValidatingReader.cs @@ -0,0 +1,1058 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Collections.Generic; +#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) +using System.Numerics; +#endif +using Newtonsoft.Json.Linq; +using Newtonsoft.Json.Schema; +using Newtonsoft.Json.Utilities; +using System.Globalization; +using System.Text.RegularExpressions; +using System.IO; +#if NET20 +using Newtonsoft.Json.Utilities.LinqBridge; +#else +using System.Linq; + +#endif + +namespace Newtonsoft.Json +{ + /// + /// + /// Represents a reader that provides validation. + /// + /// + /// JSON Schema validation has been moved to its own package. See http://www.newtonsoft.com/jsonschema for more details. + /// + /// + [Obsolete("JSON Schema validation has been moved to its own package. See http://www.newtonsoft.com/jsonschema for more details.")] + public class JsonValidatingReader : JsonReader, IJsonLineInfo + { + private class SchemaScope + { + private readonly JTokenType _tokenType; + private readonly IList _schemas; + private readonly Dictionary _requiredProperties; + + public string CurrentPropertyName { get; set; } + public int ArrayItemCount { get; set; } + public bool IsUniqueArray { get; set; } + public IList UniqueArrayItems { get; set; } + public JTokenWriter CurrentItemWriter { get; set; } + + public IList Schemas + { + get { return _schemas; } + } + + public Dictionary RequiredProperties + { + get { return _requiredProperties; } + } + + public JTokenType TokenType + { + get { return _tokenType; } + } + + public SchemaScope(JTokenType tokenType, IList schemas) + { + _tokenType = tokenType; + _schemas = schemas; + + _requiredProperties = schemas.SelectMany(GetRequiredProperties).Distinct().ToDictionary(p => p, p => false); + + if (tokenType == JTokenType.Array && schemas.Any(s => s.UniqueItems)) + { + IsUniqueArray = true; + UniqueArrayItems = new List(); + } + } + + private IEnumerable GetRequiredProperties(JsonSchemaModel schema) + { + if (schema == null || schema.Properties == null) + { + return Enumerable.Empty(); + } + + return schema.Properties.Where(p => p.Value.Required).Select(p => p.Key); + } + } + + private readonly JsonReader _reader; + private readonly Stack _stack; + private JsonSchema _schema; + private JsonSchemaModel _model; + private SchemaScope _currentScope; + + /// + /// Sets an event handler for receiving schema validation errors. + /// + public event ValidationEventHandler ValidationEventHandler; + + /// + /// Gets the text value of the current JSON token. + /// + /// + public override object Value + { + get { return _reader.Value; } + } + + /// + /// Gets the depth of the current token in the JSON document. + /// + /// The depth of the current token in the JSON document. + public override int Depth + { + get { return _reader.Depth; } + } + + /// + /// Gets the path of the current JSON token. + /// + public override string Path + { + get { return _reader.Path; } + } + + /// + /// Gets the quotation mark character used to enclose the value of a string. + /// + /// + public override char QuoteChar + { + get { return _reader.QuoteChar; } + protected internal set { } + } + + /// + /// Gets the type of the current JSON token. + /// + /// + public override JsonToken TokenType + { + get { return _reader.TokenType; } + } + + /// + /// Gets the Common Language Runtime (CLR) type for the current JSON token. + /// + /// + public override Type ValueType + { + get { return _reader.ValueType; } + } + + private void Push(SchemaScope scope) + { + _stack.Push(scope); + _currentScope = scope; + } + + private SchemaScope Pop() + { + SchemaScope poppedScope = _stack.Pop(); + _currentScope = (_stack.Count != 0) + ? _stack.Peek() + : null; + + return poppedScope; + } + + private IList CurrentSchemas + { + get { return _currentScope.Schemas; } + } + + private static readonly IList EmptySchemaList = new List(); + + private IList CurrentMemberSchemas + { + get + { + if (_currentScope == null) + { + return new List(new[] { _model }); + } + + if (_currentScope.Schemas == null || _currentScope.Schemas.Count == 0) + { + return EmptySchemaList; + } + + switch (_currentScope.TokenType) + { + case JTokenType.None: + return _currentScope.Schemas; + case JTokenType.Object: + { + if (_currentScope.CurrentPropertyName == null) + { + throw new JsonReaderException("CurrentPropertyName has not been set on scope."); + } + + IList schemas = new List(); + + foreach (JsonSchemaModel schema in CurrentSchemas) + { + JsonSchemaModel propertySchema; + if (schema.Properties != null && schema.Properties.TryGetValue(_currentScope.CurrentPropertyName, out propertySchema)) + { + schemas.Add(propertySchema); + } + if (schema.PatternProperties != null) + { + foreach (KeyValuePair patternProperty in schema.PatternProperties) + { + if (Regex.IsMatch(_currentScope.CurrentPropertyName, patternProperty.Key)) + { + schemas.Add(patternProperty.Value); + } + } + } + + if (schemas.Count == 0 && schema.AllowAdditionalProperties && schema.AdditionalProperties != null) + { + schemas.Add(schema.AdditionalProperties); + } + } + + return schemas; + } + case JTokenType.Array: + { + IList schemas = new List(); + + foreach (JsonSchemaModel schema in CurrentSchemas) + { + if (!schema.PositionalItemsValidation) + { + if (schema.Items != null && schema.Items.Count > 0) + { + schemas.Add(schema.Items[0]); + } + } + else + { + if (schema.Items != null && schema.Items.Count > 0) + { + if (schema.Items.Count > (_currentScope.ArrayItemCount - 1)) + { + schemas.Add(schema.Items[_currentScope.ArrayItemCount - 1]); + } + } + + if (schema.AllowAdditionalItems && schema.AdditionalItems != null) + { + schemas.Add(schema.AdditionalItems); + } + } + } + + return schemas; + } + case JTokenType.Constructor: + return EmptySchemaList; + default: + throw new ArgumentOutOfRangeException("TokenType", "Unexpected token type: {0}".FormatWith(CultureInfo.InvariantCulture, _currentScope.TokenType)); + } + } + } + + private void RaiseError(string message, JsonSchemaModel schema) + { + IJsonLineInfo lineInfo = this; + + string exceptionMessage = (lineInfo.HasLineInfo()) + ? message + " Line {0}, position {1}.".FormatWith(CultureInfo.InvariantCulture, lineInfo.LineNumber, lineInfo.LinePosition) + : message; + + OnValidationEvent(new JsonSchemaException(exceptionMessage, null, Path, lineInfo.LineNumber, lineInfo.LinePosition)); + } + + private void OnValidationEvent(JsonSchemaException exception) + { + ValidationEventHandler handler = ValidationEventHandler; + if (handler != null) + { + handler(this, new ValidationEventArgs(exception)); + } + else + { + throw exception; + } + } + + /// + /// Initializes a new instance of the class that + /// validates the content returned from the given . + /// + /// The to read from while validating. + public JsonValidatingReader(JsonReader reader) + { + ValidationUtils.ArgumentNotNull(reader, nameof(reader)); + _reader = reader; + _stack = new Stack(); + } + + /// + /// Gets or sets the schema. + /// + /// The schema. + public JsonSchema Schema + { + get { return _schema; } + set + { + if (TokenType != JsonToken.None) + { + throw new InvalidOperationException("Cannot change schema while validating JSON."); + } + + _schema = value; + _model = null; + } + } + + /// + /// Gets the used to construct this . + /// + /// The specified in the constructor. + public JsonReader Reader + { + get { return _reader; } + } + + private void ValidateNotDisallowed(JsonSchemaModel schema) + { + if (schema == null) + { + return; + } + + JsonSchemaType? currentNodeType = GetCurrentNodeSchemaType(); + if (currentNodeType != null) + { + if (JsonSchemaGenerator.HasFlag(schema.Disallow, currentNodeType.GetValueOrDefault())) + { + RaiseError("Type {0} is disallowed.".FormatWith(CultureInfo.InvariantCulture, currentNodeType), schema); + } + } + } + + private JsonSchemaType? GetCurrentNodeSchemaType() + { + switch (_reader.TokenType) + { + case JsonToken.StartObject: + return JsonSchemaType.Object; + case JsonToken.StartArray: + return JsonSchemaType.Array; + case JsonToken.Integer: + return JsonSchemaType.Integer; + case JsonToken.Float: + return JsonSchemaType.Float; + case JsonToken.String: + return JsonSchemaType.String; + case JsonToken.Boolean: + return JsonSchemaType.Boolean; + case JsonToken.Null: + return JsonSchemaType.Null; + default: + return null; + } + } + + /// + /// Reads the next JSON token from the stream as a . + /// + /// A . + public override int? ReadAsInt32() + { + int? i = _reader.ReadAsInt32(); + + ValidateCurrentToken(); + return i; + } + + /// + /// Reads the next JSON token from the stream as a []. + /// + /// + /// A [] or a null reference if the next JSON token is null. + /// + public override byte[] ReadAsBytes() + { + byte[] data = _reader.ReadAsBytes(); + + ValidateCurrentToken(); + return data; + } + + /// + /// Reads the next JSON token from the stream as a . + /// + /// A . + public override decimal? ReadAsDecimal() + { + decimal? d = _reader.ReadAsDecimal(); + + ValidateCurrentToken(); + return d; + } + + /// + /// Reads the next JSON token from the stream as a . + /// + /// A . + public override double? ReadAsDouble() + { + double? d = _reader.ReadAsDouble(); + + ValidateCurrentToken(); + return d; + } + + /// + /// Reads the next JSON token from the stream as a . + /// + /// A . + public override bool? ReadAsBoolean() + { + bool? b = _reader.ReadAsBoolean(); + + ValidateCurrentToken(); + return b; + } + + /// + /// Reads the next JSON token from the stream as a . + /// + /// A . This method will return null at the end of an array. + public override string ReadAsString() + { + string s = _reader.ReadAsString(); + + ValidateCurrentToken(); + return s; + } + + /// + /// Reads the next JSON token from the stream as a . + /// + /// A . This method will return null at the end of an array. + public override DateTime? ReadAsDateTime() + { + DateTime? dateTime = _reader.ReadAsDateTime(); + + ValidateCurrentToken(); + return dateTime; + } + +#if !NET20 + /// + /// Reads the next JSON token from the stream as a . + /// + /// A . + public override DateTimeOffset? ReadAsDateTimeOffset() + { + DateTimeOffset? dateTimeOffset = _reader.ReadAsDateTimeOffset(); + + ValidateCurrentToken(); + return dateTimeOffset; + } +#endif + + /// + /// Reads the next JSON token from the stream. + /// + /// + /// true if the next token was read successfully; false if there are no more tokens to read. + /// + public override bool Read() + { + if (!_reader.Read()) + { + return false; + } + + if (_reader.TokenType == JsonToken.Comment) + { + return true; + } + + ValidateCurrentToken(); + return true; + } + + private void ValidateCurrentToken() + { + // first time validate has been called. build model + if (_model == null) + { + JsonSchemaModelBuilder builder = new JsonSchemaModelBuilder(); + _model = builder.Build(_schema); + + if (!JsonTokenUtils.IsStartToken(_reader.TokenType)) + { + Push(new SchemaScope(JTokenType.None, CurrentMemberSchemas)); + } + } + + switch (_reader.TokenType) + { + case JsonToken.StartObject: + ProcessValue(); + IList objectSchemas = CurrentMemberSchemas.Where(ValidateObject).ToList(); + Push(new SchemaScope(JTokenType.Object, objectSchemas)); + WriteToken(CurrentSchemas); + break; + case JsonToken.StartArray: + ProcessValue(); + IList arraySchemas = CurrentMemberSchemas.Where(ValidateArray).ToList(); + Push(new SchemaScope(JTokenType.Array, arraySchemas)); + WriteToken(CurrentSchemas); + break; + case JsonToken.StartConstructor: + ProcessValue(); + Push(new SchemaScope(JTokenType.Constructor, null)); + WriteToken(CurrentSchemas); + break; + case JsonToken.PropertyName: + WriteToken(CurrentSchemas); + foreach (JsonSchemaModel schema in CurrentSchemas) + { + ValidatePropertyName(schema); + } + break; + case JsonToken.Raw: + ProcessValue(); + break; + case JsonToken.Integer: + ProcessValue(); + WriteToken(CurrentMemberSchemas); + foreach (JsonSchemaModel schema in CurrentMemberSchemas) + { + ValidateInteger(schema); + } + break; + case JsonToken.Float: + ProcessValue(); + WriteToken(CurrentMemberSchemas); + foreach (JsonSchemaModel schema in CurrentMemberSchemas) + { + ValidateFloat(schema); + } + break; + case JsonToken.String: + ProcessValue(); + WriteToken(CurrentMemberSchemas); + foreach (JsonSchemaModel schema in CurrentMemberSchemas) + { + ValidateString(schema); + } + break; + case JsonToken.Boolean: + ProcessValue(); + WriteToken(CurrentMemberSchemas); + foreach (JsonSchemaModel schema in CurrentMemberSchemas) + { + ValidateBoolean(schema); + } + break; + case JsonToken.Null: + ProcessValue(); + WriteToken(CurrentMemberSchemas); + foreach (JsonSchemaModel schema in CurrentMemberSchemas) + { + ValidateNull(schema); + } + break; + case JsonToken.EndObject: + WriteToken(CurrentSchemas); + foreach (JsonSchemaModel schema in CurrentSchemas) + { + ValidateEndObject(schema); + } + Pop(); + break; + case JsonToken.EndArray: + WriteToken(CurrentSchemas); + foreach (JsonSchemaModel schema in CurrentSchemas) + { + ValidateEndArray(schema); + } + Pop(); + break; + case JsonToken.EndConstructor: + WriteToken(CurrentSchemas); + Pop(); + break; + case JsonToken.Undefined: + case JsonToken.Date: + case JsonToken.Bytes: + // these have no equivalent in JSON schema + WriteToken(CurrentMemberSchemas); + break; + case JsonToken.None: + // no content, do nothing + break; + default: + throw new ArgumentOutOfRangeException(); + } + } + + private void WriteToken(IList schemas) + { + foreach (SchemaScope schemaScope in _stack) + { + bool isInUniqueArray = (schemaScope.TokenType == JTokenType.Array && schemaScope.IsUniqueArray && schemaScope.ArrayItemCount > 0); + + if (isInUniqueArray || schemas.Any(s => s.Enum != null)) + { + if (schemaScope.CurrentItemWriter == null) + { + if (JsonTokenUtils.IsEndToken(_reader.TokenType)) + { + continue; + } + + schemaScope.CurrentItemWriter = new JTokenWriter(); + } + + schemaScope.CurrentItemWriter.WriteToken(_reader, false); + + // finished writing current item + if (schemaScope.CurrentItemWriter.Top == 0 && _reader.TokenType != JsonToken.PropertyName) + { + JToken finishedItem = schemaScope.CurrentItemWriter.Token; + + // start next item with new writer + schemaScope.CurrentItemWriter = null; + + if (isInUniqueArray) + { + if (schemaScope.UniqueArrayItems.Contains(finishedItem, JToken.EqualityComparer)) + { + RaiseError("Non-unique array item at index {0}.".FormatWith(CultureInfo.InvariantCulture, schemaScope.ArrayItemCount - 1), schemaScope.Schemas.First(s => s.UniqueItems)); + } + + schemaScope.UniqueArrayItems.Add(finishedItem); + } + else if (schemas.Any(s => s.Enum != null)) + { + foreach (JsonSchemaModel schema in schemas) + { + if (schema.Enum != null) + { + if (!schema.Enum.ContainsValue(finishedItem, JToken.EqualityComparer)) + { + StringWriter sw = new StringWriter(CultureInfo.InvariantCulture); + finishedItem.WriteTo(new JsonTextWriter(sw)); + + RaiseError("Value {0} is not defined in enum.".FormatWith(CultureInfo.InvariantCulture, sw.ToString()), schema); + } + } + } + } + } + } + } + } + + private void ValidateEndObject(JsonSchemaModel schema) + { + if (schema == null) + { + return; + } + + Dictionary requiredProperties = _currentScope.RequiredProperties; + + if (requiredProperties != null) + { + List unmatchedRequiredProperties = + requiredProperties.Where(kv => !kv.Value).Select(kv => kv.Key).ToList(); + + if (unmatchedRequiredProperties.Count > 0) + { + RaiseError("Required properties are missing from object: {0}.".FormatWith(CultureInfo.InvariantCulture, string.Join(", ", unmatchedRequiredProperties.ToArray())), schema); + } + } + } + + private void ValidateEndArray(JsonSchemaModel schema) + { + if (schema == null) + { + return; + } + + int arrayItemCount = _currentScope.ArrayItemCount; + + if (schema.MaximumItems != null && arrayItemCount > schema.MaximumItems) + { + RaiseError("Array item count {0} exceeds maximum count of {1}.".FormatWith(CultureInfo.InvariantCulture, arrayItemCount, schema.MaximumItems), schema); + } + + if (schema.MinimumItems != null && arrayItemCount < schema.MinimumItems) + { + RaiseError("Array item count {0} is less than minimum count of {1}.".FormatWith(CultureInfo.InvariantCulture, arrayItemCount, schema.MinimumItems), schema); + } + } + + private void ValidateNull(JsonSchemaModel schema) + { + if (schema == null) + { + return; + } + + if (!TestType(schema, JsonSchemaType.Null)) + { + return; + } + + ValidateNotDisallowed(schema); + } + + private void ValidateBoolean(JsonSchemaModel schema) + { + if (schema == null) + { + return; + } + + if (!TestType(schema, JsonSchemaType.Boolean)) + { + return; + } + + ValidateNotDisallowed(schema); + } + + private void ValidateString(JsonSchemaModel schema) + { + if (schema == null) + { + return; + } + + if (!TestType(schema, JsonSchemaType.String)) + { + return; + } + + ValidateNotDisallowed(schema); + + string value = _reader.Value.ToString(); + + if (schema.MaximumLength != null && value.Length > schema.MaximumLength) + { + RaiseError("String '{0}' exceeds maximum length of {1}.".FormatWith(CultureInfo.InvariantCulture, value, schema.MaximumLength), schema); + } + + if (schema.MinimumLength != null && value.Length < schema.MinimumLength) + { + RaiseError("String '{0}' is less than minimum length of {1}.".FormatWith(CultureInfo.InvariantCulture, value, schema.MinimumLength), schema); + } + + if (schema.Patterns != null) + { + foreach (string pattern in schema.Patterns) + { + if (!Regex.IsMatch(value, pattern)) + { + RaiseError("String '{0}' does not match regex pattern '{1}'.".FormatWith(CultureInfo.InvariantCulture, value, pattern), schema); + } + } + } + } + + private void ValidateInteger(JsonSchemaModel schema) + { + if (schema == null) + { + return; + } + + if (!TestType(schema, JsonSchemaType.Integer)) + { + return; + } + + ValidateNotDisallowed(schema); + + object value = _reader.Value; + + if (schema.Maximum != null) + { + if (JValue.Compare(JTokenType.Integer, value, schema.Maximum) > 0) + { + RaiseError("Integer {0} exceeds maximum value of {1}.".FormatWith(CultureInfo.InvariantCulture, value, schema.Maximum), schema); + } + if (schema.ExclusiveMaximum && JValue.Compare(JTokenType.Integer, value, schema.Maximum) == 0) + { + RaiseError("Integer {0} equals maximum value of {1} and exclusive maximum is true.".FormatWith(CultureInfo.InvariantCulture, value, schema.Maximum), schema); + } + } + + if (schema.Minimum != null) + { + if (JValue.Compare(JTokenType.Integer, value, schema.Minimum) < 0) + { + RaiseError("Integer {0} is less than minimum value of {1}.".FormatWith(CultureInfo.InvariantCulture, value, schema.Minimum), schema); + } + if (schema.ExclusiveMinimum && JValue.Compare(JTokenType.Integer, value, schema.Minimum) == 0) + { + RaiseError("Integer {0} equals minimum value of {1} and exclusive minimum is true.".FormatWith(CultureInfo.InvariantCulture, value, schema.Minimum), schema); + } + } + + if (schema.DivisibleBy != null) + { + bool notDivisible; +#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) + if (value is BigInteger) + { + // not that this will lose any decimal point on DivisibleBy + // so manually raise an error if DivisibleBy is not an integer and value is not zero + BigInteger i = (BigInteger)value; + bool divisibleNonInteger = !Math.Abs(schema.DivisibleBy.Value - Math.Truncate(schema.DivisibleBy.Value)).Equals(0); + if (divisibleNonInteger) + { + notDivisible = i != 0; + } + else + { + notDivisible = i % new BigInteger(schema.DivisibleBy.Value) != 0; + } + } + else +#endif + { + notDivisible = !IsZero(Convert.ToInt64(value, CultureInfo.InvariantCulture) % schema.DivisibleBy.GetValueOrDefault()); + } + + if (notDivisible) + { + RaiseError("Integer {0} is not evenly divisible by {1}.".FormatWith(CultureInfo.InvariantCulture, JsonConvert.ToString(value), schema.DivisibleBy), schema); + } + } + } + + private void ProcessValue() + { + if (_currentScope != null && _currentScope.TokenType == JTokenType.Array) + { + _currentScope.ArrayItemCount++; + + foreach (JsonSchemaModel currentSchema in CurrentSchemas) + { + // if there is positional validation and the array index is past the number of item validation schemas and there is no additonal items then error + if (currentSchema != null + && currentSchema.PositionalItemsValidation + && !currentSchema.AllowAdditionalItems + && (currentSchema.Items == null || _currentScope.ArrayItemCount - 1 >= currentSchema.Items.Count)) + { + RaiseError("Index {0} has not been defined and the schema does not allow additional items.".FormatWith(CultureInfo.InvariantCulture, _currentScope.ArrayItemCount), currentSchema); + } + } + } + } + + private void ValidateFloat(JsonSchemaModel schema) + { + if (schema == null) + { + return; + } + + if (!TestType(schema, JsonSchemaType.Float)) + { + return; + } + + ValidateNotDisallowed(schema); + + double value = Convert.ToDouble(_reader.Value, CultureInfo.InvariantCulture); + + if (schema.Maximum != null) + { + if (value > schema.Maximum) + { + RaiseError("Float {0} exceeds maximum value of {1}.".FormatWith(CultureInfo.InvariantCulture, JsonConvert.ToString(value), schema.Maximum), schema); + } + if (schema.ExclusiveMaximum && value == schema.Maximum) + { + RaiseError("Float {0} equals maximum value of {1} and exclusive maximum is true.".FormatWith(CultureInfo.InvariantCulture, JsonConvert.ToString(value), schema.Maximum), schema); + } + } + + if (schema.Minimum != null) + { + if (value < schema.Minimum) + { + RaiseError("Float {0} is less than minimum value of {1}.".FormatWith(CultureInfo.InvariantCulture, JsonConvert.ToString(value), schema.Minimum), schema); + } + if (schema.ExclusiveMinimum && value == schema.Minimum) + { + RaiseError("Float {0} equals minimum value of {1} and exclusive minimum is true.".FormatWith(CultureInfo.InvariantCulture, JsonConvert.ToString(value), schema.Minimum), schema); + } + } + + if (schema.DivisibleBy != null) + { + double remainder = FloatingPointRemainder(value, schema.DivisibleBy.GetValueOrDefault()); + + if (!IsZero(remainder)) + { + RaiseError("Float {0} is not evenly divisible by {1}.".FormatWith(CultureInfo.InvariantCulture, JsonConvert.ToString(value), schema.DivisibleBy), schema); + } + } + } + + private static double FloatingPointRemainder(double dividend, double divisor) + { + return dividend - Math.Floor(dividend / divisor) * divisor; + } + + private static bool IsZero(double value) + { + const double epsilon = 2.2204460492503131e-016; + + return Math.Abs(value) < 20.0 * epsilon; + } + + private void ValidatePropertyName(JsonSchemaModel schema) + { + if (schema == null) + { + return; + } + + string propertyName = Convert.ToString(_reader.Value, CultureInfo.InvariantCulture); + + if (_currentScope.RequiredProperties.ContainsKey(propertyName)) + { + _currentScope.RequiredProperties[propertyName] = true; + } + + if (!schema.AllowAdditionalProperties) + { + bool propertyDefinied = IsPropertyDefinied(schema, propertyName); + + if (!propertyDefinied) + { + RaiseError("Property '{0}' has not been defined and the schema does not allow additional properties.".FormatWith(CultureInfo.InvariantCulture, propertyName), schema); + } + } + + _currentScope.CurrentPropertyName = propertyName; + } + + private bool IsPropertyDefinied(JsonSchemaModel schema, string propertyName) + { + if (schema.Properties != null && schema.Properties.ContainsKey(propertyName)) + { + return true; + } + + if (schema.PatternProperties != null) + { + foreach (string pattern in schema.PatternProperties.Keys) + { + if (Regex.IsMatch(propertyName, pattern)) + { + return true; + } + } + } + + return false; + } + + private bool ValidateArray(JsonSchemaModel schema) + { + if (schema == null) + { + return true; + } + + return (TestType(schema, JsonSchemaType.Array)); + } + + private bool ValidateObject(JsonSchemaModel schema) + { + if (schema == null) + { + return true; + } + + return (TestType(schema, JsonSchemaType.Object)); + } + + private bool TestType(JsonSchemaModel currentSchema, JsonSchemaType currentType) + { + if (!JsonSchemaGenerator.HasFlag(currentSchema.Type, currentType)) + { + RaiseError("Invalid type. Expected {0} but got {1}.".FormatWith(CultureInfo.InvariantCulture, currentSchema.Type, currentType), currentSchema); + return false; + } + + return true; + } + + bool IJsonLineInfo.HasLineInfo() + { + IJsonLineInfo lineInfo = _reader as IJsonLineInfo; + return lineInfo != null && lineInfo.HasLineInfo(); + } + + int IJsonLineInfo.LineNumber + { + get + { + IJsonLineInfo lineInfo = _reader as IJsonLineInfo; + return (lineInfo != null) ? lineInfo.LineNumber : 0; + } + } + + int IJsonLineInfo.LinePosition + { + get + { + IJsonLineInfo lineInfo = _reader as IJsonLineInfo; + return (lineInfo != null) ? lineInfo.LinePosition : 0; + } + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/JsonWriter.cs b/Common/00-1Json8.3/Json8.3/JsonWriter.cs new file mode 100644 index 0000000..293b153 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/JsonWriter.cs @@ -0,0 +1,1714 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Collections.Generic; +using System.IO; +#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) +using System.Numerics; +#endif +using Newtonsoft.Json.Utilities; +using System.Globalization; +#if NET20 +using Newtonsoft.Json.Utilities.LinqBridge; +#else +using System.Linq; + +#endif + +namespace Newtonsoft.Json +{ + /// + /// Represents a writer that provides a fast, non-cached, forward-only way of generating JSON data. + /// + public abstract class JsonWriter : IDisposable + { + internal enum State + { + Start = 0, + Property = 1, + ObjectStart = 2, + Object = 3, + ArrayStart = 4, + Array = 5, + ConstructorStart = 6, + Constructor = 7, + Closed = 8, + Error = 9 + } + + // array that gives a new state based on the current state an the token being written + private static readonly State[][] StateArray; + + internal static readonly State[][] StateArrayTempate = new[] + { + // Start PropertyName ObjectStart Object ArrayStart Array ConstructorStart Constructor Closed Error + // + /* None */new[] { State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error }, + /* StartObject */new[] { State.ObjectStart, State.ObjectStart, State.Error, State.Error, State.ObjectStart, State.ObjectStart, State.ObjectStart, State.ObjectStart, State.Error, State.Error }, + /* StartArray */new[] { State.ArrayStart, State.ArrayStart, State.Error, State.Error, State.ArrayStart, State.ArrayStart, State.ArrayStart, State.ArrayStart, State.Error, State.Error }, + /* StartConstructor */new[] { State.ConstructorStart, State.ConstructorStart, State.Error, State.Error, State.ConstructorStart, State.ConstructorStart, State.ConstructorStart, State.ConstructorStart, State.Error, State.Error }, + /* Property */new[] { State.Property, State.Error, State.Property, State.Property, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error }, + /* Comment */new[] { State.Start, State.Property, State.ObjectStart, State.Object, State.ArrayStart, State.Array, State.Constructor, State.Constructor, State.Error, State.Error }, + /* Raw */new[] { State.Start, State.Property, State.ObjectStart, State.Object, State.ArrayStart, State.Array, State.Constructor, State.Constructor, State.Error, State.Error }, + /* Value (this will be copied) */new[] { State.Start, State.Object, State.Error, State.Error, State.Array, State.Array, State.Constructor, State.Constructor, State.Error, State.Error } + }; + + internal static State[][] BuildStateArray() + { + var allStates = StateArrayTempate.ToList(); + var errorStates = StateArrayTempate[0]; + var valueStates = StateArrayTempate[7]; + + foreach (JsonToken valueToken in EnumUtils.GetValues(typeof(JsonToken))) + { + if (allStates.Count <= (int)valueToken) + { + switch (valueToken) + { + case JsonToken.Integer: + case JsonToken.Float: + case JsonToken.String: + case JsonToken.Boolean: + case JsonToken.Null: + case JsonToken.Undefined: + case JsonToken.Date: + case JsonToken.Bytes: + allStates.Add(valueStates); + break; + default: + allStates.Add(errorStates); + break; + } + } + } + + return allStates.ToArray(); + } + + static JsonWriter() + { + StateArray = BuildStateArray(); + } + + private List _stack; + private JsonPosition _currentPosition; + private State _currentState; + private Formatting _formatting; + + /// + /// Gets or sets a value indicating whether the underlying stream or + /// should be closed when the writer is closed. + /// + /// + /// true to close the underlying stream or when + /// the writer is closed; otherwise false. The default is true. + /// + public bool CloseOutput { get; set; } + + /// + /// Gets the top. + /// + /// The top. + protected internal int Top + { + get + { + int depth = (_stack != null) ? _stack.Count : 0; + if (Peek() != JsonContainerType.None) + { + depth++; + } + + return depth; + } + } + + /// + /// Gets the state of the writer. + /// + public WriteState WriteState + { + get + { + switch (_currentState) + { + case State.Error: + return WriteState.Error; + case State.Closed: + return WriteState.Closed; + case State.Object: + case State.ObjectStart: + return WriteState.Object; + case State.Array: + case State.ArrayStart: + return WriteState.Array; + case State.Constructor: + case State.ConstructorStart: + return WriteState.Constructor; + case State.Property: + return WriteState.Property; + case State.Start: + return WriteState.Start; + default: + throw JsonWriterException.Create(this, "Invalid state: " + _currentState, null); + } + } + } + + internal string ContainerPath + { + get + { + if (_currentPosition.Type == JsonContainerType.None || _stack == null) + { + return string.Empty; + } + + return JsonPosition.BuildPath(_stack, null); + } + } + + /// + /// Gets the path of the writer. + /// + public string Path + { + get + { + if (_currentPosition.Type == JsonContainerType.None) + { + return string.Empty; + } + + bool insideContainer = (_currentState != State.ArrayStart + && _currentState != State.ConstructorStart + && _currentState != State.ObjectStart); + + JsonPosition? current = insideContainer ? (JsonPosition?)_currentPosition : null; + + return JsonPosition.BuildPath(_stack, current); + } + } + + private DateFormatHandling _dateFormatHandling; + private DateTimeZoneHandling _dateTimeZoneHandling; + private StringEscapeHandling _stringEscapeHandling; + private FloatFormatHandling _floatFormatHandling; + private string _dateFormatString; + private CultureInfo _culture; + + /// + /// Indicates how JSON text output is formatted. + /// + public Formatting Formatting + { + get { return _formatting; } + set + { + if (value < Formatting.None || value > Formatting.Indented) + { + throw new ArgumentOutOfRangeException(nameof(value)); + } + + _formatting = value; + } + } + + /// + /// Get or set how dates are written to JSON text. + /// + public DateFormatHandling DateFormatHandling + { + get { return _dateFormatHandling; } + set + { + if (value < DateFormatHandling.IsoDateFormat || value > DateFormatHandling.MicrosoftDateFormat) + { + throw new ArgumentOutOfRangeException(nameof(value)); + } + + _dateFormatHandling = value; + } + } + + /// + /// Get or set how time zones are handling when writing JSON text. + /// + public DateTimeZoneHandling DateTimeZoneHandling + { + get { return _dateTimeZoneHandling; } + set + { + if (value < DateTimeZoneHandling.Local || value > DateTimeZoneHandling.RoundtripKind) + { + throw new ArgumentOutOfRangeException(nameof(value)); + } + + _dateTimeZoneHandling = value; + } + } + + /// + /// Get or set how strings are escaped when writing JSON text. + /// + public StringEscapeHandling StringEscapeHandling + { + get { return _stringEscapeHandling; } + set + { + if (value < StringEscapeHandling.Default || value > StringEscapeHandling.EscapeHtml) + { + throw new ArgumentOutOfRangeException(nameof(value)); + } + + _stringEscapeHandling = value; + OnStringEscapeHandlingChanged(); + } + } + + internal virtual void OnStringEscapeHandlingChanged() + { + // hacky but there is a calculated value that relies on StringEscapeHandling + } + + /// + /// Get or set how special floating point numbers, e.g. , + /// and , + /// are written to JSON text. + /// + public FloatFormatHandling FloatFormatHandling + { + get { return _floatFormatHandling; } + set + { + if (value < FloatFormatHandling.String || value > FloatFormatHandling.DefaultValue) + { + throw new ArgumentOutOfRangeException(nameof(value)); + } + + _floatFormatHandling = value; + } + } + + /// + /// Get or set how and values are formatting when writing JSON text. + /// + public string DateFormatString + { + get { return _dateFormatString; } + set { _dateFormatString = value; } + } + + /// + /// Gets or sets the culture used when writing JSON. Defaults to . + /// + public CultureInfo Culture + { + get { return _culture ?? CultureInfo.InvariantCulture; } + set { _culture = value; } + } + + /// + /// Creates an instance of the JsonWriter class. + /// + protected JsonWriter() + { + _currentState = State.Start; + _formatting = Formatting.None; + _dateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind; + + CloseOutput = true; + } + + internal void UpdateScopeWithFinishedValue() + { + if (_currentPosition.HasIndex) + { + _currentPosition.Position++; + } + } + + private void Push(JsonContainerType value) + { + if (_currentPosition.Type != JsonContainerType.None) + { + if (_stack == null) + { + _stack = new List(); + } + + _stack.Add(_currentPosition); + } + + _currentPosition = new JsonPosition(value); + } + + private JsonContainerType Pop() + { + JsonPosition oldPosition = _currentPosition; + + if (_stack != null && _stack.Count > 0) + { + _currentPosition = _stack[_stack.Count - 1]; + _stack.RemoveAt(_stack.Count - 1); + } + else + { + _currentPosition = new JsonPosition(); + } + + return oldPosition.Type; + } + + private JsonContainerType Peek() + { + return _currentPosition.Type; + } + + /// + /// Flushes whatever is in the buffer to the underlying streams and also flushes the underlying stream. + /// + public abstract void Flush(); + + /// + /// Closes this stream and the underlying stream. + /// + public virtual void Close() + { + AutoCompleteAll(); + } + + /// + /// Writes the beginning of a JSON object. + /// + public virtual void WriteStartObject() + { + InternalWriteStart(JsonToken.StartObject, JsonContainerType.Object); + } + + /// + /// Writes the end of a JSON object. + /// + public virtual void WriteEndObject() + { + InternalWriteEnd(JsonContainerType.Object); + } + + /// + /// Writes the beginning of a JSON array. + /// + public virtual void WriteStartArray() + { + InternalWriteStart(JsonToken.StartArray, JsonContainerType.Array); + } + + /// + /// Writes the end of an array. + /// + public virtual void WriteEndArray() + { + InternalWriteEnd(JsonContainerType.Array); + } + + /// + /// Writes the start of a constructor with the given name. + /// + /// The name of the constructor. + public virtual void WriteStartConstructor(string name) + { + InternalWriteStart(JsonToken.StartConstructor, JsonContainerType.Constructor); + } + + /// + /// Writes the end constructor. + /// + public virtual void WriteEndConstructor() + { + InternalWriteEnd(JsonContainerType.Constructor); + } + + /// + /// Writes the property name of a name/value pair on a JSON object. + /// + /// The name of the property. + public virtual void WritePropertyName(string name) + { + InternalWritePropertyName(name); + } + + /// + /// Writes the property name of a name/value pair on a JSON object. + /// + /// The name of the property. + /// A flag to indicate whether the text should be escaped when it is written as a JSON property name. + public virtual void WritePropertyName(string name, bool escape) + { + WritePropertyName(name); + } + + /// + /// Writes the end of the current JSON object or array. + /// + public virtual void WriteEnd() + { + WriteEnd(Peek()); + } + + /// + /// Writes the current token and its children. + /// + /// The to read the token from. + public void WriteToken(JsonReader reader) + { + WriteToken(reader, true); + } + + /// + /// Writes the current token. + /// + /// The to read the token from. + /// A flag indicating whether the current token's children should be written. + public void WriteToken(JsonReader reader, bool writeChildren) + { + ValidationUtils.ArgumentNotNull(reader, nameof(reader)); + + WriteToken(reader, writeChildren, true, true); + } + + /// + /// Writes the token and its value. + /// + /// The to write. + /// + /// The value to write. + /// A value is only required for tokens that have an associated value, e.g. the property name for . + /// A null value can be passed to the method for token's that don't have a value, e.g. . + public void WriteToken(JsonToken token, object value) + { + switch (token) + { + case JsonToken.None: + // read to next + break; + case JsonToken.StartObject: + WriteStartObject(); + break; + case JsonToken.StartArray: + WriteStartArray(); + break; + case JsonToken.StartConstructor: + ValidationUtils.ArgumentNotNull(value, nameof(value)); + WriteStartConstructor(value.ToString()); + break; + case JsonToken.PropertyName: + ValidationUtils.ArgumentNotNull(value, nameof(value)); + WritePropertyName(value.ToString()); + break; + case JsonToken.Comment: + WriteComment((value != null) ? value.ToString() : null); + break; + case JsonToken.Integer: + ValidationUtils.ArgumentNotNull(value, nameof(value)); +#if !(NET20 || NET35 || PORTABLE || PORTABLE40) + if (value is BigInteger) + { + WriteValue((BigInteger)value); + } + else +#endif + { + WriteValue(Convert.ToInt64(value, CultureInfo.InvariantCulture)); + } + break; + case JsonToken.Float: + ValidationUtils.ArgumentNotNull(value, nameof(value)); + if (value is decimal) + { + WriteValue((decimal)value); + } + else if (value is double) + { + WriteValue((double)value); + } + else if (value is float) + { + WriteValue((float)value); + } + else + { + WriteValue(Convert.ToDouble(value, CultureInfo.InvariantCulture)); + } + break; + case JsonToken.String: + ValidationUtils.ArgumentNotNull(value, nameof(value)); + WriteValue(value.ToString()); + break; + case JsonToken.Boolean: + ValidationUtils.ArgumentNotNull(value, nameof(value)); + WriteValue(Convert.ToBoolean(value, CultureInfo.InvariantCulture)); + break; + case JsonToken.Null: + WriteNull(); + break; + case JsonToken.Undefined: + WriteUndefined(); + break; + case JsonToken.EndObject: + WriteEndObject(); + break; + case JsonToken.EndArray: + WriteEndArray(); + break; + case JsonToken.EndConstructor: + WriteEndConstructor(); + break; + case JsonToken.Date: + ValidationUtils.ArgumentNotNull(value, nameof(value)); +#if !NET20 + if (value is DateTimeOffset) + { + WriteValue((DateTimeOffset)value); + } + else +#endif + { + WriteValue(Convert.ToDateTime(value, CultureInfo.InvariantCulture)); + } + break; + case JsonToken.Raw: + WriteRawValue((value != null) ? value.ToString() : null); + break; + case JsonToken.Bytes: + ValidationUtils.ArgumentNotNull(value, nameof(value)); + if (value is Guid) + { + WriteValue((Guid)value); + } + else + { + WriteValue((byte[])value); + } + break; + default: + throw MiscellaneousUtils.CreateArgumentOutOfRangeException(nameof(token), token, "Unexpected token type."); + } + } + + /// + /// Writes the token. + /// + /// The to write. + public void WriteToken(JsonToken token) + { + WriteToken(token, null); + } + + internal void WriteToken(JsonReader reader, bool writeChildren, bool writeDateConstructorAsDate, bool writeComments) + { + int initialDepth; + + if (reader.TokenType == JsonToken.None) + { + initialDepth = -1; + } + else if (!JsonTokenUtils.IsStartToken(reader.TokenType)) + { + initialDepth = reader.Depth + 1; + } + else + { + initialDepth = reader.Depth; + } + + WriteToken(reader, initialDepth, writeChildren, writeDateConstructorAsDate, writeComments); + } + + internal void WriteToken(JsonReader reader, int initialDepth, bool writeChildren, bool writeDateConstructorAsDate, bool writeComments) + { + do + { + // write a JValue date when the constructor is for a date + if (writeDateConstructorAsDate && reader.TokenType == JsonToken.StartConstructor && string.Equals(reader.Value.ToString(), "Date", StringComparison.Ordinal)) + { + WriteConstructorDate(reader); + } + else + { + if (reader.TokenType != JsonToken.Comment || writeComments) + { + WriteToken(reader.TokenType, reader.Value); + } + } + } while ( + // stop if we have reached the end of the token being read + initialDepth - 1 < reader.Depth - (JsonTokenUtils.IsEndToken(reader.TokenType) ? 1 : 0) + && writeChildren + && reader.Read()); + } + + private void WriteConstructorDate(JsonReader reader) + { + if (!reader.Read()) + { + throw JsonWriterException.Create(this, "Unexpected end when reading date constructor.", null); + } + if (reader.TokenType != JsonToken.Integer) + { + throw JsonWriterException.Create(this, "Unexpected token when reading date constructor. Expected Integer, got " + reader.TokenType, null); + } + + long ticks = (long)reader.Value; + DateTime date = DateTimeUtils.ConvertJavaScriptTicksToDateTime(ticks); + + if (!reader.Read()) + { + throw JsonWriterException.Create(this, "Unexpected end when reading date constructor.", null); + } + if (reader.TokenType != JsonToken.EndConstructor) + { + throw JsonWriterException.Create(this, "Unexpected token when reading date constructor. Expected EndConstructor, got " + reader.TokenType, null); + } + + WriteValue(date); + } + + private void WriteEnd(JsonContainerType type) + { + switch (type) + { + case JsonContainerType.Object: + WriteEndObject(); + break; + case JsonContainerType.Array: + WriteEndArray(); + break; + case JsonContainerType.Constructor: + WriteEndConstructor(); + break; + default: + throw JsonWriterException.Create(this, "Unexpected type when writing end: " + type, null); + } + } + + private void AutoCompleteAll() + { + while (Top > 0) + { + WriteEnd(); + } + } + + private JsonToken GetCloseTokenForType(JsonContainerType type) + { + switch (type) + { + case JsonContainerType.Object: + return JsonToken.EndObject; + case JsonContainerType.Array: + return JsonToken.EndArray; + case JsonContainerType.Constructor: + return JsonToken.EndConstructor; + default: + throw JsonWriterException.Create(this, "No close token for type: " + type, null); + } + } + + private void AutoCompleteClose(JsonContainerType type) + { + // write closing symbol and calculate new state + int levelsToComplete = 0; + + if (_currentPosition.Type == type) + { + levelsToComplete = 1; + } + else + { + int top = Top - 2; + for (int i = top; i >= 0; i--) + { + int currentLevel = top - i; + + if (_stack[currentLevel].Type == type) + { + levelsToComplete = i + 2; + break; + } + } + } + + if (levelsToComplete == 0) + { + throw JsonWriterException.Create(this, "No token to close.", null); + } + + for (int i = 0; i < levelsToComplete; i++) + { + JsonToken token = GetCloseTokenForType(Pop()); + + if (_currentState == State.Property) + { + WriteNull(); + } + + if (_formatting == Formatting.Indented) + { + if (_currentState != State.ObjectStart && _currentState != State.ArrayStart) + { + WriteIndent(); + } + } + + WriteEnd(token); + + JsonContainerType currentLevelType = Peek(); + + switch (currentLevelType) + { + case JsonContainerType.Object: + _currentState = State.Object; + break; + case JsonContainerType.Array: + _currentState = State.Array; + break; + case JsonContainerType.Constructor: + _currentState = State.Array; + break; + case JsonContainerType.None: + _currentState = State.Start; + break; + default: + throw JsonWriterException.Create(this, "Unknown JsonType: " + currentLevelType, null); + } + } + } + + /// + /// Writes the specified end token. + /// + /// The end token to write. + protected virtual void WriteEnd(JsonToken token) + { + } + + /// + /// Writes indent characters. + /// + protected virtual void WriteIndent() + { + } + + /// + /// Writes the JSON value delimiter. + /// + protected virtual void WriteValueDelimiter() + { + } + + /// + /// Writes an indent space. + /// + protected virtual void WriteIndentSpace() + { + } + + internal void AutoComplete(JsonToken tokenBeingWritten) + { + // gets new state based on the current state and what is being written + State newState = StateArray[(int)tokenBeingWritten][(int)_currentState]; + + if (newState == State.Error) + { + throw JsonWriterException.Create(this, "Token {0} in state {1} would result in an invalid JSON object.".FormatWith(CultureInfo.InvariantCulture, tokenBeingWritten.ToString(), _currentState.ToString()), null); + } + + if ((_currentState == State.Object || _currentState == State.Array || _currentState == State.Constructor) && tokenBeingWritten != JsonToken.Comment) + { + WriteValueDelimiter(); + } + + if (_formatting == Formatting.Indented) + { + if (_currentState == State.Property) + { + WriteIndentSpace(); + } + + // don't indent a property when it is the first token to be written (i.e. at the start) + if ((_currentState == State.Array || _currentState == State.ArrayStart || _currentState == State.Constructor || _currentState == State.ConstructorStart) + || (tokenBeingWritten == JsonToken.PropertyName && _currentState != State.Start)) + { + WriteIndent(); + } + } + + _currentState = newState; + } + + #region WriteValue methods + /// + /// Writes a null value. + /// + public virtual void WriteNull() + { + InternalWriteValue(JsonToken.Null); + } + + /// + /// Writes an undefined value. + /// + public virtual void WriteUndefined() + { + InternalWriteValue(JsonToken.Undefined); + } + + /// + /// Writes raw JSON without changing the writer's state. + /// + /// The raw JSON to write. + public virtual void WriteRaw(string json) + { + InternalWriteRaw(); + } + + /// + /// Writes raw JSON where a value is expected and updates the writer's state. + /// + /// The raw JSON to write. + public virtual void WriteRawValue(string json) + { + // hack. want writer to change state as if a value had been written + UpdateScopeWithFinishedValue(); + AutoComplete(JsonToken.Undefined); + WriteRaw(json); + } + + /// + /// Writes a value. + /// + /// The value to write. + public virtual void WriteValue(string value) + { + InternalWriteValue(JsonToken.String); + } + + /// + /// Writes a value. + /// + /// The value to write. + public virtual void WriteValue(int value) + { + InternalWriteValue(JsonToken.Integer); + } + + /// + /// Writes a value. + /// + /// The value to write. + [CLSCompliant(false)] + public virtual void WriteValue(uint value) + { + InternalWriteValue(JsonToken.Integer); + } + + /// + /// Writes a value. + /// + /// The value to write. + public virtual void WriteValue(long value) + { + InternalWriteValue(JsonToken.Integer); + } + + /// + /// Writes a value. + /// + /// The value to write. + [CLSCompliant(false)] + public virtual void WriteValue(ulong value) + { + InternalWriteValue(JsonToken.Integer); + } + + /// + /// Writes a value. + /// + /// The value to write. + public virtual void WriteValue(float value) + { + InternalWriteValue(JsonToken.Float); + } + + /// + /// Writes a value. + /// + /// The value to write. + public virtual void WriteValue(double value) + { + InternalWriteValue(JsonToken.Float); + } + + /// + /// Writes a value. + /// + /// The value to write. + public virtual void WriteValue(bool value) + { + InternalWriteValue(JsonToken.Boolean); + } + + /// + /// Writes a value. + /// + /// The value to write. + public virtual void WriteValue(short value) + { + InternalWriteValue(JsonToken.Integer); + } + + /// + /// Writes a value. + /// + /// The value to write. + [CLSCompliant(false)] + public virtual void WriteValue(ushort value) + { + InternalWriteValue(JsonToken.Integer); + } + + /// + /// Writes a value. + /// + /// The value to write. + public virtual void WriteValue(char value) + { + InternalWriteValue(JsonToken.String); + } + + /// + /// Writes a value. + /// + /// The value to write. + public virtual void WriteValue(byte value) + { + InternalWriteValue(JsonToken.Integer); + } + + /// + /// Writes a value. + /// + /// The value to write. + [CLSCompliant(false)] + public virtual void WriteValue(sbyte value) + { + InternalWriteValue(JsonToken.Integer); + } + + /// + /// Writes a value. + /// + /// The value to write. + public virtual void WriteValue(decimal value) + { + InternalWriteValue(JsonToken.Float); + } + + /// + /// Writes a value. + /// + /// The value to write. + public virtual void WriteValue(DateTime value) + { + InternalWriteValue(JsonToken.Date); + } + +#if !NET20 + /// + /// Writes a value. + /// + /// The value to write. + public virtual void WriteValue(DateTimeOffset value) + { + InternalWriteValue(JsonToken.Date); + } +#endif + + /// + /// Writes a value. + /// + /// The value to write. + public virtual void WriteValue(Guid value) + { + InternalWriteValue(JsonToken.String); + } + + /// + /// Writes a value. + /// + /// The value to write. + public virtual void WriteValue(TimeSpan value) + { + InternalWriteValue(JsonToken.String); + } + + /// + /// Writes a value. + /// + /// The value to write. + public virtual void WriteValue(int? value) + { + if (value == null) + { + WriteNull(); + } + else + { + WriteValue(value.GetValueOrDefault()); + } + } + + /// + /// Writes a value. + /// + /// The value to write. + [CLSCompliant(false)] + public virtual void WriteValue(uint? value) + { + if (value == null) + { + WriteNull(); + } + else + { + WriteValue(value.GetValueOrDefault()); + } + } + + /// + /// Writes a value. + /// + /// The value to write. + public virtual void WriteValue(long? value) + { + if (value == null) + { + WriteNull(); + } + else + { + WriteValue(value.GetValueOrDefault()); + } + } + + /// + /// Writes a value. + /// + /// The value to write. + [CLSCompliant(false)] + public virtual void WriteValue(ulong? value) + { + if (value == null) + { + WriteNull(); + } + else + { + WriteValue(value.GetValueOrDefault()); + } + } + + /// + /// Writes a value. + /// + /// The value to write. + public virtual void WriteValue(float? value) + { + if (value == null) + { + WriteNull(); + } + else + { + WriteValue(value.GetValueOrDefault()); + } + } + + /// + /// Writes a value. + /// + /// The value to write. + public virtual void WriteValue(double? value) + { + if (value == null) + { + WriteNull(); + } + else + { + WriteValue(value.GetValueOrDefault()); + } + } + + /// + /// Writes a value. + /// + /// The value to write. + public virtual void WriteValue(bool? value) + { + if (value == null) + { + WriteNull(); + } + else + { + WriteValue(value.GetValueOrDefault()); + } + } + + /// + /// Writes a value. + /// + /// The value to write. + public virtual void WriteValue(short? value) + { + if (value == null) + { + WriteNull(); + } + else + { + WriteValue(value.GetValueOrDefault()); + } + } + + /// + /// Writes a value. + /// + /// The value to write. + [CLSCompliant(false)] + public virtual void WriteValue(ushort? value) + { + if (value == null) + { + WriteNull(); + } + else + { + WriteValue(value.GetValueOrDefault()); + } + } + + /// + /// Writes a value. + /// + /// The value to write. + public virtual void WriteValue(char? value) + { + if (value == null) + { + WriteNull(); + } + else + { + WriteValue(value.GetValueOrDefault()); + } + } + + /// + /// Writes a value. + /// + /// The value to write. + public virtual void WriteValue(byte? value) + { + if (value == null) + { + WriteNull(); + } + else + { + WriteValue(value.GetValueOrDefault()); + } + } + + /// + /// Writes a value. + /// + /// The value to write. + [CLSCompliant(false)] + public virtual void WriteValue(sbyte? value) + { + if (value == null) + { + WriteNull(); + } + else + { + WriteValue(value.GetValueOrDefault()); + } + } + + /// + /// Writes a value. + /// + /// The value to write. + public virtual void WriteValue(decimal? value) + { + if (value == null) + { + WriteNull(); + } + else + { + WriteValue(value.GetValueOrDefault()); + } + } + + /// + /// Writes a value. + /// + /// The value to write. + public virtual void WriteValue(DateTime? value) + { + if (value == null) + { + WriteNull(); + } + else + { + WriteValue(value.GetValueOrDefault()); + } + } + +#if !NET20 + /// + /// Writes a value. + /// + /// The value to write. + public virtual void WriteValue(DateTimeOffset? value) + { + if (value == null) + { + WriteNull(); + } + else + { + WriteValue(value.GetValueOrDefault()); + } + } +#endif + + /// + /// Writes a value. + /// + /// The value to write. + public virtual void WriteValue(Guid? value) + { + if (value == null) + { + WriteNull(); + } + else + { + WriteValue(value.GetValueOrDefault()); + } + } + + /// + /// Writes a value. + /// + /// The value to write. + public virtual void WriteValue(TimeSpan? value) + { + if (value == null) + { + WriteNull(); + } + else + { + WriteValue(value.GetValueOrDefault()); + } + } + + /// + /// Writes a [] value. + /// + /// The [] value to write. + public virtual void WriteValue(byte[] value) + { + if (value == null) + { + WriteNull(); + } + else + { + InternalWriteValue(JsonToken.Bytes); + } + } + + /// + /// Writes a value. + /// + /// The value to write. + public virtual void WriteValue(Uri value) + { + if (value == null) + { + WriteNull(); + } + else + { + InternalWriteValue(JsonToken.String); + } + } + + /// + /// Writes a value. + /// An error will raised if the value cannot be written as a single JSON token. + /// + /// The value to write. + public virtual void WriteValue(object value) + { + if (value == null) + { + WriteNull(); + } + else + { +#if !(NET20 || NET35 || PORTABLE || PORTABLE40) + // this is here because adding a WriteValue(BigInteger) to JsonWriter will + // mean the user has to add a reference to System.Numerics.dll + if (value is BigInteger) + { + throw CreateUnsupportedTypeException(this, value); + } +#endif + + WriteValue(this, ConvertUtils.GetTypeCode(value.GetType()), value); + } + } + #endregion + + /// + /// Writes out a comment /*...*/ containing the specified text. + /// + /// Text to place inside the comment. + public virtual void WriteComment(string text) + { + InternalWriteComment(); + } + + /// + /// Writes out the given white space. + /// + /// The string of white space characters. + public virtual void WriteWhitespace(string ws) + { + InternalWriteWhitespace(ws); + } + + void IDisposable.Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + /// + /// Releases unmanaged and - optionally - managed resources + /// + /// true to release both managed and unmanaged resources; false to release only unmanaged resources. + protected virtual void Dispose(bool disposing) + { + if (_currentState != State.Closed && disposing) + { + Close(); + } + } + + internal static void WriteValue(JsonWriter writer, PrimitiveTypeCode typeCode, object value) + { + switch (typeCode) + { + case PrimitiveTypeCode.Char: + writer.WriteValue((char)value); + break; + case PrimitiveTypeCode.CharNullable: + writer.WriteValue((value == null) ? (char?)null : (char)value); + break; + case PrimitiveTypeCode.Boolean: + writer.WriteValue((bool)value); + break; + case PrimitiveTypeCode.BooleanNullable: + writer.WriteValue((value == null) ? (bool?)null : (bool)value); + break; + case PrimitiveTypeCode.SByte: + writer.WriteValue((sbyte)value); + break; + case PrimitiveTypeCode.SByteNullable: + writer.WriteValue((value == null) ? (sbyte?)null : (sbyte)value); + break; + case PrimitiveTypeCode.Int16: + writer.WriteValue((short)value); + break; + case PrimitiveTypeCode.Int16Nullable: + writer.WriteValue((value == null) ? (short?)null : (short)value); + break; + case PrimitiveTypeCode.UInt16: + writer.WriteValue((ushort)value); + break; + case PrimitiveTypeCode.UInt16Nullable: + writer.WriteValue((value == null) ? (ushort?)null : (ushort)value); + break; + case PrimitiveTypeCode.Int32: + writer.WriteValue((int)value); + break; + case PrimitiveTypeCode.Int32Nullable: + writer.WriteValue((value == null) ? (int?)null : (int)value); + break; + case PrimitiveTypeCode.Byte: + writer.WriteValue((byte)value); + break; + case PrimitiveTypeCode.ByteNullable: + writer.WriteValue((value == null) ? (byte?)null : (byte)value); + break; + case PrimitiveTypeCode.UInt32: + writer.WriteValue((uint)value); + break; + case PrimitiveTypeCode.UInt32Nullable: + writer.WriteValue((value == null) ? (uint?)null : (uint)value); + break; + case PrimitiveTypeCode.Int64: + writer.WriteValue((long)value); + break; + case PrimitiveTypeCode.Int64Nullable: + writer.WriteValue((value == null) ? (long?)null : (long)value); + break; + case PrimitiveTypeCode.UInt64: + writer.WriteValue((ulong)value); + break; + case PrimitiveTypeCode.UInt64Nullable: + writer.WriteValue((value == null) ? (ulong?)null : (ulong)value); + break; + case PrimitiveTypeCode.Single: + writer.WriteValue((float)value); + break; + case PrimitiveTypeCode.SingleNullable: + writer.WriteValue((value == null) ? (float?)null : (float)value); + break; + case PrimitiveTypeCode.Double: + writer.WriteValue((double)value); + break; + case PrimitiveTypeCode.DoubleNullable: + writer.WriteValue((value == null) ? (double?)null : (double)value); + break; + case PrimitiveTypeCode.DateTime: + writer.WriteValue((DateTime)value); + break; + case PrimitiveTypeCode.DateTimeNullable: + writer.WriteValue((value == null) ? (DateTime?)null : (DateTime)value); + break; +#if !NET20 + case PrimitiveTypeCode.DateTimeOffset: + writer.WriteValue((DateTimeOffset)value); + break; + case PrimitiveTypeCode.DateTimeOffsetNullable: + writer.WriteValue((value == null) ? (DateTimeOffset?)null : (DateTimeOffset)value); + break; +#endif + case PrimitiveTypeCode.Decimal: + writer.WriteValue((decimal)value); + break; + case PrimitiveTypeCode.DecimalNullable: + writer.WriteValue((value == null) ? (decimal?)null : (decimal)value); + break; + case PrimitiveTypeCode.Guid: + writer.WriteValue((Guid)value); + break; + case PrimitiveTypeCode.GuidNullable: + writer.WriteValue((value == null) ? (Guid?)null : (Guid)value); + break; + case PrimitiveTypeCode.TimeSpan: + writer.WriteValue((TimeSpan)value); + break; + case PrimitiveTypeCode.TimeSpanNullable: + writer.WriteValue((value == null) ? (TimeSpan?)null : (TimeSpan)value); + break; +#if !(PORTABLE || PORTABLE40 || NET35 || NET20) + case PrimitiveTypeCode.BigInteger: + // this will call to WriteValue(object) + writer.WriteValue((BigInteger)value); + break; + case PrimitiveTypeCode.BigIntegerNullable: + // this will call to WriteValue(object) + writer.WriteValue((value == null) ? (BigInteger?)null : (BigInteger)value); + break; +#endif + case PrimitiveTypeCode.Uri: + writer.WriteValue((Uri)value); + break; + case PrimitiveTypeCode.String: + writer.WriteValue((string)value); + break; + case PrimitiveTypeCode.Bytes: + writer.WriteValue((byte[])value); + break; +#if !(PORTABLE || DOTNET) + case PrimitiveTypeCode.DBNull: + writer.WriteNull(); + break; +#endif + default: +#if !PORTABLE + if (value is IConvertible) + { + // the value is a non-standard IConvertible + // convert to the underlying value and retry + IConvertible convertable = (IConvertible)value; + + TypeInformation typeInformation = ConvertUtils.GetTypeInformation(convertable); + + // if convertable has an underlying typecode of Object then attempt to convert it to a string + PrimitiveTypeCode resolvedTypeCode = (typeInformation.TypeCode == PrimitiveTypeCode.Object) ? PrimitiveTypeCode.String : typeInformation.TypeCode; + Type resolvedType = (typeInformation.TypeCode == PrimitiveTypeCode.Object) ? typeof(string) : typeInformation.Type; + + object convertedValue = convertable.ToType(resolvedType, CultureInfo.InvariantCulture); + + WriteValue(writer, resolvedTypeCode, convertedValue); + break; + } + else +#endif + { + throw CreateUnsupportedTypeException(writer, value); + } + } + } + + private static JsonWriterException CreateUnsupportedTypeException(JsonWriter writer, object value) + { + return JsonWriterException.Create(writer, "Unsupported type: {0}. Use the JsonSerializer class to get the object's JSON representation.".FormatWith(CultureInfo.InvariantCulture, value.GetType()), null); + } + + /// + /// Sets the state of the JsonWriter, + /// + /// The JsonToken being written. + /// The value being written. + protected void SetWriteState(JsonToken token, object value) + { + switch (token) + { + case JsonToken.StartObject: + InternalWriteStart(token, JsonContainerType.Object); + break; + case JsonToken.StartArray: + InternalWriteStart(token, JsonContainerType.Array); + break; + case JsonToken.StartConstructor: + InternalWriteStart(token, JsonContainerType.Constructor); + break; + case JsonToken.PropertyName: + if (!(value is string)) + { + throw new ArgumentException("A name is required when setting property name state.", nameof(value)); + } + + InternalWritePropertyName((string)value); + break; + case JsonToken.Comment: + InternalWriteComment(); + break; + case JsonToken.Raw: + InternalWriteRaw(); + break; + case JsonToken.Integer: + case JsonToken.Float: + case JsonToken.String: + case JsonToken.Boolean: + case JsonToken.Date: + case JsonToken.Bytes: + case JsonToken.Null: + case JsonToken.Undefined: + InternalWriteValue(token); + break; + case JsonToken.EndObject: + InternalWriteEnd(JsonContainerType.Object); + break; + case JsonToken.EndArray: + InternalWriteEnd(JsonContainerType.Array); + break; + case JsonToken.EndConstructor: + InternalWriteEnd(JsonContainerType.Constructor); + break; + default: + throw new ArgumentOutOfRangeException(nameof(token)); + } + } + + internal void InternalWriteEnd(JsonContainerType container) + { + AutoCompleteClose(container); + } + + internal void InternalWritePropertyName(string name) + { + _currentPosition.PropertyName = name; + AutoComplete(JsonToken.PropertyName); + } + + internal void InternalWriteRaw() + { + } + + internal void InternalWriteStart(JsonToken token, JsonContainerType container) + { + UpdateScopeWithFinishedValue(); + AutoComplete(token); + Push(container); + } + + internal void InternalWriteValue(JsonToken token) + { + UpdateScopeWithFinishedValue(); + AutoComplete(token); + } + + internal void InternalWriteWhitespace(string ws) + { + if (ws != null) + { + if (!StringUtils.IsWhiteSpace(ws)) + { + throw JsonWriterException.Create(this, "Only white space characters should be used.", null); + } + } + } + + internal void InternalWriteComment() + { + AutoComplete(JsonToken.Comment); + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/JsonWriterException.cs b/Common/00-1Json8.3/Json8.3/JsonWriterException.cs new file mode 100644 index 0000000..2bfa78d --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/JsonWriterException.cs @@ -0,0 +1,107 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Collections.Generic; +using System.Runtime.Serialization; +using System.Text; + +namespace Newtonsoft.Json +{ + /// + /// The exception thrown when an error occurs while reading JSON text. + /// +#if !(DOTNET || PORTABLE40 || PORTABLE) + [Serializable] +#endif + public class JsonWriterException : JsonException + { + /// + /// Gets the path to the JSON where the error occurred. + /// + /// The path to the JSON where the error occurred. + public string Path { get; private set; } + + /// + /// Initializes a new instance of the class. + /// + public JsonWriterException() + { + } + + /// + /// Initializes a new instance of the class + /// with a specified error message. + /// + /// The error message that explains the reason for the exception. + public JsonWriterException(string message) + : base(message) + { + } + + /// + /// Initializes a new instance of the class + /// with a specified error message and a reference to the inner exception that is the cause of this exception. + /// + /// The error message that explains the reason for the exception. + /// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no inner exception is specified. + public JsonWriterException(string message, Exception innerException) + : base(message, innerException) + { + } + +#if !(DOTNET || PORTABLE40 || PORTABLE) + /// + /// Initializes a new instance of the class. + /// + /// The that holds the serialized object data about the exception being thrown. + /// The that contains contextual information about the source or destination. + /// The parameter is null. + /// The class name is null or is zero (0). + public JsonWriterException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } +#endif + + internal JsonWriterException(string message, Exception innerException, string path) + : base(message, innerException) + { + Path = path; + } + + internal static JsonWriterException Create(JsonWriter writer, string message, Exception ex) + { + return Create(writer.ContainerPath, message, ex); + } + + internal static JsonWriterException Create(string path, string message, Exception ex) + { + message = JsonPosition.FormatMessage(null, path, message); + + return new JsonWriterException(message, ex, path); + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Linq/CommentHandling.cs b/Common/00-1Json8.3/Json8.3/Linq/CommentHandling.cs new file mode 100644 index 0000000..d178df8 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Linq/CommentHandling.cs @@ -0,0 +1,34 @@ +namespace Newtonsoft.Json.Linq +{ + /// + /// Specifies how JSON comments are handled when loading JSON. + /// + public enum CommentHandling + { + /// + /// Ignore comments. + /// + Ignore = 0, + + /// + /// Load comments as a with type . + /// + Load = 1 + } + + /// + /// Specifies how line information is handled when loading JSON. + /// + public enum LineInfoHandling + { + /// + /// Ignore line information. + /// + Ignore = 0, + + /// + /// Load line information. + /// + Load = 1 + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Linq/Extensions.cs b/Common/00-1Json8.3/Json8.3/Linq/Extensions.cs new file mode 100644 index 0000000..f9f8976 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Linq/Extensions.cs @@ -0,0 +1,332 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Collections.Generic; +using Newtonsoft.Json.Utilities; +using System.Globalization; +#if NET20 +using Newtonsoft.Json.Utilities.LinqBridge; +#else +using System.Linq; + +#endif + +namespace Newtonsoft.Json.Linq +{ + /// + /// Contains the LINQ to JSON extension methods. + /// + public static class Extensions + { + /// + /// Returns a collection of tokens that contains the ancestors of every token in the source collection. + /// + /// The type of the objects in source, constrained to . + /// An of that contains the source collection. + /// An of that contains the ancestors of every token in the source collection. + public static IJEnumerable Ancestors(this IEnumerable source) where T : JToken + { + ValidationUtils.ArgumentNotNull(source, nameof(source)); + + return source.SelectMany(j => j.Ancestors()).AsJEnumerable(); + } + + /// + /// Returns a collection of tokens that contains every token in the source collection, and the ancestors of every token in the source collection. + /// + /// The type of the objects in source, constrained to . + /// An of that contains the source collection. + /// An of that contains every token in the source collection, the ancestors of every token in the source collection. + public static IJEnumerable AncestorsAndSelf(this IEnumerable source) where T : JToken + { + ValidationUtils.ArgumentNotNull(source, nameof(source)); + + return source.SelectMany(j => j.AncestorsAndSelf()).AsJEnumerable(); + } + + /// + /// Returns a collection of tokens that contains the descendants of every token in the source collection. + /// + /// The type of the objects in source, constrained to . + /// An of that contains the source collection. + /// An of that contains the descendants of every token in the source collection. + public static IJEnumerable Descendants(this IEnumerable source) where T : JContainer + { + ValidationUtils.ArgumentNotNull(source, nameof(source)); + + return source.SelectMany(j => j.Descendants()).AsJEnumerable(); + } + + /// + /// Returns a collection of tokens that contains every token in the source collection, and the descendants of every token in the source collection. + /// + /// The type of the objects in source, constrained to . + /// An of that contains the source collection. + /// An of that contains every token in the source collection, and the descendants of every token in the source collection. + public static IJEnumerable DescendantsAndSelf(this IEnumerable source) where T : JContainer + { + ValidationUtils.ArgumentNotNull(source, nameof(source)); + + return source.SelectMany(j => j.DescendantsAndSelf()).AsJEnumerable(); + } + + /// + /// Returns a collection of child properties of every object in the source collection. + /// + /// An of that contains the source collection. + /// An of that contains the properties of every object in the source collection. + public static IJEnumerable Properties(this IEnumerable source) + { + ValidationUtils.ArgumentNotNull(source, nameof(source)); + + return source.SelectMany(d => d.Properties()).AsJEnumerable(); + } + + /// + /// Returns a collection of child values of every object in the source collection with the given key. + /// + /// An of that contains the source collection. + /// The token key. + /// An of that contains the values of every token in the source collection with the given key. + public static IJEnumerable Values(this IEnumerable source, object key) + { + return Values(source, key).AsJEnumerable(); + } + + /// + /// Returns a collection of child values of every object in the source collection. + /// + /// An of that contains the source collection. + /// An of that contains the values of every token in the source collection. + public static IJEnumerable Values(this IEnumerable source) + { + return source.Values(null); + } + + /// + /// Returns a collection of converted child values of every object in the source collection with the given key. + /// + /// The type to convert the values to. + /// An of that contains the source collection. + /// The token key. + /// An that contains the converted values of every token in the source collection with the given key. + public static IEnumerable Values(this IEnumerable source, object key) + { + return Values(source, key); + } + + /// + /// Returns a collection of converted child values of every object in the source collection. + /// + /// The type to convert the values to. + /// An of that contains the source collection. + /// An that contains the converted values of every token in the source collection. + public static IEnumerable Values(this IEnumerable source) + { + return Values(source, null); + } + + /// + /// Converts the value. + /// + /// The type to convert the value to. + /// A cast as a of . + /// A converted value. + public static U Value(this IEnumerable value) + { + return value.Value(); + } + + /// + /// Converts the value. + /// + /// The source collection type. + /// The type to convert the value to. + /// A cast as a of . + /// A converted value. + public static U Value(this IEnumerable value) where T : JToken + { + ValidationUtils.ArgumentNotNull(value, nameof(value)); + + JToken token = value as JToken; + if (token == null) + { + throw new ArgumentException("Source value must be a JToken."); + } + + return token.Convert(); + } + + internal static IEnumerable Values(this IEnumerable source, object key) where T : JToken + { + ValidationUtils.ArgumentNotNull(source, nameof(source)); + + foreach (JToken token in source) + { + if (key == null) + { + if (token is JValue) + { + yield return Convert((JValue)token); + } + else + { + foreach (JToken t in token.Children()) + { + yield return t.Convert(); + } + } + } + else + { + JToken value = token[key]; + if (value != null) + { + yield return value.Convert(); + } + } + } + + yield break; + } + + //TODO + //public static IEnumerable InDocumentOrder(this IEnumerable source) where T : JObject; + + /// + /// Returns a collection of child tokens of every array in the source collection. + /// + /// The source collection type. + /// An of that contains the source collection. + /// An of that contains the values of every token in the source collection. + public static IJEnumerable Children(this IEnumerable source) where T : JToken + { + return Children(source).AsJEnumerable(); + } + + /// + /// Returns a collection of converted child tokens of every array in the source collection. + /// + /// An of that contains the source collection. + /// The type to convert the values to. + /// The source collection type. + /// An that contains the converted values of every token in the source collection. + public static IEnumerable Children(this IEnumerable source) where T : JToken + { + ValidationUtils.ArgumentNotNull(source, nameof(source)); + + return source.SelectMany(c => c.Children()).Convert(); + } + + internal static IEnumerable Convert(this IEnumerable source) where T : JToken + { + ValidationUtils.ArgumentNotNull(source, nameof(source)); + + foreach (T token in source) + { + yield return Convert(token); + } + } + + internal static U Convert(this T token) where T : JToken + { + if (token == null) + { + return default(U); + } + + if (token is U + // don't want to cast JValue to its interfaces, want to get the internal value + && typeof(U) != typeof(IComparable) && typeof(U) != typeof(IFormattable)) + { + // HACK + return (U)(object)token; + } + else + { + JValue value = token as JValue; + if (value == null) + { + throw new InvalidCastException("Cannot cast {0} to {1}.".FormatWith(CultureInfo.InvariantCulture, token.GetType(), typeof(T))); + } + + if (value.Value is U) + { + return (U)value.Value; + } + + Type targetType = typeof(U); + + if (ReflectionUtils.IsNullableType(targetType)) + { + if (value.Value == null) + { + return default(U); + } + + targetType = Nullable.GetUnderlyingType(targetType); + } + + return (U)System.Convert.ChangeType(value.Value, targetType, CultureInfo.InvariantCulture); + } + } + + //TODO + //public static void Remove(this IEnumerable source) where T : JContainer; + + /// + /// Returns the input typed as . + /// + /// An of that contains the source collection. + /// The input typed as . + public static IJEnumerable AsJEnumerable(this IEnumerable source) + { + return source.AsJEnumerable(); + } + + /// + /// Returns the input typed as . + /// + /// The source collection type. + /// An of that contains the source collection. + /// The input typed as . + public static IJEnumerable AsJEnumerable(this IEnumerable source) where T : JToken + { + if (source == null) + { + return null; + } + else if (source is IJEnumerable) + { + return (IJEnumerable)source; + } + else + { + return new JEnumerable(source); + } + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Linq/IJEnumerable.cs b/Common/00-1Json8.3/Json8.3/Linq/IJEnumerable.cs new file mode 100644 index 0000000..fff8c2e --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Linq/IJEnumerable.cs @@ -0,0 +1,46 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System.Collections.Generic; + +namespace Newtonsoft.Json.Linq +{ + /// + /// Represents a collection of objects. + /// + /// The type of token + public interface IJEnumerable< +#if !(NET20 || NET35) + out +#endif + T> : IEnumerable where T : JToken + { + /// + /// Gets the with the specified key. + /// + /// + IJEnumerable this[object key] { get; } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Linq/JArray.cs b/Common/00-1Json8.3/Json8.3/Linq/JArray.cs new file mode 100644 index 0000000..5ca9a16 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Linq/JArray.cs @@ -0,0 +1,406 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Collections; +using System.Collections.Generic; +using Newtonsoft.Json.Utilities; +using System.IO; +using System.Globalization; + +namespace Newtonsoft.Json.Linq +{ + /// + /// Represents a JSON array. + /// + /// + /// + /// + public class JArray : JContainer, IList + { + private readonly List _values = new List(); + + /// + /// Gets the container's children tokens. + /// + /// The container's children tokens. + protected override IList ChildrenTokens + { + get { return _values; } + } + + /// + /// Gets the node type for this . + /// + /// The type. + public override JTokenType Type + { + get { return JTokenType.Array; } + } + + /// + /// Initializes a new instance of the class. + /// + public JArray() + { + } + + /// + /// Initializes a new instance of the class from another object. + /// + /// A object to copy from. + public JArray(JArray other) + : base(other) + { + } + + /// + /// Initializes a new instance of the class with the specified content. + /// + /// The contents of the array. + public JArray(params object[] content) + : this((object)content) + { + } + + /// + /// Initializes a new instance of the class with the specified content. + /// + /// The contents of the array. + public JArray(object content) + { + Add(content); + } + + internal override bool DeepEquals(JToken node) + { + JArray t = node as JArray; + return (t != null && ContentsEqual(t)); + } + + internal override JToken CloneToken() + { + return new JArray(this); + } + + /// + /// Loads an from a . + /// + /// A that will be read for the content of the . + /// A that contains the JSON that was read from the specified . + public new static JArray Load(JsonReader reader) + { + return Load(reader, null); + } + + /// + /// Loads an from a . + /// + /// A that will be read for the content of the . + /// The used to load the JSON. + /// If this is null, default load settings will be used. + /// A that contains the JSON that was read from the specified . + public new static JArray Load(JsonReader reader, JsonLoadSettings settings) + { + if (reader.TokenType == JsonToken.None) + { + if (!reader.Read()) + { + throw JsonReaderException.Create(reader, "Error reading JArray from JsonReader."); + } + } + + reader.MoveToContent(); + + if (reader.TokenType != JsonToken.StartArray) + { + throw JsonReaderException.Create(reader, "Error reading JArray from JsonReader. Current JsonReader item is not an array: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); + } + + JArray a = new JArray(); + a.SetLineInfo(reader as IJsonLineInfo, settings); + + a.ReadTokenFrom(reader, settings); + + return a; + } + + /// + /// Load a from a string that contains JSON. + /// + /// A that contains JSON. + /// A populated from the string that contains JSON. + /// + /// + /// + public new static JArray Parse(string json) + { + return Parse(json, null); + } + + /// + /// Load a from a string that contains JSON. + /// + /// A that contains JSON. + /// The used to load the JSON. + /// If this is null, default load settings will be used. + /// A populated from the string that contains JSON. + /// + /// + /// + public new static JArray Parse(string json, JsonLoadSettings settings) + { + using (JsonReader reader = new JsonTextReader(new StringReader(json))) + { + JArray a = Load(reader, settings); + + if (reader.Read() && reader.TokenType != JsonToken.Comment) + { + throw JsonReaderException.Create(reader, "Additional text found in JSON string after parsing content."); + } + + return a; + } + } + + /// + /// Creates a from an object. + /// + /// The object that will be used to create . + /// A with the values of the specified object + public new static JArray FromObject(object o) + { + return FromObject(o, JsonSerializer.CreateDefault()); + } + + /// + /// Creates a from an object. + /// + /// The object that will be used to create . + /// The that will be used to read the object. + /// A with the values of the specified object + public new static JArray FromObject(object o, JsonSerializer jsonSerializer) + { + JToken token = FromObjectInternal(o, jsonSerializer); + + if (token.Type != JTokenType.Array) + { + throw new ArgumentException("Object serialized to {0}. JArray instance expected.".FormatWith(CultureInfo.InvariantCulture, token.Type)); + } + + return (JArray)token; + } + + /// + /// Writes this token to a . + /// + /// A into which this method will write. + /// A collection of which will be used when writing the token. + public override void WriteTo(JsonWriter writer, params JsonConverter[] converters) + { + writer.WriteStartArray(); + + for (int i = 0; i < _values.Count; i++) + { + _values[i].WriteTo(writer, converters); + } + + writer.WriteEndArray(); + } + + /// + /// Gets the with the specified key. + /// + /// The with the specified key. + public override JToken this[object key] + { + get + { + ValidationUtils.ArgumentNotNull(key, nameof(key)); + + if (!(key is int)) + { + throw new ArgumentException("Accessed JArray values with invalid key value: {0}. Int32 array index expected.".FormatWith(CultureInfo.InvariantCulture, MiscellaneousUtils.ToString(key))); + } + + return GetItem((int)key); + } + set + { + ValidationUtils.ArgumentNotNull(key, nameof(key)); + + if (!(key is int)) + { + throw new ArgumentException("Set JArray values with invalid key value: {0}. Int32 array index expected.".FormatWith(CultureInfo.InvariantCulture, MiscellaneousUtils.ToString(key))); + } + + SetItem((int)key, value); + } + } + + /// + /// Gets or sets the at the specified index. + /// + /// + public JToken this[int index] + { + get { return GetItem(index); } + set { SetItem(index, value); } + } + + internal override void MergeItem(object content, JsonMergeSettings settings) + { + IEnumerable a = (IsMultiContent(content) || content is JArray) + ? (IEnumerable)content + : null; + if (a == null) + { + return; + } + + MergeEnumerableContent(this, a, settings); + } + + #region IList Members + /// + /// Determines the index of a specific item in the . + /// + /// The object to locate in the . + /// + /// The index of if found in the list; otherwise, -1. + /// + public int IndexOf(JToken item) + { + return IndexOfItem(item); + } + + /// + /// Inserts an item to the at the specified index. + /// + /// The zero-based index at which should be inserted. + /// The object to insert into the . + /// + /// is not a valid index in the . + /// The is read-only. + public void Insert(int index, JToken item) + { + InsertItem(index, item, false); + } + + /// + /// Removes the item at the specified index. + /// + /// The zero-based index of the item to remove. + /// + /// is not a valid index in the . + /// The is read-only. + public void RemoveAt(int index) + { + RemoveItemAt(index); + } + + /// + /// Returns an enumerator that iterates through the collection. + /// + /// + /// A that can be used to iterate through the collection. + /// + public IEnumerator GetEnumerator() + { + return Children().GetEnumerator(); + } + #endregion + + #region ICollection Members + /// + /// Adds an item to the . + /// + /// The object to add to the . + /// The is read-only. + public void Add(JToken item) + { + Add((object)item); + } + + /// + /// Removes all items from the . + /// + /// The is read-only. + public void Clear() + { + ClearItems(); + } + + /// + /// Determines whether the contains a specific value. + /// + /// The object to locate in the . + /// + /// true if is found in the ; otherwise, false. + /// + public bool Contains(JToken item) + { + return ContainsItem(item); + } + + /// + /// Copies to. + /// + /// The array. + /// Index of the array. + public void CopyTo(JToken[] array, int arrayIndex) + { + CopyItemsTo(array, arrayIndex); + } + + /// + /// Gets a value indicating whether the is read-only. + /// + /// true if the is read-only; otherwise, false. + public bool IsReadOnly + { + get { return false; } + } + + /// + /// Removes the first occurrence of a specific object from the . + /// + /// The object to remove from the . + /// + /// true if was successfully removed from the ; otherwise, false. This method also returns false if is not found in the original . + /// + /// The is read-only. + public bool Remove(JToken item) + { + return RemoveItem(item); + } + #endregion + + internal override int GetDeepHashCode() + { + return ContentsHashCode(); + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Linq/JConstructor.cs b/Common/00-1Json8.3/Json8.3/Linq/JConstructor.cs new file mode 100644 index 0000000..0a49a93 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Linq/JConstructor.cs @@ -0,0 +1,247 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Collections; +using System.Collections.Generic; +using Newtonsoft.Json.Utilities; +using System.Globalization; + +namespace Newtonsoft.Json.Linq +{ + /// + /// Represents a JSON constructor. + /// + public class JConstructor : JContainer + { + private string _name; + private readonly List _values = new List(); + + /// + /// Gets the container's children tokens. + /// + /// The container's children tokens. + protected override IList ChildrenTokens + { + get { return _values; } + } + + internal override void MergeItem(object content, JsonMergeSettings settings) + { + JConstructor c = content as JConstructor; + if (c == null) + { + return; + } + + if (c.Name != null) + { + Name = c.Name; + } + MergeEnumerableContent(this, c, settings); + } + + /// + /// Gets or sets the name of this constructor. + /// + /// The constructor name. + public string Name + { + get { return _name; } + set { _name = value; } + } + + /// + /// Gets the node type for this . + /// + /// The type. + public override JTokenType Type + { + get { return JTokenType.Constructor; } + } + + /// + /// Initializes a new instance of the class. + /// + public JConstructor() + { + } + + /// + /// Initializes a new instance of the class from another object. + /// + /// A object to copy from. + public JConstructor(JConstructor other) + : base(other) + { + _name = other.Name; + } + + /// + /// Initializes a new instance of the class with the specified name and content. + /// + /// The constructor name. + /// The contents of the constructor. + public JConstructor(string name, params object[] content) + : this(name, (object)content) + { + } + + /// + /// Initializes a new instance of the class with the specified name and content. + /// + /// The constructor name. + /// The contents of the constructor. + public JConstructor(string name, object content) + : this(name) + { + Add(content); + } + + /// + /// Initializes a new instance of the class with the specified name. + /// + /// The constructor name. + public JConstructor(string name) + { + if (name == null) + { + throw new ArgumentNullException(nameof(name)); + } + + if (name.Length == 0) + { + throw new ArgumentException("Constructor name cannot be empty.", nameof(name)); + } + + _name = name; + } + + internal override bool DeepEquals(JToken node) + { + JConstructor c = node as JConstructor; + return (c != null && _name == c.Name && ContentsEqual(c)); + } + + internal override JToken CloneToken() + { + return new JConstructor(this); + } + + /// + /// Writes this token to a . + /// + /// A into which this method will write. + /// A collection of which will be used when writing the token. + public override void WriteTo(JsonWriter writer, params JsonConverter[] converters) + { + writer.WriteStartConstructor(_name); + + foreach (JToken token in Children()) + { + token.WriteTo(writer, converters); + } + + writer.WriteEndConstructor(); + } + + /// + /// Gets the with the specified key. + /// + /// The with the specified key. + public override JToken this[object key] + { + get + { + ValidationUtils.ArgumentNotNull(key, nameof(key)); + + if (!(key is int)) + { + throw new ArgumentException("Accessed JConstructor values with invalid key value: {0}. Argument position index expected.".FormatWith(CultureInfo.InvariantCulture, MiscellaneousUtils.ToString(key))); + } + + return GetItem((int)key); + } + set + { + ValidationUtils.ArgumentNotNull(key, nameof(key)); + + if (!(key is int)) + { + throw new ArgumentException("Set JConstructor values with invalid key value: {0}. Argument position index expected.".FormatWith(CultureInfo.InvariantCulture, MiscellaneousUtils.ToString(key))); + } + + SetItem((int)key, value); + } + } + + internal override int GetDeepHashCode() + { + return _name.GetHashCode() ^ ContentsHashCode(); + } + + /// + /// Loads an from a . + /// + /// A that will be read for the content of the . + /// A that contains the JSON that was read from the specified . + public new static JConstructor Load(JsonReader reader) + { + return Load(reader, null); + } + + /// + /// Loads an from a . + /// + /// A that will be read for the content of the . + /// The used to load the JSON. + /// If this is null, default load settings will be used. + /// A that contains the JSON that was read from the specified . + public new static JConstructor Load(JsonReader reader, JsonLoadSettings settings) + { + if (reader.TokenType == JsonToken.None) + { + if (!reader.Read()) + { + throw JsonReaderException.Create(reader, "Error reading JConstructor from JsonReader."); + } + } + + reader.MoveToContent(); + + if (reader.TokenType != JsonToken.StartConstructor) + { + throw JsonReaderException.Create(reader, "Error reading JConstructor from JsonReader. Current JsonReader item is not a constructor: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); + } + + JConstructor c = new JConstructor((string)reader.Value); + c.SetLineInfo(reader as IJsonLineInfo, settings); + + c.ReadTokenFrom(reader, settings); + + return c; + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Linq/JContainer.cs b/Common/00-1Json8.3/Json8.3/Linq/JContainer.cs new file mode 100644 index 0000000..6e90201 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Linq/JContainer.cs @@ -0,0 +1,1256 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Collections.Generic; +#if !PORTABLE40 +using System.Collections.Specialized; +#endif +using System.Threading; +using Newtonsoft.Json.Utilities; +using System.Collections; +using System.Globalization; +using System.ComponentModel; +#if NET20 +using Newtonsoft.Json.Utilities.LinqBridge; +#else +using System.Linq; + +#endif + +namespace Newtonsoft.Json.Linq +{ + /// + /// Represents a token that can contain other tokens. + /// + public abstract class JContainer : JToken, IList +#if !(DOTNET || PORTABLE || PORTABLE40) + , ITypedList, IBindingList +#endif + , IList +#if !(NET20 || NET35 || PORTABLE40) + , INotifyCollectionChanged +#endif + { +#if !(DOTNET || PORTABLE40 || PORTABLE) + internal ListChangedEventHandler _listChanged; + internal AddingNewEventHandler _addingNew; + + /// + /// Occurs when the list changes or an item in the list changes. + /// + public event ListChangedEventHandler ListChanged + { + add { _listChanged += value; } + remove { _listChanged -= value; } + } + + /// + /// Occurs before an item is added to the collection. + /// + public event AddingNewEventHandler AddingNew + { + add { _addingNew += value; } + remove { _addingNew -= value; } + } +#endif +#if !(NET20 || NET35 || PORTABLE40) + internal NotifyCollectionChangedEventHandler _collectionChanged; + + /// + /// Occurs when the items list of the collection has changed, or the collection is reset. + /// + public event NotifyCollectionChangedEventHandler CollectionChanged + { + add { _collectionChanged += value; } + remove { _collectionChanged -= value; } + } +#endif + + /// + /// Gets the container's children tokens. + /// + /// The container's children tokens. + protected abstract IList ChildrenTokens { get; } + + private object _syncRoot; +#if !(PORTABLE40) + private bool _busy; +#endif + + internal JContainer() + { + } + + internal JContainer(JContainer other) + : this() + { + ValidationUtils.ArgumentNotNull(other, nameof(other)); + + int i = 0; + foreach (JToken child in other) + { + AddInternal(i, child, false); + i++; + } + } + + internal void CheckReentrancy() + { +#if !(PORTABLE40) + if (_busy) + { + throw new InvalidOperationException("Cannot change {0} during a collection change event.".FormatWith(CultureInfo.InvariantCulture, GetType())); + } +#endif + } + + internal virtual IList CreateChildrenCollection() + { + return new List(); + } + +#if !(DOTNET || PORTABLE40 || PORTABLE) + /// + /// Raises the event. + /// + /// The instance containing the event data. + protected virtual void OnAddingNew(AddingNewEventArgs e) + { + AddingNewEventHandler handler = _addingNew; + if (handler != null) + { + handler(this, e); + } + } + + /// + /// Raises the event. + /// + /// The instance containing the event data. + protected virtual void OnListChanged(ListChangedEventArgs e) + { + ListChangedEventHandler handler = _listChanged; + + if (handler != null) + { + _busy = true; + try + { + handler(this, e); + } + finally + { + _busy = false; + } + } + } +#endif +#if !(NET20 || NET35 || PORTABLE40) + /// + /// Raises the event. + /// + /// The instance containing the event data. + protected virtual void OnCollectionChanged(NotifyCollectionChangedEventArgs e) + { + NotifyCollectionChangedEventHandler handler = _collectionChanged; + + if (handler != null) + { + _busy = true; + try + { + handler(this, e); + } + finally + { + _busy = false; + } + } + } +#endif + + /// + /// Gets a value indicating whether this token has child tokens. + /// + /// + /// true if this token has child values; otherwise, false. + /// + public override bool HasValues + { + get { return ChildrenTokens.Count > 0; } + } + + internal bool ContentsEqual(JContainer container) + { + if (container == this) + { + return true; + } + + IList t1 = ChildrenTokens; + IList t2 = container.ChildrenTokens; + + if (t1.Count != t2.Count) + { + return false; + } + + for (int i = 0; i < t1.Count; i++) + { + if (!t1[i].DeepEquals(t2[i])) + { + return false; + } + } + + return true; + } + + /// + /// Get the first child token of this token. + /// + /// + /// A containing the first child token of the . + /// + public override JToken First + { + get + { + IList children = ChildrenTokens; + return (children.Count > 0) ? children[0] : null; + } + } + + /// + /// Get the last child token of this token. + /// + /// + /// A containing the last child token of the . + /// + public override JToken Last + { + get + { + IList children = ChildrenTokens; + int count = children.Count; + return (count > 0) ? children[count - 1] : null; + } + } + + /// + /// Returns a collection of the child tokens of this token, in document order. + /// + /// + /// An of containing the child tokens of this , in document order. + /// + public override JEnumerable Children() + { + return new JEnumerable(ChildrenTokens); + } + + /// + /// Returns a collection of the child values of this token, in document order. + /// + /// The type to convert the values to. + /// + /// A containing the child values of this , in document order. + /// + public override IEnumerable Values() + { + return ChildrenTokens.Convert(); + } + + /// + /// Returns a collection of the descendant tokens for this token in document order. + /// + /// An containing the descendant tokens of the . + public IEnumerable Descendants() + { + return GetDescendants(false); + } + + /// + /// Returns a collection of the tokens that contain this token, and all descendant tokens of this token, in document order. + /// + /// An containing this token, and all the descendant tokens of the . + public IEnumerable DescendantsAndSelf() + { + return GetDescendants(true); + } + + internal IEnumerable GetDescendants(bool self) + { + if (self) + { + yield return this; + } + + foreach (JToken o in ChildrenTokens) + { + yield return o; + JContainer c = o as JContainer; + if (c != null) + { + foreach (JToken d in c.Descendants()) + { + yield return d; + } + } + } + } + + internal bool IsMultiContent(object content) + { + return (content is IEnumerable && !(content is string) && !(content is JToken) && !(content is byte[])); + } + + internal JToken EnsureParentToken(JToken item, bool skipParentCheck) + { + if (item == null) + { + return JValue.CreateNull(); + } + + if (skipParentCheck) + { + return item; + } + + // to avoid a token having multiple parents or creating a recursive loop, create a copy if... + // the item already has a parent + // the item is being added to itself + // the item is being added to the root parent of itself + if (item.Parent != null || item == this || (item.HasValues && Root == item)) + { + item = item.CloneToken(); + } + + return item; + } + + private class JTokenReferenceEqualityComparer : IEqualityComparer + { + public static readonly JTokenReferenceEqualityComparer Instance = new JTokenReferenceEqualityComparer(); + + public bool Equals(JToken x, JToken y) + { + return ReferenceEquals(x, y); + } + + public int GetHashCode(JToken obj) + { + if (obj == null) + { + return 0; + } + + return obj.GetHashCode(); + } + } + + internal int IndexOfItem(JToken item) + { + return ChildrenTokens.IndexOf(item, JTokenReferenceEqualityComparer.Instance); + } + + internal virtual void InsertItem(int index, JToken item, bool skipParentCheck) + { + IList children = ChildrenTokens; + + if (index > children.Count) + { + throw new ArgumentOutOfRangeException(nameof(index), "Index must be within the bounds of the List."); + } + + CheckReentrancy(); + + item = EnsureParentToken(item, skipParentCheck); + + JToken previous = (index == 0) ? null : children[index - 1]; + // haven't inserted new token yet so next token is still at the inserting index + JToken next = (index == children.Count) ? null : children[index]; + + ValidateToken(item, null); + + item.Parent = this; + + item.Previous = previous; + if (previous != null) + { + previous.Next = item; + } + + item.Next = next; + if (next != null) + { + next.Previous = item; + } + + children.Insert(index, item); + +#if !(DOTNET || PORTABLE40 || PORTABLE) + if (_listChanged != null) + { + OnListChanged(new ListChangedEventArgs(ListChangedType.ItemAdded, index)); + } +#endif +#if !(NET20 || NET35 || PORTABLE40) + if (_collectionChanged != null) + { + OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item, index)); + } +#endif + } + + internal virtual void RemoveItemAt(int index) + { + IList children = ChildrenTokens; + + if (index < 0) + { + throw new ArgumentOutOfRangeException(nameof(index), "Index is less than 0."); + } + if (index >= children.Count) + { + throw new ArgumentOutOfRangeException(nameof(index), "Index is equal to or greater than Count."); + } + + CheckReentrancy(); + + JToken item = children[index]; + JToken previous = (index == 0) ? null : children[index - 1]; + JToken next = (index == children.Count - 1) ? null : children[index + 1]; + + if (previous != null) + { + previous.Next = next; + } + if (next != null) + { + next.Previous = previous; + } + + item.Parent = null; + item.Previous = null; + item.Next = null; + + children.RemoveAt(index); + +#if !(DOTNET || PORTABLE40 || PORTABLE) + if (_listChanged != null) + { + OnListChanged(new ListChangedEventArgs(ListChangedType.ItemDeleted, index)); + } +#endif +#if !(NET20 || NET35 || PORTABLE40) + if (_collectionChanged != null) + { + OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, item, index)); + } +#endif + } + + internal virtual bool RemoveItem(JToken item) + { + int index = IndexOfItem(item); + if (index >= 0) + { + RemoveItemAt(index); + return true; + } + + return false; + } + + internal virtual JToken GetItem(int index) + { + return ChildrenTokens[index]; + } + + internal virtual void SetItem(int index, JToken item) + { + IList children = ChildrenTokens; + + if (index < 0) + { + throw new ArgumentOutOfRangeException(nameof(index), "Index is less than 0."); + } + if (index >= children.Count) + { + throw new ArgumentOutOfRangeException(nameof(index), "Index is equal to or greater than Count."); + } + + JToken existing = children[index]; + + if (IsTokenUnchanged(existing, item)) + { + return; + } + + CheckReentrancy(); + + item = EnsureParentToken(item, false); + + ValidateToken(item, existing); + + JToken previous = (index == 0) ? null : children[index - 1]; + JToken next = (index == children.Count - 1) ? null : children[index + 1]; + + item.Parent = this; + + item.Previous = previous; + if (previous != null) + { + previous.Next = item; + } + + item.Next = next; + if (next != null) + { + next.Previous = item; + } + + children[index] = item; + + existing.Parent = null; + existing.Previous = null; + existing.Next = null; + +#if !(DOTNET || PORTABLE || PORTABLE40) + if (_listChanged != null) + { + OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, index)); + } +#endif +#if !(NET20 || NET35 || PORTABLE40) + if (_collectionChanged != null) + { + OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, item, existing, index)); + } +#endif + } + + internal virtual void ClearItems() + { + CheckReentrancy(); + + IList children = ChildrenTokens; + + foreach (JToken item in children) + { + item.Parent = null; + item.Previous = null; + item.Next = null; + } + + children.Clear(); + +#if !(DOTNET || PORTABLE40 || PORTABLE) + if (_listChanged != null) + { + OnListChanged(new ListChangedEventArgs(ListChangedType.Reset, -1)); + } +#endif +#if !(NET20 || NET35 || PORTABLE40) + if (_collectionChanged != null) + { + OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); + } +#endif + } + + internal virtual void ReplaceItem(JToken existing, JToken replacement) + { + if (existing == null || existing.Parent != this) + { + return; + } + + int index = IndexOfItem(existing); + SetItem(index, replacement); + } + + internal virtual bool ContainsItem(JToken item) + { + return (IndexOfItem(item) != -1); + } + + internal virtual void CopyItemsTo(Array array, int arrayIndex) + { + if (array == null) + { + throw new ArgumentNullException(nameof(array)); + } + if (arrayIndex < 0) + { + throw new ArgumentOutOfRangeException(nameof(arrayIndex), "arrayIndex is less than 0."); + } + if (arrayIndex >= array.Length && arrayIndex != 0) + { + throw new ArgumentException("arrayIndex is equal to or greater than the length of array."); + } + if (Count > array.Length - arrayIndex) + { + throw new ArgumentException("The number of elements in the source JObject is greater than the available space from arrayIndex to the end of the destination array."); + } + + int index = 0; + foreach (JToken token in ChildrenTokens) + { + array.SetValue(token, arrayIndex + index); + index++; + } + } + + internal static bool IsTokenUnchanged(JToken currentValue, JToken newValue) + { + JValue v1 = currentValue as JValue; + if (v1 != null) + { + // null will get turned into a JValue of type null + if (v1.Type == JTokenType.Null && newValue == null) + { + return true; + } + + return v1.Equals(newValue); + } + + return false; + } + + internal virtual void ValidateToken(JToken o, JToken existing) + { + ValidationUtils.ArgumentNotNull(o, nameof(o)); + + if (o.Type == JTokenType.Property) + { + throw new ArgumentException("Can not add {0} to {1}.".FormatWith(CultureInfo.InvariantCulture, o.GetType(), GetType())); + } + } + + /// + /// Adds the specified content as children of this . + /// + /// The content to be added. + public virtual void Add(object content) + { + AddInternal(ChildrenTokens.Count, content, false); + } + + internal void AddAndSkipParentCheck(JToken token) + { + AddInternal(ChildrenTokens.Count, token, true); + } + + /// + /// Adds the specified content as the first children of this . + /// + /// The content to be added. + public void AddFirst(object content) + { + AddInternal(0, content, false); + } + + internal void AddInternal(int index, object content, bool skipParentCheck) + { + if (IsMultiContent(content)) + { + IEnumerable enumerable = (IEnumerable)content; + + int multiIndex = index; + foreach (object c in enumerable) + { + AddInternal(multiIndex, c, skipParentCheck); + multiIndex++; + } + } + else + { + JToken item = CreateFromContent(content); + + InsertItem(index, item, skipParentCheck); + } + } + + internal static JToken CreateFromContent(object content) + { + if (content is JToken) + { + return (JToken)content; + } + + return new JValue(content); + } + + /// + /// Creates an that can be used to add tokens to the . + /// + /// An that is ready to have content written to it. + public JsonWriter CreateWriter() + { + return new JTokenWriter(this); + } + + /// + /// Replaces the children nodes of this token with the specified content. + /// + /// The content. + public void ReplaceAll(object content) + { + ClearItems(); + Add(content); + } + + /// + /// Removes the child nodes from this token. + /// + public void RemoveAll() + { + ClearItems(); + } + + internal abstract void MergeItem(object content, JsonMergeSettings settings); + + /// + /// Merge the specified content into this . + /// + /// The content to be merged. + public void Merge(object content) + { + MergeItem(content, new JsonMergeSettings()); + } + + /// + /// Merge the specified content into this using . + /// + /// The content to be merged. + /// The used to merge the content. + public void Merge(object content, JsonMergeSettings settings) + { + MergeItem(content, settings); + } + + internal void ReadTokenFrom(JsonReader reader, JsonLoadSettings options) + { + int startDepth = reader.Depth; + + if (!reader.Read()) + { + throw JsonReaderException.Create(reader, "Error reading {0} from JsonReader.".FormatWith(CultureInfo.InvariantCulture, GetType().Name)); + } + + ReadContentFrom(reader, options); + + int endDepth = reader.Depth; + + if (endDepth > startDepth) + { + throw JsonReaderException.Create(reader, "Unexpected end of content while loading {0}.".FormatWith(CultureInfo.InvariantCulture, GetType().Name)); + } + } + + internal void ReadContentFrom(JsonReader r, JsonLoadSettings settings) + { + ValidationUtils.ArgumentNotNull(r, nameof(r)); + IJsonLineInfo lineInfo = r as IJsonLineInfo; + + JContainer parent = this; + + do + { + if (parent is JProperty && ((JProperty)parent).Value != null) + { + if (parent == this) + { + return; + } + + parent = parent.Parent; + } + + switch (r.TokenType) + { + case JsonToken.None: + // new reader. move to actual content + break; + case JsonToken.StartArray: + JArray a = new JArray(); + a.SetLineInfo(lineInfo, settings); + parent.Add(a); + parent = a; + break; + + case JsonToken.EndArray: + if (parent == this) + { + return; + } + + parent = parent.Parent; + break; + case JsonToken.StartObject: + JObject o = new JObject(); + o.SetLineInfo(lineInfo, settings); + parent.Add(o); + parent = o; + break; + case JsonToken.EndObject: + if (parent == this) + { + return; + } + + parent = parent.Parent; + break; + case JsonToken.StartConstructor: + JConstructor constructor = new JConstructor(r.Value.ToString()); + constructor.SetLineInfo(lineInfo, settings); + parent.Add(constructor); + parent = constructor; + break; + case JsonToken.EndConstructor: + if (parent == this) + { + return; + } + + parent = parent.Parent; + break; + case JsonToken.String: + case JsonToken.Integer: + case JsonToken.Float: + case JsonToken.Date: + case JsonToken.Boolean: + case JsonToken.Bytes: + JValue v = new JValue(r.Value); + v.SetLineInfo(lineInfo, settings); + parent.Add(v); + break; + case JsonToken.Comment: + if (settings != null && settings.CommentHandling == CommentHandling.Load) + { + v = JValue.CreateComment(r.Value.ToString()); + v.SetLineInfo(lineInfo, settings); + parent.Add(v); + } + break; + case JsonToken.Null: + v = JValue.CreateNull(); + v.SetLineInfo(lineInfo, settings); + parent.Add(v); + break; + case JsonToken.Undefined: + v = JValue.CreateUndefined(); + v.SetLineInfo(lineInfo, settings); + parent.Add(v); + break; + case JsonToken.PropertyName: + string propertyName = r.Value.ToString(); + JProperty property = new JProperty(propertyName); + property.SetLineInfo(lineInfo, settings); + JObject parentObject = (JObject)parent; + // handle multiple properties with the same name in JSON + JProperty existingPropertyWithName = parentObject.Property(propertyName); + if (existingPropertyWithName == null) + { + parent.Add(property); + } + else + { + existingPropertyWithName.Replace(property); + } + parent = property; + break; + default: + throw new InvalidOperationException("The JsonReader should not be on a token of type {0}.".FormatWith(CultureInfo.InvariantCulture, r.TokenType)); + } + } while (r.Read()); + } + + internal int ContentsHashCode() + { + int hashCode = 0; + foreach (JToken item in ChildrenTokens) + { + hashCode ^= item.GetDeepHashCode(); + } + return hashCode; + } + +#if !(DOTNET || PORTABLE40 || PORTABLE) + string ITypedList.GetListName(PropertyDescriptor[] listAccessors) + { + return string.Empty; + } + + PropertyDescriptorCollection ITypedList.GetItemProperties(PropertyDescriptor[] listAccessors) + { + ICustomTypeDescriptor d = First as ICustomTypeDescriptor; + if (d != null) + { + return d.GetProperties(); + } + + return null; + } +#endif + + #region IList Members + int IList.IndexOf(JToken item) + { + return IndexOfItem(item); + } + + void IList.Insert(int index, JToken item) + { + InsertItem(index, item, false); + } + + void IList.RemoveAt(int index) + { + RemoveItemAt(index); + } + + JToken IList.this[int index] + { + get { return GetItem(index); } + set { SetItem(index, value); } + } + #endregion + + #region ICollection Members + void ICollection.Add(JToken item) + { + Add(item); + } + + void ICollection.Clear() + { + ClearItems(); + } + + bool ICollection.Contains(JToken item) + { + return ContainsItem(item); + } + + void ICollection.CopyTo(JToken[] array, int arrayIndex) + { + CopyItemsTo(array, arrayIndex); + } + + bool ICollection.IsReadOnly + { + get { return false; } + } + + bool ICollection.Remove(JToken item) + { + return RemoveItem(item); + } + #endregion + + private JToken EnsureValue(object value) + { + if (value == null) + { + return null; + } + + if (value is JToken) + { + return (JToken)value; + } + + throw new ArgumentException("Argument is not a JToken."); + } + + #region IList Members + int IList.Add(object value) + { + Add(EnsureValue(value)); + return Count - 1; + } + + void IList.Clear() + { + ClearItems(); + } + + bool IList.Contains(object value) + { + return ContainsItem(EnsureValue(value)); + } + + int IList.IndexOf(object value) + { + return IndexOfItem(EnsureValue(value)); + } + + void IList.Insert(int index, object value) + { + InsertItem(index, EnsureValue(value), false); + } + + bool IList.IsFixedSize + { + get { return false; } + } + + bool IList.IsReadOnly + { + get { return false; } + } + + void IList.Remove(object value) + { + RemoveItem(EnsureValue(value)); + } + + void IList.RemoveAt(int index) + { + RemoveItemAt(index); + } + + object IList.this[int index] + { + get { return GetItem(index); } + set { SetItem(index, EnsureValue(value)); } + } + #endregion + + #region ICollection Members + void ICollection.CopyTo(Array array, int index) + { + CopyItemsTo(array, index); + } + + /// + /// Gets the count of child JSON tokens. + /// + /// The count of child JSON tokens + public int Count + { + get { return ChildrenTokens.Count; } + } + + bool ICollection.IsSynchronized + { + get { return false; } + } + + object ICollection.SyncRoot + { + get + { + if (_syncRoot == null) + { + Interlocked.CompareExchange(ref _syncRoot, new object(), null); + } + + return _syncRoot; + } + } + #endregion + + #region IBindingList Members +#if !(DOTNET || PORTABLE || PORTABLE40) + void IBindingList.AddIndex(PropertyDescriptor property) + { + } + + object IBindingList.AddNew() + { + AddingNewEventArgs args = new AddingNewEventArgs(); + OnAddingNew(args); + + if (args.NewObject == null) + { + throw new JsonException("Could not determine new value to add to '{0}'.".FormatWith(CultureInfo.InvariantCulture, GetType())); + } + + if (!(args.NewObject is JToken)) + { + throw new JsonException("New item to be added to collection must be compatible with {0}.".FormatWith(CultureInfo.InvariantCulture, typeof(JToken))); + } + + JToken newItem = (JToken)args.NewObject; + Add(newItem); + + return newItem; + } + + bool IBindingList.AllowEdit + { + get { return true; } + } + + bool IBindingList.AllowNew + { + get { return true; } + } + + bool IBindingList.AllowRemove + { + get { return true; } + } + + void IBindingList.ApplySort(PropertyDescriptor property, ListSortDirection direction) + { + throw new NotSupportedException(); + } + + int IBindingList.Find(PropertyDescriptor property, object key) + { + throw new NotSupportedException(); + } + + bool IBindingList.IsSorted + { + get { return false; } + } + + void IBindingList.RemoveIndex(PropertyDescriptor property) + { + } + + void IBindingList.RemoveSort() + { + throw new NotSupportedException(); + } + + ListSortDirection IBindingList.SortDirection + { + get { return ListSortDirection.Ascending; } + } + + PropertyDescriptor IBindingList.SortProperty + { + get { return null; } + } + + bool IBindingList.SupportsChangeNotification + { + get { return true; } + } + + bool IBindingList.SupportsSearching + { + get { return false; } + } + + bool IBindingList.SupportsSorting + { + get { return false; } + } +#endif + #endregion + + internal static void MergeEnumerableContent(JContainer target, IEnumerable content, JsonMergeSettings settings) + { + switch (settings.MergeArrayHandling) + { + case MergeArrayHandling.Concat: + foreach (JToken item in content) + { + target.Add(item); + } + break; + case MergeArrayHandling.Union: +#if !NET20 + HashSet items = new HashSet(target, EqualityComparer); + + foreach (JToken item in content) + { + if (items.Add(item)) + { + target.Add(item); + } + } +#else + IDictionary items = new Dictionary(EqualityComparer); + foreach (JToken t in target) + { + items[t] = true; + } + + foreach (JToken item in content) + { + if (!items.ContainsKey(item)) + { + items[item] = true; + target.Add(item); + } + } +#endif + break; + case MergeArrayHandling.Replace: + target.ClearItems(); + foreach (JToken item in content) + { + target.Add(item); + } + break; + case MergeArrayHandling.Merge: + int i = 0; + foreach (object targetItem in content) + { + if (i < target.Count) + { + JToken sourceItem = target[i]; + + JContainer existingContainer = sourceItem as JContainer; + if (existingContainer != null) + { + existingContainer.Merge(targetItem, settings); + } + else + { + if (targetItem != null) + { + JToken contentValue = CreateFromContent(targetItem); + if (contentValue.Type != JTokenType.Null) + { + target[i] = contentValue; + } + } + } + } + else + { + target.Add(targetItem); + } + + i++; + } + break; + default: + throw new ArgumentOutOfRangeException(nameof(settings), "Unexpected merge array handling when merging JSON."); + } + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Linq/JEnumerable.cs b/Common/00-1Json8.3/Json8.3/Linq/JEnumerable.cs new file mode 100644 index 0000000..612d428 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Linq/JEnumerable.cs @@ -0,0 +1,151 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Collections.Generic; +#if NET20 +using Newtonsoft.Json.Utilities.LinqBridge; +#else +using System.Linq; +#endif +using Newtonsoft.Json.Utilities; +using System.Collections; + +namespace Newtonsoft.Json.Linq +{ + /// + /// Represents a collection of objects. + /// + /// The type of token + public struct JEnumerable : IJEnumerable, IEquatable> where T : JToken + { + /// + /// An empty collection of objects. + /// + public static readonly JEnumerable Empty = new JEnumerable(Enumerable.Empty()); + + private readonly IEnumerable _enumerable; + + /// + /// Initializes a new instance of the struct. + /// + /// The enumerable. + public JEnumerable(IEnumerable enumerable) + { + ValidationUtils.ArgumentNotNull(enumerable, nameof(enumerable)); + + _enumerable = enumerable; + } + + /// + /// Returns an enumerator that iterates through the collection. + /// + /// + /// A that can be used to iterate through the collection. + /// + public IEnumerator GetEnumerator() + { + if (_enumerable == null) + { + return Empty.GetEnumerator(); + } + + return _enumerable.GetEnumerator(); + } + + /// + /// Returns an enumerator that iterates through a collection. + /// + /// + /// An object that can be used to iterate through the collection. + /// + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + /// + /// Gets the with the specified key. + /// + /// + public IJEnumerable this[object key] + { + get + { + if (_enumerable == null) + { + return JEnumerable.Empty; + } + + return new JEnumerable(_enumerable.Values(key)); + } + } + + /// + /// Determines whether the specified is equal to this instance. + /// + /// The to compare with this instance. + /// + /// true if the specified is equal to this instance; otherwise, false. + /// + public bool Equals(JEnumerable other) + { + return Equals(_enumerable, other._enumerable); + } + + /// + /// Determines whether the specified is equal to this instance. + /// + /// The to compare with this instance. + /// + /// true if the specified is equal to this instance; otherwise, false. + /// + public override bool Equals(object obj) + { + if (obj is JEnumerable) + { + return Equals((JEnumerable)obj); + } + + return false; + } + + /// + /// Returns a hash code for this instance. + /// + /// + /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. + /// + public override int GetHashCode() + { + if (_enumerable == null) + { + return 0; + } + + return _enumerable.GetHashCode(); + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Linq/JObject.cs b/Common/00-1Json8.3/Json8.3/Linq/JObject.cs new file mode 100644 index 0000000..7e7d49c --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Linq/JObject.cs @@ -0,0 +1,905 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +#if !PORTABLE40 +using System.Collections.Specialized; +#endif +using System.ComponentModel; +#if !(NET35 || NET20 || PORTABLE40) +using System.Dynamic; +using System.Linq.Expressions; +#endif +using System.IO; +using Newtonsoft.Json.Utilities; +using System.Globalization; +#if NET20 +using Newtonsoft.Json.Utilities.LinqBridge; +#else +using System.Linq; + +#endif + +namespace Newtonsoft.Json.Linq +{ + /// + /// Represents a JSON object. + /// + /// + /// + /// + public class JObject : JContainer, IDictionary, INotifyPropertyChanged +#if !(DOTNET || PORTABLE40 || PORTABLE) + , ICustomTypeDescriptor +#endif +#if !(NET20 || PORTABLE40 || PORTABLE) + , INotifyPropertyChanging +#endif + { + private readonly JPropertyKeyedCollection _properties = new JPropertyKeyedCollection(); + + /// + /// Gets the container's children tokens. + /// + /// The container's children tokens. + protected override IList ChildrenTokens + { + get { return _properties; } + } + + /// + /// Occurs when a property value changes. + /// + public event PropertyChangedEventHandler PropertyChanged; + +#if !(NET20 || PORTABLE || PORTABLE40) + /// + /// Occurs when a property value is changing. + /// + public event PropertyChangingEventHandler PropertyChanging; +#endif + + /// + /// Initializes a new instance of the class. + /// + public JObject() + { + } + + /// + /// Initializes a new instance of the class from another object. + /// + /// A object to copy from. + public JObject(JObject other) + : base(other) + { + } + + /// + /// Initializes a new instance of the class with the specified content. + /// + /// The contents of the object. + public JObject(params object[] content) + : this((object)content) + { + } + + /// + /// Initializes a new instance of the class with the specified content. + /// + /// The contents of the object. + public JObject(object content) + { + Add(content); + } + + internal override bool DeepEquals(JToken node) + { + JObject t = node as JObject; + if (t == null) + { + return false; + } + + return _properties.Compare(t._properties); + } + + internal override void InsertItem(int index, JToken item, bool skipParentCheck) + { + // don't add comments to JObject, no name to reference comment by + if (item != null && item.Type == JTokenType.Comment) + { + return; + } + + base.InsertItem(index, item, skipParentCheck); + } + + internal override void ValidateToken(JToken o, JToken existing) + { + ValidationUtils.ArgumentNotNull(o, nameof(o)); + + if (o.Type != JTokenType.Property) + { + throw new ArgumentException("Can not add {0} to {1}.".FormatWith(CultureInfo.InvariantCulture, o.GetType(), GetType())); + } + + JProperty newProperty = (JProperty)o; + + if (existing != null) + { + JProperty existingProperty = (JProperty)existing; + + if (newProperty.Name == existingProperty.Name) + { + return; + } + } + + if (_properties.TryGetValue(newProperty.Name, out existing)) + { + throw new ArgumentException("Can not add property {0} to {1}. Property with the same name already exists on object.".FormatWith(CultureInfo.InvariantCulture, newProperty.Name, GetType())); + } + } + + internal override void MergeItem(object content, JsonMergeSettings settings) + { + JObject o = content as JObject; + if (o == null) + { + return; + } + + foreach (KeyValuePair contentItem in o) + { + JProperty existingProperty = Property(contentItem.Key); + + if (existingProperty == null) + { + Add(contentItem.Key, contentItem.Value); + } + else if (contentItem.Value != null) + { + JContainer existingContainer = existingProperty.Value as JContainer; + if (existingContainer == null) + { + if (contentItem.Value.Type != JTokenType.Null || settings?.MergeNullValueHandling == MergeNullValueHandling.Merge) + { + existingProperty.Value = contentItem.Value; + } + } + else if (existingContainer.Type != contentItem.Value.Type) + { + existingProperty.Value = contentItem.Value; + } + else + { + existingContainer.Merge(contentItem.Value, settings); + } + } + } + } + + internal void InternalPropertyChanged(JProperty childProperty) + { + OnPropertyChanged(childProperty.Name); +#if !(DOTNET || PORTABLE40 || PORTABLE) + if (_listChanged != null) + { + OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, IndexOfItem(childProperty))); + } +#endif +#if !(NET20 || NET35 || PORTABLE40) + if (_collectionChanged != null) + { + OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, childProperty, childProperty, IndexOfItem(childProperty))); + } +#endif + } + + internal void InternalPropertyChanging(JProperty childProperty) + { +#if !(NET20 || PORTABLE40 || PORTABLE) + OnPropertyChanging(childProperty.Name); +#endif + } + + internal override JToken CloneToken() + { + return new JObject(this); + } + + /// + /// Gets the node type for this . + /// + /// The type. + public override JTokenType Type + { + get { return JTokenType.Object; } + } + + /// + /// Gets an of this object's properties. + /// + /// An of this object's properties. + public IEnumerable Properties() + { + return _properties.Cast(); + } + + /// + /// Gets a the specified name. + /// + /// The property name. + /// A with the specified name or null. + public JProperty Property(string name) + { + if (name == null) + { + return null; + } + + JToken property; + _properties.TryGetValue(name, out property); + return (JProperty)property; + } + + /// + /// Gets an of this object's property values. + /// + /// An of this object's property values. + public JEnumerable PropertyValues() + { + return new JEnumerable(Properties().Select(p => p.Value)); + } + + /// + /// Gets the with the specified key. + /// + /// The with the specified key. + public override JToken this[object key] + { + get + { + ValidationUtils.ArgumentNotNull(key, nameof(key)); + + string propertyName = key as string; + if (propertyName == null) + { + throw new ArgumentException("Accessed JObject values with invalid key value: {0}. Object property name expected.".FormatWith(CultureInfo.InvariantCulture, MiscellaneousUtils.ToString(key))); + } + + return this[propertyName]; + } + set + { + ValidationUtils.ArgumentNotNull(key, nameof(key)); + + string propertyName = key as string; + if (propertyName == null) + { + throw new ArgumentException("Set JObject values with invalid key value: {0}. Object property name expected.".FormatWith(CultureInfo.InvariantCulture, MiscellaneousUtils.ToString(key))); + } + + this[propertyName] = value; + } + } + + /// + /// Gets or sets the with the specified property name. + /// + /// + public JToken this[string propertyName] + { + get + { + ValidationUtils.ArgumentNotNull(propertyName, nameof(propertyName)); + + JProperty property = Property(propertyName); + + return (property != null) ? property.Value : null; + } + set + { + JProperty property = Property(propertyName); + if (property != null) + { + property.Value = value; + } + else + { +#if !(NET20 || PORTABLE40 || PORTABLE) + OnPropertyChanging(propertyName); +#endif + Add(new JProperty(propertyName, value)); + OnPropertyChanged(propertyName); + } + } + } + + /// + /// Loads an from a . + /// + /// A that will be read for the content of the . + /// A that contains the JSON that was read from the specified . + public new static JObject Load(JsonReader reader) + { + return Load(reader, null); + } + + /// + /// Loads an from a . + /// + /// A that will be read for the content of the . + /// The used to load the JSON. + /// If this is null, default load settings will be used. + /// A that contains the JSON that was read from the specified . + public new static JObject Load(JsonReader reader, JsonLoadSettings settings) + { + ValidationUtils.ArgumentNotNull(reader, nameof(reader)); + + if (reader.TokenType == JsonToken.None) + { + if (!reader.Read()) + { + throw JsonReaderException.Create(reader, "Error reading JObject from JsonReader."); + } + } + + reader.MoveToContent(); + + if (reader.TokenType != JsonToken.StartObject) + { + throw JsonReaderException.Create(reader, "Error reading JObject from JsonReader. Current JsonReader item is not an object: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); + } + + JObject o = new JObject(); + o.SetLineInfo(reader as IJsonLineInfo, settings); + + o.ReadTokenFrom(reader, settings); + + return o; + } + + /// + /// Load a from a string that contains JSON. + /// + /// A that contains JSON. + /// A populated from the string that contains JSON. + /// + /// + /// + public new static JObject Parse(string json) + { + return Parse(json, null); + } + + /// + /// Load a from a string that contains JSON. + /// + /// A that contains JSON. + /// The used to load the JSON. + /// If this is null, default load settings will be used. + /// A populated from the string that contains JSON. + /// + /// + /// + public new static JObject Parse(string json, JsonLoadSettings settings) + { + using (JsonReader reader = new JsonTextReader(new StringReader(json))) + { + JObject o = Load(reader, settings); + + if (reader.Read() && reader.TokenType != JsonToken.Comment) + { + throw JsonReaderException.Create(reader, "Additional text found in JSON string after parsing content."); + } + + return o; + } + } + + /// + /// Creates a from an object. + /// + /// The object that will be used to create . + /// A with the values of the specified object + public new static JObject FromObject(object o) + { + return FromObject(o, JsonSerializer.CreateDefault()); + } + + /// + /// Creates a from an object. + /// + /// The object that will be used to create . + /// The that will be used to read the object. + /// A with the values of the specified object + public new static JObject FromObject(object o, JsonSerializer jsonSerializer) + { + JToken token = FromObjectInternal(o, jsonSerializer); + + if (token != null && token.Type != JTokenType.Object) + { + throw new ArgumentException("Object serialized to {0}. JObject instance expected.".FormatWith(CultureInfo.InvariantCulture, token.Type)); + } + + return (JObject)token; + } + + /// + /// Writes this token to a . + /// + /// A into which this method will write. + /// A collection of which will be used when writing the token. + public override void WriteTo(JsonWriter writer, params JsonConverter[] converters) + { + writer.WriteStartObject(); + + for (int i = 0; i < _properties.Count; i++) + { + _properties[i].WriteTo(writer, converters); + } + + writer.WriteEndObject(); + } + + /// + /// Gets the with the specified property name. + /// + /// Name of the property. + /// The with the specified property name. + public JToken GetValue(string propertyName) + { + return GetValue(propertyName, StringComparison.Ordinal); + } + + /// + /// Gets the with the specified property name. + /// The exact property name will be searched for first and if no matching property is found then + /// the will be used to match a property. + /// + /// Name of the property. + /// One of the enumeration values that specifies how the strings will be compared. + /// The with the specified property name. + public JToken GetValue(string propertyName, StringComparison comparison) + { + if (propertyName == null) + { + return null; + } + + // attempt to get value via dictionary first for performance + JProperty property = Property(propertyName); + if (property != null) + { + return property.Value; + } + + // test above already uses this comparison so no need to repeat + if (comparison != StringComparison.Ordinal) + { + foreach (JProperty p in _properties) + { + if (string.Equals(p.Name, propertyName, comparison)) + { + return p.Value; + } + } + } + + return null; + } + + /// + /// Tries to get the with the specified property name. + /// The exact property name will be searched for first and if no matching property is found then + /// the will be used to match a property. + /// + /// Name of the property. + /// The value. + /// One of the enumeration values that specifies how the strings will be compared. + /// true if a value was successfully retrieved; otherwise, false. + public bool TryGetValue(string propertyName, StringComparison comparison, out JToken value) + { + value = GetValue(propertyName, comparison); + return (value != null); + } + + #region IDictionary Members + /// + /// Adds the specified property name. + /// + /// Name of the property. + /// The value. + public void Add(string propertyName, JToken value) + { + Add(new JProperty(propertyName, value)); + } + + bool IDictionary.ContainsKey(string key) + { + return _properties.Contains(key); + } + + ICollection IDictionary.Keys + { + // todo: make order the collection returned match JObject order + get { return _properties.Keys; } + } + + /// + /// Removes the property with the specified name. + /// + /// Name of the property. + /// true if item was successfully removed; otherwise, false. + public bool Remove(string propertyName) + { + JProperty property = Property(propertyName); + if (property == null) + { + return false; + } + + property.Remove(); + return true; + } + + /// + /// Tries the get value. + /// + /// Name of the property. + /// The value. + /// true if a value was successfully retrieved; otherwise, false. + public bool TryGetValue(string propertyName, out JToken value) + { + JProperty property = Property(propertyName); + if (property == null) + { + value = null; + return false; + } + + value = property.Value; + return true; + } + + ICollection IDictionary.Values + { + get + { + // todo: need to wrap _properties.Values with a collection to get the JProperty value + throw new NotImplementedException(); + } + } + #endregion + + #region ICollection> Members + void ICollection>.Add(KeyValuePair item) + { + Add(new JProperty(item.Key, item.Value)); + } + + void ICollection>.Clear() + { + RemoveAll(); + } + + bool ICollection>.Contains(KeyValuePair item) + { + JProperty property = Property(item.Key); + if (property == null) + { + return false; + } + + return (property.Value == item.Value); + } + + void ICollection>.CopyTo(KeyValuePair[] array, int arrayIndex) + { + if (array == null) + { + throw new ArgumentNullException(nameof(array)); + } + if (arrayIndex < 0) + { + throw new ArgumentOutOfRangeException(nameof(arrayIndex), "arrayIndex is less than 0."); + } + if (arrayIndex >= array.Length && arrayIndex != 0) + { + throw new ArgumentException("arrayIndex is equal to or greater than the length of array."); + } + if (Count > array.Length - arrayIndex) + { + throw new ArgumentException("The number of elements in the source JObject is greater than the available space from arrayIndex to the end of the destination array."); + } + + int index = 0; + foreach (JProperty property in _properties) + { + array[arrayIndex + index] = new KeyValuePair(property.Name, property.Value); + index++; + } + } + + bool ICollection>.IsReadOnly + { + get { return false; } + } + + bool ICollection>.Remove(KeyValuePair item) + { + if (!((ICollection>)this).Contains(item)) + { + return false; + } + + ((IDictionary)this).Remove(item.Key); + return true; + } + #endregion + + internal override int GetDeepHashCode() + { + return ContentsHashCode(); + } + + /// + /// Returns an enumerator that iterates through the collection. + /// + /// + /// A that can be used to iterate through the collection. + /// + public IEnumerator> GetEnumerator() + { + foreach (JProperty property in _properties) + { + yield return new KeyValuePair(property.Name, property.Value); + } + } + + /// + /// Raises the event with the provided arguments. + /// + /// Name of the property. + protected virtual void OnPropertyChanged(string propertyName) + { + if (PropertyChanged != null) + { + PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); + } + } + +#if !(PORTABLE40 || PORTABLE || NET20) + /// + /// Raises the event with the provided arguments. + /// + /// Name of the property. + protected virtual void OnPropertyChanging(string propertyName) + { + if (PropertyChanging != null) + { + PropertyChanging(this, new PropertyChangingEventArgs(propertyName)); + } + } +#endif + +#if !(DOTNET || PORTABLE40 || PORTABLE) + // include custom type descriptor on JObject rather than use a provider because the properties are specific to a type + + #region ICustomTypeDescriptor + /// + /// Returns the properties for this instance of a component. + /// + /// + /// A that represents the properties for this component instance. + /// + PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties() + { + return ((ICustomTypeDescriptor)this).GetProperties(null); + } + + /// + /// Returns the properties for this instance of a component using the attribute array as a filter. + /// + /// An array of type that is used as a filter. + /// + /// A that represents the filtered properties for this component instance. + /// + PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[] attributes) + { + PropertyDescriptorCollection descriptors = new PropertyDescriptorCollection(null); + + foreach (KeyValuePair propertyValue in this) + { + descriptors.Add(new JPropertyDescriptor(propertyValue.Key)); + } + + return descriptors; + } + + /// + /// Returns a collection of custom attributes for this instance of a component. + /// + /// + /// An containing the attributes for this object. + /// + AttributeCollection ICustomTypeDescriptor.GetAttributes() + { + return AttributeCollection.Empty; + } + + /// + /// Returns the class name of this instance of a component. + /// + /// + /// The class name of the object, or null if the class does not have a name. + /// + string ICustomTypeDescriptor.GetClassName() + { + return null; + } + + /// + /// Returns the name of this instance of a component. + /// + /// + /// The name of the object, or null if the object does not have a name. + /// + string ICustomTypeDescriptor.GetComponentName() + { + return null; + } + + /// + /// Returns a type converter for this instance of a component. + /// + /// + /// A that is the converter for this object, or null if there is no for this object. + /// + TypeConverter ICustomTypeDescriptor.GetConverter() + { + return new TypeConverter(); + } + + /// + /// Returns the default event for this instance of a component. + /// + /// + /// An that represents the default event for this object, or null if this object does not have events. + /// + EventDescriptor ICustomTypeDescriptor.GetDefaultEvent() + { + return null; + } + + /// + /// Returns the default property for this instance of a component. + /// + /// + /// A that represents the default property for this object, or null if this object does not have properties. + /// + PropertyDescriptor ICustomTypeDescriptor.GetDefaultProperty() + { + return null; + } + + /// + /// Returns an editor of the specified type for this instance of a component. + /// + /// A that represents the editor for this object. + /// + /// An of the specified type that is the editor for this object, or null if the editor cannot be found. + /// + object ICustomTypeDescriptor.GetEditor(Type editorBaseType) + { + return null; + } + + /// + /// Returns the events for this instance of a component using the specified attribute array as a filter. + /// + /// An array of type that is used as a filter. + /// + /// An that represents the filtered events for this component instance. + /// + EventDescriptorCollection ICustomTypeDescriptor.GetEvents(Attribute[] attributes) + { + return EventDescriptorCollection.Empty; + } + + /// + /// Returns the events for this instance of a component. + /// + /// + /// An that represents the events for this component instance. + /// + EventDescriptorCollection ICustomTypeDescriptor.GetEvents() + { + return EventDescriptorCollection.Empty; + } + + /// + /// Returns an object that contains the property described by the specified property descriptor. + /// + /// A that represents the property whose owner is to be found. + /// + /// An that represents the owner of the specified property. + /// + object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd) + { + return null; + } + #endregion + +#endif + +#if !(NET35 || NET20 || PORTABLE40) + /// + /// Returns the responsible for binding operations performed on this object. + /// + /// The expression tree representation of the runtime value. + /// + /// The to bind this object. + /// + protected override DynamicMetaObject GetMetaObject(Expression parameter) + { + return new DynamicProxyMetaObject(parameter, this, new JObjectDynamicProxy(), true); + } + + private class JObjectDynamicProxy : DynamicProxy + { + public override bool TryGetMember(JObject instance, GetMemberBinder binder, out object result) + { + // result can be null + result = instance[binder.Name]; + return true; + } + + public override bool TrySetMember(JObject instance, SetMemberBinder binder, object value) + { + JToken v = value as JToken; + + // this can throw an error if value isn't a valid for a JValue + if (v == null) + { + v = new JValue(value); + } + + instance[binder.Name] = v; + return true; + } + + public override IEnumerable GetDynamicMemberNames(JObject instance) + { + return instance.Properties().Select(p => p.Name); + } + } +#endif + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Linq/JProperty.cs b/Common/00-1Json8.3/Json8.3/Linq/JProperty.cs new file mode 100644 index 0000000..a1049cf --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Linq/JProperty.cs @@ -0,0 +1,400 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Collections; +using System.Collections.Generic; +using Newtonsoft.Json.Utilities; +using System.Diagnostics; +using System.Globalization; + +namespace Newtonsoft.Json.Linq +{ + /// + /// Represents a JSON property. + /// + public class JProperty : JContainer + { + #region JPropertyList + private class JPropertyList : IList + { + internal JToken _token; + + public IEnumerator GetEnumerator() + { + if (_token != null) + { + yield return _token; + } + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + public void Add(JToken item) + { + _token = item; + } + + public void Clear() + { + _token = null; + } + + public bool Contains(JToken item) + { + return (_token == item); + } + + public void CopyTo(JToken[] array, int arrayIndex) + { + if (_token != null) + { + array[arrayIndex] = _token; + } + } + + public bool Remove(JToken item) + { + if (_token == item) + { + _token = null; + return true; + } + return false; + } + + public int Count + { + get { return (_token != null) ? 1 : 0; } + } + + public bool IsReadOnly + { + get { return false; } + } + + public int IndexOf(JToken item) + { + return (_token == item) ? 0 : -1; + } + + public void Insert(int index, JToken item) + { + if (index == 0) + { + _token = item; + } + } + + public void RemoveAt(int index) + { + if (index == 0) + { + _token = null; + } + } + + public JToken this[int index] + { + get { return (index == 0) ? _token : null; } + set + { + if (index == 0) + { + _token = value; + } + } + } + } + #endregion + + private readonly JPropertyList _content = new JPropertyList(); + private readonly string _name; + + /// + /// Gets the container's children tokens. + /// + /// The container's children tokens. + protected override IList ChildrenTokens + { + get { return _content; } + } + + /// + /// Gets the property name. + /// + /// The property name. + public string Name + { + [DebuggerStepThrough] + get { return _name; } + } + + /// + /// Gets or sets the property value. + /// + /// The property value. + public JToken Value + { + [DebuggerStepThrough] + get { return _content._token; } + set + { + CheckReentrancy(); + + JToken newValue = value ?? JValue.CreateNull(); + + if (_content._token == null) + { + InsertItem(0, newValue, false); + } + else + { + SetItem(0, newValue); + } + } + } + + /// + /// Initializes a new instance of the class from another object. + /// + /// A object to copy from. + public JProperty(JProperty other) + : base(other) + { + _name = other.Name; + } + + internal override JToken GetItem(int index) + { + if (index != 0) + { + throw new ArgumentOutOfRangeException(); + } + + return Value; + } + + internal override void SetItem(int index, JToken item) + { + if (index != 0) + { + throw new ArgumentOutOfRangeException(); + } + + if (IsTokenUnchanged(Value, item)) + { + return; + } + + if (Parent != null) + { + ((JObject)Parent).InternalPropertyChanging(this); + } + + base.SetItem(0, item); + + if (Parent != null) + { + ((JObject)Parent).InternalPropertyChanged(this); + } + } + + internal override bool RemoveItem(JToken item) + { + throw new JsonException("Cannot add or remove items from {0}.".FormatWith(CultureInfo.InvariantCulture, typeof(JProperty))); + } + + internal override void RemoveItemAt(int index) + { + throw new JsonException("Cannot add or remove items from {0}.".FormatWith(CultureInfo.InvariantCulture, typeof(JProperty))); + } + + internal override void InsertItem(int index, JToken item, bool skipParentCheck) + { + // don't add comments to JProperty + if (item != null && item.Type == JTokenType.Comment) + { + return; + } + + if (Value != null) + { + throw new JsonException("{0} cannot have multiple values.".FormatWith(CultureInfo.InvariantCulture, typeof(JProperty))); + } + + base.InsertItem(0, item, false); + } + + internal override bool ContainsItem(JToken item) + { + return (Value == item); + } + + internal override void MergeItem(object content, JsonMergeSettings settings) + { + JProperty p = content as JProperty; + if (p == null) + { + return; + } + + if (p.Value != null && p.Value.Type != JTokenType.Null) + { + Value = p.Value; + } + } + + internal override void ClearItems() + { + throw new JsonException("Cannot add or remove items from {0}.".FormatWith(CultureInfo.InvariantCulture, typeof(JProperty))); + } + + internal override bool DeepEquals(JToken node) + { + JProperty t = node as JProperty; + return (t != null && _name == t.Name && ContentsEqual(t)); + } + + internal override JToken CloneToken() + { + return new JProperty(this); + } + + /// + /// Gets the node type for this . + /// + /// The type. + public override JTokenType Type + { + [DebuggerStepThrough] + get { return JTokenType.Property; } + } + + internal JProperty(string name) + { + // called from JTokenWriter + ValidationUtils.ArgumentNotNull(name, nameof(name)); + + _name = name; + } + + /// + /// Initializes a new instance of the class. + /// + /// The property name. + /// The property content. + public JProperty(string name, params object[] content) + : this(name, (object)content) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The property name. + /// The property content. + public JProperty(string name, object content) + { + ValidationUtils.ArgumentNotNull(name, nameof(name)); + + _name = name; + + Value = IsMultiContent(content) + ? new JArray(content) + : CreateFromContent(content); + } + + /// + /// Writes this token to a . + /// + /// A into which this method will write. + /// A collection of which will be used when writing the token. + public override void WriteTo(JsonWriter writer, params JsonConverter[] converters) + { + writer.WritePropertyName(_name); + + JToken value = Value; + if (value != null) + { + value.WriteTo(writer, converters); + } + else + { + writer.WriteNull(); + } + } + + internal override int GetDeepHashCode() + { + return _name.GetHashCode() ^ ((Value != null) ? Value.GetDeepHashCode() : 0); + } + + /// + /// Loads an from a . + /// + /// A that will be read for the content of the . + /// A that contains the JSON that was read from the specified . + public new static JProperty Load(JsonReader reader) + { + return Load(reader, null); + } + + /// + /// Loads an from a . + /// + /// A that will be read for the content of the . + /// The used to load the JSON. + /// If this is null, default load settings will be used. + /// A that contains the JSON that was read from the specified . + public new static JProperty Load(JsonReader reader, JsonLoadSettings settings) + { + if (reader.TokenType == JsonToken.None) + { + if (!reader.Read()) + { + throw JsonReaderException.Create(reader, "Error reading JProperty from JsonReader."); + } + } + + reader.MoveToContent(); + + if (reader.TokenType != JsonToken.PropertyName) + { + throw JsonReaderException.Create(reader, "Error reading JProperty from JsonReader. Current JsonReader item is not a property: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); + } + + JProperty p = new JProperty((string)reader.Value); + p.SetLineInfo(reader as IJsonLineInfo, settings); + + p.ReadTokenFrom(reader, settings); + + return p; + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Linq/JPropertyDescriptor.cs b/Common/00-1Json8.3/Json8.3/Linq/JPropertyDescriptor.cs new file mode 100644 index 0000000..00eb857 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Linq/JPropertyDescriptor.cs @@ -0,0 +1,166 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +#if !(DOTNET || PORTABLE || PORTABLE40) +using System; +using System.ComponentModel; + +namespace Newtonsoft.Json.Linq +{ + /// + /// Represents a view of a . + /// + public class JPropertyDescriptor : PropertyDescriptor + { + /// + /// Initializes a new instance of the class. + /// + /// The name. + public JPropertyDescriptor(string name) + : base(name, null) + { + } + + private static JObject CastInstance(object instance) + { + return (JObject)instance; + } + + /// + /// When overridden in a derived class, returns whether resetting an object changes its value. + /// + /// + /// true if resetting the component changes its value; otherwise, false. + /// + /// The component to test for reset capability. + /// + public override bool CanResetValue(object component) + { + return false; + } + + /// + /// When overridden in a derived class, gets the current value of the property on a component. + /// + /// + /// The value of a property for a given component. + /// + /// The component with the property for which to retrieve the value. + /// + public override object GetValue(object component) + { + JToken token = CastInstance(component)[Name]; + + return token; + } + + /// + /// When overridden in a derived class, resets the value for this property of the component to the default value. + /// + /// The component with the property value that is to be reset to the default value. + /// + public override void ResetValue(object component) + { + } + + /// + /// When overridden in a derived class, sets the value of the component to a different value. + /// + /// The component with the property value that is to be set. + /// The new value. + /// + public override void SetValue(object component, object value) + { + JToken token = (value is JToken) ? (JToken)value : new JValue(value); + + CastInstance(component)[Name] = token; + } + + /// + /// When overridden in a derived class, determines a value indicating whether the value of this property needs to be persisted. + /// + /// + /// true if the property should be persisted; otherwise, false. + /// + /// The component with the property to be examined for persistence. + /// + public override bool ShouldSerializeValue(object component) + { + return false; + } + + /// + /// When overridden in a derived class, gets the type of the component this property is bound to. + /// + /// + /// A that represents the type of component this property is bound to. When the or methods are invoked, the object specified might be an instance of this type. + /// + public override Type ComponentType + { + get { return typeof(JObject); } + } + + /// + /// When overridden in a derived class, gets a value indicating whether this property is read-only. + /// + /// + /// true if the property is read-only; otherwise, false. + /// + public override bool IsReadOnly + { + get { return false; } + } + + /// + /// When overridden in a derived class, gets the type of the property. + /// + /// + /// A that represents the type of the property. + /// + public override Type PropertyType + { + get { return typeof(object); } + } + + /// + /// Gets the hash code for the name of the member. + /// + /// + /// + /// The hash code for the name of the member. + /// + protected override int NameHashCode + { + get + { + // override property to fix up an error in its documentation + int nameHashCode = base.NameHashCode; + return nameHashCode; + } + } + } +} + +#endif \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Linq/JPropertyKeyedCollection.cs b/Common/00-1Json8.3/Json8.3/Linq/JPropertyKeyedCollection.cs new file mode 100644 index 0000000..867d741 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Linq/JPropertyKeyedCollection.cs @@ -0,0 +1,280 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; + +namespace Newtonsoft.Json.Linq +{ + internal class JPropertyKeyedCollection : Collection + { + private static readonly IEqualityComparer Comparer = StringComparer.Ordinal; + + private Dictionary _dictionary; + + private void AddKey(string key, JToken item) + { + EnsureDictionary(); + _dictionary[key] = item; + } + + protected void ChangeItemKey(JToken item, string newKey) + { + if (!ContainsItem(item)) + { + throw new ArgumentException("The specified item does not exist in this KeyedCollection."); + } + + string keyForItem = GetKeyForItem(item); + if (!Comparer.Equals(keyForItem, newKey)) + { + if (newKey != null) + { + AddKey(newKey, item); + } + + if (keyForItem != null) + { + RemoveKey(keyForItem); + } + } + } + + protected override void ClearItems() + { + base.ClearItems(); + + if (_dictionary != null) + { + _dictionary.Clear(); + } + } + + public bool Contains(string key) + { + if (key == null) + { + throw new ArgumentNullException(nameof(key)); + } + + if (_dictionary != null) + { + return _dictionary.ContainsKey(key); + } + + return false; + } + + private bool ContainsItem(JToken item) + { + if (_dictionary == null) + { + return false; + } + + string key = GetKeyForItem(item); + JToken value; + return _dictionary.TryGetValue(key, out value); + } + + private void EnsureDictionary() + { + if (_dictionary == null) + { + _dictionary = new Dictionary(Comparer); + } + } + + private string GetKeyForItem(JToken item) + { + return ((JProperty)item).Name; + } + + protected override void InsertItem(int index, JToken item) + { + AddKey(GetKeyForItem(item), item); + base.InsertItem(index, item); + } + + public bool Remove(string key) + { + if (key == null) + { + throw new ArgumentNullException(nameof(key)); + } + + if (_dictionary != null) + { + return _dictionary.ContainsKey(key) && Remove(_dictionary[key]); + } + + return false; + } + + protected override void RemoveItem(int index) + { + string keyForItem = GetKeyForItem(Items[index]); + RemoveKey(keyForItem); + base.RemoveItem(index); + } + + private void RemoveKey(string key) + { + if (_dictionary != null) + { + _dictionary.Remove(key); + } + } + + protected override void SetItem(int index, JToken item) + { + string keyForItem = GetKeyForItem(item); + string keyAtIndex = GetKeyForItem(Items[index]); + + if (Comparer.Equals(keyAtIndex, keyForItem)) + { + if (_dictionary != null) + { + _dictionary[keyForItem] = item; + } + } + else + { + AddKey(keyForItem, item); + + if (keyAtIndex != null) + { + RemoveKey(keyAtIndex); + } + } + base.SetItem(index, item); + } + + public JToken this[string key] + { + get + { + if (key == null) + { + throw new ArgumentNullException(nameof(key)); + } + + if (_dictionary != null) + { + return _dictionary[key]; + } + + throw new KeyNotFoundException(); + } + } + + public bool TryGetValue(string key, out JToken value) + { + if (_dictionary == null) + { + value = null; + return false; + } + + return _dictionary.TryGetValue(key, out value); + } + + public ICollection Keys + { + get + { + EnsureDictionary(); + return _dictionary.Keys; + } + } + + public ICollection Values + { + get + { + EnsureDictionary(); + return _dictionary.Values; + } + } + + public bool Compare(JPropertyKeyedCollection other) + { + if (this == other) + { + return true; + } + + // dictionaries in JavaScript aren't ordered + // ignore order when comparing properties + Dictionary d1 = _dictionary; + Dictionary d2 = other._dictionary; + + if (d1 == null && d2 == null) + { + return true; + } + + if (d1 == null) + { + return (d2.Count == 0); + } + + if (d2 == null) + { + return (d1.Count == 0); + } + + if (d1.Count != d2.Count) + { + return false; + } + + foreach (KeyValuePair keyAndProperty in d1) + { + JToken secondValue; + if (!d2.TryGetValue(keyAndProperty.Key, out secondValue)) + { + return false; + } + + JProperty p1 = (JProperty)keyAndProperty.Value; + JProperty p2 = (JProperty)secondValue; + + if (p1.Value == null) + { + return (p2.Value == null); + } + + if (!p1.Value.DeepEquals(p2.Value)) + { + return false; + } + } + + return true; + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Linq/JRaw.cs b/Common/00-1Json8.3/Json8.3/Linq/JRaw.cs new file mode 100644 index 0000000..fec5a57 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Linq/JRaw.cs @@ -0,0 +1,75 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System.Globalization; +using System.IO; + +namespace Newtonsoft.Json.Linq +{ + /// + /// Represents a raw JSON string. + /// + public class JRaw : JValue + { + /// + /// Initializes a new instance of the class from another object. + /// + /// A object to copy from. + public JRaw(JRaw other) + : base(other) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The raw json. + public JRaw(object rawJson) + : base(rawJson, JTokenType.Raw) + { + } + + /// + /// Creates an instance of with the content of the reader's current token. + /// + /// The reader. + /// An instance of with the content of the reader's current token. + public static JRaw Create(JsonReader reader) + { + using (StringWriter sw = new StringWriter(CultureInfo.InvariantCulture)) + using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) + { + jsonWriter.WriteToken(reader); + + return new JRaw(sw.ToString()); + } + } + + internal override JToken CloneToken() + { + return new JRaw(this); + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Linq/JToken.cs b/Common/00-1Json8.3/Json8.3/Linq/JToken.cs new file mode 100644 index 0000000..7a16284 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Linq/JToken.cs @@ -0,0 +1,2704 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Collections.Generic; +using Newtonsoft.Json.Linq.JsonPath; +#if !(NET35 || NET20 || PORTABLE40) +using System.Dynamic; +using System.Linq.Expressions; +#endif +using System.IO; +#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) +using System.Numerics; +#endif +using System.Text; +using Newtonsoft.Json.Utilities; +using System.Diagnostics; +using System.Globalization; +using System.Collections; +#if NET20 +using Newtonsoft.Json.Utilities.LinqBridge; +#else +using System.Linq; + +#endif + +namespace Newtonsoft.Json.Linq +{ + /// + /// Represents an abstract JSON token. + /// + public abstract class JToken : IJEnumerable, IJsonLineInfo +#if !(DOTNET || PORTABLE40 || PORTABLE) + , ICloneable +#endif +#if !(NET35 || NET20 || PORTABLE40) + , IDynamicMetaObjectProvider +#endif + { + private static JTokenEqualityComparer _equalityComparer; + + private JContainer _parent; + private JToken _previous; + private JToken _next; + private object _annotations; + + private static readonly JTokenType[] BooleanTypes = new[] { JTokenType.Integer, JTokenType.Float, JTokenType.String, JTokenType.Comment, JTokenType.Raw, JTokenType.Boolean }; + private static readonly JTokenType[] NumberTypes = new[] { JTokenType.Integer, JTokenType.Float, JTokenType.String, JTokenType.Comment, JTokenType.Raw, JTokenType.Boolean }; +#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) + private static readonly JTokenType[] BigIntegerTypes = new[] { JTokenType.Integer, JTokenType.Float, JTokenType.String, JTokenType.Comment, JTokenType.Raw, JTokenType.Boolean, JTokenType.Bytes }; +#endif + private static readonly JTokenType[] StringTypes = new[] { JTokenType.Date, JTokenType.Integer, JTokenType.Float, JTokenType.String, JTokenType.Comment, JTokenType.Raw, JTokenType.Boolean, JTokenType.Bytes, JTokenType.Guid, JTokenType.TimeSpan, JTokenType.Uri }; + private static readonly JTokenType[] GuidTypes = new[] { JTokenType.String, JTokenType.Comment, JTokenType.Raw, JTokenType.Guid, JTokenType.Bytes }; + private static readonly JTokenType[] TimeSpanTypes = new[] { JTokenType.String, JTokenType.Comment, JTokenType.Raw, JTokenType.TimeSpan }; + private static readonly JTokenType[] UriTypes = new[] { JTokenType.String, JTokenType.Comment, JTokenType.Raw, JTokenType.Uri }; + private static readonly JTokenType[] CharTypes = new[] { JTokenType.Integer, JTokenType.Float, JTokenType.String, JTokenType.Comment, JTokenType.Raw }; + private static readonly JTokenType[] DateTimeTypes = new[] { JTokenType.Date, JTokenType.String, JTokenType.Comment, JTokenType.Raw }; + private static readonly JTokenType[] BytesTypes = new[] { JTokenType.Bytes, JTokenType.String, JTokenType.Comment, JTokenType.Raw, JTokenType.Integer }; + + /// + /// Gets a comparer that can compare two tokens for value equality. + /// + /// A that can compare two nodes for value equality. + public static JTokenEqualityComparer EqualityComparer + { + get + { + if (_equalityComparer == null) + { + _equalityComparer = new JTokenEqualityComparer(); + } + + return _equalityComparer; + } + } + + /// + /// Gets or sets the parent. + /// + /// The parent. + public JContainer Parent + { + [DebuggerStepThrough] + get { return _parent; } + internal set { _parent = value; } + } + + /// + /// Gets the root of this . + /// + /// The root of this . + public JToken Root + { + get + { + JContainer parent = Parent; + if (parent == null) + { + return this; + } + + while (parent.Parent != null) + { + parent = parent.Parent; + } + + return parent; + } + } + + internal abstract JToken CloneToken(); + internal abstract bool DeepEquals(JToken node); + + /// + /// Gets the node type for this . + /// + /// The type. + public abstract JTokenType Type { get; } + + /// + /// Gets a value indicating whether this token has child tokens. + /// + /// + /// true if this token has child values; otherwise, false. + /// + public abstract bool HasValues { get; } + + /// + /// Compares the values of two tokens, including the values of all descendant tokens. + /// + /// The first to compare. + /// The second to compare. + /// true if the tokens are equal; otherwise false. + public static bool DeepEquals(JToken t1, JToken t2) + { + return (t1 == t2 || (t1 != null && t2 != null && t1.DeepEquals(t2))); + } + + /// + /// Gets the next sibling token of this node. + /// + /// The that contains the next sibling token. + public JToken Next + { + get { return _next; } + internal set { _next = value; } + } + + /// + /// Gets the previous sibling token of this node. + /// + /// The that contains the previous sibling token. + public JToken Previous + { + get { return _previous; } + internal set { _previous = value; } + } + + /// + /// Gets the path of the JSON token. + /// + public string Path + { + get + { + if (Parent == null) + { + return string.Empty; + } + + IList ancestors = AncestorsAndSelf().Reverse().ToList(); + + List positions = new List(); + for (int i = 0; i < ancestors.Count; i++) + { + JToken current = ancestors[i]; + JToken next = null; + if (i + 1 < ancestors.Count) + { + next = ancestors[i + 1]; + } + else if (ancestors[i].Type == JTokenType.Property) + { + next = ancestors[i]; + } + + if (next != null) + { + switch (current.Type) + { + case JTokenType.Property: + JProperty property = (JProperty)current; + positions.Add(new JsonPosition(JsonContainerType.Object) { PropertyName = property.Name }); + break; + case JTokenType.Array: + case JTokenType.Constructor: + int index = ((IList)current).IndexOf(next); + + positions.Add(new JsonPosition(JsonContainerType.Array) { Position = index }); + break; + } + } + } + + return JsonPosition.BuildPath(positions, null); + } + } + + internal JToken() + { + } + + /// + /// Adds the specified content immediately after this token. + /// + /// A content object that contains simple content or a collection of content objects to be added after this token. + public void AddAfterSelf(object content) + { + if (_parent == null) + { + throw new InvalidOperationException("The parent is missing."); + } + + int index = _parent.IndexOfItem(this); + _parent.AddInternal(index + 1, content, false); + } + + /// + /// Adds the specified content immediately before this token. + /// + /// A content object that contains simple content or a collection of content objects to be added before this token. + public void AddBeforeSelf(object content) + { + if (_parent == null) + { + throw new InvalidOperationException("The parent is missing."); + } + + int index = _parent.IndexOfItem(this); + _parent.AddInternal(index, content, false); + } + + /// + /// Returns a collection of the ancestor tokens of this token. + /// + /// A collection of the ancestor tokens of this token. + public IEnumerable Ancestors() + { + return GetAncestors(false); + } + + /// + /// Returns a collection of tokens that contain this token, and the ancestors of this token. + /// + /// A collection of tokens that contain this token, and the ancestors of this token. + public IEnumerable AncestorsAndSelf() + { + return GetAncestors(true); + } + + internal IEnumerable GetAncestors(bool self) + { + for (JToken current = self ? this : Parent; current != null; current = current.Parent) + { + yield return current; + } + } + + /// + /// Returns a collection of the sibling tokens after this token, in document order. + /// + /// A collection of the sibling tokens after this tokens, in document order. + public IEnumerable AfterSelf() + { + if (Parent == null) + { + yield break; + } + + for (JToken o = Next; o != null; o = o.Next) + { + yield return o; + } + } + + /// + /// Returns a collection of the sibling tokens before this token, in document order. + /// + /// A collection of the sibling tokens before this token, in document order. + public IEnumerable BeforeSelf() + { + for (JToken o = Parent.First; o != this; o = o.Next) + { + yield return o; + } + } + + /// + /// Gets the with the specified key. + /// + /// The with the specified key. + public virtual JToken this[object key] + { + get { throw new InvalidOperationException("Cannot access child value on {0}.".FormatWith(CultureInfo.InvariantCulture, GetType())); } + set { throw new InvalidOperationException("Cannot set child value on {0}.".FormatWith(CultureInfo.InvariantCulture, GetType())); } + } + + /// + /// Gets the with the specified key converted to the specified type. + /// + /// The type to convert the token to. + /// The token key. + /// The converted token value. + public virtual T Value(object key) + { + JToken token = this[key]; + + // null check to fix MonoTouch issue - https://github.com/dolbz/Newtonsoft.Json/commit/a24e3062846b30ee505f3271ac08862bb471b822 + return token == null ? default(T) : Extensions.Convert(token); + } + + /// + /// Get the first child token of this token. + /// + /// A containing the first child token of the . + public virtual JToken First + { + get { throw new InvalidOperationException("Cannot access child value on {0}.".FormatWith(CultureInfo.InvariantCulture, GetType())); } + } + + /// + /// Get the last child token of this token. + /// + /// A containing the last child token of the . + public virtual JToken Last + { + get { throw new InvalidOperationException("Cannot access child value on {0}.".FormatWith(CultureInfo.InvariantCulture, GetType())); } + } + + /// + /// Returns a collection of the child tokens of this token, in document order. + /// + /// An of containing the child tokens of this , in document order. + public virtual JEnumerable Children() + { + return JEnumerable.Empty; + } + + /// + /// Returns a collection of the child tokens of this token, in document order, filtered by the specified type. + /// + /// The type to filter the child tokens on. + /// A containing the child tokens of this , in document order. + public JEnumerable Children() where T : JToken + { + return new JEnumerable(Children().OfType()); + } + + /// + /// Returns a collection of the child values of this token, in document order. + /// + /// The type to convert the values to. + /// A containing the child values of this , in document order. + public virtual IEnumerable Values() + { + throw new InvalidOperationException("Cannot access child value on {0}.".FormatWith(CultureInfo.InvariantCulture, GetType())); + } + + /// + /// Removes this token from its parent. + /// + public void Remove() + { + if (_parent == null) + { + throw new InvalidOperationException("The parent is missing."); + } + + _parent.RemoveItem(this); + } + + /// + /// Replaces this token with the specified token. + /// + /// The value. + public void Replace(JToken value) + { + if (_parent == null) + { + throw new InvalidOperationException("The parent is missing."); + } + + _parent.ReplaceItem(this, value); + } + + /// + /// Writes this token to a . + /// + /// A into which this method will write. + /// A collection of which will be used when writing the token. + public abstract void WriteTo(JsonWriter writer, params JsonConverter[] converters); + + /// + /// Returns the indented JSON for this token. + /// + /// + /// The indented JSON for this token. + /// + public override string ToString() + { + return ToString(Formatting.Indented); + } + + /// + /// Returns the JSON for this token using the given formatting and converters. + /// + /// Indicates how the output is formatted. + /// A collection of which will be used when writing the token. + /// The JSON for this token using the given formatting and converters. + public string ToString(Formatting formatting, params JsonConverter[] converters) + { + using (StringWriter sw = new StringWriter(CultureInfo.InvariantCulture)) + { + JsonTextWriter jw = new JsonTextWriter(sw); + jw.Formatting = formatting; + + WriteTo(jw, converters); + + return sw.ToString(); + } + } + + private static JValue EnsureValue(JToken value) + { + if (value == null) + { + throw new ArgumentNullException(nameof(value)); + } + + if (value is JProperty) + { + value = ((JProperty)value).Value; + } + + JValue v = value as JValue; + + return v; + } + + private static string GetType(JToken token) + { + ValidationUtils.ArgumentNotNull(token, nameof(token)); + + if (token is JProperty) + { + token = ((JProperty)token).Value; + } + + return token.Type.ToString(); + } + + private static bool ValidateToken(JToken o, JTokenType[] validTypes, bool nullable) + { + return (Array.IndexOf(validTypes, o.Type) != -1) || (nullable && (o.Type == JTokenType.Null || o.Type == JTokenType.Undefined)); + } + + #region Cast from operators + /// + /// Performs an explicit conversion from to . + /// + /// The value. + /// The result of the conversion. + public static explicit operator bool(JToken value) + { + JValue v = EnsureValue(value); + if (v == null || !ValidateToken(v, BooleanTypes, false)) + { + throw new ArgumentException("Can not convert {0} to Boolean.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } + +#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) + if (v.Value is BigInteger) + { + return Convert.ToBoolean((int)(BigInteger)v.Value); + } +#endif + + return Convert.ToBoolean(v.Value, CultureInfo.InvariantCulture); + } + +#if !NET20 + /// + /// Performs an explicit conversion from to . + /// + /// The value. + /// The result of the conversion. + public static explicit operator DateTimeOffset(JToken value) + { + JValue v = EnsureValue(value); + if (v == null || !ValidateToken(v, DateTimeTypes, false)) + { + throw new ArgumentException("Can not convert {0} to DateTimeOffset.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } + + if (v.Value is DateTimeOffset) + { + return (DateTimeOffset)v.Value; + } + if (v.Value is string) + { + return DateTimeOffset.Parse((string)v.Value, CultureInfo.InvariantCulture); + } + return new DateTimeOffset(Convert.ToDateTime(v.Value, CultureInfo.InvariantCulture)); + } +#endif + + /// + /// Performs an explicit conversion from to . + /// + /// The value. + /// The result of the conversion. + public static explicit operator bool?(JToken value) + { + if (value == null) + { + return null; + } + + JValue v = EnsureValue(value); + if (v == null || !ValidateToken(v, BooleanTypes, true)) + { + throw new ArgumentException("Can not convert {0} to Boolean.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } + +#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) + if (v.Value is BigInteger) + { + return Convert.ToBoolean((int)(BigInteger)v.Value); + } +#endif + + return (v.Value != null) ? (bool?)Convert.ToBoolean(v.Value, CultureInfo.InvariantCulture) : null; + } + + /// + /// Performs an explicit conversion from to . + /// + /// The value. + /// The result of the conversion. + public static explicit operator long(JToken value) + { + JValue v = EnsureValue(value); + if (v == null || !ValidateToken(v, NumberTypes, false)) + { + throw new ArgumentException("Can not convert {0} to Int64.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } + +#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) + if (v.Value is BigInteger) + { + return (long)(BigInteger)v.Value; + } +#endif + + return Convert.ToInt64(v.Value, CultureInfo.InvariantCulture); + } + + /// + /// Performs an explicit conversion from to . + /// + /// The value. + /// The result of the conversion. + public static explicit operator DateTime?(JToken value) + { + if (value == null) + { + return null; + } + + JValue v = EnsureValue(value); + if (v == null || !ValidateToken(v, DateTimeTypes, true)) + { + throw new ArgumentException("Can not convert {0} to DateTime.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } + +#if !NET20 + if (v.Value is DateTimeOffset) + { + return ((DateTimeOffset)v.Value).DateTime; + } +#endif + + return (v.Value != null) ? (DateTime?)Convert.ToDateTime(v.Value, CultureInfo.InvariantCulture) : null; + } + +#if !NET20 + /// + /// Performs an explicit conversion from to . + /// + /// The value. + /// The result of the conversion. + public static explicit operator DateTimeOffset?(JToken value) + { + if (value == null) + { + return null; + } + + JValue v = EnsureValue(value); + if (v == null || !ValidateToken(v, DateTimeTypes, true)) + { + throw new ArgumentException("Can not convert {0} to DateTimeOffset.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } + + if (v.Value == null) + { + return null; + } + if (v.Value is DateTimeOffset) + { + return (DateTimeOffset?)v.Value; + } + if (v.Value is string) + { + return DateTimeOffset.Parse((string)v.Value, CultureInfo.InvariantCulture); + } + return new DateTimeOffset(Convert.ToDateTime(v.Value, CultureInfo.InvariantCulture)); + } +#endif + + /// + /// Performs an explicit conversion from to . + /// + /// The value. + /// The result of the conversion. + public static explicit operator decimal?(JToken value) + { + if (value == null) + { + return null; + } + + JValue v = EnsureValue(value); + if (v == null || !ValidateToken(v, NumberTypes, true)) + { + throw new ArgumentException("Can not convert {0} to Decimal.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } + +#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) + if (v.Value is BigInteger) + { + return (decimal?)(BigInteger)v.Value; + } +#endif + + return (v.Value != null) ? (decimal?)Convert.ToDecimal(v.Value, CultureInfo.InvariantCulture) : null; + } + + /// + /// Performs an explicit conversion from to . + /// + /// The value. + /// The result of the conversion. + public static explicit operator double?(JToken value) + { + if (value == null) + { + return null; + } + + JValue v = EnsureValue(value); + if (v == null || !ValidateToken(v, NumberTypes, true)) + { + throw new ArgumentException("Can not convert {0} to Double.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } + +#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) + if (v.Value is BigInteger) + { + return (double?)(BigInteger)v.Value; + } +#endif + + return (v.Value != null) ? (double?)Convert.ToDouble(v.Value, CultureInfo.InvariantCulture) : null; + } + + /// + /// Performs an explicit conversion from to . + /// + /// The value. + /// The result of the conversion. + public static explicit operator char?(JToken value) + { + if (value == null) + { + return null; + } + + JValue v = EnsureValue(value); + if (v == null || !ValidateToken(v, CharTypes, true)) + { + throw new ArgumentException("Can not convert {0} to Char.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } + +#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) + if (v.Value is BigInteger) + { + return (char?)(BigInteger)v.Value; + } +#endif + + return (v.Value != null) ? (char?)Convert.ToChar(v.Value, CultureInfo.InvariantCulture) : null; + } + + /// + /// Performs an explicit conversion from to . + /// + /// The value. + /// The result of the conversion. + public static explicit operator int(JToken value) + { + JValue v = EnsureValue(value); + if (v == null || !ValidateToken(v, NumberTypes, false)) + { + throw new ArgumentException("Can not convert {0} to Int32.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } + +#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) + if (v.Value is BigInteger) + { + return (int)(BigInteger)v.Value; + } +#endif + + return Convert.ToInt32(v.Value, CultureInfo.InvariantCulture); + } + + /// + /// Performs an explicit conversion from to . + /// + /// The value. + /// The result of the conversion. + public static explicit operator short(JToken value) + { + JValue v = EnsureValue(value); + if (v == null || !ValidateToken(v, NumberTypes, false)) + { + throw new ArgumentException("Can not convert {0} to Int16.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } + +#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) + if (v.Value is BigInteger) + { + return (short)(BigInteger)v.Value; + } +#endif + + return Convert.ToInt16(v.Value, CultureInfo.InvariantCulture); + } + + /// + /// Performs an explicit conversion from to . + /// + /// The value. + /// The result of the conversion. + [CLSCompliant(false)] + public static explicit operator ushort(JToken value) + { + JValue v = EnsureValue(value); + if (v == null || !ValidateToken(v, NumberTypes, false)) + { + throw new ArgumentException("Can not convert {0} to UInt16.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } + +#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) + if (v.Value is BigInteger) + { + return (ushort)(BigInteger)v.Value; + } +#endif + + return Convert.ToUInt16(v.Value, CultureInfo.InvariantCulture); + } + + /// + /// Performs an explicit conversion from to . + /// + /// The value. + /// The result of the conversion. + [CLSCompliant(false)] + public static explicit operator char(JToken value) + { + JValue v = EnsureValue(value); + if (v == null || !ValidateToken(v, CharTypes, false)) + { + throw new ArgumentException("Can not convert {0} to Char.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } + +#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) + if (v.Value is BigInteger) + { + return (char)(BigInteger)v.Value; + } +#endif + + return Convert.ToChar(v.Value, CultureInfo.InvariantCulture); + } + + /// + /// Performs an explicit conversion from to . + /// + /// The value. + /// The result of the conversion. + public static explicit operator byte(JToken value) + { + JValue v = EnsureValue(value); + if (v == null || !ValidateToken(v, NumberTypes, false)) + { + throw new ArgumentException("Can not convert {0} to Byte.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } + +#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) + if (v.Value is BigInteger) + { + return (byte)(BigInteger)v.Value; + } +#endif + + return Convert.ToByte(v.Value, CultureInfo.InvariantCulture); + } + + /// + /// Performs an explicit conversion from to . + /// + /// The value. + /// The result of the conversion. + [CLSCompliant(false)] + public static explicit operator sbyte(JToken value) + { + JValue v = EnsureValue(value); + if (v == null || !ValidateToken(v, NumberTypes, false)) + { + throw new ArgumentException("Can not convert {0} to SByte.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } + +#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) + if (v.Value is BigInteger) + { + return (sbyte)(BigInteger)v.Value; + } +#endif + + return Convert.ToSByte(v.Value, CultureInfo.InvariantCulture); + } + + /// + /// Performs an explicit conversion from to . + /// + /// The value. + /// The result of the conversion. + public static explicit operator int?(JToken value) + { + if (value == null) + { + return null; + } + + JValue v = EnsureValue(value); + if (v == null || !ValidateToken(v, NumberTypes, true)) + { + throw new ArgumentException("Can not convert {0} to Int32.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } + +#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) + if (v.Value is BigInteger) + { + return (int?)(BigInteger)v.Value; + } +#endif + + return (v.Value != null) ? (int?)Convert.ToInt32(v.Value, CultureInfo.InvariantCulture) : null; + } + + /// + /// Performs an explicit conversion from to . + /// + /// The value. + /// The result of the conversion. + public static explicit operator short?(JToken value) + { + if (value == null) + { + return null; + } + + JValue v = EnsureValue(value); + if (v == null || !ValidateToken(v, NumberTypes, true)) + { + throw new ArgumentException("Can not convert {0} to Int16.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } + +#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) + if (v.Value is BigInteger) + { + return (short?)(BigInteger)v.Value; + } +#endif + + return (v.Value != null) ? (short?)Convert.ToInt16(v.Value, CultureInfo.InvariantCulture) : null; + } + + /// + /// Performs an explicit conversion from to . + /// + /// The value. + /// The result of the conversion. + [CLSCompliant(false)] + public static explicit operator ushort?(JToken value) + { + if (value == null) + { + return null; + } + + JValue v = EnsureValue(value); + if (v == null || !ValidateToken(v, NumberTypes, true)) + { + throw new ArgumentException("Can not convert {0} to UInt16.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } + +#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) + if (v.Value is BigInteger) + { + return (ushort?)(BigInteger)v.Value; + } +#endif + + return (v.Value != null) ? (ushort?)Convert.ToUInt16(v.Value, CultureInfo.InvariantCulture) : null; + } + + /// + /// Performs an explicit conversion from to . + /// + /// The value. + /// The result of the conversion. + public static explicit operator byte?(JToken value) + { + if (value == null) + { + return null; + } + + JValue v = EnsureValue(value); + if (v == null || !ValidateToken(v, NumberTypes, true)) + { + throw new ArgumentException("Can not convert {0} to Byte.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } + +#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) + if (v.Value is BigInteger) + { + return (byte?)(BigInteger)v.Value; + } +#endif + + return (v.Value != null) ? (byte?)Convert.ToByte(v.Value, CultureInfo.InvariantCulture) : null; + } + + /// + /// Performs an explicit conversion from to . + /// + /// The value. + /// The result of the conversion. + [CLSCompliant(false)] + public static explicit operator sbyte?(JToken value) + { + if (value == null) + { + return null; + } + + JValue v = EnsureValue(value); + if (v == null || !ValidateToken(v, NumberTypes, true)) + { + throw new ArgumentException("Can not convert {0} to SByte.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } + +#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) + if (v.Value is BigInteger) + { + return (sbyte?)(BigInteger)v.Value; + } +#endif + + return (v.Value != null) ? (sbyte?)Convert.ToSByte(v.Value, CultureInfo.InvariantCulture) : null; + } + + /// + /// Performs an explicit conversion from to . + /// + /// The value. + /// The result of the conversion. + public static explicit operator DateTime(JToken value) + { + JValue v = EnsureValue(value); + if (v == null || !ValidateToken(v, DateTimeTypes, false)) + { + throw new ArgumentException("Can not convert {0} to DateTime.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } + +#if !NET20 + if (v.Value is DateTimeOffset) + { + return ((DateTimeOffset)v.Value).DateTime; + } +#endif + + return Convert.ToDateTime(v.Value, CultureInfo.InvariantCulture); + } + + /// + /// Performs an explicit conversion from to . + /// + /// The value. + /// The result of the conversion. + public static explicit operator long?(JToken value) + { + if (value == null) + { + return null; + } + + JValue v = EnsureValue(value); + if (v == null || !ValidateToken(v, NumberTypes, true)) + { + throw new ArgumentException("Can not convert {0} to Int64.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } + +#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) + if (v.Value is BigInteger) + { + return (long?)(BigInteger)v.Value; + } +#endif + + return (v.Value != null) ? (long?)Convert.ToInt64(v.Value, CultureInfo.InvariantCulture) : null; + } + + /// + /// Performs an explicit conversion from to . + /// + /// The value. + /// The result of the conversion. + public static explicit operator float?(JToken value) + { + if (value == null) + { + return null; + } + + JValue v = EnsureValue(value); + if (v == null || !ValidateToken(v, NumberTypes, true)) + { + throw new ArgumentException("Can not convert {0} to Single.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } + +#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) + if (v.Value is BigInteger) + { + return (float?)(BigInteger)v.Value; + } +#endif + + return (v.Value != null) ? (float?)Convert.ToSingle(v.Value, CultureInfo.InvariantCulture) : null; + } + + /// + /// Performs an explicit conversion from to . + /// + /// The value. + /// The result of the conversion. + public static explicit operator decimal(JToken value) + { + JValue v = EnsureValue(value); + if (v == null || !ValidateToken(v, NumberTypes, false)) + { + throw new ArgumentException("Can not convert {0} to Decimal.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } + +#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) + if (v.Value is BigInteger) + { + return (decimal)(BigInteger)v.Value; + } +#endif + + return Convert.ToDecimal(v.Value, CultureInfo.InvariantCulture); + } + + /// + /// Performs an explicit conversion from to . + /// + /// The value. + /// The result of the conversion. + [CLSCompliant(false)] + public static explicit operator uint?(JToken value) + { + if (value == null) + { + return null; + } + + JValue v = EnsureValue(value); + if (v == null || !ValidateToken(v, NumberTypes, true)) + { + throw new ArgumentException("Can not convert {0} to UInt32.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } + +#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) + if (v.Value is BigInteger) + { + return (uint?)(BigInteger)v.Value; + } +#endif + + return (v.Value != null) ? (uint?)Convert.ToUInt32(v.Value, CultureInfo.InvariantCulture) : null; + } + + /// + /// Performs an explicit conversion from to . + /// + /// The value. + /// The result of the conversion. + [CLSCompliant(false)] + public static explicit operator ulong?(JToken value) + { + if (value == null) + { + return null; + } + + JValue v = EnsureValue(value); + if (v == null || !ValidateToken(v, NumberTypes, true)) + { + throw new ArgumentException("Can not convert {0} to UInt64.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } + +#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) + if (v.Value is BigInteger) + { + return (ulong?)(BigInteger)v.Value; + } +#endif + + return (v.Value != null) ? (ulong?)Convert.ToUInt64(v.Value, CultureInfo.InvariantCulture) : null; + } + + /// + /// Performs an explicit conversion from to . + /// + /// The value. + /// The result of the conversion. + public static explicit operator double(JToken value) + { + JValue v = EnsureValue(value); + if (v == null || !ValidateToken(v, NumberTypes, false)) + { + throw new ArgumentException("Can not convert {0} to Double.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } + +#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) + if (v.Value is BigInteger) + { + return (double)(BigInteger)v.Value; + } +#endif + + return Convert.ToDouble(v.Value, CultureInfo.InvariantCulture); + } + + /// + /// Performs an explicit conversion from to . + /// + /// The value. + /// The result of the conversion. + public static explicit operator float(JToken value) + { + JValue v = EnsureValue(value); + if (v == null || !ValidateToken(v, NumberTypes, false)) + { + throw new ArgumentException("Can not convert {0} to Single.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } + +#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) + if (v.Value is BigInteger) + { + return (float)(BigInteger)v.Value; + } +#endif + + return Convert.ToSingle(v.Value, CultureInfo.InvariantCulture); + } + + /// + /// Performs an explicit conversion from to . + /// + /// The value. + /// The result of the conversion. + public static explicit operator string(JToken value) + { + if (value == null) + { + return null; + } + + JValue v = EnsureValue(value); + if (v == null || !ValidateToken(v, StringTypes, true)) + { + throw new ArgumentException("Can not convert {0} to String.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } + + if (v.Value == null) + { + return null; + } + if (v.Value is byte[]) + { + return Convert.ToBase64String((byte[])v.Value); + } +#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) + if (v.Value is BigInteger) + { + return ((BigInteger)v.Value).ToString(CultureInfo.InvariantCulture); + } +#endif + + return Convert.ToString(v.Value, CultureInfo.InvariantCulture); + } + + /// + /// Performs an explicit conversion from to . + /// + /// The value. + /// The result of the conversion. + [CLSCompliant(false)] + public static explicit operator uint(JToken value) + { + JValue v = EnsureValue(value); + if (v == null || !ValidateToken(v, NumberTypes, false)) + { + throw new ArgumentException("Can not convert {0} to UInt32.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } + +#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) + if (v.Value is BigInteger) + { + return (uint)(BigInteger)v.Value; + } +#endif + + return Convert.ToUInt32(v.Value, CultureInfo.InvariantCulture); + } + + /// + /// Performs an explicit conversion from to . + /// + /// The value. + /// The result of the conversion. + [CLSCompliant(false)] + public static explicit operator ulong(JToken value) + { + JValue v = EnsureValue(value); + if (v == null || !ValidateToken(v, NumberTypes, false)) + { + throw new ArgumentException("Can not convert {0} to UInt64.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } + +#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) + if (v.Value is BigInteger) + { + return (ulong)(BigInteger)v.Value; + } +#endif + + return Convert.ToUInt64(v.Value, CultureInfo.InvariantCulture); + } + + /// + /// Performs an explicit conversion from to []. + /// + /// The value. + /// The result of the conversion. + public static explicit operator byte[](JToken value) + { + if (value == null) + { + return null; + } + + JValue v = EnsureValue(value); + if (v == null || !ValidateToken(v, BytesTypes, false)) + { + throw new ArgumentException("Can not convert {0} to byte array.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } + + if (v.Value is string) + { + return Convert.FromBase64String(Convert.ToString(v.Value, CultureInfo.InvariantCulture)); + } +#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) + if (v.Value is BigInteger) + { + return ((BigInteger)v.Value).ToByteArray(); + } +#endif + + if (v.Value is byte[]) + { + return (byte[])v.Value; + } + + throw new ArgumentException("Can not convert {0} to byte array.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } + + /// + /// Performs an explicit conversion from to . + /// + /// The value. + /// The result of the conversion. + public static explicit operator Guid(JToken value) + { + JValue v = EnsureValue(value); + if (v == null || !ValidateToken(v, GuidTypes, false)) + { + throw new ArgumentException("Can not convert {0} to Guid.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } + + if (v.Value is byte[]) + { + return new Guid((byte[])v.Value); + } + + return (v.Value is Guid) ? (Guid)v.Value : new Guid(Convert.ToString(v.Value, CultureInfo.InvariantCulture)); + } + + /// + /// Performs an explicit conversion from to . + /// + /// The value. + /// The result of the conversion. + public static explicit operator Guid?(JToken value) + { + if (value == null) + { + return null; + } + + JValue v = EnsureValue(value); + if (v == null || !ValidateToken(v, GuidTypes, true)) + { + throw new ArgumentException("Can not convert {0} to Guid.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } + + if (v.Value == null) + { + return null; + } + + if (v.Value is byte[]) + { + return new Guid((byte[])v.Value); + } + + return (v.Value is Guid) ? (Guid)v.Value : new Guid(Convert.ToString(v.Value, CultureInfo.InvariantCulture)); + } + + /// + /// Performs an explicit conversion from to . + /// + /// The value. + /// The result of the conversion. + public static explicit operator TimeSpan(JToken value) + { + JValue v = EnsureValue(value); + if (v == null || !ValidateToken(v, TimeSpanTypes, false)) + { + throw new ArgumentException("Can not convert {0} to TimeSpan.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } + + return (v.Value is TimeSpan) ? (TimeSpan)v.Value : ConvertUtils.ParseTimeSpan(Convert.ToString(v.Value, CultureInfo.InvariantCulture)); + } + + /// + /// Performs an explicit conversion from to . + /// + /// The value. + /// The result of the conversion. + public static explicit operator TimeSpan?(JToken value) + { + if (value == null) + { + return null; + } + + JValue v = EnsureValue(value); + if (v == null || !ValidateToken(v, TimeSpanTypes, true)) + { + throw new ArgumentException("Can not convert {0} to TimeSpan.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } + + if (v.Value == null) + { + return null; + } + + return (v.Value is TimeSpan) ? (TimeSpan)v.Value : ConvertUtils.ParseTimeSpan(Convert.ToString(v.Value, CultureInfo.InvariantCulture)); + } + + /// + /// Performs an explicit conversion from to . + /// + /// The value. + /// The result of the conversion. + public static explicit operator Uri(JToken value) + { + if (value == null) + { + return null; + } + + JValue v = EnsureValue(value); + if (v == null || !ValidateToken(v, UriTypes, true)) + { + throw new ArgumentException("Can not convert {0} to Uri.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } + + if (v.Value == null) + { + return null; + } + + return (v.Value is Uri) ? (Uri)v.Value : new Uri(Convert.ToString(v.Value, CultureInfo.InvariantCulture)); + } + +#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) + private static BigInteger ToBigInteger(JToken value) + { + JValue v = EnsureValue(value); + if (v == null || !ValidateToken(v, BigIntegerTypes, false)) + { + throw new ArgumentException("Can not convert {0} to BigInteger.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } + + return ConvertUtils.ToBigInteger(v.Value); + } + + private static BigInteger? ToBigIntegerNullable(JToken value) + { + JValue v = EnsureValue(value); + if (v == null || !ValidateToken(v, BigIntegerTypes, true)) + { + throw new ArgumentException("Can not convert {0} to BigInteger.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } + + if (v.Value == null) + { + return null; + } + + return ConvertUtils.ToBigInteger(v.Value); + } +#endif + #endregion + + #region Cast to operators + /// + /// Performs an implicit conversion from to . + /// + /// The value to create a from. + /// The initialized with the specified value. + public static implicit operator JToken(bool value) + { + return new JValue(value); + } + +#if !NET20 + /// + /// Performs an implicit conversion from to . + /// + /// The value to create a from. + /// The initialized with the specified value. + public static implicit operator JToken(DateTimeOffset value) + { + return new JValue(value); + } +#endif + + /// + /// Performs an implicit conversion from to . + /// + /// The value to create a from. + /// The initialized with the specified value. + public static implicit operator JToken(byte value) + { + return new JValue(value); + } + + /// + /// Performs an implicit conversion from to . + /// + /// The value to create a from. + /// The initialized with the specified value. + public static implicit operator JToken(byte? value) + { + return new JValue(value); + } + + /// + /// Performs an implicit conversion from to . + /// + /// The value to create a from. + /// The initialized with the specified value. + [CLSCompliant(false)] + public static implicit operator JToken(sbyte value) + { + return new JValue(value); + } + + /// + /// Performs an implicit conversion from to . + /// + /// The value to create a from. + /// The initialized with the specified value. + [CLSCompliant(false)] + public static implicit operator JToken(sbyte? value) + { + return new JValue(value); + } + + /// + /// Performs an implicit conversion from to . + /// + /// The value to create a from. + /// The initialized with the specified value. + public static implicit operator JToken(bool? value) + { + return new JValue(value); + } + + /// + /// Performs an implicit conversion from to . + /// + /// The value to create a from. + /// The initialized with the specified value. + public static implicit operator JToken(long value) + { + return new JValue(value); + } + + /// + /// Performs an implicit conversion from to . + /// + /// The value to create a from. + /// The initialized with the specified value. + public static implicit operator JToken(DateTime? value) + { + return new JValue(value); + } + +#if !NET20 + /// + /// Performs an implicit conversion from to . + /// + /// The value to create a from. + /// The initialized with the specified value. + public static implicit operator JToken(DateTimeOffset? value) + { + return new JValue(value); + } +#endif + + /// + /// Performs an implicit conversion from to . + /// + /// The value to create a from. + /// The initialized with the specified value. + public static implicit operator JToken(decimal? value) + { + return new JValue(value); + } + + /// + /// Performs an implicit conversion from to . + /// + /// The value to create a from. + /// The initialized with the specified value. + public static implicit operator JToken(double? value) + { + return new JValue(value); + } + + /// + /// Performs an implicit conversion from to . + /// + /// The value to create a from. + /// The initialized with the specified value. + [CLSCompliant(false)] + public static implicit operator JToken(short value) + { + return new JValue(value); + } + + /// + /// Performs an implicit conversion from to . + /// + /// The value to create a from. + /// The initialized with the specified value. + [CLSCompliant(false)] + public static implicit operator JToken(ushort value) + { + return new JValue(value); + } + + /// + /// Performs an implicit conversion from to . + /// + /// The value to create a from. + /// The initialized with the specified value. + public static implicit operator JToken(int value) + { + return new JValue(value); + } + + /// + /// Performs an implicit conversion from to . + /// + /// The value to create a from. + /// The initialized with the specified value. + public static implicit operator JToken(int? value) + { + return new JValue(value); + } + + /// + /// Performs an implicit conversion from to . + /// + /// The value to create a from. + /// The initialized with the specified value. + public static implicit operator JToken(DateTime value) + { + return new JValue(value); + } + + /// + /// Performs an implicit conversion from to . + /// + /// The value to create a from. + /// The initialized with the specified value. + public static implicit operator JToken(long? value) + { + return new JValue(value); + } + + /// + /// Performs an implicit conversion from to . + /// + /// The value to create a from. + /// The initialized with the specified value. + public static implicit operator JToken(float? value) + { + return new JValue(value); + } + + /// + /// Performs an implicit conversion from to . + /// + /// The value to create a from. + /// The initialized with the specified value. + public static implicit operator JToken(decimal value) + { + return new JValue(value); + } + + /// + /// Performs an implicit conversion from to . + /// + /// The value to create a from. + /// The initialized with the specified value. + [CLSCompliant(false)] + public static implicit operator JToken(short? value) + { + return new JValue(value); + } + + /// + /// Performs an implicit conversion from to . + /// + /// The value to create a from. + /// The initialized with the specified value. + [CLSCompliant(false)] + public static implicit operator JToken(ushort? value) + { + return new JValue(value); + } + + /// + /// Performs an implicit conversion from to . + /// + /// The value to create a from. + /// The initialized with the specified value. + [CLSCompliant(false)] + public static implicit operator JToken(uint? value) + { + return new JValue(value); + } + + /// + /// Performs an implicit conversion from to . + /// + /// The value to create a from. + /// The initialized with the specified value. + [CLSCompliant(false)] + public static implicit operator JToken(ulong? value) + { + return new JValue(value); + } + + /// + /// Performs an implicit conversion from to . + /// + /// The value to create a from. + /// The initialized with the specified value. + public static implicit operator JToken(double value) + { + return new JValue(value); + } + + /// + /// Performs an implicit conversion from to . + /// + /// The value to create a from. + /// The initialized with the specified value. + public static implicit operator JToken(float value) + { + return new JValue(value); + } + + /// + /// Performs an implicit conversion from to . + /// + /// The value to create a from. + /// The initialized with the specified value. + public static implicit operator JToken(string value) + { + return new JValue(value); + } + + /// + /// Performs an implicit conversion from to . + /// + /// The value to create a from. + /// The initialized with the specified value. + [CLSCompliant(false)] + public static implicit operator JToken(uint value) + { + return new JValue(value); + } + + /// + /// Performs an implicit conversion from to . + /// + /// The value to create a from. + /// The initialized with the specified value. + [CLSCompliant(false)] + public static implicit operator JToken(ulong value) + { + return new JValue(value); + } + + /// + /// Performs an implicit conversion from [] to . + /// + /// The value to create a from. + /// The initialized with the specified value. + public static implicit operator JToken(byte[] value) + { + return new JValue(value); + } + + /// + /// Performs an implicit conversion from to . + /// + /// The value to create a from. + /// The initialized with the specified value. + public static implicit operator JToken(Uri value) + { + return new JValue(value); + } + + /// + /// Performs an implicit conversion from to . + /// + /// The value to create a from. + /// The initialized with the specified value. + public static implicit operator JToken(TimeSpan value) + { + return new JValue(value); + } + + /// + /// Performs an implicit conversion from to . + /// + /// The value to create a from. + /// The initialized with the specified value. + public static implicit operator JToken(TimeSpan? value) + { + return new JValue(value); + } + + /// + /// Performs an implicit conversion from to . + /// + /// The value to create a from. + /// The initialized with the specified value. + public static implicit operator JToken(Guid value) + { + return new JValue(value); + } + + /// + /// Performs an implicit conversion from to . + /// + /// The value to create a from. + /// The initialized with the specified value. + public static implicit operator JToken(Guid? value) + { + return new JValue(value); + } + #endregion + + IEnumerator IEnumerable.GetEnumerator() + { + return ((IEnumerable)this).GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return Children().GetEnumerator(); + } + + internal abstract int GetDeepHashCode(); + + IJEnumerable IJEnumerable.this[object key] + { + get { return this[key]; } + } + + /// + /// Creates an for this token. + /// + /// An that can be used to read this token and its descendants. + public JsonReader CreateReader() + { + return new JTokenReader(this, Path); + } + + internal static JToken FromObjectInternal(object o, JsonSerializer jsonSerializer) + { + ValidationUtils.ArgumentNotNull(o, nameof(o)); + ValidationUtils.ArgumentNotNull(jsonSerializer, nameof(jsonSerializer)); + + JToken token; + using (JTokenWriter jsonWriter = new JTokenWriter()) + { + jsonSerializer.Serialize(jsonWriter, o); + token = jsonWriter.Token; + } + + return token; + } + + /// + /// Creates a from an object. + /// + /// The object that will be used to create . + /// A with the value of the specified object + public static JToken FromObject(object o) + { + return FromObjectInternal(o, JsonSerializer.CreateDefault()); + } + + /// + /// Creates a from an object using the specified . + /// + /// The object that will be used to create . + /// The that will be used when reading the object. + /// A with the value of the specified object + public static JToken FromObject(object o, JsonSerializer jsonSerializer) + { + return FromObjectInternal(o, jsonSerializer); + } + + /// + /// Creates the specified .NET type from the . + /// + /// The object type that the token will be deserialized to. + /// The new object created from the JSON value. + public T ToObject() + { + return (T)ToObject(typeof(T)); + } + + /// + /// Creates the specified .NET type from the . + /// + /// The object type that the token will be deserialized to. + /// The new object created from the JSON value. + public object ToObject(Type objectType) + { + if (JsonConvert.DefaultSettings == null) + { + bool isEnum; + PrimitiveTypeCode typeCode = ConvertUtils.GetTypeCode(objectType, out isEnum); + + if (isEnum) + { + if (Type == JTokenType.String) + { + try + { + // use serializer so JsonConverter(typeof(StringEnumConverter)) + EnumMemberAttributes are respected + return ToObject(objectType, JsonSerializer.CreateDefault()); + } + catch (Exception ex) + { + Type enumType = objectType.IsEnum() ? objectType : Nullable.GetUnderlyingType(objectType); + throw new ArgumentException("Could not convert '{0}' to {1}.".FormatWith(CultureInfo.InvariantCulture, (string)this, enumType.Name), ex); + } + } + + if (Type == JTokenType.Integer) + { + Type enumType = objectType.IsEnum() ? objectType : Nullable.GetUnderlyingType(objectType); + return Enum.ToObject(enumType, ((JValue)this).Value); + } + } + + switch (typeCode) + { + case PrimitiveTypeCode.BooleanNullable: + return (bool?)this; + case PrimitiveTypeCode.Boolean: + return (bool)this; + case PrimitiveTypeCode.CharNullable: + return (char?)this; + case PrimitiveTypeCode.Char: + return (char)this; + case PrimitiveTypeCode.SByte: + return (sbyte?)this; + case PrimitiveTypeCode.SByteNullable: + return (sbyte)this; + case PrimitiveTypeCode.ByteNullable: + return (byte?)this; + case PrimitiveTypeCode.Byte: + return (byte)this; + case PrimitiveTypeCode.Int16Nullable: + return (short?)this; + case PrimitiveTypeCode.Int16: + return (short)this; + case PrimitiveTypeCode.UInt16Nullable: + return (ushort?)this; + case PrimitiveTypeCode.UInt16: + return (ushort)this; + case PrimitiveTypeCode.Int32Nullable: + return (int?)this; + case PrimitiveTypeCode.Int32: + return (int)this; + case PrimitiveTypeCode.UInt32Nullable: + return (uint?)this; + case PrimitiveTypeCode.UInt32: + return (uint)this; + case PrimitiveTypeCode.Int64Nullable: + return (long?)this; + case PrimitiveTypeCode.Int64: + return (long)this; + case PrimitiveTypeCode.UInt64Nullable: + return (ulong?)this; + case PrimitiveTypeCode.UInt64: + return (ulong)this; + case PrimitiveTypeCode.SingleNullable: + return (float?)this; + case PrimitiveTypeCode.Single: + return (float)this; + case PrimitiveTypeCode.DoubleNullable: + return (double?)this; + case PrimitiveTypeCode.Double: + return (double)this; + case PrimitiveTypeCode.DecimalNullable: + return (decimal?)this; + case PrimitiveTypeCode.Decimal: + return (decimal)this; + case PrimitiveTypeCode.DateTimeNullable: + return (DateTime?)this; + case PrimitiveTypeCode.DateTime: + return (DateTime)this; +#if !NET20 + case PrimitiveTypeCode.DateTimeOffsetNullable: + return (DateTimeOffset?)this; + case PrimitiveTypeCode.DateTimeOffset: + return (DateTimeOffset)this; +#endif + case PrimitiveTypeCode.String: + return (string)this; + case PrimitiveTypeCode.GuidNullable: + return (Guid?)this; + case PrimitiveTypeCode.Guid: + return (Guid)this; + case PrimitiveTypeCode.Uri: + return (Uri)this; + case PrimitiveTypeCode.TimeSpanNullable: + return (TimeSpan?)this; + case PrimitiveTypeCode.TimeSpan: + return (TimeSpan)this; +#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) + case PrimitiveTypeCode.BigIntegerNullable: + return ToBigIntegerNullable(this); + case PrimitiveTypeCode.BigInteger: + return ToBigInteger(this); +#endif + } + } + + return ToObject(objectType, JsonSerializer.CreateDefault()); + } + + /// + /// Creates the specified .NET type from the using the specified . + /// + /// The object type that the token will be deserialized to. + /// The that will be used when creating the object. + /// The new object created from the JSON value. + public T ToObject(JsonSerializer jsonSerializer) + { + return (T)ToObject(typeof(T), jsonSerializer); + } + + /// + /// Creates the specified .NET type from the using the specified . + /// + /// The object type that the token will be deserialized to. + /// The that will be used when creating the object. + /// The new object created from the JSON value. + public object ToObject(Type objectType, JsonSerializer jsonSerializer) + { + ValidationUtils.ArgumentNotNull(jsonSerializer, nameof(jsonSerializer)); + + using (JTokenReader jsonReader = new JTokenReader(this)) + { + return jsonSerializer.Deserialize(jsonReader, objectType); + } + } + + /// + /// Creates a from a . + /// + /// An positioned at the token to read into this . + /// + /// An that contains the token and its descendant tokens + /// that were read from the reader. The runtime type of the token is determined + /// by the token type of the first token encountered in the reader. + /// + public static JToken ReadFrom(JsonReader reader) + { + return ReadFrom(reader, null); + } + + /// + /// Creates a from a . + /// + /// An positioned at the token to read into this . + /// The used to load the JSON. + /// If this is null, default load settings will be used. + /// + /// An that contains the token and its descendant tokens + /// that were read from the reader. The runtime type of the token is determined + /// by the token type of the first token encountered in the reader. + /// + public static JToken ReadFrom(JsonReader reader, JsonLoadSettings settings) + { + ValidationUtils.ArgumentNotNull(reader, nameof(reader)); + + if (reader.TokenType == JsonToken.None) + { + bool hasContent = (settings != null && settings.CommentHandling == CommentHandling.Ignore) + ? reader.ReadAndMoveToContent() + : reader.Read(); + + if (!hasContent) + { + throw JsonReaderException.Create(reader, "Error reading JToken from JsonReader."); + } + } + + IJsonLineInfo lineInfo = reader as IJsonLineInfo; + + switch (reader.TokenType) + { + case JsonToken.StartObject: + return JObject.Load(reader, settings); + case JsonToken.StartArray: + return JArray.Load(reader, settings); + case JsonToken.StartConstructor: + return JConstructor.Load(reader, settings); + case JsonToken.PropertyName: + return JProperty.Load(reader, settings); + case JsonToken.String: + case JsonToken.Integer: + case JsonToken.Float: + case JsonToken.Date: + case JsonToken.Boolean: + case JsonToken.Bytes: + JValue v = new JValue(reader.Value); + v.SetLineInfo(lineInfo, settings); + return v; + case JsonToken.Comment: + v = JValue.CreateComment(reader.Value.ToString()); + v.SetLineInfo(lineInfo, settings); + return v; + case JsonToken.Null: + v = JValue.CreateNull(); + v.SetLineInfo(lineInfo, settings); + return v; + case JsonToken.Undefined: + v = JValue.CreateUndefined(); + v.SetLineInfo(lineInfo, settings); + return v; + default: + throw JsonReaderException.Create(reader, "Error reading JToken from JsonReader. Unexpected token: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); + } + } + + /// + /// Load a from a string that contains JSON. + /// + /// A that contains JSON. + /// A populated from the string that contains JSON. + public static JToken Parse(string json) + { + return Parse(json, null); + } + + /// + /// Load a from a string that contains JSON. + /// + /// A that contains JSON. + /// The used to load the JSON. + /// If this is null, default load settings will be used. + /// A populated from the string that contains JSON. + public static JToken Parse(string json, JsonLoadSettings settings) + { + using (JsonReader reader = new JsonTextReader(new StringReader(json))) + { + JToken t = Load(reader, settings); + + if (reader.Read() && reader.TokenType != JsonToken.Comment) + { + throw JsonReaderException.Create(reader, "Additional text found in JSON string after parsing content."); + } + + return t; + } + } + + /// + /// Creates a from a . + /// + /// An positioned at the token to read into this . + /// The used to load the JSON. + /// If this is null, default load settings will be used. + /// + /// An that contains the token and its descendant tokens + /// that were read from the reader. The runtime type of the token is determined + /// by the token type of the first token encountered in the reader. + /// + public static JToken Load(JsonReader reader, JsonLoadSettings settings) + { + return ReadFrom(reader, settings); + } + + /// + /// Creates a from a . + /// + /// An positioned at the token to read into this . + /// + /// An that contains the token and its descendant tokens + /// that were read from the reader. The runtime type of the token is determined + /// by the token type of the first token encountered in the reader. + /// + public static JToken Load(JsonReader reader) + { + return Load(reader, null); + } + + internal void SetLineInfo(IJsonLineInfo lineInfo, JsonLoadSettings settings) + { + if (settings != null && settings.LineInfoHandling == LineInfoHandling.Load) + { + return; + } + + if (lineInfo == null || !lineInfo.HasLineInfo()) + { + return; + } + + SetLineInfo(lineInfo.LineNumber, lineInfo.LinePosition); + } + + private class LineInfoAnnotation + { + internal readonly int LineNumber; + internal readonly int LinePosition; + + public LineInfoAnnotation(int lineNumber, int linePosition) + { + LineNumber = lineNumber; + LinePosition = linePosition; + } + } + + internal void SetLineInfo(int lineNumber, int linePosition) + { + AddAnnotation(new LineInfoAnnotation(lineNumber, linePosition)); + } + + bool IJsonLineInfo.HasLineInfo() + { + return (Annotation() != null); + } + + int IJsonLineInfo.LineNumber + { + get + { + LineInfoAnnotation annotation = Annotation(); + if (annotation != null) + { + return annotation.LineNumber; + } + + return 0; + } + } + + int IJsonLineInfo.LinePosition + { + get + { + LineInfoAnnotation annotation = Annotation(); + if (annotation != null) + { + return annotation.LinePosition; + } + + return 0; + } + } + + /// + /// Selects a using a JPath expression. Selects the token that matches the object path. + /// + /// + /// A that contains a JPath expression. + /// + /// A , or null. + public JToken SelectToken(string path) + { + return SelectToken(path, false); + } + + /// + /// Selects a using a JPath expression. Selects the token that matches the object path. + /// + /// + /// A that contains a JPath expression. + /// + /// A flag to indicate whether an error should be thrown if no tokens are found when evaluating part of the expression. + /// A . + public JToken SelectToken(string path, bool errorWhenNoMatch) + { + JPath p = new JPath(path); + + JToken token = null; + foreach (JToken t in p.Evaluate(this, errorWhenNoMatch)) + { + if (token != null) + { + throw new JsonException("Path returned multiple tokens."); + } + + token = t; + } + + return token; + } + + /// + /// Selects a collection of elements using a JPath expression. + /// + /// + /// A that contains a JPath expression. + /// + /// An that contains the selected elements. + public IEnumerable SelectTokens(string path) + { + return SelectTokens(path, false); + } + + /// + /// Selects a collection of elements using a JPath expression. + /// + /// + /// A that contains a JPath expression. + /// + /// A flag to indicate whether an error should be thrown if no tokens are found when evaluating part of the expression. + /// An that contains the selected elements. + public IEnumerable SelectTokens(string path, bool errorWhenNoMatch) + { + JPath p = new JPath(path); + return p.Evaluate(this, errorWhenNoMatch); + } + +#if !(NET35 || NET20 || PORTABLE40) + /// + /// Returns the responsible for binding operations performed on this object. + /// + /// The expression tree representation of the runtime value. + /// + /// The to bind this object. + /// + protected virtual DynamicMetaObject GetMetaObject(Expression parameter) + { + return new DynamicProxyMetaObject(parameter, this, new DynamicProxy(), true); + } + + /// + /// Returns the responsible for binding operations performed on this object. + /// + /// The expression tree representation of the runtime value. + /// + /// The to bind this object. + /// + DynamicMetaObject IDynamicMetaObjectProvider.GetMetaObject(Expression parameter) + { + return GetMetaObject(parameter); + } +#endif + +#if !(DOTNET || PORTABLE || PORTABLE40) + object ICloneable.Clone() + { + return DeepClone(); + } +#endif + + /// + /// Creates a new instance of the . All child tokens are recursively cloned. + /// + /// A new instance of the . + public JToken DeepClone() + { + return CloneToken(); + } + + /// + /// Adds an object to the annotation list of this . + /// + /// The annotation to add. + public void AddAnnotation(object annotation) + { + if (annotation == null) + { + throw new ArgumentNullException(nameof(annotation)); + } + + if (_annotations == null) + { + _annotations = (annotation is object[]) ? new[] { annotation } : annotation; + } + else + { + object[] annotations = _annotations as object[]; + if (annotations == null) + { + _annotations = new[] { _annotations, annotation }; + } + else + { + int index = 0; + while (index < annotations.Length && annotations[index] != null) + { + index++; + } + if (index == annotations.Length) + { + Array.Resize(ref annotations, index * 2); + _annotations = annotations; + } + annotations[index] = annotation; + } + } + } + + /// + /// Get the first annotation object of the specified type from this . + /// + /// The type of the annotation to retrieve. + /// The first annotation object that matches the specified type, or null if no annotation is of the specified type. + public T Annotation() where T : class + { + if (_annotations != null) + { + object[] annotations = _annotations as object[]; + if (annotations == null) + { + return (_annotations as T); + } + for (int i = 0; i < annotations.Length; i++) + { + object annotation = annotations[i]; + if (annotation == null) + { + break; + } + + T local = annotation as T; + if (local != null) + { + return local; + } + } + } + + return default(T); + } + + /// + /// Gets the first annotation object of the specified type from this . + /// + /// The of the annotation to retrieve. + /// The first annotation object that matches the specified type, or null if no annotation is of the specified type. + public object Annotation(Type type) + { + if (type == null) + { + throw new ArgumentNullException(nameof(type)); + } + + if (_annotations != null) + { + object[] annotations = _annotations as object[]; + if (annotations == null) + { + if (type.IsInstanceOfType(_annotations)) + { + return _annotations; + } + } + else + { + for (int i = 0; i < annotations.Length; i++) + { + object o = annotations[i]; + if (o == null) + { + break; + } + + if (type.IsInstanceOfType(o)) + { + return o; + } + } + } + } + + return null; + } + + /// + /// Gets a collection of annotations of the specified type for this . + /// + /// The type of the annotations to retrieve. + /// An that contains the annotations for this . + public IEnumerable Annotations() where T : class + { + if (_annotations == null) + { + yield break; + } + + object[] annotations = _annotations as object[]; + if (annotations != null) + { + for (int i = 0; i < annotations.Length; i++) + { + object o = annotations[i]; + if (o == null) + { + break; + } + + T casted = o as T; + if (casted != null) + { + yield return casted; + } + } + yield break; + } + + T annotation = _annotations as T; + if (annotation == null) + { + yield break; + } + + yield return annotation; + } + + /// + /// Gets a collection of annotations of the specified type for this . + /// + /// The of the annotations to retrieve. + /// An of that contains the annotations that match the specified type for this . + public IEnumerable Annotations(Type type) + { + if (type == null) + { + throw new ArgumentNullException(nameof(type)); + } + + if (_annotations == null) + { + yield break; + } + + object[] annotations = _annotations as object[]; + if (annotations != null) + { + for (int i = 0; i < annotations.Length; i++) + { + object o = annotations[i]; + if (o == null) + { + break; + } + + if (type.IsInstanceOfType(o)) + { + yield return o; + } + } + yield break; + } + + if (!type.IsInstanceOfType(_annotations)) + { + yield break; + } + + yield return _annotations; + } + + /// + /// Removes the annotations of the specified type from this . + /// + /// The type of annotations to remove. + public void RemoveAnnotations() where T : class + { + if (_annotations != null) + { + object[] annotations = _annotations as object[]; + if (annotations == null) + { + if (_annotations is T) + { + _annotations = null; + } + } + else + { + int index = 0; + int keepCount = 0; + while (index < annotations.Length) + { + object obj2 = annotations[index]; + if (obj2 == null) + { + break; + } + + if (!(obj2 is T)) + { + annotations[keepCount++] = obj2; + } + + index++; + } + + if (keepCount != 0) + { + while (keepCount < index) + { + annotations[keepCount++] = null; + } + } + else + { + _annotations = null; + } + } + } + } + + /// + /// Removes the annotations of the specified type from this . + /// + /// The of annotations to remove. + public void RemoveAnnotations(Type type) + { + if (type == null) + { + throw new ArgumentNullException(nameof(type)); + } + + if (_annotations != null) + { + object[] annotations = _annotations as object[]; + if (annotations == null) + { + if (type.IsInstanceOfType(_annotations)) + { + _annotations = null; + } + } + else + { + int index = 0; + int keepCount = 0; + while (index < annotations.Length) + { + object o = annotations[index]; + if (o == null) + { + break; + } + + if (!type.IsInstanceOfType(o)) + { + annotations[keepCount++] = o; + } + + index++; + } + + if (keepCount != 0) + { + while (keepCount < index) + { + annotations[keepCount++] = null; + } + } + else + { + _annotations = null; + } + } + } + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Linq/JTokenEqualityComparer.cs b/Common/00-1Json8.3/Json8.3/Linq/JTokenEqualityComparer.cs new file mode 100644 index 0000000..fd10537 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Linq/JTokenEqualityComparer.cs @@ -0,0 +1,64 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System.Collections.Generic; + +namespace Newtonsoft.Json.Linq +{ + /// + /// Compares tokens to determine whether they are equal. + /// + public class JTokenEqualityComparer : IEqualityComparer + { + /// + /// Determines whether the specified objects are equal. + /// + /// The first object of type to compare. + /// The second object of type to compare. + /// + /// true if the specified objects are equal; otherwise, false. + /// + public bool Equals(JToken x, JToken y) + { + return JToken.DeepEquals(x, y); + } + + /// + /// Returns a hash code for the specified object. + /// + /// The for which a hash code is to be returned. + /// A hash code for the specified object. + /// The type of is a reference type and is null. + public int GetHashCode(JToken obj) + { + if (obj == null) + { + return 0; + } + + return obj.GetDeepHashCode(); + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Linq/JTokenReader.cs b/Common/00-1Json8.3/Json8.3/Linq/JTokenReader.cs new file mode 100644 index 0000000..5f0ca87 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Linq/JTokenReader.cs @@ -0,0 +1,330 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using Newtonsoft.Json.Utilities; + +namespace Newtonsoft.Json.Linq +{ + /// + /// Represents a reader that provides fast, non-cached, forward-only access to serialized JSON data. + /// + public class JTokenReader : JsonReader, IJsonLineInfo + { + private readonly string _initialPath; + private readonly JToken _root; + private JToken _parent; + private JToken _current; + + /// + /// Gets the at the reader's current position. + /// + public JToken CurrentToken + { + get { return _current; } + } + + /// + /// Initializes a new instance of the class. + /// + /// The token to read from. + public JTokenReader(JToken token) + { + ValidationUtils.ArgumentNotNull(token, nameof(token)); + + _root = token; + } + + internal JTokenReader(JToken token, string initialPath) + : this(token) + { + _initialPath = initialPath; + } + + /// + /// Reads the next JSON token from the stream. + /// + /// + /// true if the next token was read successfully; false if there are no more tokens to read. + /// + public override bool Read() + { + if (CurrentState != State.Start) + { + if (_current == null) + { + return false; + } + + JContainer container = _current as JContainer; + if (container != null && _parent != container) + { + return ReadInto(container); + } + else + { + return ReadOver(_current); + } + } + + _current = _root; + SetToken(_current); + return true; + } + + private bool ReadOver(JToken t) + { + if (t == _root) + { + return ReadToEnd(); + } + + JToken next = t.Next; + if ((next == null || next == t) || t == t.Parent.Last) + { + if (t.Parent == null) + { + return ReadToEnd(); + } + + return SetEnd(t.Parent); + } + else + { + _current = next; + SetToken(_current); + return true; + } + } + + private bool ReadToEnd() + { + _current = null; + SetToken(JsonToken.None); + return false; + } + + private JsonToken? GetEndToken(JContainer c) + { + switch (c.Type) + { + case JTokenType.Object: + return JsonToken.EndObject; + case JTokenType.Array: + return JsonToken.EndArray; + case JTokenType.Constructor: + return JsonToken.EndConstructor; + case JTokenType.Property: + return null; + default: + throw MiscellaneousUtils.CreateArgumentOutOfRangeException("Type", c.Type, "Unexpected JContainer type."); + } + } + + private bool ReadInto(JContainer c) + { + JToken firstChild = c.First; + if (firstChild == null) + { + return SetEnd(c); + } + else + { + SetToken(firstChild); + _current = firstChild; + _parent = c; + return true; + } + } + + private bool SetEnd(JContainer c) + { + JsonToken? endToken = GetEndToken(c); + if (endToken != null) + { + SetToken(endToken.GetValueOrDefault()); + _current = c; + _parent = c; + return true; + } + else + { + return ReadOver(c); + } + } + + private void SetToken(JToken token) + { + switch (token.Type) + { + case JTokenType.Object: + SetToken(JsonToken.StartObject); + break; + case JTokenType.Array: + SetToken(JsonToken.StartArray); + break; + case JTokenType.Constructor: + SetToken(JsonToken.StartConstructor, ((JConstructor)token).Name); + break; + case JTokenType.Property: + SetToken(JsonToken.PropertyName, ((JProperty)token).Name); + break; + case JTokenType.Comment: + SetToken(JsonToken.Comment, ((JValue)token).Value); + break; + case JTokenType.Integer: + SetToken(JsonToken.Integer, ((JValue)token).Value); + break; + case JTokenType.Float: + SetToken(JsonToken.Float, ((JValue)token).Value); + break; + case JTokenType.String: + SetToken(JsonToken.String, ((JValue)token).Value); + break; + case JTokenType.Boolean: + SetToken(JsonToken.Boolean, ((JValue)token).Value); + break; + case JTokenType.Null: + SetToken(JsonToken.Null, ((JValue)token).Value); + break; + case JTokenType.Undefined: + SetToken(JsonToken.Undefined, ((JValue)token).Value); + break; + case JTokenType.Date: + SetToken(JsonToken.Date, ((JValue)token).Value); + break; + case JTokenType.Raw: + SetToken(JsonToken.Raw, ((JValue)token).Value); + break; + case JTokenType.Bytes: + SetToken(JsonToken.Bytes, ((JValue)token).Value); + break; + case JTokenType.Guid: + SetToken(JsonToken.String, SafeToString(((JValue)token).Value)); + break; + case JTokenType.Uri: + object v = ((JValue)token).Value; + if (v is Uri) + { + SetToken(JsonToken.String, ((Uri)v).OriginalString); + } + else + { + SetToken(JsonToken.String, SafeToString(v)); + } + break; + case JTokenType.TimeSpan: + SetToken(JsonToken.String, SafeToString(((JValue)token).Value)); + break; + default: + throw MiscellaneousUtils.CreateArgumentOutOfRangeException("Type", token.Type, "Unexpected JTokenType."); + } + } + + private string SafeToString(object value) + { + return (value != null) ? value.ToString() : null; + } + + bool IJsonLineInfo.HasLineInfo() + { + if (CurrentState == State.Start) + { + return false; + } + + IJsonLineInfo info = _current; + return (info != null && info.HasLineInfo()); + } + + int IJsonLineInfo.LineNumber + { + get + { + if (CurrentState == State.Start) + { + return 0; + } + + IJsonLineInfo info = _current; + if (info != null) + { + return info.LineNumber; + } + + return 0; + } + } + + int IJsonLineInfo.LinePosition + { + get + { + if (CurrentState == State.Start) + { + return 0; + } + + IJsonLineInfo info = _current; + if (info != null) + { + return info.LinePosition; + } + + return 0; + } + } + + /// + /// Gets the path of the current JSON token. + /// + public override string Path + { + get + { + string path = base.Path; + + if (!string.IsNullOrEmpty(_initialPath)) + { + if (string.IsNullOrEmpty(path)) + { + return _initialPath; + } + + if (path.StartsWith('[')) + { + path = _initialPath + path; + } + else + { + path = _initialPath + "." + path; + } + } + + return path; + } + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Linq/JTokenType.cs b/Common/00-1Json8.3/Json8.3/Linq/JTokenType.cs new file mode 100644 index 0000000..3691873 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Linq/JTokenType.cs @@ -0,0 +1,123 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +namespace Newtonsoft.Json.Linq +{ + /// + /// Specifies the type of token. + /// + public enum JTokenType + { + /// + /// No token type has been set. + /// + None = 0, + + /// + /// A JSON object. + /// + Object = 1, + + /// + /// A JSON array. + /// + Array = 2, + + /// + /// A JSON constructor. + /// + Constructor = 3, + + /// + /// A JSON object property. + /// + Property = 4, + + /// + /// A comment. + /// + Comment = 5, + + /// + /// An integer value. + /// + Integer = 6, + + /// + /// A float value. + /// + Float = 7, + + /// + /// A string value. + /// + String = 8, + + /// + /// A boolean value. + /// + Boolean = 9, + + /// + /// A null value. + /// + Null = 10, + + /// + /// An undefined value. + /// + Undefined = 11, + + /// + /// A date value. + /// + Date = 12, + + /// + /// A raw JSON value. + /// + Raw = 13, + + /// + /// A collection of bytes value. + /// + Bytes = 14, + + /// + /// A Guid value. + /// + Guid = 15, + + /// + /// A Uri value. + /// + Uri = 16, + + /// + /// A TimeSpan value. + /// + TimeSpan = 17 + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Linq/JTokenWriter.cs b/Common/00-1Json8.3/Json8.3/Linq/JTokenWriter.cs new file mode 100644 index 0000000..0331850 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Linq/JTokenWriter.cs @@ -0,0 +1,489 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Globalization; +#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) +using System.Numerics; +#endif +using Newtonsoft.Json.Utilities; + +namespace Newtonsoft.Json.Linq +{ + /// + /// Represents a writer that provides a fast, non-cached, forward-only way of generating JSON data. + /// + public class JTokenWriter : JsonWriter + { + private JContainer _token; + private JContainer _parent; + // used when writer is writing single value and the value has no containing parent + private JValue _value; + private JToken _current; + + /// + /// Gets the at the writer's current position. + /// + public JToken CurrentToken + { + get { return _current; } + } + + /// + /// Gets the token being writen. + /// + /// The token being writen. + public JToken Token + { + get + { + if (_token != null) + { + return _token; + } + + return _value; + } + } + + /// + /// Initializes a new instance of the class writing to the given . + /// + /// The container being written to. + public JTokenWriter(JContainer container) + { + ValidationUtils.ArgumentNotNull(container, nameof(container)); + + _token = container; + _parent = container; + } + + /// + /// Initializes a new instance of the class. + /// + public JTokenWriter() + { + } + + /// + /// Flushes whatever is in the buffer to the underlying streams and also flushes the underlying stream. + /// + public override void Flush() + { + } + + /// + /// Closes this stream and the underlying stream. + /// + public override void Close() + { + base.Close(); + } + + /// + /// Writes the beginning of a JSON object. + /// + public override void WriteStartObject() + { + base.WriteStartObject(); + + AddParent(new JObject()); + } + + private void AddParent(JContainer container) + { + if (_parent == null) + { + _token = container; + } + else + { + _parent.AddAndSkipParentCheck(container); + } + + _parent = container; + _current = container; + } + + private void RemoveParent() + { + _current = _parent; + _parent = _parent.Parent; + + if (_parent != null && _parent.Type == JTokenType.Property) + { + _parent = _parent.Parent; + } + } + + /// + /// Writes the beginning of a JSON array. + /// + public override void WriteStartArray() + { + base.WriteStartArray(); + + AddParent(new JArray()); + } + + /// + /// Writes the start of a constructor with the given name. + /// + /// The name of the constructor. + public override void WriteStartConstructor(string name) + { + base.WriteStartConstructor(name); + + AddParent(new JConstructor(name)); + } + + /// + /// Writes the end. + /// + /// The token. + protected override void WriteEnd(JsonToken token) + { + RemoveParent(); + } + + /// + /// Writes the property name of a name/value pair on a JSON object. + /// + /// The name of the property. + public override void WritePropertyName(string name) + { + JObject o = _parent as JObject; + if (o != null) + { + // avoid duplicate property name exception + // last property name wins + o.Remove(name); + } + + AddParent(new JProperty(name)); + + // don't set state until after in case of an error + // incorrect state will cause issues if writer is disposed when closing open properties + base.WritePropertyName(name); + } + + private void AddValue(object value, JsonToken token) + { + AddValue(new JValue(value), token); + } + + internal void AddValue(JValue value, JsonToken token) + { + if (_parent != null) + { + _parent.Add(value); + _current = _parent.Last; + + if (_parent.Type == JTokenType.Property) + { + _parent = _parent.Parent; + } + } + else + { + _value = value ?? JValue.CreateNull(); + _current = _value; + } + } + + #region WriteValue methods + /// + /// Writes a value. + /// An error will raised if the value cannot be written as a single JSON token. + /// + /// The value to write. + public override void WriteValue(object value) + { +#if !(NET20 || NET35 || PORTABLE || PORTABLE40) + if (value is BigInteger) + { + InternalWriteValue(JsonToken.Integer); + AddValue(value, JsonToken.Integer); + } + else +#endif + { + base.WriteValue(value); + } + } + + /// + /// Writes a null value. + /// + public override void WriteNull() + { + base.WriteNull(); + AddValue(null, JsonToken.Null); + } + + /// + /// Writes an undefined value. + /// + public override void WriteUndefined() + { + base.WriteUndefined(); + AddValue(null, JsonToken.Undefined); + } + + /// + /// Writes raw JSON. + /// + /// The raw JSON to write. + public override void WriteRaw(string json) + { + base.WriteRaw(json); + AddValue(new JRaw(json), JsonToken.Raw); + } + + /// + /// Writes out a comment /*...*/ containing the specified text. + /// + /// Text to place inside the comment. + public override void WriteComment(string text) + { + base.WriteComment(text); + AddValue(JValue.CreateComment(text), JsonToken.Comment); + } + + /// + /// Writes a value. + /// + /// The value to write. + public override void WriteValue(string value) + { + base.WriteValue(value); + AddValue(value, JsonToken.String); + } + + /// + /// Writes a value. + /// + /// The value to write. + public override void WriteValue(int value) + { + base.WriteValue(value); + AddValue(value, JsonToken.Integer); + } + + /// + /// Writes a value. + /// + /// The value to write. + [CLSCompliant(false)] + public override void WriteValue(uint value) + { + base.WriteValue(value); + AddValue(value, JsonToken.Integer); + } + + /// + /// Writes a value. + /// + /// The value to write. + public override void WriteValue(long value) + { + base.WriteValue(value); + AddValue(value, JsonToken.Integer); + } + + /// + /// Writes a value. + /// + /// The value to write. + [CLSCompliant(false)] + public override void WriteValue(ulong value) + { + base.WriteValue(value); + AddValue(value, JsonToken.Integer); + } + + /// + /// Writes a value. + /// + /// The value to write. + public override void WriteValue(float value) + { + base.WriteValue(value); + AddValue(value, JsonToken.Float); + } + + /// + /// Writes a value. + /// + /// The value to write. + public override void WriteValue(double value) + { + base.WriteValue(value); + AddValue(value, JsonToken.Float); + } + + /// + /// Writes a value. + /// + /// The value to write. + public override void WriteValue(bool value) + { + base.WriteValue(value); + AddValue(value, JsonToken.Boolean); + } + + /// + /// Writes a value. + /// + /// The value to write. + public override void WriteValue(short value) + { + base.WriteValue(value); + AddValue(value, JsonToken.Integer); + } + + /// + /// Writes a value. + /// + /// The value to write. + [CLSCompliant(false)] + public override void WriteValue(ushort value) + { + base.WriteValue(value); + AddValue(value, JsonToken.Integer); + } + + /// + /// Writes a value. + /// + /// The value to write. + public override void WriteValue(char value) + { + base.WriteValue(value); + string s = null; +#if !(DOTNET || PORTABLE40 || PORTABLE) + s = value.ToString(CultureInfo.InvariantCulture); +#else + s = value.ToString(); +#endif + AddValue(s, JsonToken.String); + } + + /// + /// Writes a value. + /// + /// The value to write. + public override void WriteValue(byte value) + { + base.WriteValue(value); + AddValue(value, JsonToken.Integer); + } + + /// + /// Writes a value. + /// + /// The value to write. + [CLSCompliant(false)] + public override void WriteValue(sbyte value) + { + base.WriteValue(value); + AddValue(value, JsonToken.Integer); + } + + /// + /// Writes a value. + /// + /// The value to write. + public override void WriteValue(decimal value) + { + base.WriteValue(value); + AddValue(value, JsonToken.Float); + } + + /// + /// Writes a value. + /// + /// The value to write. + public override void WriteValue(DateTime value) + { + base.WriteValue(value); + value = DateTimeUtils.EnsureDateTime(value, DateTimeZoneHandling); + AddValue(value, JsonToken.Date); + } + +#if !NET20 + /// + /// Writes a value. + /// + /// The value to write. + public override void WriteValue(DateTimeOffset value) + { + base.WriteValue(value); + AddValue(value, JsonToken.Date); + } +#endif + + /// + /// Writes a [] value. + /// + /// The [] value to write. + public override void WriteValue(byte[] value) + { + base.WriteValue(value); + AddValue(value, JsonToken.Bytes); + } + + /// + /// Writes a value. + /// + /// The value to write. + public override void WriteValue(TimeSpan value) + { + base.WriteValue(value); + AddValue(value, JsonToken.String); + } + + /// + /// Writes a value. + /// + /// The value to write. + public override void WriteValue(Guid value) + { + base.WriteValue(value); + AddValue(value, JsonToken.String); + } + + /// + /// Writes a value. + /// + /// The value to write. + public override void WriteValue(Uri value) + { + base.WriteValue(value); + AddValue(value, JsonToken.String); + } + #endregion + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Linq/JValue.cs b/Common/00-1Json8.3/Json8.3/Linq/JValue.cs new file mode 100644 index 0000000..8dd1297 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Linq/JValue.cs @@ -0,0 +1,1186 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Collections.Generic; +using Newtonsoft.Json.Utilities; +using System.Globalization; +#if !(NET35 || NET20 || PORTABLE40) +using System.Dynamic; +using System.Linq.Expressions; +#endif +#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) +using System.Numerics; + +#endif + +namespace Newtonsoft.Json.Linq +{ + /// + /// Represents a value in JSON (string, integer, date, etc). + /// + public class JValue : JToken, IEquatable, IFormattable, IComparable, IComparable +#if !PORTABLE + , IConvertible +#endif + { + private JTokenType _valueType; + private object _value; + + internal JValue(object value, JTokenType type) + { + _value = value; + _valueType = type; + } + + /// + /// Initializes a new instance of the class from another object. + /// + /// A object to copy from. + public JValue(JValue other) + : this(other.Value, other.Type) + { + } + + /// + /// Initializes a new instance of the class with the given value. + /// + /// The value. + public JValue(long value) + : this(value, JTokenType.Integer) + { + } + + /// + /// Initializes a new instance of the class with the given value. + /// + /// The value. + public JValue(decimal value) + : this(value, JTokenType.Float) + { + } + + /// + /// Initializes a new instance of the class with the given value. + /// + /// The value. + public JValue(char value) + : this(value, JTokenType.String) + { + } + + /// + /// Initializes a new instance of the class with the given value. + /// + /// The value. + [CLSCompliant(false)] + public JValue(ulong value) + : this(value, JTokenType.Integer) + { + } + + /// + /// Initializes a new instance of the class with the given value. + /// + /// The value. + public JValue(double value) + : this(value, JTokenType.Float) + { + } + + /// + /// Initializes a new instance of the class with the given value. + /// + /// The value. + public JValue(float value) + : this(value, JTokenType.Float) + { + } + + /// + /// Initializes a new instance of the class with the given value. + /// + /// The value. + public JValue(DateTime value) + : this(value, JTokenType.Date) + { + } + +#if !NET20 + /// + /// Initializes a new instance of the class with the given value. + /// + /// The value. + public JValue(DateTimeOffset value) + : this(value, JTokenType.Date) + { + } +#endif + + /// + /// Initializes a new instance of the class with the given value. + /// + /// The value. + public JValue(bool value) + : this(value, JTokenType.Boolean) + { + } + + /// + /// Initializes a new instance of the class with the given value. + /// + /// The value. + public JValue(string value) + : this(value, JTokenType.String) + { + } + + /// + /// Initializes a new instance of the class with the given value. + /// + /// The value. + public JValue(Guid value) + : this(value, JTokenType.Guid) + { + } + + /// + /// Initializes a new instance of the class with the given value. + /// + /// The value. + public JValue(Uri value) + : this(value, (value != null) ? JTokenType.Uri : JTokenType.Null) + { + } + + /// + /// Initializes a new instance of the class with the given value. + /// + /// The value. + public JValue(TimeSpan value) + : this(value, JTokenType.TimeSpan) + { + } + + /// + /// Initializes a new instance of the class with the given value. + /// + /// The value. + public JValue(object value) + : this(value, GetValueType(null, value)) + { + } + + internal override bool DeepEquals(JToken node) + { + JValue other = node as JValue; + if (other == null) + { + return false; + } + if (other == this) + { + return true; + } + + return ValuesEquals(this, other); + } + + /// + /// Gets a value indicating whether this token has child tokens. + /// + /// + /// true if this token has child values; otherwise, false. + /// + public override bool HasValues + { + get { return false; } + } + +#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) + private static int CompareBigInteger(BigInteger i1, object i2) + { + int result = i1.CompareTo(ConvertUtils.ToBigInteger(i2)); + + if (result != 0) + { + return result; + } + + // converting a fractional number to a BigInteger will lose the fraction + // check for fraction if result is two numbers are equal + if (i2 is decimal) + { + decimal d = (decimal)i2; + return (0m).CompareTo(Math.Abs(d - Math.Truncate(d))); + } + else if (i2 is double || i2 is float) + { + double d = Convert.ToDouble(i2, CultureInfo.InvariantCulture); + return (0d).CompareTo(Math.Abs(d - Math.Truncate(d))); + } + + return result; + } +#endif + + internal static int Compare(JTokenType valueType, object objA, object objB) + { + if (objA == null && objB == null) + { + return 0; + } + if (objA != null && objB == null) + { + return 1; + } + if (objA == null && objB != null) + { + return -1; + } + + switch (valueType) + { + case JTokenType.Integer: +#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) + if (objA is BigInteger) + { + return CompareBigInteger((BigInteger)objA, objB); + } + if (objB is BigInteger) + { + return -CompareBigInteger((BigInteger)objB, objA); + } +#endif + if (objA is ulong || objB is ulong || objA is decimal || objB is decimal) + { + return Convert.ToDecimal(objA, CultureInfo.InvariantCulture).CompareTo(Convert.ToDecimal(objB, CultureInfo.InvariantCulture)); + } + else if (objA is float || objB is float || objA is double || objB is double) + { + return CompareFloat(objA, objB); + } + else + { + return Convert.ToInt64(objA, CultureInfo.InvariantCulture).CompareTo(Convert.ToInt64(objB, CultureInfo.InvariantCulture)); + } + case JTokenType.Float: +#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) + if (objA is BigInteger) + { + return CompareBigInteger((BigInteger)objA, objB); + } + if (objB is BigInteger) + { + return -CompareBigInteger((BigInteger)objB, objA); + } +#endif + return CompareFloat(objA, objB); + case JTokenType.Comment: + case JTokenType.String: + case JTokenType.Raw: + string s1 = Convert.ToString(objA, CultureInfo.InvariantCulture); + string s2 = Convert.ToString(objB, CultureInfo.InvariantCulture); + + return string.CompareOrdinal(s1, s2); + case JTokenType.Boolean: + bool b1 = Convert.ToBoolean(objA, CultureInfo.InvariantCulture); + bool b2 = Convert.ToBoolean(objB, CultureInfo.InvariantCulture); + + return b1.CompareTo(b2); + case JTokenType.Date: +#if !NET20 + if (objA is DateTime) + { +#endif + DateTime date1 = (DateTime)objA; + DateTime date2; + +#if !NET20 + if (objB is DateTimeOffset) + { + date2 = ((DateTimeOffset)objB).DateTime; + } + else +#endif + { + date2 = Convert.ToDateTime(objB, CultureInfo.InvariantCulture); + } + + return date1.CompareTo(date2); +#if !NET20 + } + else + { + DateTimeOffset date1 = (DateTimeOffset)objA; + DateTimeOffset date2; + + if (objB is DateTimeOffset) + { + date2 = (DateTimeOffset)objB; + } + else + { + date2 = new DateTimeOffset(Convert.ToDateTime(objB, CultureInfo.InvariantCulture)); + } + + return date1.CompareTo(date2); + } +#endif + case JTokenType.Bytes: + if (!(objB is byte[])) + { + throw new ArgumentException("Object must be of type byte[]."); + } + + byte[] bytes1 = objA as byte[]; + byte[] bytes2 = objB as byte[]; + if (bytes1 == null) + { + return -1; + } + if (bytes2 == null) + { + return 1; + } + + return MiscellaneousUtils.ByteArrayCompare(bytes1, bytes2); + case JTokenType.Guid: + if (!(objB is Guid)) + { + throw new ArgumentException("Object must be of type Guid."); + } + + Guid guid1 = (Guid)objA; + Guid guid2 = (Guid)objB; + + return guid1.CompareTo(guid2); + case JTokenType.Uri: + if (!(objB is Uri)) + { + throw new ArgumentException("Object must be of type Uri."); + } + + Uri uri1 = (Uri)objA; + Uri uri2 = (Uri)objB; + + return Comparer.Default.Compare(uri1.ToString(), uri2.ToString()); + case JTokenType.TimeSpan: + if (!(objB is TimeSpan)) + { + throw new ArgumentException("Object must be of type TimeSpan."); + } + + TimeSpan ts1 = (TimeSpan)objA; + TimeSpan ts2 = (TimeSpan)objB; + + return ts1.CompareTo(ts2); + default: + throw MiscellaneousUtils.CreateArgumentOutOfRangeException("valueType", valueType, "Unexpected value type: {0}".FormatWith(CultureInfo.InvariantCulture, valueType)); + } + } + + private static int CompareFloat(object objA, object objB) + { + double d1 = Convert.ToDouble(objA, CultureInfo.InvariantCulture); + double d2 = Convert.ToDouble(objB, CultureInfo.InvariantCulture); + + // take into account possible floating point errors + if (MathUtils.ApproxEquals(d1, d2)) + { + return 0; + } + + return d1.CompareTo(d2); + } + +#if !(NET35 || NET20 || PORTABLE40) + private static bool Operation(ExpressionType operation, object objA, object objB, out object result) + { + if (objA is string || objB is string) + { + if (operation == ExpressionType.Add || operation == ExpressionType.AddAssign) + { + result = ((objA != null) ? objA.ToString() : null) + ((objB != null) ? objB.ToString() : null); + return true; + } + } + +#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) + if (objA is BigInteger || objB is BigInteger) + { + if (objA == null || objB == null) + { + result = null; + return true; + } + + // not that this will lose the fraction + // BigInteger doesn't have operators with non-integer types + BigInteger i1 = ConvertUtils.ToBigInteger(objA); + BigInteger i2 = ConvertUtils.ToBigInteger(objB); + + switch (operation) + { + case ExpressionType.Add: + case ExpressionType.AddAssign: + result = i1 + i2; + return true; + case ExpressionType.Subtract: + case ExpressionType.SubtractAssign: + result = i1 - i2; + return true; + case ExpressionType.Multiply: + case ExpressionType.MultiplyAssign: + result = i1 * i2; + return true; + case ExpressionType.Divide: + case ExpressionType.DivideAssign: + result = i1 / i2; + return true; + } + } + else +#endif + if (objA is ulong || objB is ulong || objA is decimal || objB is decimal) + { + if (objA == null || objB == null) + { + result = null; + return true; + } + + decimal d1 = Convert.ToDecimal(objA, CultureInfo.InvariantCulture); + decimal d2 = Convert.ToDecimal(objB, CultureInfo.InvariantCulture); + + switch (operation) + { + case ExpressionType.Add: + case ExpressionType.AddAssign: + result = d1 + d2; + return true; + case ExpressionType.Subtract: + case ExpressionType.SubtractAssign: + result = d1 - d2; + return true; + case ExpressionType.Multiply: + case ExpressionType.MultiplyAssign: + result = d1 * d2; + return true; + case ExpressionType.Divide: + case ExpressionType.DivideAssign: + result = d1 / d2; + return true; + } + } + else if (objA is float || objB is float || objA is double || objB is double) + { + if (objA == null || objB == null) + { + result = null; + return true; + } + + double d1 = Convert.ToDouble(objA, CultureInfo.InvariantCulture); + double d2 = Convert.ToDouble(objB, CultureInfo.InvariantCulture); + + switch (operation) + { + case ExpressionType.Add: + case ExpressionType.AddAssign: + result = d1 + d2; + return true; + case ExpressionType.Subtract: + case ExpressionType.SubtractAssign: + result = d1 - d2; + return true; + case ExpressionType.Multiply: + case ExpressionType.MultiplyAssign: + result = d1 * d2; + return true; + case ExpressionType.Divide: + case ExpressionType.DivideAssign: + result = d1 / d2; + return true; + } + } + else if (objA is int || objA is uint || objA is long || objA is short || objA is ushort || objA is sbyte || objA is byte || + objB is int || objB is uint || objB is long || objB is short || objB is ushort || objB is sbyte || objB is byte) + { + if (objA == null || objB == null) + { + result = null; + return true; + } + + long l1 = Convert.ToInt64(objA, CultureInfo.InvariantCulture); + long l2 = Convert.ToInt64(objB, CultureInfo.InvariantCulture); + + switch (operation) + { + case ExpressionType.Add: + case ExpressionType.AddAssign: + result = l1 + l2; + return true; + case ExpressionType.Subtract: + case ExpressionType.SubtractAssign: + result = l1 - l2; + return true; + case ExpressionType.Multiply: + case ExpressionType.MultiplyAssign: + result = l1 * l2; + return true; + case ExpressionType.Divide: + case ExpressionType.DivideAssign: + result = l1 / l2; + return true; + } + } + + result = null; + return false; + } +#endif + + internal override JToken CloneToken() + { + return new JValue(this); + } + + /// + /// Creates a comment with the given value. + /// + /// The value. + /// A comment with the given value. + public static JValue CreateComment(string value) + { + return new JValue(value, JTokenType.Comment); + } + + /// + /// Creates a string with the given value. + /// + /// The value. + /// A string with the given value. + public static JValue CreateString(string value) + { + return new JValue(value, JTokenType.String); + } + + /// + /// Creates a null value. + /// + /// A null value. + public static JValue CreateNull() + { + return new JValue(null, JTokenType.Null); + } + + /// + /// Creates a undefined value. + /// + /// A undefined value. + public static JValue CreateUndefined() + { + return new JValue(null, JTokenType.Undefined); + } + + private static JTokenType GetValueType(JTokenType? current, object value) + { + if (value == null) + { + return JTokenType.Null; + } +#if !(DOTNET || PORTABLE40 || PORTABLE) + else if (value == DBNull.Value) + { + return JTokenType.Null; + } +#endif + else if (value is string) + { + return GetStringValueType(current); + } + else if (value is long || value is int || value is short || value is sbyte + || value is ulong || value is uint || value is ushort || value is byte) + { + return JTokenType.Integer; + } + else if (value is Enum) + { + return JTokenType.Integer; + } +#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) + else if (value is BigInteger) + { + return JTokenType.Integer; + } +#endif + else if (value is double || value is float || value is decimal) + { + return JTokenType.Float; + } + else if (value is DateTime) + { + return JTokenType.Date; + } +#if !NET20 + else if (value is DateTimeOffset) + { + return JTokenType.Date; + } +#endif + else if (value is byte[]) + { + return JTokenType.Bytes; + } + else if (value is bool) + { + return JTokenType.Boolean; + } + else if (value is Guid) + { + return JTokenType.Guid; + } + else if (value is Uri) + { + return JTokenType.Uri; + } + else if (value is TimeSpan) + { + return JTokenType.TimeSpan; + } + + throw new ArgumentException("Could not determine JSON object type for type {0}.".FormatWith(CultureInfo.InvariantCulture, value.GetType())); + } + + private static JTokenType GetStringValueType(JTokenType? current) + { + if (current == null) + { + return JTokenType.String; + } + + switch (current.GetValueOrDefault()) + { + case JTokenType.Comment: + case JTokenType.String: + case JTokenType.Raw: + return current.GetValueOrDefault(); + default: + return JTokenType.String; + } + } + + /// + /// Gets the node type for this . + /// + /// The type. + public override JTokenType Type + { + get { return _valueType; } + } + + /// + /// Gets or sets the underlying token value. + /// + /// The underlying token value. + public object Value + { + get { return _value; } + set + { + Type currentType = (_value != null) ? _value.GetType() : null; + Type newType = (value != null) ? value.GetType() : null; + + if (currentType != newType) + { + _valueType = GetValueType(_valueType, value); + } + + _value = value; + } + } + + /// + /// Writes this token to a . + /// + /// A into which this method will write. + /// A collection of which will be used when writing the token. + public override void WriteTo(JsonWriter writer, params JsonConverter[] converters) + { + if (converters != null && converters.Length > 0 && _value != null) + { + JsonConverter matchingConverter = JsonSerializer.GetMatchingConverter(converters, _value.GetType()); + if (matchingConverter != null && matchingConverter.CanWrite) + { + matchingConverter.WriteJson(writer, _value, JsonSerializer.CreateDefault()); + return; + } + } + + switch (_valueType) + { + case JTokenType.Comment: + writer.WriteComment((_value != null) ? _value.ToString() : null); + return; + case JTokenType.Raw: + writer.WriteRawValue((_value != null) ? _value.ToString() : null); + return; + case JTokenType.Null: + writer.WriteNull(); + return; + case JTokenType.Undefined: + writer.WriteUndefined(); + return; + case JTokenType.Integer: + if (_value is int) + { + writer.WriteValue((int)_value); + } + else if (_value is long) + { + writer.WriteValue((long)_value); + } + else if (_value is ulong) + { + writer.WriteValue((ulong)_value); + } +#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) + else if (_value is BigInteger) + { + writer.WriteValue((BigInteger)_value); + } +#endif + else + { + writer.WriteValue(Convert.ToInt64(_value, CultureInfo.InvariantCulture)); + } + return; + case JTokenType.Float: + if (_value is decimal) + { + writer.WriteValue((decimal)_value); + } + else if (_value is double) + { + writer.WriteValue((double)_value); + } + else if (_value is float) + { + writer.WriteValue((float)_value); + } + else + { + writer.WriteValue(Convert.ToDouble(_value, CultureInfo.InvariantCulture)); + } + return; + case JTokenType.String: + writer.WriteValue((_value != null) ? _value.ToString() : null); + return; + case JTokenType.Boolean: + writer.WriteValue(Convert.ToBoolean(_value, CultureInfo.InvariantCulture)); + return; + case JTokenType.Date: +#if !NET20 + if (_value is DateTimeOffset) + { + writer.WriteValue((DateTimeOffset)_value); + } + else +#endif + { + writer.WriteValue(Convert.ToDateTime(_value, CultureInfo.InvariantCulture)); + } + return; + case JTokenType.Bytes: + writer.WriteValue((byte[])_value); + return; + case JTokenType.Guid: + case JTokenType.TimeSpan: + writer.WriteValue((_value != null) ? _value.ToString() : null); + return; + case JTokenType.Uri: + writer.WriteValue((_value != null) ? ((Uri)_value).OriginalString : null); + return; + } + + throw MiscellaneousUtils.CreateArgumentOutOfRangeException("TokenType", _valueType, "Unexpected token type."); + } + + internal override int GetDeepHashCode() + { + int valueHashCode = (_value != null) ? _value.GetHashCode() : 0; + + // GetHashCode on an enum boxes so cast to int + return ((int)_valueType).GetHashCode() ^ valueHashCode; + } + + private static bool ValuesEquals(JValue v1, JValue v2) + { + return (v1 == v2 || (v1._valueType == v2._valueType && Compare(v1._valueType, v1._value, v2._value) == 0)); + } + + /// + /// Indicates whether the current object is equal to another object of the same type. + /// + /// + /// true if the current object is equal to the parameter; otherwise, false. + /// + /// An object to compare with this object. + public bool Equals(JValue other) + { + if (other == null) + { + return false; + } + + return ValuesEquals(this, other); + } + + /// + /// Determines whether the specified is equal to the current . + /// + /// The to compare with the current . + /// + /// true if the specified is equal to the current ; otherwise, false. + /// + /// + /// The parameter is null. + /// + public override bool Equals(object obj) + { + if (obj == null) + { + return false; + } + + JValue otherValue = obj as JValue; + if (otherValue != null) + { + return Equals(otherValue); + } + + return base.Equals(obj); + } + + /// + /// Serves as a hash function for a particular type. + /// + /// + /// A hash code for the current . + /// + public override int GetHashCode() + { + if (_value == null) + { + return 0; + } + + return _value.GetHashCode(); + } + + /// + /// Returns a that represents this instance. + /// + /// + /// A that represents this instance. + /// + public override string ToString() + { + if (_value == null) + { + return string.Empty; + } + + return _value.ToString(); + } + + /// + /// Returns a that represents this instance. + /// + /// The format. + /// + /// A that represents this instance. + /// + public string ToString(string format) + { + return ToString(format, CultureInfo.CurrentCulture); + } + + /// + /// Returns a that represents this instance. + /// + /// The format provider. + /// + /// A that represents this instance. + /// + public string ToString(IFormatProvider formatProvider) + { + return ToString(null, formatProvider); + } + + /// + /// Returns a that represents this instance. + /// + /// The format. + /// The format provider. + /// + /// A that represents this instance. + /// + public string ToString(string format, IFormatProvider formatProvider) + { + if (_value == null) + { + return string.Empty; + } + + IFormattable formattable = _value as IFormattable; + if (formattable != null) + { + return formattable.ToString(format, formatProvider); + } + else + { + return _value.ToString(); + } + } + +#if !(NET35 || NET20 || PORTABLE40) + /// + /// Returns the responsible for binding operations performed on this object. + /// + /// The expression tree representation of the runtime value. + /// + /// The to bind this object. + /// + protected override DynamicMetaObject GetMetaObject(Expression parameter) + { + return new DynamicProxyMetaObject(parameter, this, new JValueDynamicProxy(), true); + } + + private class JValueDynamicProxy : DynamicProxy + { + public override bool TryConvert(JValue instance, ConvertBinder binder, out object result) + { + if (binder.Type == typeof(JValue) || binder.Type == typeof(JToken)) + { + result = instance; + return true; + } + + object value = instance.Value; + + if (value == null) + { + result = null; + return ReflectionUtils.IsNullable(binder.Type); + } + + result = ConvertUtils.Convert(value, CultureInfo.InvariantCulture, binder.Type); + return true; + } + + public override bool TryBinaryOperation(JValue instance, BinaryOperationBinder binder, object arg, out object result) + { + object compareValue = (arg is JValue) ? ((JValue)arg).Value : arg; + + switch (binder.Operation) + { + case ExpressionType.Equal: + result = (Compare(instance.Type, instance.Value, compareValue) == 0); + return true; + case ExpressionType.NotEqual: + result = (Compare(instance.Type, instance.Value, compareValue) != 0); + return true; + case ExpressionType.GreaterThan: + result = (Compare(instance.Type, instance.Value, compareValue) > 0); + return true; + case ExpressionType.GreaterThanOrEqual: + result = (Compare(instance.Type, instance.Value, compareValue) >= 0); + return true; + case ExpressionType.LessThan: + result = (Compare(instance.Type, instance.Value, compareValue) < 0); + return true; + case ExpressionType.LessThanOrEqual: + result = (Compare(instance.Type, instance.Value, compareValue) <= 0); + return true; + case ExpressionType.Add: + case ExpressionType.AddAssign: + case ExpressionType.Subtract: + case ExpressionType.SubtractAssign: + case ExpressionType.Multiply: + case ExpressionType.MultiplyAssign: + case ExpressionType.Divide: + case ExpressionType.DivideAssign: + if (Operation(binder.Operation, instance.Value, compareValue, out result)) + { + result = new JValue(result); + return true; + } + break; + } + + result = null; + return false; + } + } +#endif + + int IComparable.CompareTo(object obj) + { + if (obj == null) + { + return 1; + } + + object otherValue = (obj is JValue) ? ((JValue)obj).Value : obj; + + return Compare(_valueType, _value, otherValue); + } + + /// + /// Compares the current instance with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other object. + /// + /// An object to compare with this instance. + /// + /// A 32-bit signed integer that indicates the relative order of the objects being compared. The return value has these meanings: + /// Value + /// Meaning + /// Less than zero + /// This instance is less than . + /// Zero + /// This instance is equal to . + /// Greater than zero + /// This instance is greater than . + /// + /// + /// is not the same type as this instance. + /// + public int CompareTo(JValue obj) + { + if (obj == null) + { + return 1; + } + + return Compare(_valueType, _value, obj._value); + } + +#if !PORTABLE + TypeCode IConvertible.GetTypeCode() + { + if (_value == null) + { + return TypeCode.Empty; + } + + IConvertible convertable = _value as IConvertible; + + if (convertable == null) + { + return TypeCode.Object; + } + + return convertable.GetTypeCode(); + } + + bool IConvertible.ToBoolean(IFormatProvider provider) + { + return (bool)this; + } + + char IConvertible.ToChar(IFormatProvider provider) + { + return (char)this; + } + + sbyte IConvertible.ToSByte(IFormatProvider provider) + { + return (sbyte)this; + } + + byte IConvertible.ToByte(IFormatProvider provider) + { + return (byte)this; + } + + short IConvertible.ToInt16(IFormatProvider provider) + { + return (short)this; + } + + ushort IConvertible.ToUInt16(IFormatProvider provider) + { + return (ushort)this; + } + + int IConvertible.ToInt32(IFormatProvider provider) + { + return (int)this; + } + + uint IConvertible.ToUInt32(IFormatProvider provider) + { + return (uint)this; + } + + long IConvertible.ToInt64(IFormatProvider provider) + { + return (long)this; + } + + ulong IConvertible.ToUInt64(IFormatProvider provider) + { + return (ulong)this; + } + + float IConvertible.ToSingle(IFormatProvider provider) + { + return (float)this; + } + + double IConvertible.ToDouble(IFormatProvider provider) + { + return (double)this; + } + + decimal IConvertible.ToDecimal(IFormatProvider provider) + { + return (decimal)this; + } + + DateTime IConvertible.ToDateTime(IFormatProvider provider) + { + return (DateTime)this; + } + + object IConvertible.ToType(Type conversionType, IFormatProvider provider) + { + return ToObject(conversionType); + } +#endif + } +} diff --git a/Common/00-1Json8.3/Json8.3/Linq/JsonLoadSettings.cs b/Common/00-1Json8.3/Json8.3/Linq/JsonLoadSettings.cs new file mode 100644 index 0000000..5f2e70f --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Linq/JsonLoadSettings.cs @@ -0,0 +1,49 @@ +using System; + +namespace Newtonsoft.Json.Linq +{ + /// + /// Specifies the settings used when loading JSON. + /// + public class JsonLoadSettings + { + private CommentHandling _commentHandling; + private LineInfoHandling _lineInfoHandling; + + /// + /// Gets or sets how JSON comments are handled when loading JSON. + /// + /// The JSON comment handling. + public CommentHandling CommentHandling + { + get { return _commentHandling; } + set + { + if (value < CommentHandling.Ignore || value > CommentHandling.Load) + { + throw new ArgumentOutOfRangeException(nameof(value)); + } + + _commentHandling = value; + } + } + + /// + /// Gets or sets how JSON line info is handled when loading JSON. + /// + /// The JSON line info handling. + public LineInfoHandling LineInfoHandling + { + get { return _lineInfoHandling; } + set + { + if (value < LineInfoHandling.Ignore || value > LineInfoHandling.Load) + { + throw new ArgumentOutOfRangeException(nameof(value)); + } + + _lineInfoHandling = value; + } + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Linq/JsonMergeSettings.cs b/Common/00-1Json8.3/Json8.3/Linq/JsonMergeSettings.cs new file mode 100644 index 0000000..9542095 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Linq/JsonMergeSettings.cs @@ -0,0 +1,49 @@ +using System; + +namespace Newtonsoft.Json.Linq +{ + /// + /// Specifies the settings used when merging JSON. + /// + public class JsonMergeSettings + { + private MergeArrayHandling _mergeArrayHandling; + private MergeNullValueHandling _mergeNullValueHandling; + + /// + /// Gets or sets the method used when merging JSON arrays. + /// + /// The method used when merging JSON arrays. + public MergeArrayHandling MergeArrayHandling + { + get { return _mergeArrayHandling; } + set + { + if (value < MergeArrayHandling.Concat || value > MergeArrayHandling.Merge) + { + throw new ArgumentOutOfRangeException(nameof(value)); + } + + _mergeArrayHandling = value; + } + } + + /// + /// Gets or sets how how null value properties are merged. + /// + /// How null value properties are merged. + public MergeNullValueHandling MergeNullValueHandling + { + get { return _mergeNullValueHandling; } + set + { + if (value < MergeNullValueHandling.Ignore || value > MergeNullValueHandling.Merge) + { + throw new ArgumentOutOfRangeException(nameof(value)); + } + + _mergeNullValueHandling = value; + } + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Linq/JsonPath/ArrayIndexFilter.cs b/Common/00-1Json8.3/Json8.3/Linq/JsonPath/ArrayIndexFilter.cs new file mode 100644 index 0000000..05537a4 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Linq/JsonPath/ArrayIndexFilter.cs @@ -0,0 +1,44 @@ +using System.Collections.Generic; +using System.Globalization; +using Newtonsoft.Json.Utilities; + +namespace Newtonsoft.Json.Linq.JsonPath +{ + internal class ArrayIndexFilter : PathFilter + { + public int? Index { get; set; } + + public override IEnumerable ExecuteFilter(IEnumerable current, bool errorWhenNoMatch) + { + foreach (JToken t in current) + { + if (Index != null) + { + JToken v = GetTokenIndex(t, errorWhenNoMatch, Index.GetValueOrDefault()); + + if (v != null) + { + yield return v; + } + } + else + { + if (t is JArray || t is JConstructor) + { + foreach (JToken v in t) + { + yield return v; + } + } + else + { + if (errorWhenNoMatch) + { + throw new JsonException("Index * not valid on {0}.".FormatWith(CultureInfo.InvariantCulture, t.GetType().Name)); + } + } + } + } + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Linq/JsonPath/ArrayMultipleIndexFilter.cs b/Common/00-1Json8.3/Json8.3/Linq/JsonPath/ArrayMultipleIndexFilter.cs new file mode 100644 index 0000000..81d64e3 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Linq/JsonPath/ArrayMultipleIndexFilter.cs @@ -0,0 +1,25 @@ +using System.Collections.Generic; + +namespace Newtonsoft.Json.Linq.JsonPath +{ + internal class ArrayMultipleIndexFilter : PathFilter + { + public List Indexes { get; set; } + + public override IEnumerable ExecuteFilter(IEnumerable current, bool errorWhenNoMatch) + { + foreach (JToken t in current) + { + foreach (int i in Indexes) + { + JToken v = GetTokenIndex(t, errorWhenNoMatch, i); + + if (v != null) + { + yield return v; + } + } + } + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Linq/JsonPath/ArraySliceFilter.cs b/Common/00-1Json8.3/Json8.3/Linq/JsonPath/ArraySliceFilter.cs new file mode 100644 index 0000000..65139d2 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Linq/JsonPath/ArraySliceFilter.cs @@ -0,0 +1,88 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using Newtonsoft.Json.Utilities; + +namespace Newtonsoft.Json.Linq.JsonPath +{ + internal class ArraySliceFilter : PathFilter + { + public int? Start { get; set; } + public int? End { get; set; } + public int? Step { get; set; } + + public override IEnumerable ExecuteFilter(IEnumerable current, bool errorWhenNoMatch) + { + if (Step == 0) + { + throw new JsonException("Step cannot be zero."); + } + + foreach (JToken t in current) + { + JArray a = t as JArray; + if (a != null) + { + // set defaults for null arguments + int stepCount = Step ?? 1; + int startIndex = Start ?? ((stepCount > 0) ? 0 : a.Count - 1); + int stopIndex = End ?? ((stepCount > 0) ? a.Count : -1); + + // start from the end of the list if start is negitive + if (Start < 0) + { + startIndex = a.Count + startIndex; + } + + // end from the start of the list if stop is negitive + if (End < 0) + { + stopIndex = a.Count + stopIndex; + } + + // ensure indexes keep within collection bounds + startIndex = Math.Max(startIndex, (stepCount > 0) ? 0 : int.MinValue); + startIndex = Math.Min(startIndex, (stepCount > 0) ? a.Count : a.Count - 1); + stopIndex = Math.Max(stopIndex, -1); + stopIndex = Math.Min(stopIndex, a.Count); + + bool positiveStep = (stepCount > 0); + + if (IsValid(startIndex, stopIndex, positiveStep)) + { + for (int i = startIndex; IsValid(i, stopIndex, positiveStep); i += stepCount) + { + yield return a[i]; + } + } + else + { + if (errorWhenNoMatch) + { + throw new JsonException("Array slice of {0} to {1} returned no results.".FormatWith(CultureInfo.InvariantCulture, + Start != null ? Start.GetValueOrDefault().ToString(CultureInfo.InvariantCulture) : "*", + End != null ? End.GetValueOrDefault().ToString(CultureInfo.InvariantCulture) : "*")); + } + } + } + else + { + if (errorWhenNoMatch) + { + throw new JsonException("Array slice is not valid on {0}.".FormatWith(CultureInfo.InvariantCulture, t.GetType().Name)); + } + } + } + } + + private bool IsValid(int index, int stopIndex, bool positiveStep) + { + if (positiveStep) + { + return (index < stopIndex); + } + + return (index > stopIndex); + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Linq/JsonPath/FieldFilter.cs b/Common/00-1Json8.3/Json8.3/Linq/JsonPath/FieldFilter.cs new file mode 100644 index 0000000..e349466 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Linq/JsonPath/FieldFilter.cs @@ -0,0 +1,49 @@ +using System.Collections.Generic; +using System.Globalization; +using Newtonsoft.Json.Utilities; + +namespace Newtonsoft.Json.Linq.JsonPath +{ + internal class FieldFilter : PathFilter + { + public string Name { get; set; } + + public override IEnumerable ExecuteFilter(IEnumerable current, bool errorWhenNoMatch) + { + foreach (JToken t in current) + { + JObject o = t as JObject; + if (o != null) + { + if (Name != null) + { + JToken v = o[Name]; + + if (v != null) + { + yield return v; + } + else if (errorWhenNoMatch) + { + throw new JsonException("Property '{0}' does not exist on JObject.".FormatWith(CultureInfo.InvariantCulture, Name)); + } + } + else + { + foreach (KeyValuePair p in o) + { + yield return p.Value; + } + } + } + else + { + if (errorWhenNoMatch) + { + throw new JsonException("Property '{0}' not valid on {1}.".FormatWith(CultureInfo.InvariantCulture, Name ?? "*", t.GetType().Name)); + } + } + } + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Linq/JsonPath/FieldMultipleFilter.cs b/Common/00-1Json8.3/Json8.3/Linq/JsonPath/FieldMultipleFilter.cs new file mode 100644 index 0000000..940818a --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Linq/JsonPath/FieldMultipleFilter.cs @@ -0,0 +1,48 @@ +using System.Collections.Generic; +using System.Globalization; +#if NET20 +using Newtonsoft.Json.Utilities.LinqBridge; +#else +using System.Linq; +#endif +using Newtonsoft.Json.Utilities; + +namespace Newtonsoft.Json.Linq.JsonPath +{ + internal class FieldMultipleFilter : PathFilter + { + public List Names { get; set; } + + public override IEnumerable ExecuteFilter(IEnumerable current, bool errorWhenNoMatch) + { + foreach (JToken t in current) + { + JObject o = t as JObject; + if (o != null) + { + foreach (string name in Names) + { + JToken v = o[name]; + + if (v != null) + { + yield return v; + } + + if (errorWhenNoMatch) + { + throw new JsonException("Property '{0}' does not exist on JObject.".FormatWith(CultureInfo.InvariantCulture, name)); + } + } + } + else + { + if (errorWhenNoMatch) + { + throw new JsonException("Properties {0} not valid on {1}.".FormatWith(CultureInfo.InvariantCulture, string.Join(", ", Names.Select(n => "'" + n + "'").ToArray()), t.GetType().Name)); + } + } + } + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Linq/JsonPath/JPath.cs b/Common/00-1Json8.3/Json8.3/Linq/JsonPath/JPath.cs new file mode 100644 index 0000000..a8346a1 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Linq/JsonPath/JPath.cs @@ -0,0 +1,777 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Text; +using Newtonsoft.Json.Utilities; + +namespace Newtonsoft.Json.Linq.JsonPath +{ + internal class JPath + { + private readonly string _expression; + public List Filters { get; private set; } + + private int _currentIndex; + + public JPath(string expression) + { + ValidationUtils.ArgumentNotNull(expression, nameof(expression)); + _expression = expression; + Filters = new List(); + + ParseMain(); + } + + private void ParseMain() + { + int currentPartStartIndex = _currentIndex; + + EatWhitespace(); + + if (_expression.Length == _currentIndex) + { + return; + } + + if (_expression[_currentIndex] == '$') + { + if (_expression.Length == 1) + { + return; + } + + // only increment position for "$." or "$[" + // otherwise assume property that starts with $ + char c = _expression[_currentIndex + 1]; + if (c == '.' || c == '[') + { + _currentIndex++; + currentPartStartIndex = _currentIndex; + } + } + + if (!ParsePath(Filters, currentPartStartIndex, false)) + { + int lastCharacterIndex = _currentIndex; + + EatWhitespace(); + + if (_currentIndex < _expression.Length) + { + throw new JsonException("Unexpected character while parsing path: " + _expression[lastCharacterIndex]); + } + } + } + + private bool ParsePath(List filters, int currentPartStartIndex, bool query) + { + bool scan = false; + bool followingIndexer = false; + bool followingDot = false; + + bool ended = false; + while (_currentIndex < _expression.Length && !ended) + { + char currentChar = _expression[_currentIndex]; + + switch (currentChar) + { + case '[': + case '(': + if (_currentIndex > currentPartStartIndex) + { + string member = _expression.Substring(currentPartStartIndex, _currentIndex - currentPartStartIndex); + if (member == "*") + { + member = null; + } + + PathFilter filter = (scan) ? (PathFilter)new ScanFilter { Name = member } : new FieldFilter { Name = member }; + filters.Add(filter); + scan = false; + } + + filters.Add(ParseIndexer(currentChar)); + _currentIndex++; + currentPartStartIndex = _currentIndex; + followingIndexer = true; + followingDot = false; + break; + case ']': + case ')': + ended = true; + break; + case ' ': + if (_currentIndex < _expression.Length) + { + ended = true; + } + break; + case '.': + if (_currentIndex > currentPartStartIndex) + { + string member = _expression.Substring(currentPartStartIndex, _currentIndex - currentPartStartIndex); + if (member == "*") + { + member = null; + } + + PathFilter filter = (scan) ? (PathFilter)new ScanFilter { Name = member } : new FieldFilter { Name = member }; + filters.Add(filter); + scan = false; + } + if (_currentIndex + 1 < _expression.Length && _expression[_currentIndex + 1] == '.') + { + scan = true; + _currentIndex++; + } + _currentIndex++; + currentPartStartIndex = _currentIndex; + followingIndexer = false; + followingDot = true; + break; + default: + if (query && (currentChar == '=' || currentChar == '<' || currentChar == '!' || currentChar == '>' || currentChar == '|' || currentChar == '&')) + { + ended = true; + } + else + { + if (followingIndexer) + { + throw new JsonException("Unexpected character following indexer: " + currentChar); + } + + _currentIndex++; + } + break; + } + } + + bool atPathEnd = (_currentIndex == _expression.Length); + + if (_currentIndex > currentPartStartIndex) + { + string member = _expression.Substring(currentPartStartIndex, _currentIndex - currentPartStartIndex).TrimEnd(); + if (member == "*") + { + member = null; + } + PathFilter filter = (scan) ? (PathFilter)new ScanFilter { Name = member } : new FieldFilter { Name = member }; + filters.Add(filter); + } + else + { + // no field name following dot in path and at end of base path/query + if (followingDot && (atPathEnd || query)) + { + throw new JsonException("Unexpected end while parsing path."); + } + } + + return atPathEnd; + } + + private PathFilter ParseIndexer(char indexerOpenChar) + { + _currentIndex++; + + char indexerCloseChar = (indexerOpenChar == '[') ? ']' : ')'; + + EnsureLength("Path ended with open indexer."); + + EatWhitespace(); + + if (_expression[_currentIndex] == '\'') + { + return ParseQuotedField(indexerCloseChar); + } + else if (_expression[_currentIndex] == '?') + { + return ParseQuery(indexerCloseChar); + } + else + { + return ParseArrayIndexer(indexerCloseChar); + } + } + + private PathFilter ParseArrayIndexer(char indexerCloseChar) + { + int start = _currentIndex; + int? end = null; + List indexes = null; + int colonCount = 0; + int? startIndex = null; + int? endIndex = null; + int? step = null; + + while (_currentIndex < _expression.Length) + { + char currentCharacter = _expression[_currentIndex]; + + if (currentCharacter == ' ') + { + end = _currentIndex; + EatWhitespace(); + continue; + } + + if (currentCharacter == indexerCloseChar) + { + int length = (end ?? _currentIndex) - start; + + if (indexes != null) + { + if (length == 0) + { + throw new JsonException("Array index expected."); + } + + string indexer = _expression.Substring(start, length); + int index = Convert.ToInt32(indexer, CultureInfo.InvariantCulture); + + indexes.Add(index); + return new ArrayMultipleIndexFilter { Indexes = indexes }; + } + else if (colonCount > 0) + { + if (length > 0) + { + string indexer = _expression.Substring(start, length); + int index = Convert.ToInt32(indexer, CultureInfo.InvariantCulture); + + if (colonCount == 1) + { + endIndex = index; + } + else + { + step = index; + } + } + + return new ArraySliceFilter { Start = startIndex, End = endIndex, Step = step }; + } + else + { + if (length == 0) + { + throw new JsonException("Array index expected."); + } + + string indexer = _expression.Substring(start, length); + int index = Convert.ToInt32(indexer, CultureInfo.InvariantCulture); + + return new ArrayIndexFilter { Index = index }; + } + } + else if (currentCharacter == ',') + { + int length = (end ?? _currentIndex) - start; + + if (length == 0) + { + throw new JsonException("Array index expected."); + } + + if (indexes == null) + { + indexes = new List(); + } + + string indexer = _expression.Substring(start, length); + indexes.Add(Convert.ToInt32(indexer, CultureInfo.InvariantCulture)); + + _currentIndex++; + + EatWhitespace(); + + start = _currentIndex; + end = null; + } + else if (currentCharacter == '*') + { + _currentIndex++; + EnsureLength("Path ended with open indexer."); + EatWhitespace(); + + if (_expression[_currentIndex] != indexerCloseChar) + { + throw new JsonException("Unexpected character while parsing path indexer: " + currentCharacter); + } + + return new ArrayIndexFilter(); + } + else if (currentCharacter == ':') + { + int length = (end ?? _currentIndex) - start; + + if (length > 0) + { + string indexer = _expression.Substring(start, length); + int index = Convert.ToInt32(indexer, CultureInfo.InvariantCulture); + + if (colonCount == 0) + { + startIndex = index; + } + else if (colonCount == 1) + { + endIndex = index; + } + else + { + step = index; + } + } + + colonCount++; + + _currentIndex++; + + EatWhitespace(); + + start = _currentIndex; + end = null; + } + else if (!char.IsDigit(currentCharacter) && currentCharacter != '-') + { + throw new JsonException("Unexpected character while parsing path indexer: " + currentCharacter); + } + else + { + if (end != null) + { + throw new JsonException("Unexpected character while parsing path indexer: " + currentCharacter); + } + + _currentIndex++; + } + } + + throw new JsonException("Path ended with open indexer."); + } + + private void EatWhitespace() + { + while (_currentIndex < _expression.Length) + { + if (_expression[_currentIndex] != ' ') + { + break; + } + + _currentIndex++; + } + } + + private PathFilter ParseQuery(char indexerCloseChar) + { + _currentIndex++; + EnsureLength("Path ended with open indexer."); + + if (_expression[_currentIndex] != '(') + { + throw new JsonException("Unexpected character while parsing path indexer: " + _expression[_currentIndex]); + } + + _currentIndex++; + + QueryExpression expression = ParseExpression(); + + _currentIndex++; + EnsureLength("Path ended with open indexer."); + EatWhitespace(); + + if (_expression[_currentIndex] != indexerCloseChar) + { + throw new JsonException("Unexpected character while parsing path indexer: " + _expression[_currentIndex]); + } + + return new QueryFilter + { + Expression = expression + }; + } + + private QueryExpression ParseExpression() + { + QueryExpression rootExpression = null; + CompositeExpression parentExpression = null; + + while (_currentIndex < _expression.Length) + { + EatWhitespace(); + + if (_expression[_currentIndex] != '@') + { + throw new JsonException("Unexpected character while parsing path query: " + _expression[_currentIndex]); + } + + _currentIndex++; + + List expressionPath = new List(); + + if (ParsePath(expressionPath, _currentIndex, true)) + { + throw new JsonException("Path ended with open query."); + } + + EatWhitespace(); + EnsureLength("Path ended with open query."); + + QueryOperator op; + object value = null; + if (_expression[_currentIndex] == ')' + || _expression[_currentIndex] == '|' + || _expression[_currentIndex] == '&') + { + op = QueryOperator.Exists; + } + else + { + op = ParseOperator(); + + EatWhitespace(); + EnsureLength("Path ended with open query."); + + value = ParseValue(); + + EatWhitespace(); + EnsureLength("Path ended with open query."); + } + + BooleanQueryExpression booleanExpression = new BooleanQueryExpression + { + Path = expressionPath, + Operator = op, + Value = (op != QueryOperator.Exists) ? new JValue(value) : null + }; + + if (_expression[_currentIndex] == ')') + { + if (parentExpression != null) + { + parentExpression.Expressions.Add(booleanExpression); + return rootExpression; + } + + return booleanExpression; + } + if (_expression[_currentIndex] == '&' && Match("&&")) + { + if (parentExpression == null || parentExpression.Operator != QueryOperator.And) + { + CompositeExpression andExpression = new CompositeExpression { Operator = QueryOperator.And }; + + if (parentExpression != null) + { + parentExpression.Expressions.Add(andExpression); + } + + parentExpression = andExpression; + + if (rootExpression == null) + { + rootExpression = parentExpression; + } + } + + parentExpression.Expressions.Add(booleanExpression); + } + if (_expression[_currentIndex] == '|' && Match("||")) + { + if (parentExpression == null || parentExpression.Operator != QueryOperator.Or) + { + CompositeExpression orExpression = new CompositeExpression { Operator = QueryOperator.Or }; + + if (parentExpression != null) + { + parentExpression.Expressions.Add(orExpression); + } + + parentExpression = orExpression; + + if (rootExpression == null) + { + rootExpression = parentExpression; + } + } + + parentExpression.Expressions.Add(booleanExpression); + } + } + + throw new JsonException("Path ended with open query."); + } + + private object ParseValue() + { + char currentChar = _expression[_currentIndex]; + if (currentChar == '\'') + { + return ReadQuotedString(); + } + else if (char.IsDigit(currentChar) || currentChar == '-') + { + StringBuilder sb = new StringBuilder(); + sb.Append(currentChar); + + _currentIndex++; + while (_currentIndex < _expression.Length) + { + currentChar = _expression[_currentIndex]; + if (currentChar == ' ' || currentChar == ')') + { + string numberText = sb.ToString(); + + if (numberText.IndexOfAny(new char[] { '.', 'E', 'e' }) != -1) + { + double d; + if (double.TryParse(numberText, NumberStyles.Float | NumberStyles.AllowThousands, CultureInfo.InvariantCulture, out d)) + { + return d; + } + else + { + throw new JsonException("Could not read query value."); + } + } + else + { + long l; + if (long.TryParse(numberText, NumberStyles.Integer, CultureInfo.InvariantCulture, out l)) + { + return l; + } + else + { + throw new JsonException("Could not read query value."); + } + } + } + else + { + sb.Append(currentChar); + _currentIndex++; + } + } + } + else if (currentChar == 't') + { + if (Match("true")) + { + return true; + } + } + else if (currentChar == 'f') + { + if (Match("false")) + { + return false; + } + } + else if (currentChar == 'n') + { + if (Match("null")) + { + return null; + } + } + + throw new JsonException("Could not read query value."); + } + + private string ReadQuotedString() + { + StringBuilder sb = new StringBuilder(); + + _currentIndex++; + while (_currentIndex < _expression.Length) + { + char currentChar = _expression[_currentIndex]; + if (currentChar == '\\' && _currentIndex + 1 < _expression.Length) + { + _currentIndex++; + + if (_expression[_currentIndex] == '\'') + { + sb.Append('\''); + } + else if (_expression[_currentIndex] == '\\') + { + sb.Append('\\'); + } + else + { + throw new JsonException(@"Unknown escape chracter: \" + _expression[_currentIndex]); + } + + _currentIndex++; + } + else if (currentChar == '\'') + { + _currentIndex++; + { + return sb.ToString(); + } + } + else + { + _currentIndex++; + sb.Append(currentChar); + } + } + + throw new JsonException("Path ended with an open string."); + } + + private bool Match(string s) + { + int currentPosition = _currentIndex; + foreach (char c in s) + { + if (currentPosition < _expression.Length && _expression[currentPosition] == c) + { + currentPosition++; + } + else + { + return false; + } + } + + _currentIndex = currentPosition; + return true; + } + + private QueryOperator ParseOperator() + { + if (_currentIndex + 1 >= _expression.Length) + { + throw new JsonException("Path ended with open query."); + } + + if (Match("==")) + { + return QueryOperator.Equals; + } + if (Match("!=") || Match("<>")) + { + return QueryOperator.NotEquals; + } + if (Match("<=")) + { + return QueryOperator.LessThanOrEquals; + } + if (Match("<")) + { + return QueryOperator.LessThan; + } + if (Match(">=")) + { + return QueryOperator.GreaterThanOrEquals; + } + if (Match(">")) + { + return QueryOperator.GreaterThan; + } + + throw new JsonException("Could not read query operator."); + } + + private PathFilter ParseQuotedField(char indexerCloseChar) + { + List fields = null; + + while (_currentIndex < _expression.Length) + { + string field = ReadQuotedString(); + + EatWhitespace(); + EnsureLength("Path ended with open indexer."); + + if (_expression[_currentIndex] == indexerCloseChar) + { + if (fields != null) + { + fields.Add(field); + return new FieldMultipleFilter { Names = fields }; + } + else + { + return new FieldFilter { Name = field }; + } + } + else if (_expression[_currentIndex] == ',') + { + _currentIndex++; + EatWhitespace(); + + if (fields == null) + { + fields = new List(); + } + + fields.Add(field); + } + else + { + throw new JsonException("Unexpected character while parsing path indexer: " + _expression[_currentIndex]); + } + } + + throw new JsonException("Path ended with open indexer."); + } + + private void EnsureLength(string message) + { + if (_currentIndex >= _expression.Length) + { + throw new JsonException(message); + } + } + + internal IEnumerable Evaluate(JToken t, bool errorWhenNoMatch) + { + return Evaluate(Filters, t, errorWhenNoMatch); + } + + internal static IEnumerable Evaluate(List filters, JToken t, bool errorWhenNoMatch) + { + IEnumerable current = new[] { t }; + foreach (PathFilter filter in filters) + { + current = filter.ExecuteFilter(current, errorWhenNoMatch); + } + + return current; + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Linq/JsonPath/PathFilter.cs b/Common/00-1Json8.3/Json8.3/Linq/JsonPath/PathFilter.cs new file mode 100644 index 0000000..c1bce17 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Linq/JsonPath/PathFilter.cs @@ -0,0 +1,55 @@ +using System.Collections.Generic; +using System.Globalization; +using Newtonsoft.Json.Utilities; + +namespace Newtonsoft.Json.Linq.JsonPath +{ + internal abstract class PathFilter + { + public abstract IEnumerable ExecuteFilter(IEnumerable current, bool errorWhenNoMatch); + + protected static JToken GetTokenIndex(JToken t, bool errorWhenNoMatch, int index) + { + JArray a = t as JArray; + JConstructor c = t as JConstructor; + + if (a != null) + { + if (a.Count <= index) + { + if (errorWhenNoMatch) + { + throw new JsonException("Index {0} outside the bounds of JArray.".FormatWith(CultureInfo.InvariantCulture, index)); + } + + return null; + } + + return a[index]; + } + else if (c != null) + { + if (c.Count <= index) + { + if (errorWhenNoMatch) + { + throw new JsonException("Index {0} outside the bounds of JConstructor.".FormatWith(CultureInfo.InvariantCulture, index)); + } + + return null; + } + + return c[index]; + } + else + { + if (errorWhenNoMatch) + { + throw new JsonException("Index {0} not valid on {1}.".FormatWith(CultureInfo.InvariantCulture, index, t.GetType().Name)); + } + + return null; + } + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Linq/JsonPath/QueryExpression.cs b/Common/00-1Json8.3/Json8.3/Linq/JsonPath/QueryExpression.cs new file mode 100644 index 0000000..3b5c44e --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Linq/JsonPath/QueryExpression.cs @@ -0,0 +1,180 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using Newtonsoft.Json.Utilities; + +namespace Newtonsoft.Json.Linq.JsonPath +{ + internal enum QueryOperator + { + None = 0, + Equals = 1, + NotEquals = 2, + Exists = 3, + LessThan = 4, + LessThanOrEquals = 5, + GreaterThan = 6, + GreaterThanOrEquals = 7, + And = 8, + Or = 9 + } + + internal abstract class QueryExpression + { + public QueryOperator Operator { get; set; } + + public abstract bool IsMatch(JToken t); + } + + internal class CompositeExpression : QueryExpression + { + public List Expressions { get; set; } + + public CompositeExpression() + { + Expressions = new List(); + } + + public override bool IsMatch(JToken t) + { + switch (Operator) + { + case QueryOperator.And: + foreach (QueryExpression e in Expressions) + { + if (!e.IsMatch(t)) + { + return false; + } + } + return true; + case QueryOperator.Or: + foreach (QueryExpression e in Expressions) + { + if (e.IsMatch(t)) + { + return true; + } + } + return false; + default: + throw new ArgumentOutOfRangeException(); + } + } + } + + internal class BooleanQueryExpression : QueryExpression + { + public List Path { get; set; } + public JValue Value { get; set; } + + public override bool IsMatch(JToken t) + { + IEnumerable pathResult = JPath.Evaluate(Path, t, false); + + foreach (JToken r in pathResult) + { + JValue v = r as JValue; + switch (Operator) + { + case QueryOperator.Equals: + if (v != null && EqualsWithStringCoercion(v, Value)) + { + return true; + } + break; + case QueryOperator.NotEquals: + if (v != null && !EqualsWithStringCoercion(v, Value)) + { + return true; + } + break; + case QueryOperator.GreaterThan: + if (v != null && v.CompareTo(Value) > 0) + { + return true; + } + break; + case QueryOperator.GreaterThanOrEquals: + if (v != null && v.CompareTo(Value) >= 0) + { + return true; + } + break; + case QueryOperator.LessThan: + if (v != null && v.CompareTo(Value) < 0) + { + return true; + } + break; + case QueryOperator.LessThanOrEquals: + if (v != null && v.CompareTo(Value) <= 0) + { + return true; + } + break; + case QueryOperator.Exists: + return true; + default: + throw new ArgumentOutOfRangeException(); + } + } + + return false; + } + + private bool EqualsWithStringCoercion(JValue value, JValue queryValue) + { + if (value.Equals(queryValue)) + { + return true; + } + + if (queryValue.Type != JTokenType.String) + { + return false; + } + + string queryValueString = (string)queryValue.Value; + + string currentValueString; + + // potential performance issue with converting every value to string? + switch (value.Type) + { + case JTokenType.Date: + using (StringWriter writer = StringUtils.CreateStringWriter(64)) + { +#if !NET20 + if (value.Value is DateTimeOffset) + { + DateTimeUtils.WriteDateTimeOffsetString(writer, (DateTimeOffset)value.Value, DateFormatHandling.IsoDateFormat, null, CultureInfo.InvariantCulture); + } + else +#endif + { + DateTimeUtils.WriteDateTimeString(writer, (DateTime)value.Value, DateFormatHandling.IsoDateFormat, null, CultureInfo.InvariantCulture); + } + + currentValueString = writer.ToString(); + } + break; + case JTokenType.Bytes: + currentValueString = Convert.ToBase64String((byte[])value.Value); + break; + case JTokenType.Guid: + case JTokenType.TimeSpan: + currentValueString = value.Value.ToString(); + break; + case JTokenType.Uri: + currentValueString = ((Uri)value.Value).OriginalString; + break; + default: + return false; + } + + return string.Equals(currentValueString, queryValueString, StringComparison.Ordinal); + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Linq/JsonPath/QueryFilter.cs b/Common/00-1Json8.3/Json8.3/Linq/JsonPath/QueryFilter.cs new file mode 100644 index 0000000..9dab576 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Linq/JsonPath/QueryFilter.cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; + +namespace Newtonsoft.Json.Linq.JsonPath +{ + internal class QueryFilter : PathFilter + { + public QueryExpression Expression { get; set; } + + public override IEnumerable ExecuteFilter(IEnumerable current, bool errorWhenNoMatch) + { + foreach (JToken t in current) + { + foreach (JToken v in t) + { + if (Expression.IsMatch(v)) + { + yield return v; + } + } + } + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Linq/JsonPath/ScanFilter.cs b/Common/00-1Json8.3/Json8.3/Linq/JsonPath/ScanFilter.cs new file mode 100644 index 0000000..930adc4 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Linq/JsonPath/ScanFilter.cs @@ -0,0 +1,63 @@ +using System.Collections.Generic; + +namespace Newtonsoft.Json.Linq.JsonPath +{ + internal class ScanFilter : PathFilter + { + public string Name { get; set; } + + public override IEnumerable ExecuteFilter(IEnumerable current, bool errorWhenNoMatch) + { + foreach (JToken root in current) + { + if (Name == null) + { + yield return root; + } + + JToken value = root; + JToken container = root; + + while (true) + { + if (container != null && container.HasValues) + { + value = container.First; + } + else + { + while (value != null && value != root && value == value.Parent.Last) + { + value = value.Parent; + } + + if (value == null || value == root) + { + break; + } + + value = value.Next; + } + + JProperty e = value as JProperty; + if (e != null) + { + if (e.Name == Name) + { + yield return e.Value; + } + } + else + { + if (Name == null) + { + yield return value; + } + } + + container = value as JContainer; + } + } + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Linq/MergeArrayHandling.cs b/Common/00-1Json8.3/Json8.3/Linq/MergeArrayHandling.cs new file mode 100644 index 0000000..5e7fadf --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Linq/MergeArrayHandling.cs @@ -0,0 +1,20 @@ +namespace Newtonsoft.Json.Linq +{ + /// + /// Specifies how JSON arrays are merged together. + /// + public enum MergeArrayHandling + { + /// Concatenate arrays. + Concat = 0, + + /// Union arrays, skipping items that already exist. + Union = 1, + + /// Replace all array items. + Replace = 2, + + /// Merge array items together, matched by index. + Merge = 3 + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Linq/MergeNullValueHandling.cs b/Common/00-1Json8.3/Json8.3/Linq/MergeNullValueHandling.cs new file mode 100644 index 0000000..30d3d84 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Linq/MergeNullValueHandling.cs @@ -0,0 +1,21 @@ +using System; + +namespace Newtonsoft.Json.Linq +{ + /// + /// Specifies how null value properties are merged. + /// + [Flags] + public enum MergeNullValueHandling + { + /// + /// The content's null value properties will be ignored during merging. + /// + Ignore = 0, + + /// + /// The content's null value properties will be merged. + /// + Merge = 1 + } +} diff --git a/Common/00-1Json8.3/Json8.3/MemberSerialization.cs b/Common/00-1Json8.3/Json8.3/MemberSerialization.cs new file mode 100644 index 0000000..8309992 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/MemberSerialization.cs @@ -0,0 +1,58 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Runtime.Serialization; +using Newtonsoft.Json.Serialization; + +namespace Newtonsoft.Json +{ + /// + /// Specifies the member serialization options for the . + /// + public enum MemberSerialization + { +#pragma warning disable 1584,1711,1572,1581,1580,1574 + /// + /// All public members are serialized by default. Members can be excluded using or . + /// This is the default member serialization mode. + /// + OptOut = 0, + + /// + /// Only members marked with or are serialized. + /// This member serialization mode can also be set by marking the class with . + /// + OptIn = 1, + + /// + /// All public and private fields are serialized. Members can be excluded using or . + /// This member serialization mode can also be set by marking the class with + /// and setting IgnoreSerializableAttribute on to false. + /// + Fields = 2 +#pragma warning restore 1584,1711,1572,1581,1580,1574 + } +} diff --git a/Common/00-1Json8.3/Json8.3/MetadataPropertyHandling.cs b/Common/00-1Json8.3/Json8.3/MetadataPropertyHandling.cs new file mode 100644 index 0000000..5bdacd8 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/MetadataPropertyHandling.cs @@ -0,0 +1,52 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Collections.Generic; +using System.Text; + +namespace Newtonsoft.Json +{ + /// + /// Specifies metadata property handling options for the . + /// + public enum MetadataPropertyHandling + { + /// + /// Read metadata properties located at the start of a JSON object. + /// + Default = 0, + + /// + /// Read metadata properties located anywhere in a JSON object. Note that this setting will impact performance. + /// + ReadAhead = 1, + + /// + /// Do not try to read metadata properties. + /// + Ignore = 2 + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/MissingMemberHandling.cs b/Common/00-1Json8.3/Json8.3/MissingMemberHandling.cs new file mode 100644 index 0000000..4e35081 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/MissingMemberHandling.cs @@ -0,0 +1,47 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Collections.Generic; +using System.Text; + +namespace Newtonsoft.Json +{ + /// + /// Specifies missing member handling options for the . + /// + public enum MissingMemberHandling + { + /// + /// Ignore a missing member and do not attempt to deserialize it. + /// + Ignore = 0, + + /// + /// Throw a when a missing member is encountered during deserialization. + /// + Error = 1 + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/NullValueHandling.cs b/Common/00-1Json8.3/Json8.3/NullValueHandling.cs new file mode 100644 index 0000000..8a88c16 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/NullValueHandling.cs @@ -0,0 +1,47 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +namespace Newtonsoft.Json +{ + /// + /// Specifies null value handling options for the . + /// + /// + /// + /// + /// + public enum NullValueHandling + { + /// + /// Include null values when serializing and deserializing objects. + /// + Include = 0, + + /// + /// Ignore null values when serializing and deserializing objects. + /// + Ignore = 1 + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/ObjectCreationHandling.cs b/Common/00-1Json8.3/Json8.3/ObjectCreationHandling.cs new file mode 100644 index 0000000..cc53b14 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/ObjectCreationHandling.cs @@ -0,0 +1,48 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +namespace Newtonsoft.Json +{ + /// + /// Specifies how object creation is handled by the . + /// + public enum ObjectCreationHandling + { + /// + /// Reuse existing objects, create new objects when needed. + /// + Auto = 0, + + /// + /// Only reuse existing objects. + /// + Reuse = 1, + + /// + /// Always create new objects. + /// + Replace = 2 + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/PreserveReferencesHandling.cs b/Common/00-1Json8.3/Json8.3/PreserveReferencesHandling.cs new file mode 100644 index 0000000..61fcbd4 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/PreserveReferencesHandling.cs @@ -0,0 +1,62 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Collections.Generic; +using System.Text; + +namespace Newtonsoft.Json +{ + /// + /// Specifies reference handling options for the . + /// Note that references cannot be preserved when a value is set via a non-default constructor such as types that implement ISerializable. + /// + /// + /// + /// + [Flags] + public enum PreserveReferencesHandling + { + /// + /// Do not preserve references when serializing types. + /// + None = 0, + + /// + /// Preserve references when serializing into a JSON object structure. + /// + Objects = 1, + + /// + /// Preserve references when serializing into a JSON array structure. + /// + Arrays = 2, + + /// + /// Preserve references when serializing. + /// + All = Objects | Arrays + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Properties/AssemblyInfo.cs b/Common/00-1Json8.3/Json8.3/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..899509d --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// 有关程序集的一般信息由以下 +// 控制。更改这些特性值可修改 +// 与程序集关联的信息。 +[assembly: AssemblyTitle("Json8.3")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("Json8.3")] +[assembly: AssemblyCopyright("Copyright © 2022")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// 将 ComVisible 设置为 false 会使此程序集中的类型 +//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型 +//请将此类型的 ComVisible 特性设置为 true。 +[assembly: ComVisible(false)] + +// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID +[assembly: Guid("1a10fdb2-1a6a-44a8-ab4d-33387563247e")] + +// 程序集的版本信息由下列四个值组成: +// +// 主版本 +// 次版本 +// 生成号 +// 修订号 +// +//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值 +//通过使用 "*",如下所示: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Common/00-1Json8.3/Json8.3/ReferenceLoopHandling.cs b/Common/00-1Json8.3/Json8.3/ReferenceLoopHandling.cs new file mode 100644 index 0000000..bfa5133 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/ReferenceLoopHandling.cs @@ -0,0 +1,52 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Collections.Generic; +using System.Text; + +namespace Newtonsoft.Json +{ + /// + /// Specifies reference loop handling options for the . + /// + public enum ReferenceLoopHandling + { + /// + /// Throw a when a loop is encountered. + /// + Error = 0, + + /// + /// Ignore loop references and do not serialize. + /// + Ignore = 1, + + /// + /// Serialize loop references. + /// + Serialize = 2 + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Required.cs b/Common/00-1Json8.3/Json8.3/Required.cs new file mode 100644 index 0000000..47c91e1 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Required.cs @@ -0,0 +1,53 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +namespace Newtonsoft.Json +{ + /// + /// Indicating whether a property is required. + /// + public enum Required + { + /// + /// The property is not required. The default state. + /// + Default = 0, + + /// + /// The property must be defined in JSON but can be a null value. + /// + AllowNull = 1, + + /// + /// The property must be defined in JSON and cannot be a null value. + /// + Always = 2, + + /// + /// The property is not required but it cannot be a null value. + /// + DisallowNull = 3 + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Schema/Extensions.cs b/Common/00-1Json8.3/Json8.3/Schema/Extensions.cs new file mode 100644 index 0000000..6cfbf30 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Schema/Extensions.cs @@ -0,0 +1,137 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Collections.Generic; +using Newtonsoft.Json.Linq; +using Newtonsoft.Json.Utilities; + +namespace Newtonsoft.Json.Schema +{ + /// + /// + /// Contains the JSON schema extension methods. + /// + /// + /// JSON Schema validation has been moved to its own package. See http://www.newtonsoft.com/jsonschema for more details. + /// + /// + [Obsolete("JSON Schema validation has been moved to its own package. See http://www.newtonsoft.com/jsonschema for more details.")] + public static class Extensions + { + /// + /// + /// Determines whether the is valid. + /// + /// + /// JSON Schema validation has been moved to its own package. See http://www.newtonsoft.com/jsonschema for more details. + /// + /// + /// The source to test. + /// The schema to test with. + /// + /// true if the specified is valid; otherwise, false. + /// + [Obsolete("JSON Schema validation has been moved to its own package. See http://www.newtonsoft.com/jsonschema for more details.")] + public static bool IsValid(this JToken source, JsonSchema schema) + { + bool valid = true; + source.Validate(schema, (sender, args) => { valid = false; }); + return valid; + } + + /// + /// + /// Determines whether the is valid. + /// + /// + /// JSON Schema validation has been moved to its own package. See http://www.newtonsoft.com/jsonschema for more details. + /// + /// + /// The source to test. + /// The schema to test with. + /// When this method returns, contains any error messages generated while validating. + /// + /// true if the specified is valid; otherwise, false. + /// + [Obsolete("JSON Schema validation has been moved to its own package. See http://www.newtonsoft.com/jsonschema for more details.")] + public static bool IsValid(this JToken source, JsonSchema schema, out IList errorMessages) + { + IList errors = new List(); + + source.Validate(schema, (sender, args) => errors.Add(args.Message)); + + errorMessages = errors; + return (errorMessages.Count == 0); + } + + /// + /// + /// Validates the specified . + /// + /// + /// JSON Schema validation has been moved to its own package. See http://www.newtonsoft.com/jsonschema for more details. + /// + /// + /// The source to test. + /// The schema to test with. + [Obsolete("JSON Schema validation has been moved to its own package. See http://www.newtonsoft.com/jsonschema for more details.")] + public static void Validate(this JToken source, JsonSchema schema) + { + source.Validate(schema, null); + } + + /// + /// + /// Validates the specified . + /// + /// + /// JSON Schema validation has been moved to its own package. See http://www.newtonsoft.com/jsonschema for more details. + /// + /// + /// The source to test. + /// The schema to test with. + /// The validation event handler. + [Obsolete("JSON Schema validation has been moved to its own package. See http://www.newtonsoft.com/jsonschema for more details.")] + public static void Validate(this JToken source, JsonSchema schema, ValidationEventHandler validationEventHandler) + { + ValidationUtils.ArgumentNotNull(source, nameof(source)); + ValidationUtils.ArgumentNotNull(schema, nameof(schema)); + + using (JsonValidatingReader reader = new JsonValidatingReader(source.CreateReader())) + { + reader.Schema = schema; + if (validationEventHandler != null) + { + reader.ValidationEventHandler += validationEventHandler; + } + + while (reader.Read()) + { + } + } + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Schema/JsonSchema.cs b/Common/00-1Json8.3/Json8.3/Schema/JsonSchema.cs new file mode 100644 index 0000000..7b32225 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Schema/JsonSchema.cs @@ -0,0 +1,356 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Collections.Generic; +using System.IO; +using Newtonsoft.Json.Linq; +using Newtonsoft.Json.Utilities; +using System.Globalization; + +namespace Newtonsoft.Json.Schema +{ + /// + /// + /// An in-memory representation of a JSON Schema. + /// + /// + /// JSON Schema validation has been moved to its own package. See http://www.newtonsoft.com/jsonschema for more details. + /// + /// + [Obsolete("JSON Schema validation has been moved to its own package. See http://www.newtonsoft.com/jsonschema for more details.")] + public class JsonSchema + { + /// + /// Gets or sets the id. + /// + public string Id { get; set; } + + /// + /// Gets or sets the title. + /// + public string Title { get; set; } + + /// + /// Gets or sets whether the object is required. + /// + public bool? Required { get; set; } + + /// + /// Gets or sets whether the object is read only. + /// + public bool? ReadOnly { get; set; } + + /// + /// Gets or sets whether the object is visible to users. + /// + public bool? Hidden { get; set; } + + /// + /// Gets or sets whether the object is transient. + /// + public bool? Transient { get; set; } + + /// + /// Gets or sets the description of the object. + /// + public string Description { get; set; } + + /// + /// Gets or sets the types of values allowed by the object. + /// + /// The type. + public JsonSchemaType? Type { get; set; } + + /// + /// Gets or sets the pattern. + /// + /// The pattern. + public string Pattern { get; set; } + + /// + /// Gets or sets the minimum length. + /// + /// The minimum length. + public int? MinimumLength { get; set; } + + /// + /// Gets or sets the maximum length. + /// + /// The maximum length. + public int? MaximumLength { get; set; } + + /// + /// Gets or sets a number that the value should be divisble by. + /// + /// A number that the value should be divisble by. + public double? DivisibleBy { get; set; } + + /// + /// Gets or sets the minimum. + /// + /// The minimum. + public double? Minimum { get; set; } + + /// + /// Gets or sets the maximum. + /// + /// The maximum. + public double? Maximum { get; set; } + + /// + /// Gets or sets a flag indicating whether the value can not equal the number defined by the "minimum" attribute. + /// + /// A flag indicating whether the value can not equal the number defined by the "minimum" attribute. + public bool? ExclusiveMinimum { get; set; } + + /// + /// Gets or sets a flag indicating whether the value can not equal the number defined by the "maximum" attribute. + /// + /// A flag indicating whether the value can not equal the number defined by the "maximum" attribute. + public bool? ExclusiveMaximum { get; set; } + + /// + /// Gets or sets the minimum number of items. + /// + /// The minimum number of items. + public int? MinimumItems { get; set; } + + /// + /// Gets or sets the maximum number of items. + /// + /// The maximum number of items. + public int? MaximumItems { get; set; } + + /// + /// Gets or sets the of items. + /// + /// The of items. + public IList Items { get; set; } + + /// + /// Gets or sets a value indicating whether items in an array are validated using the instance at their array position from . + /// + /// + /// true if items are validated using their array position; otherwise, false. + /// + public bool PositionalItemsValidation { get; set; } + + /// + /// Gets or sets the of additional items. + /// + /// The of additional items. + public JsonSchema AdditionalItems { get; set; } + + /// + /// Gets or sets a value indicating whether additional items are allowed. + /// + /// + /// true if additional items are allowed; otherwise, false. + /// + public bool AllowAdditionalItems { get; set; } + + /// + /// Gets or sets whether the array items must be unique. + /// + public bool UniqueItems { get; set; } + + /// + /// Gets or sets the of properties. + /// + /// The of properties. + public IDictionary Properties { get; set; } + + /// + /// Gets or sets the of additional properties. + /// + /// The of additional properties. + public JsonSchema AdditionalProperties { get; set; } + + /// + /// Gets or sets the pattern properties. + /// + /// The pattern properties. + public IDictionary PatternProperties { get; set; } + + /// + /// Gets or sets a value indicating whether additional properties are allowed. + /// + /// + /// true if additional properties are allowed; otherwise, false. + /// + public bool AllowAdditionalProperties { get; set; } + + /// + /// Gets or sets the required property if this property is present. + /// + /// The required property if this property is present. + public string Requires { get; set; } + + /// + /// Gets or sets the a collection of valid enum values allowed. + /// + /// A collection of valid enum values allowed. + public IList Enum { get; set; } + + /// + /// Gets or sets disallowed types. + /// + /// The disallow types. + public JsonSchemaType? Disallow { get; set; } + + /// + /// Gets or sets the default value. + /// + /// The default value. + public JToken Default { get; set; } + + /// + /// Gets or sets the collection of that this schema extends. + /// + /// The collection of that this schema extends. + public IList Extends { get; set; } + + /// + /// Gets or sets the format. + /// + /// The format. + public string Format { get; set; } + + internal string Location { get; set; } + + private readonly string _internalId = Guid.NewGuid().ToString("N"); + + internal string InternalId + { + get { return _internalId; } + } + + // if this is set then this schema instance is just a deferred reference + // and will be replaced when the schema reference is resolved + internal string DeferredReference { get; set; } + internal bool ReferencesResolved { get; set; } + + /// + /// Initializes a new instance of the class. + /// + public JsonSchema() + { + AllowAdditionalProperties = true; + AllowAdditionalItems = true; + } + + /// + /// Reads a from the specified . + /// + /// The containing the JSON Schema to read. + /// The object representing the JSON Schema. + public static JsonSchema Read(JsonReader reader) + { + return Read(reader, new JsonSchemaResolver()); + } + + /// + /// Reads a from the specified . + /// + /// The containing the JSON Schema to read. + /// The to use when resolving schema references. + /// The object representing the JSON Schema. + public static JsonSchema Read(JsonReader reader, JsonSchemaResolver resolver) + { + ValidationUtils.ArgumentNotNull(reader, nameof(reader)); + ValidationUtils.ArgumentNotNull(resolver, nameof(resolver)); + + JsonSchemaBuilder builder = new JsonSchemaBuilder(resolver); + return builder.Read(reader); + } + + /// + /// Load a from a string that contains schema JSON. + /// + /// A that contains JSON. + /// A populated from the string that contains JSON. + public static JsonSchema Parse(string json) + { + return Parse(json, new JsonSchemaResolver()); + } + + /// + /// Parses the specified json. + /// + /// The json. + /// The resolver. + /// A populated from the string that contains JSON. + public static JsonSchema Parse(string json, JsonSchemaResolver resolver) + { + ValidationUtils.ArgumentNotNull(json, nameof(json)); + + using (JsonReader reader = new JsonTextReader(new StringReader(json))) + { + return Read(reader, resolver); + } + } + + /// + /// Writes this schema to a . + /// + /// A into which this method will write. + public void WriteTo(JsonWriter writer) + { + WriteTo(writer, new JsonSchemaResolver()); + } + + /// + /// Writes this schema to a using the specified . + /// + /// A into which this method will write. + /// The resolver used. + public void WriteTo(JsonWriter writer, JsonSchemaResolver resolver) + { + ValidationUtils.ArgumentNotNull(writer, nameof(writer)); + ValidationUtils.ArgumentNotNull(resolver, nameof(resolver)); + + JsonSchemaWriter schemaWriter = new JsonSchemaWriter(writer, resolver); + schemaWriter.WriteSchema(this); + } + + /// + /// Returns a that represents the current . + /// + /// + /// A that represents the current . + /// + public override string ToString() + { + StringWriter writer = new StringWriter(CultureInfo.InvariantCulture); + JsonTextWriter jsonWriter = new JsonTextWriter(writer); + jsonWriter.Formatting = Formatting.Indented; + + WriteTo(jsonWriter); + + return writer.ToString(); + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Schema/JsonSchemaBuilder.cs b/Common/00-1Json8.3/Json8.3/Schema/JsonSchemaBuilder.cs new file mode 100644 index 0000000..6947520 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Schema/JsonSchemaBuilder.cs @@ -0,0 +1,495 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Collections.Generic; +using Newtonsoft.Json.Serialization; +#if NET20 +using Newtonsoft.Json.Utilities.LinqBridge; +#else +using System.Linq; +#endif +using System.Globalization; +using Newtonsoft.Json.Utilities; +using Newtonsoft.Json.Linq; + +namespace Newtonsoft.Json.Schema +{ + [Obsolete("JSON Schema validation has been moved to its own package. See http://www.newtonsoft.com/jsonschema for more details.")] + internal class JsonSchemaBuilder + { + private readonly IList _stack; + private readonly JsonSchemaResolver _resolver; + private readonly IDictionary _documentSchemas; + private JsonSchema _currentSchema; + private JObject _rootSchema; + + public JsonSchemaBuilder(JsonSchemaResolver resolver) + { + _stack = new List(); + _documentSchemas = new Dictionary(); + _resolver = resolver; + } + + private void Push(JsonSchema value) + { + _currentSchema = value; + _stack.Add(value); + _resolver.LoadedSchemas.Add(value); + _documentSchemas.Add(value.Location, value); + } + + private JsonSchema Pop() + { + JsonSchema poppedSchema = _currentSchema; + _stack.RemoveAt(_stack.Count - 1); + _currentSchema = _stack.LastOrDefault(); + + return poppedSchema; + } + + private JsonSchema CurrentSchema + { + get { return _currentSchema; } + } + + internal JsonSchema Read(JsonReader reader) + { + JToken schemaToken = JToken.ReadFrom(reader); + + _rootSchema = schemaToken as JObject; + + JsonSchema schema = BuildSchema(schemaToken); + + ResolveReferences(schema); + + return schema; + } + + private string UnescapeReference(string reference) + { + return Uri.UnescapeDataString(reference).Replace("~1", "/").Replace("~0", "~"); + } + + private JsonSchema ResolveReferences(JsonSchema schema) + { + if (schema.DeferredReference != null) + { + string reference = schema.DeferredReference; + + bool locationReference = (reference.StartsWith("#", StringComparison.Ordinal)); + if (locationReference) + { + reference = UnescapeReference(reference); + } + + JsonSchema resolvedSchema = _resolver.GetSchema(reference); + + if (resolvedSchema == null) + { + if (locationReference) + { + string[] escapedParts = schema.DeferredReference.TrimStart('#').Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries); + JToken currentToken = _rootSchema; + foreach (string escapedPart in escapedParts) + { + string part = UnescapeReference(escapedPart); + + if (currentToken.Type == JTokenType.Object) + { + currentToken = currentToken[part]; + } + else if (currentToken.Type == JTokenType.Array || currentToken.Type == JTokenType.Constructor) + { + int index; + if (int.TryParse(part, out index) && index >= 0 && index < currentToken.Count()) + { + currentToken = currentToken[index]; + } + else + { + currentToken = null; + } + } + + if (currentToken == null) + { + break; + } + } + + if (currentToken != null) + { + resolvedSchema = BuildSchema(currentToken); + } + } + + if (resolvedSchema == null) + { + throw new JsonException("Could not resolve schema reference '{0}'.".FormatWith(CultureInfo.InvariantCulture, schema.DeferredReference)); + } + } + + schema = resolvedSchema; + } + + if (schema.ReferencesResolved) + { + return schema; + } + + schema.ReferencesResolved = true; + + if (schema.Extends != null) + { + for (int i = 0; i < schema.Extends.Count; i++) + { + schema.Extends[i] = ResolveReferences(schema.Extends[i]); + } + } + + if (schema.Items != null) + { + for (int i = 0; i < schema.Items.Count; i++) + { + schema.Items[i] = ResolveReferences(schema.Items[i]); + } + } + + if (schema.AdditionalItems != null) + { + schema.AdditionalItems = ResolveReferences(schema.AdditionalItems); + } + + if (schema.PatternProperties != null) + { + foreach (KeyValuePair patternProperty in schema.PatternProperties.ToList()) + { + schema.PatternProperties[patternProperty.Key] = ResolveReferences(patternProperty.Value); + } + } + + if (schema.Properties != null) + { + foreach (KeyValuePair property in schema.Properties.ToList()) + { + schema.Properties[property.Key] = ResolveReferences(property.Value); + } + } + + if (schema.AdditionalProperties != null) + { + schema.AdditionalProperties = ResolveReferences(schema.AdditionalProperties); + } + + return schema; + } + + private JsonSchema BuildSchema(JToken token) + { + JObject schemaObject = token as JObject; + if (schemaObject == null) + { + throw JsonException.Create(token, token.Path, "Expected object while parsing schema object, got {0}.".FormatWith(CultureInfo.InvariantCulture, token.Type)); + } + + JToken referenceToken; + if (schemaObject.TryGetValue(JsonTypeReflector.RefPropertyName, out referenceToken)) + { + JsonSchema deferredSchema = new JsonSchema(); + deferredSchema.DeferredReference = (string)referenceToken; + + return deferredSchema; + } + + string location = token.Path.Replace(".", "/").Replace("[", "/").Replace("]", string.Empty); + if (!string.IsNullOrEmpty(location)) + { + location = "/" + location; + } + location = "#" + location; + + JsonSchema existingSchema; + if (_documentSchemas.TryGetValue(location, out existingSchema)) + { + return existingSchema; + } + + Push(new JsonSchema { Location = location }); + + ProcessSchemaProperties(schemaObject); + + return Pop(); + } + + private void ProcessSchemaProperties(JObject schemaObject) + { + foreach (KeyValuePair property in schemaObject) + { + switch (property.Key) + { + case JsonSchemaConstants.TypePropertyName: + CurrentSchema.Type = ProcessType(property.Value); + break; + case JsonSchemaConstants.IdPropertyName: + CurrentSchema.Id = (string)property.Value; + break; + case JsonSchemaConstants.TitlePropertyName: + CurrentSchema.Title = (string)property.Value; + break; + case JsonSchemaConstants.DescriptionPropertyName: + CurrentSchema.Description = (string)property.Value; + break; + case JsonSchemaConstants.PropertiesPropertyName: + CurrentSchema.Properties = ProcessProperties(property.Value); + break; + case JsonSchemaConstants.ItemsPropertyName: + ProcessItems(property.Value); + break; + case JsonSchemaConstants.AdditionalPropertiesPropertyName: + ProcessAdditionalProperties(property.Value); + break; + case JsonSchemaConstants.AdditionalItemsPropertyName: + ProcessAdditionalItems(property.Value); + break; + case JsonSchemaConstants.PatternPropertiesPropertyName: + CurrentSchema.PatternProperties = ProcessProperties(property.Value); + break; + case JsonSchemaConstants.RequiredPropertyName: + CurrentSchema.Required = (bool)property.Value; + break; + case JsonSchemaConstants.RequiresPropertyName: + CurrentSchema.Requires = (string)property.Value; + break; + case JsonSchemaConstants.MinimumPropertyName: + CurrentSchema.Minimum = (double)property.Value; + break; + case JsonSchemaConstants.MaximumPropertyName: + CurrentSchema.Maximum = (double)property.Value; + break; + case JsonSchemaConstants.ExclusiveMinimumPropertyName: + CurrentSchema.ExclusiveMinimum = (bool)property.Value; + break; + case JsonSchemaConstants.ExclusiveMaximumPropertyName: + CurrentSchema.ExclusiveMaximum = (bool)property.Value; + break; + case JsonSchemaConstants.MaximumLengthPropertyName: + CurrentSchema.MaximumLength = (int)property.Value; + break; + case JsonSchemaConstants.MinimumLengthPropertyName: + CurrentSchema.MinimumLength = (int)property.Value; + break; + case JsonSchemaConstants.MaximumItemsPropertyName: + CurrentSchema.MaximumItems = (int)property.Value; + break; + case JsonSchemaConstants.MinimumItemsPropertyName: + CurrentSchema.MinimumItems = (int)property.Value; + break; + case JsonSchemaConstants.DivisibleByPropertyName: + CurrentSchema.DivisibleBy = (double)property.Value; + break; + case JsonSchemaConstants.DisallowPropertyName: + CurrentSchema.Disallow = ProcessType(property.Value); + break; + case JsonSchemaConstants.DefaultPropertyName: + CurrentSchema.Default = property.Value.DeepClone(); + break; + case JsonSchemaConstants.HiddenPropertyName: + CurrentSchema.Hidden = (bool)property.Value; + break; + case JsonSchemaConstants.ReadOnlyPropertyName: + CurrentSchema.ReadOnly = (bool)property.Value; + break; + case JsonSchemaConstants.FormatPropertyName: + CurrentSchema.Format = (string)property.Value; + break; + case JsonSchemaConstants.PatternPropertyName: + CurrentSchema.Pattern = (string)property.Value; + break; + case JsonSchemaConstants.EnumPropertyName: + ProcessEnum(property.Value); + break; + case JsonSchemaConstants.ExtendsPropertyName: + ProcessExtends(property.Value); + break; + case JsonSchemaConstants.UniqueItemsPropertyName: + CurrentSchema.UniqueItems = (bool)property.Value; + break; + } + } + } + + private void ProcessExtends(JToken token) + { + IList schemas = new List(); + + if (token.Type == JTokenType.Array) + { + foreach (JToken schemaObject in token) + { + schemas.Add(BuildSchema(schemaObject)); + } + } + else + { + JsonSchema schema = BuildSchema(token); + if (schema != null) + { + schemas.Add(schema); + } + } + + if (schemas.Count > 0) + { + CurrentSchema.Extends = schemas; + } + } + + private void ProcessEnum(JToken token) + { + if (token.Type != JTokenType.Array) + { + throw JsonException.Create(token, token.Path, "Expected Array token while parsing enum values, got {0}.".FormatWith(CultureInfo.InvariantCulture, token.Type)); + } + + CurrentSchema.Enum = new List(); + + foreach (JToken enumValue in token) + { + CurrentSchema.Enum.Add(enumValue.DeepClone()); + } + } + + private void ProcessAdditionalProperties(JToken token) + { + if (token.Type == JTokenType.Boolean) + { + CurrentSchema.AllowAdditionalProperties = (bool)token; + } + else + { + CurrentSchema.AdditionalProperties = BuildSchema(token); + } + } + + private void ProcessAdditionalItems(JToken token) + { + if (token.Type == JTokenType.Boolean) + { + CurrentSchema.AllowAdditionalItems = (bool)token; + } + else + { + CurrentSchema.AdditionalItems = BuildSchema(token); + } + } + + private IDictionary ProcessProperties(JToken token) + { + IDictionary properties = new Dictionary(); + + if (token.Type != JTokenType.Object) + { + throw JsonException.Create(token, token.Path, "Expected Object token while parsing schema properties, got {0}.".FormatWith(CultureInfo.InvariantCulture, token.Type)); + } + + foreach (JProperty propertyToken in token) + { + if (properties.ContainsKey(propertyToken.Name)) + { + throw new JsonException("Property {0} has already been defined in schema.".FormatWith(CultureInfo.InvariantCulture, propertyToken.Name)); + } + + properties.Add(propertyToken.Name, BuildSchema(propertyToken.Value)); + } + + return properties; + } + + private void ProcessItems(JToken token) + { + CurrentSchema.Items = new List(); + + switch (token.Type) + { + case JTokenType.Object: + CurrentSchema.Items.Add(BuildSchema(token)); + CurrentSchema.PositionalItemsValidation = false; + break; + case JTokenType.Array: + CurrentSchema.PositionalItemsValidation = true; + foreach (JToken schemaToken in token) + { + CurrentSchema.Items.Add(BuildSchema(schemaToken)); + } + break; + default: + throw JsonException.Create(token, token.Path, "Expected array or JSON schema object, got {0}.".FormatWith(CultureInfo.InvariantCulture, token.Type)); + } + } + + private JsonSchemaType? ProcessType(JToken token) + { + switch (token.Type) + { + case JTokenType.Array: + // ensure type is in blank state before ORing values + JsonSchemaType? type = JsonSchemaType.None; + + foreach (JToken typeToken in token) + { + if (typeToken.Type != JTokenType.String) + { + throw JsonException.Create(typeToken, typeToken.Path, "Exception JSON schema type string token, got {0}.".FormatWith(CultureInfo.InvariantCulture, token.Type)); + } + + type = type | MapType((string)typeToken); + } + + return type; + case JTokenType.String: + return MapType((string)token); + default: + throw JsonException.Create(token, token.Path, "Expected array or JSON schema type string token, got {0}.".FormatWith(CultureInfo.InvariantCulture, token.Type)); + } + } + + internal static JsonSchemaType MapType(string type) + { + JsonSchemaType mappedType; + if (!JsonSchemaConstants.JsonSchemaTypeMapping.TryGetValue(type, out mappedType)) + { + throw new JsonException("Invalid JSON schema type: {0}".FormatWith(CultureInfo.InvariantCulture, type)); + } + + return mappedType; + } + + internal static string MapType(JsonSchemaType type) + { + return JsonSchemaConstants.JsonSchemaTypeMapping.Single(kv => kv.Value == type).Key; + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Schema/JsonSchemaConstants.cs b/Common/00-1Json8.3/Json8.3/Schema/JsonSchemaConstants.cs new file mode 100644 index 0000000..2309a52 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Schema/JsonSchemaConstants.cs @@ -0,0 +1,80 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Collections.Generic; + +namespace Newtonsoft.Json.Schema +{ + [Obsolete("JSON Schema validation has been moved to its own package. See http://www.newtonsoft.com/jsonschema for more details.")] + internal static class JsonSchemaConstants + { + public const string TypePropertyName = "type"; + public const string PropertiesPropertyName = "properties"; + public const string ItemsPropertyName = "items"; + public const string AdditionalItemsPropertyName = "additionalItems"; + public const string RequiredPropertyName = "required"; + public const string PatternPropertiesPropertyName = "patternProperties"; + public const string AdditionalPropertiesPropertyName = "additionalProperties"; + public const string RequiresPropertyName = "requires"; + public const string MinimumPropertyName = "minimum"; + public const string MaximumPropertyName = "maximum"; + public const string ExclusiveMinimumPropertyName = "exclusiveMinimum"; + public const string ExclusiveMaximumPropertyName = "exclusiveMaximum"; + public const string MinimumItemsPropertyName = "minItems"; + public const string MaximumItemsPropertyName = "maxItems"; + public const string PatternPropertyName = "pattern"; + public const string MaximumLengthPropertyName = "maxLength"; + public const string MinimumLengthPropertyName = "minLength"; + public const string EnumPropertyName = "enum"; + public const string ReadOnlyPropertyName = "readonly"; + public const string TitlePropertyName = "title"; + public const string DescriptionPropertyName = "description"; + public const string FormatPropertyName = "format"; + public const string DefaultPropertyName = "default"; + public const string TransientPropertyName = "transient"; + public const string DivisibleByPropertyName = "divisibleBy"; + public const string HiddenPropertyName = "hidden"; + public const string DisallowPropertyName = "disallow"; + public const string ExtendsPropertyName = "extends"; + public const string IdPropertyName = "id"; + public const string UniqueItemsPropertyName = "uniqueItems"; + + public const string OptionValuePropertyName = "value"; + public const string OptionLabelPropertyName = "label"; + + public static readonly IDictionary JsonSchemaTypeMapping = new Dictionary + { + { "string", JsonSchemaType.String }, + { "object", JsonSchemaType.Object }, + { "integer", JsonSchemaType.Integer }, + { "number", JsonSchemaType.Float }, + { "null", JsonSchemaType.Null }, + { "boolean", JsonSchemaType.Boolean }, + { "array", JsonSchemaType.Array }, + { "any", JsonSchemaType.Any } + }; + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Schema/JsonSchemaException.cs b/Common/00-1Json8.3/Json8.3/Schema/JsonSchemaException.cs new file mode 100644 index 0000000..f9503db --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Schema/JsonSchemaException.cs @@ -0,0 +1,113 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Runtime.Serialization; + +namespace Newtonsoft.Json.Schema +{ + /// + /// + /// Returns detailed information about the schema exception. + /// + /// + /// JSON Schema validation has been moved to its own package. See http://www.newtonsoft.com/jsonschema for more details. + /// + /// +#if !(DOTNET || PORTABLE40 || PORTABLE) + [Serializable] +#endif + [Obsolete("JSON Schema validation has been moved to its own package. See http://www.newtonsoft.com/jsonschema for more details.")] + public class JsonSchemaException : JsonException + { + /// + /// Gets the line number indicating where the error occurred. + /// + /// The line number indicating where the error occurred. + public int LineNumber { get; private set; } + + /// + /// Gets the line position indicating where the error occurred. + /// + /// The line position indicating where the error occurred. + public int LinePosition { get; private set; } + + /// + /// Gets the path to the JSON where the error occurred. + /// + /// The path to the JSON where the error occurred. + public string Path { get; private set; } + + /// + /// Initializes a new instance of the class. + /// + public JsonSchemaException() + { + } + + /// + /// Initializes a new instance of the class + /// with a specified error message. + /// + /// The error message that explains the reason for the exception. + public JsonSchemaException(string message) + : base(message) + { + } + + /// + /// Initializes a new instance of the class + /// with a specified error message and a reference to the inner exception that is the cause of this exception. + /// + /// The error message that explains the reason for the exception. + /// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no inner exception is specified. + public JsonSchemaException(string message, Exception innerException) + : base(message, innerException) + { + } + +#if !(DOTNET || PORTABLE40 || PORTABLE) + /// + /// Initializes a new instance of the class. + /// + /// The that holds the serialized object data about the exception being thrown. + /// The that contains contextual information about the source or destination. + /// The parameter is null. + /// The class name is null or is zero (0). + public JsonSchemaException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } +#endif + + internal JsonSchemaException(string message, Exception innerException, string path, int lineNumber, int linePosition) + : base(message, innerException) + { + Path = path; + LineNumber = lineNumber; + LinePosition = linePosition; + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Schema/JsonSchemaGenerator.cs b/Common/00-1Json8.3/Json8.3/Schema/JsonSchemaGenerator.cs new file mode 100644 index 0000000..f003fdc --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Schema/JsonSchemaGenerator.cs @@ -0,0 +1,515 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Globalization; +using System.ComponentModel; +using System.Collections.Generic; +using Newtonsoft.Json.Linq; +using Newtonsoft.Json.Utilities; +using Newtonsoft.Json.Serialization; +#if NET20 +using Newtonsoft.Json.Utilities.LinqBridge; +#else +using System.Linq; + +#endif + +namespace Newtonsoft.Json.Schema +{ + /// + /// + /// Generates a from a specified . + /// + /// + /// JSON Schema validation has been moved to its own package. See http://www.newtonsoft.com/jsonschema for more details. + /// + /// + [Obsolete("JSON Schema validation has been moved to its own package. See http://www.newtonsoft.com/jsonschema for more details.")] + public class JsonSchemaGenerator + { + /// + /// Gets or sets how undefined schemas are handled by the serializer. + /// + public UndefinedSchemaIdHandling UndefinedSchemaIdHandling { get; set; } + + private IContractResolver _contractResolver; + + /// + /// Gets or sets the contract resolver. + /// + /// The contract resolver. + public IContractResolver ContractResolver + { + get + { + if (_contractResolver == null) + { + return DefaultContractResolver.Instance; + } + + return _contractResolver; + } + set { _contractResolver = value; } + } + + private class TypeSchema + { + public Type Type { get; private set; } + public JsonSchema Schema { get; private set; } + + public TypeSchema(Type type, JsonSchema schema) + { + ValidationUtils.ArgumentNotNull(type, nameof(type)); + ValidationUtils.ArgumentNotNull(schema, nameof(schema)); + + Type = type; + Schema = schema; + } + } + + private JsonSchemaResolver _resolver; + private readonly IList _stack = new List(); + private JsonSchema _currentSchema; + + private JsonSchema CurrentSchema + { + get { return _currentSchema; } + } + + private void Push(TypeSchema typeSchema) + { + _currentSchema = typeSchema.Schema; + _stack.Add(typeSchema); + _resolver.LoadedSchemas.Add(typeSchema.Schema); + } + + private TypeSchema Pop() + { + TypeSchema popped = _stack[_stack.Count - 1]; + _stack.RemoveAt(_stack.Count - 1); + TypeSchema newValue = _stack.LastOrDefault(); + if (newValue != null) + { + _currentSchema = newValue.Schema; + } + else + { + _currentSchema = null; + } + + return popped; + } + + /// + /// Generate a from the specified type. + /// + /// The type to generate a from. + /// A generated from the specified type. + public JsonSchema Generate(Type type) + { + return Generate(type, new JsonSchemaResolver(), false); + } + + /// + /// Generate a from the specified type. + /// + /// The type to generate a from. + /// The used to resolve schema references. + /// A generated from the specified type. + public JsonSchema Generate(Type type, JsonSchemaResolver resolver) + { + return Generate(type, resolver, false); + } + + /// + /// Generate a from the specified type. + /// + /// The type to generate a from. + /// Specify whether the generated root will be nullable. + /// A generated from the specified type. + public JsonSchema Generate(Type type, bool rootSchemaNullable) + { + return Generate(type, new JsonSchemaResolver(), rootSchemaNullable); + } + + /// + /// Generate a from the specified type. + /// + /// The type to generate a from. + /// The used to resolve schema references. + /// Specify whether the generated root will be nullable. + /// A generated from the specified type. + public JsonSchema Generate(Type type, JsonSchemaResolver resolver, bool rootSchemaNullable) + { + ValidationUtils.ArgumentNotNull(type, nameof(type)); + ValidationUtils.ArgumentNotNull(resolver, nameof(resolver)); + + _resolver = resolver; + + return GenerateInternal(type, (!rootSchemaNullable) ? Required.Always : Required.Default, false); + } + + private string GetTitle(Type type) + { + JsonContainerAttribute containerAttribute = JsonTypeReflector.GetCachedAttribute(type); + + if (containerAttribute != null && !string.IsNullOrEmpty(containerAttribute.Title)) + { + return containerAttribute.Title; + } + + return null; + } + + private string GetDescription(Type type) + { + JsonContainerAttribute containerAttribute = JsonTypeReflector.GetCachedAttribute(type); + + if (containerAttribute != null && !string.IsNullOrEmpty(containerAttribute.Description)) + { + return containerAttribute.Description; + } + +#if !(DOTNET || PORTABLE40 || PORTABLE) + DescriptionAttribute descriptionAttribute = ReflectionUtils.GetAttribute(type); + if (descriptionAttribute != null) + { + return descriptionAttribute.Description; + } +#endif + + return null; + } + + private string GetTypeId(Type type, bool explicitOnly) + { + JsonContainerAttribute containerAttribute = JsonTypeReflector.GetCachedAttribute(type); + + if (containerAttribute != null && !string.IsNullOrEmpty(containerAttribute.Id)) + { + return containerAttribute.Id; + } + + if (explicitOnly) + { + return null; + } + + switch (UndefinedSchemaIdHandling) + { + case UndefinedSchemaIdHandling.UseTypeName: + return type.FullName; + case UndefinedSchemaIdHandling.UseAssemblyQualifiedName: + return type.AssemblyQualifiedName; + default: + return null; + } + } + + private JsonSchema GenerateInternal(Type type, Required valueRequired, bool required) + { + ValidationUtils.ArgumentNotNull(type, nameof(type)); + + string resolvedId = GetTypeId(type, false); + string explicitId = GetTypeId(type, true); + + if (!string.IsNullOrEmpty(resolvedId)) + { + JsonSchema resolvedSchema = _resolver.GetSchema(resolvedId); + if (resolvedSchema != null) + { + // resolved schema is not null but referencing member allows nulls + // change resolved schema to allow nulls. hacky but what are ya gonna do? + if (valueRequired != Required.Always && !HasFlag(resolvedSchema.Type, JsonSchemaType.Null)) + { + resolvedSchema.Type |= JsonSchemaType.Null; + } + if (required && resolvedSchema.Required != true) + { + resolvedSchema.Required = true; + } + + return resolvedSchema; + } + } + + // test for unresolved circular reference + if (_stack.Any(tc => tc.Type == type)) + { + throw new JsonException("Unresolved circular reference for type '{0}'. Explicitly define an Id for the type using a JsonObject/JsonArray attribute or automatically generate a type Id using the UndefinedSchemaIdHandling property.".FormatWith(CultureInfo.InvariantCulture, type)); + } + + JsonContract contract = ContractResolver.ResolveContract(type); + JsonConverter converter; + if ((converter = contract.Converter) != null || (converter = contract.InternalConverter) != null) + { + JsonSchema converterSchema = converter.GetSchema(); + if (converterSchema != null) + { + return converterSchema; + } + } + + Push(new TypeSchema(type, new JsonSchema())); + + if (explicitId != null) + { + CurrentSchema.Id = explicitId; + } + + if (required) + { + CurrentSchema.Required = true; + } + CurrentSchema.Title = GetTitle(type); + CurrentSchema.Description = GetDescription(type); + + if (converter != null) + { + // todo: Add GetSchema to JsonConverter and use here? + CurrentSchema.Type = JsonSchemaType.Any; + } + else + { + switch (contract.ContractType) + { + case JsonContractType.Object: + CurrentSchema.Type = AddNullType(JsonSchemaType.Object, valueRequired); + CurrentSchema.Id = GetTypeId(type, false); + GenerateObjectSchema(type, (JsonObjectContract)contract); + break; + case JsonContractType.Array: + CurrentSchema.Type = AddNullType(JsonSchemaType.Array, valueRequired); + + CurrentSchema.Id = GetTypeId(type, false); + + JsonArrayAttribute arrayAttribute = JsonTypeReflector.GetCachedAttribute(type); + bool allowNullItem = (arrayAttribute == null || arrayAttribute.AllowNullItems); + + Type collectionItemType = ReflectionUtils.GetCollectionItemType(type); + if (collectionItemType != null) + { + CurrentSchema.Items = new List(); + CurrentSchema.Items.Add(GenerateInternal(collectionItemType, (!allowNullItem) ? Required.Always : Required.Default, false)); + } + break; + case JsonContractType.Primitive: + CurrentSchema.Type = GetJsonSchemaType(type, valueRequired); + + if (CurrentSchema.Type == JsonSchemaType.Integer && type.IsEnum() && !type.IsDefined(typeof(FlagsAttribute), true)) + { + CurrentSchema.Enum = new List(); + + IList> enumValues = EnumUtils.GetNamesAndValues(type); + foreach (EnumValue enumValue in enumValues) + { + JToken value = JToken.FromObject(enumValue.Value); + + CurrentSchema.Enum.Add(value); + } + } + break; + case JsonContractType.String: + JsonSchemaType schemaType = (!ReflectionUtils.IsNullable(contract.UnderlyingType)) + ? JsonSchemaType.String + : AddNullType(JsonSchemaType.String, valueRequired); + + CurrentSchema.Type = schemaType; + break; + case JsonContractType.Dictionary: + CurrentSchema.Type = AddNullType(JsonSchemaType.Object, valueRequired); + + Type keyType; + Type valueType; + ReflectionUtils.GetDictionaryKeyValueTypes(type, out keyType, out valueType); + + if (keyType != null) + { + JsonContract keyContract = ContractResolver.ResolveContract(keyType); + + // can be converted to a string + if (keyContract.ContractType == JsonContractType.Primitive) + { + CurrentSchema.AdditionalProperties = GenerateInternal(valueType, Required.Default, false); + } + } + break; +#if !(DOTNET || PORTABLE || PORTABLE40) + case JsonContractType.Serializable: + CurrentSchema.Type = AddNullType(JsonSchemaType.Object, valueRequired); + CurrentSchema.Id = GetTypeId(type, false); + GenerateISerializableContract(type, (JsonISerializableContract)contract); + break; +#endif +#if !(NET35 || NET20 || PORTABLE40) + case JsonContractType.Dynamic: +#endif + case JsonContractType.Linq: + CurrentSchema.Type = JsonSchemaType.Any; + break; + default: + throw new JsonException("Unexpected contract type: {0}".FormatWith(CultureInfo.InvariantCulture, contract)); + } + } + + return Pop().Schema; + } + + private JsonSchemaType AddNullType(JsonSchemaType type, Required valueRequired) + { + if (valueRequired != Required.Always) + { + return type | JsonSchemaType.Null; + } + + return type; + } + + private bool HasFlag(DefaultValueHandling value, DefaultValueHandling flag) + { + return ((value & flag) == flag); + } + + private void GenerateObjectSchema(Type type, JsonObjectContract contract) + { + CurrentSchema.Properties = new Dictionary(); + foreach (JsonProperty property in contract.Properties) + { + if (!property.Ignored) + { + bool optional = property.NullValueHandling == NullValueHandling.Ignore || + HasFlag(property.DefaultValueHandling.GetValueOrDefault(), DefaultValueHandling.Ignore) || + property.ShouldSerialize != null || + property.GetIsSpecified != null; + + JsonSchema propertySchema = GenerateInternal(property.PropertyType, property.Required, !optional); + + if (property.DefaultValue != null) + { + propertySchema.Default = JToken.FromObject(property.DefaultValue); + } + + CurrentSchema.Properties.Add(property.PropertyName, propertySchema); + } + } + + if (type.IsSealed()) + { + CurrentSchema.AllowAdditionalProperties = false; + } + } + +#if !(DOTNET || PORTABLE || PORTABLE40) + private void GenerateISerializableContract(Type type, JsonISerializableContract contract) + { + CurrentSchema.AllowAdditionalProperties = true; + } +#endif + + internal static bool HasFlag(JsonSchemaType? value, JsonSchemaType flag) + { + // default value is Any + if (value == null) + { + return true; + } + + bool match = ((value & flag) == flag); + if (match) + { + return true; + } + + // integer is a subset of float + if (flag == JsonSchemaType.Integer && (value & JsonSchemaType.Float) == JsonSchemaType.Float) + { + return true; + } + + return false; + } + + private JsonSchemaType GetJsonSchemaType(Type type, Required valueRequired) + { + JsonSchemaType schemaType = JsonSchemaType.None; + if (valueRequired != Required.Always && ReflectionUtils.IsNullable(type)) + { + schemaType = JsonSchemaType.Null; + if (ReflectionUtils.IsNullableType(type)) + { + type = Nullable.GetUnderlyingType(type); + } + } + + PrimitiveTypeCode typeCode = ConvertUtils.GetTypeCode(type); + + switch (typeCode) + { + case PrimitiveTypeCode.Empty: + case PrimitiveTypeCode.Object: + return schemaType | JsonSchemaType.String; +#if !(DOTNET || PORTABLE) + case PrimitiveTypeCode.DBNull: + return schemaType | JsonSchemaType.Null; +#endif + case PrimitiveTypeCode.Boolean: + return schemaType | JsonSchemaType.Boolean; + case PrimitiveTypeCode.Char: + return schemaType | JsonSchemaType.String; + case PrimitiveTypeCode.SByte: + case PrimitiveTypeCode.Byte: + case PrimitiveTypeCode.Int16: + case PrimitiveTypeCode.UInt16: + case PrimitiveTypeCode.Int32: + case PrimitiveTypeCode.UInt32: + case PrimitiveTypeCode.Int64: + case PrimitiveTypeCode.UInt64: +#if !(PORTABLE || NET35 || NET20) + case PrimitiveTypeCode.BigInteger: +#endif + return schemaType | JsonSchemaType.Integer; + case PrimitiveTypeCode.Single: + case PrimitiveTypeCode.Double: + case PrimitiveTypeCode.Decimal: + return schemaType | JsonSchemaType.Float; + // convert to string? + case PrimitiveTypeCode.DateTime: +#if !NET20 + case PrimitiveTypeCode.DateTimeOffset: +#endif + return schemaType | JsonSchemaType.String; + case PrimitiveTypeCode.String: + case PrimitiveTypeCode.Uri: + case PrimitiveTypeCode.Guid: + case PrimitiveTypeCode.TimeSpan: + case PrimitiveTypeCode.Bytes: + return schemaType | JsonSchemaType.String; + default: + throw new JsonException("Unexpected type code '{0}' for type '{1}'.".FormatWith(CultureInfo.InvariantCulture, typeCode, type)); + } + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Schema/JsonSchemaModel.cs b/Common/00-1Json8.3/Json8.3/Schema/JsonSchemaModel.cs new file mode 100644 index 0000000..7ff9706 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Schema/JsonSchemaModel.cs @@ -0,0 +1,125 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Collections.Generic; +using Newtonsoft.Json.Linq; +using Newtonsoft.Json.Utilities; + +namespace Newtonsoft.Json.Schema +{ + [Obsolete("JSON Schema validation has been moved to its own package. See http://www.newtonsoft.com/jsonschema for more details.")] + internal class JsonSchemaModel + { + public bool Required { get; set; } + public JsonSchemaType Type { get; set; } + public int? MinimumLength { get; set; } + public int? MaximumLength { get; set; } + public double? DivisibleBy { get; set; } + public double? Minimum { get; set; } + public double? Maximum { get; set; } + public bool ExclusiveMinimum { get; set; } + public bool ExclusiveMaximum { get; set; } + public int? MinimumItems { get; set; } + public int? MaximumItems { get; set; } + public IList Patterns { get; set; } + public IList Items { get; set; } + public IDictionary Properties { get; set; } + public IDictionary PatternProperties { get; set; } + public JsonSchemaModel AdditionalProperties { get; set; } + public JsonSchemaModel AdditionalItems { get; set; } + public bool PositionalItemsValidation { get; set; } + public bool AllowAdditionalProperties { get; set; } + public bool AllowAdditionalItems { get; set; } + public bool UniqueItems { get; set; } + public IList Enum { get; set; } + public JsonSchemaType Disallow { get; set; } + + public JsonSchemaModel() + { + Type = JsonSchemaType.Any; + AllowAdditionalProperties = true; + AllowAdditionalItems = true; + Required = false; + } + + public static JsonSchemaModel Create(IList schemata) + { + JsonSchemaModel model = new JsonSchemaModel(); + + foreach (JsonSchema schema in schemata) + { + Combine(model, schema); + } + + return model; + } + + private static void Combine(JsonSchemaModel model, JsonSchema schema) + { + // Version 3 of the Draft JSON Schema has the default value of Not Required + model.Required = model.Required || (schema.Required ?? false); + model.Type = model.Type & (schema.Type ?? JsonSchemaType.Any); + + model.MinimumLength = MathUtils.Max(model.MinimumLength, schema.MinimumLength); + model.MaximumLength = MathUtils.Min(model.MaximumLength, schema.MaximumLength); + + // not sure what is the best way to combine divisibleBy + model.DivisibleBy = MathUtils.Max(model.DivisibleBy, schema.DivisibleBy); + + model.Minimum = MathUtils.Max(model.Minimum, schema.Minimum); + model.Maximum = MathUtils.Max(model.Maximum, schema.Maximum); + model.ExclusiveMinimum = model.ExclusiveMinimum || (schema.ExclusiveMinimum ?? false); + model.ExclusiveMaximum = model.ExclusiveMaximum || (schema.ExclusiveMaximum ?? false); + + model.MinimumItems = MathUtils.Max(model.MinimumItems, schema.MinimumItems); + model.MaximumItems = MathUtils.Min(model.MaximumItems, schema.MaximumItems); + model.PositionalItemsValidation = model.PositionalItemsValidation || schema.PositionalItemsValidation; + model.AllowAdditionalProperties = model.AllowAdditionalProperties && schema.AllowAdditionalProperties; + model.AllowAdditionalItems = model.AllowAdditionalItems && schema.AllowAdditionalItems; + model.UniqueItems = model.UniqueItems || schema.UniqueItems; + if (schema.Enum != null) + { + if (model.Enum == null) + { + model.Enum = new List(); + } + + model.Enum.AddRangeDistinct(schema.Enum, JToken.EqualityComparer); + } + model.Disallow = model.Disallow | (schema.Disallow ?? JsonSchemaType.None); + + if (schema.Pattern != null) + { + if (model.Patterns == null) + { + model.Patterns = new List(); + } + + model.Patterns.AddDistinct(schema.Pattern); + } + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Schema/JsonSchemaModelBuilder.cs b/Common/00-1Json8.3/Json8.3/Schema/JsonSchemaModelBuilder.cs new file mode 100644 index 0000000..84b8c85 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Schema/JsonSchemaModelBuilder.cs @@ -0,0 +1,213 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Collections.Generic; +#if NET20 +using Newtonsoft.Json.Utilities.LinqBridge; +#else +using System.Linq; + +#endif + +namespace Newtonsoft.Json.Schema +{ + [Obsolete("JSON Schema validation has been moved to its own package. See http://www.newtonsoft.com/jsonschema for more details.")] + internal class JsonSchemaModelBuilder + { + private JsonSchemaNodeCollection _nodes = new JsonSchemaNodeCollection(); + private Dictionary _nodeModels = new Dictionary(); + private JsonSchemaNode _node; + + public JsonSchemaModel Build(JsonSchema schema) + { + _nodes = new JsonSchemaNodeCollection(); + _node = AddSchema(null, schema); + + _nodeModels = new Dictionary(); + JsonSchemaModel model = BuildNodeModel(_node); + + return model; + } + + public JsonSchemaNode AddSchema(JsonSchemaNode existingNode, JsonSchema schema) + { + string newId; + if (existingNode != null) + { + if (existingNode.Schemas.Contains(schema)) + { + return existingNode; + } + + newId = JsonSchemaNode.GetId(existingNode.Schemas.Union(new[] { schema })); + } + else + { + newId = JsonSchemaNode.GetId(new[] { schema }); + } + + if (_nodes.Contains(newId)) + { + return _nodes[newId]; + } + + JsonSchemaNode currentNode = (existingNode != null) + ? existingNode.Combine(schema) + : new JsonSchemaNode(schema); + + _nodes.Add(currentNode); + + AddProperties(schema.Properties, currentNode.Properties); + + AddProperties(schema.PatternProperties, currentNode.PatternProperties); + + if (schema.Items != null) + { + for (int i = 0; i < schema.Items.Count; i++) + { + AddItem(currentNode, i, schema.Items[i]); + } + } + + if (schema.AdditionalItems != null) + { + AddAdditionalItems(currentNode, schema.AdditionalItems); + } + + if (schema.AdditionalProperties != null) + { + AddAdditionalProperties(currentNode, schema.AdditionalProperties); + } + + if (schema.Extends != null) + { + foreach (JsonSchema jsonSchema in schema.Extends) + { + currentNode = AddSchema(currentNode, jsonSchema); + } + } + + return currentNode; + } + + public void AddProperties(IDictionary source, IDictionary target) + { + if (source != null) + { + foreach (KeyValuePair property in source) + { + AddProperty(target, property.Key, property.Value); + } + } + } + + public void AddProperty(IDictionary target, string propertyName, JsonSchema schema) + { + JsonSchemaNode propertyNode; + target.TryGetValue(propertyName, out propertyNode); + + target[propertyName] = AddSchema(propertyNode, schema); + } + + public void AddItem(JsonSchemaNode parentNode, int index, JsonSchema schema) + { + JsonSchemaNode existingItemNode = (parentNode.Items.Count > index) + ? parentNode.Items[index] + : null; + + JsonSchemaNode newItemNode = AddSchema(existingItemNode, schema); + + if (!(parentNode.Items.Count > index)) + { + parentNode.Items.Add(newItemNode); + } + else + { + parentNode.Items[index] = newItemNode; + } + } + + public void AddAdditionalProperties(JsonSchemaNode parentNode, JsonSchema schema) + { + parentNode.AdditionalProperties = AddSchema(parentNode.AdditionalProperties, schema); + } + + public void AddAdditionalItems(JsonSchemaNode parentNode, JsonSchema schema) + { + parentNode.AdditionalItems = AddSchema(parentNode.AdditionalItems, schema); + } + + private JsonSchemaModel BuildNodeModel(JsonSchemaNode node) + { + JsonSchemaModel model; + if (_nodeModels.TryGetValue(node, out model)) + { + return model; + } + + model = JsonSchemaModel.Create(node.Schemas); + _nodeModels[node] = model; + + foreach (KeyValuePair property in node.Properties) + { + if (model.Properties == null) + { + model.Properties = new Dictionary(); + } + + model.Properties[property.Key] = BuildNodeModel(property.Value); + } + foreach (KeyValuePair property in node.PatternProperties) + { + if (model.PatternProperties == null) + { + model.PatternProperties = new Dictionary(); + } + + model.PatternProperties[property.Key] = BuildNodeModel(property.Value); + } + foreach (JsonSchemaNode t in node.Items) + { + if (model.Items == null) + { + model.Items = new List(); + } + + model.Items.Add(BuildNodeModel(t)); + } + if (node.AdditionalProperties != null) + { + model.AdditionalProperties = BuildNodeModel(node.AdditionalProperties); + } + if (node.AdditionalItems != null) + { + model.AdditionalItems = BuildNodeModel(node.AdditionalItems); + } + + return model; + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Schema/JsonSchemaNode.cs b/Common/00-1Json8.3/Json8.3/Schema/JsonSchemaNode.cs new file mode 100644 index 0000000..05ca2de --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Schema/JsonSchemaNode.cs @@ -0,0 +1,81 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +#if NET20 +using Newtonsoft.Json.Utilities.LinqBridge; +#else +using System.Linq; + +#endif + +namespace Newtonsoft.Json.Schema +{ + [Obsolete("JSON Schema validation has been moved to its own package. See http://www.newtonsoft.com/jsonschema for more details.")] + internal class JsonSchemaNode + { + public string Id { get; private set; } + public ReadOnlyCollection Schemas { get; private set; } + public Dictionary Properties { get; private set; } + public Dictionary PatternProperties { get; private set; } + public List Items { get; private set; } + public JsonSchemaNode AdditionalProperties { get; set; } + public JsonSchemaNode AdditionalItems { get; set; } + + public JsonSchemaNode(JsonSchema schema) + { + Schemas = new ReadOnlyCollection(new[] { schema }); + Properties = new Dictionary(); + PatternProperties = new Dictionary(); + Items = new List(); + + Id = GetId(Schemas); + } + + private JsonSchemaNode(JsonSchemaNode source, JsonSchema schema) + { + Schemas = new ReadOnlyCollection(source.Schemas.Union(new[] { schema }).ToList()); + Properties = new Dictionary(source.Properties); + PatternProperties = new Dictionary(source.PatternProperties); + Items = new List(source.Items); + AdditionalProperties = source.AdditionalProperties; + AdditionalItems = source.AdditionalItems; + + Id = GetId(Schemas); + } + + public JsonSchemaNode Combine(JsonSchema schema) + { + return new JsonSchemaNode(this, schema); + } + + public static string GetId(IEnumerable schemata) + { + return string.Join("-", schemata.Select(s => s.InternalId).OrderBy(id => id, StringComparer.Ordinal).ToArray()); + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Schema/JsonSchemaNodeCollection.cs b/Common/00-1Json8.3/Json8.3/Schema/JsonSchemaNodeCollection.cs new file mode 100644 index 0000000..c96ab22 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Schema/JsonSchemaNodeCollection.cs @@ -0,0 +1,39 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Collections.ObjectModel; + +namespace Newtonsoft.Json.Schema +{ + [Obsolete("JSON Schema validation has been moved to its own package. See http://www.newtonsoft.com/jsonschema for more details.")] + internal class JsonSchemaNodeCollection : KeyedCollection + { + protected override string GetKeyForItem(JsonSchemaNode item) + { + return item.Id; + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Schema/JsonSchemaResolver.cs b/Common/00-1Json8.3/Json8.3/Schema/JsonSchemaResolver.cs new file mode 100644 index 0000000..5a8e6ce --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Schema/JsonSchemaResolver.cs @@ -0,0 +1,79 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Collections.Generic; +#if NET20 +using Newtonsoft.Json.Utilities.LinqBridge; +#else +using System.Linq; + +#endif + +namespace Newtonsoft.Json.Schema +{ + /// + /// + /// Resolves from an id. + /// + /// + /// JSON Schema validation has been moved to its own package. See http://www.newtonsoft.com/jsonschema for more details. + /// + /// + [Obsolete("JSON Schema validation has been moved to its own package. See http://www.newtonsoft.com/jsonschema for more details.")] + public class JsonSchemaResolver + { + /// + /// Gets or sets the loaded schemas. + /// + /// The loaded schemas. + public IList LoadedSchemas { get; protected set; } + + /// + /// Initializes a new instance of the class. + /// + public JsonSchemaResolver() + { + LoadedSchemas = new List(); + } + + /// + /// Gets a for the specified reference. + /// + /// The id. + /// A for the specified reference. + public virtual JsonSchema GetSchema(string reference) + { + JsonSchema schema = LoadedSchemas.SingleOrDefault(s => string.Equals(s.Id, reference, StringComparison.Ordinal)); + + if (schema == null) + { + schema = LoadedSchemas.SingleOrDefault(s => string.Equals(s.Location, reference, StringComparison.Ordinal)); + } + + return schema; + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Schema/JsonSchemaType.cs b/Common/00-1Json8.3/Json8.3/Schema/JsonSchemaType.cs new file mode 100644 index 0000000..c8af6bc --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Schema/JsonSchemaType.cs @@ -0,0 +1,87 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; + +namespace Newtonsoft.Json.Schema +{ + /// + /// + /// The value types allowed by the . + /// + /// + /// JSON Schema validation has been moved to its own package. See http://www.newtonsoft.com/jsonschema for more details. + /// + /// + [Flags] + [Obsolete("JSON Schema validation has been moved to its own package. See http://www.newtonsoft.com/jsonschema for more details.")] + public enum JsonSchemaType + { + /// + /// No type specified. + /// + None = 0, + + /// + /// String type. + /// + String = 1, + + /// + /// Float type. + /// + Float = 2, + + /// + /// Integer type. + /// + Integer = 4, + + /// + /// Boolean type. + /// + Boolean = 8, + + /// + /// Object type. + /// + Object = 16, + + /// + /// Array type. + /// + Array = 32, + + /// + /// Null type. + /// + Null = 64, + + /// + /// Any type. + /// + Any = String | Float | Integer | Boolean | Object | Array | Null + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Schema/JsonSchemaWriter.cs b/Common/00-1Json8.3/Json8.3/Schema/JsonSchemaWriter.cs new file mode 100644 index 0000000..c4d64ed --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Schema/JsonSchemaWriter.cs @@ -0,0 +1,259 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Collections.Generic; +using Newtonsoft.Json.Linq; +using Newtonsoft.Json.Serialization; +using Newtonsoft.Json.Utilities; +#if NET20 +using Newtonsoft.Json.Utilities.LinqBridge; +#else +using System.Linq; + +#endif + +namespace Newtonsoft.Json.Schema +{ + [Obsolete("JSON Schema validation has been moved to its own package. See http://www.newtonsoft.com/jsonschema for more details.")] + internal class JsonSchemaWriter + { + private readonly JsonWriter _writer; + private readonly JsonSchemaResolver _resolver; + + public JsonSchemaWriter(JsonWriter writer, JsonSchemaResolver resolver) + { + ValidationUtils.ArgumentNotNull(writer, nameof(writer)); + _writer = writer; + _resolver = resolver; + } + + private void ReferenceOrWriteSchema(JsonSchema schema) + { + if (schema.Id != null && _resolver.GetSchema(schema.Id) != null) + { + _writer.WriteStartObject(); + _writer.WritePropertyName(JsonTypeReflector.RefPropertyName); + _writer.WriteValue(schema.Id); + _writer.WriteEndObject(); + } + else + { + WriteSchema(schema); + } + } + + public void WriteSchema(JsonSchema schema) + { + ValidationUtils.ArgumentNotNull(schema, nameof(schema)); + + if (!_resolver.LoadedSchemas.Contains(schema)) + { + _resolver.LoadedSchemas.Add(schema); + } + + _writer.WriteStartObject(); + WritePropertyIfNotNull(_writer, JsonSchemaConstants.IdPropertyName, schema.Id); + WritePropertyIfNotNull(_writer, JsonSchemaConstants.TitlePropertyName, schema.Title); + WritePropertyIfNotNull(_writer, JsonSchemaConstants.DescriptionPropertyName, schema.Description); + WritePropertyIfNotNull(_writer, JsonSchemaConstants.RequiredPropertyName, schema.Required); + WritePropertyIfNotNull(_writer, JsonSchemaConstants.ReadOnlyPropertyName, schema.ReadOnly); + WritePropertyIfNotNull(_writer, JsonSchemaConstants.HiddenPropertyName, schema.Hidden); + WritePropertyIfNotNull(_writer, JsonSchemaConstants.TransientPropertyName, schema.Transient); + if (schema.Type != null) + { + WriteType(JsonSchemaConstants.TypePropertyName, _writer, schema.Type.GetValueOrDefault()); + } + if (!schema.AllowAdditionalProperties) + { + _writer.WritePropertyName(JsonSchemaConstants.AdditionalPropertiesPropertyName); + _writer.WriteValue(schema.AllowAdditionalProperties); + } + else + { + if (schema.AdditionalProperties != null) + { + _writer.WritePropertyName(JsonSchemaConstants.AdditionalPropertiesPropertyName); + ReferenceOrWriteSchema(schema.AdditionalProperties); + } + } + if (!schema.AllowAdditionalItems) + { + _writer.WritePropertyName(JsonSchemaConstants.AdditionalItemsPropertyName); + _writer.WriteValue(schema.AllowAdditionalItems); + } + else + { + if (schema.AdditionalItems != null) + { + _writer.WritePropertyName(JsonSchemaConstants.AdditionalItemsPropertyName); + ReferenceOrWriteSchema(schema.AdditionalItems); + } + } + WriteSchemaDictionaryIfNotNull(_writer, JsonSchemaConstants.PropertiesPropertyName, schema.Properties); + WriteSchemaDictionaryIfNotNull(_writer, JsonSchemaConstants.PatternPropertiesPropertyName, schema.PatternProperties); + WriteItems(schema); + WritePropertyIfNotNull(_writer, JsonSchemaConstants.MinimumPropertyName, schema.Minimum); + WritePropertyIfNotNull(_writer, JsonSchemaConstants.MaximumPropertyName, schema.Maximum); + WritePropertyIfNotNull(_writer, JsonSchemaConstants.ExclusiveMinimumPropertyName, schema.ExclusiveMinimum); + WritePropertyIfNotNull(_writer, JsonSchemaConstants.ExclusiveMaximumPropertyName, schema.ExclusiveMaximum); + WritePropertyIfNotNull(_writer, JsonSchemaConstants.MinimumLengthPropertyName, schema.MinimumLength); + WritePropertyIfNotNull(_writer, JsonSchemaConstants.MaximumLengthPropertyName, schema.MaximumLength); + WritePropertyIfNotNull(_writer, JsonSchemaConstants.MinimumItemsPropertyName, schema.MinimumItems); + WritePropertyIfNotNull(_writer, JsonSchemaConstants.MaximumItemsPropertyName, schema.MaximumItems); + WritePropertyIfNotNull(_writer, JsonSchemaConstants.DivisibleByPropertyName, schema.DivisibleBy); + WritePropertyIfNotNull(_writer, JsonSchemaConstants.FormatPropertyName, schema.Format); + WritePropertyIfNotNull(_writer, JsonSchemaConstants.PatternPropertyName, schema.Pattern); + if (schema.Enum != null) + { + _writer.WritePropertyName(JsonSchemaConstants.EnumPropertyName); + _writer.WriteStartArray(); + foreach (JToken token in schema.Enum) + { + token.WriteTo(_writer); + } + _writer.WriteEndArray(); + } + if (schema.Default != null) + { + _writer.WritePropertyName(JsonSchemaConstants.DefaultPropertyName); + schema.Default.WriteTo(_writer); + } + if (schema.Disallow != null) + { + WriteType(JsonSchemaConstants.DisallowPropertyName, _writer, schema.Disallow.GetValueOrDefault()); + } + if (schema.Extends != null && schema.Extends.Count > 0) + { + _writer.WritePropertyName(JsonSchemaConstants.ExtendsPropertyName); + if (schema.Extends.Count == 1) + { + ReferenceOrWriteSchema(schema.Extends[0]); + } + else + { + _writer.WriteStartArray(); + foreach (JsonSchema jsonSchema in schema.Extends) + { + ReferenceOrWriteSchema(jsonSchema); + } + _writer.WriteEndArray(); + } + } + _writer.WriteEndObject(); + } + + private void WriteSchemaDictionaryIfNotNull(JsonWriter writer, string propertyName, IDictionary properties) + { + if (properties != null) + { + writer.WritePropertyName(propertyName); + writer.WriteStartObject(); + foreach (KeyValuePair property in properties) + { + writer.WritePropertyName(property.Key); + ReferenceOrWriteSchema(property.Value); + } + writer.WriteEndObject(); + } + } + + private void WriteItems(JsonSchema schema) + { + if (schema.Items == null && !schema.PositionalItemsValidation) + { + return; + } + + _writer.WritePropertyName(JsonSchemaConstants.ItemsPropertyName); + + if (!schema.PositionalItemsValidation) + { + if (schema.Items != null && schema.Items.Count > 0) + { + ReferenceOrWriteSchema(schema.Items[0]); + } + else + { + _writer.WriteStartObject(); + _writer.WriteEndObject(); + } + return; + } + + _writer.WriteStartArray(); + if (schema.Items != null) + { + foreach (JsonSchema itemSchema in schema.Items) + { + ReferenceOrWriteSchema(itemSchema); + } + } + _writer.WriteEndArray(); + } + + private void WriteType(string propertyName, JsonWriter writer, JsonSchemaType type) + { + IList types; + if (System.Enum.IsDefined(typeof(JsonSchemaType), type)) + { + types = new List { type }; + } + else + { + types = EnumUtils.GetFlagsValues(type).Where(v => v != JsonSchemaType.None).ToList(); + } + + if (types.Count == 0) + { + return; + } + + writer.WritePropertyName(propertyName); + + if (types.Count == 1) + { + writer.WriteValue(JsonSchemaBuilder.MapType(types[0])); + return; + } + + writer.WriteStartArray(); + foreach (JsonSchemaType jsonSchemaType in types) + { + writer.WriteValue(JsonSchemaBuilder.MapType(jsonSchemaType)); + } + writer.WriteEndArray(); + } + + private void WritePropertyIfNotNull(JsonWriter writer, string propertyName, object value) + { + if (value != null) + { + writer.WritePropertyName(propertyName); + writer.WriteValue(value); + } + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Schema/UndefinedSchemaIdHandling.cs b/Common/00-1Json8.3/Json8.3/Schema/UndefinedSchemaIdHandling.cs new file mode 100644 index 0000000..dfff8b1 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Schema/UndefinedSchemaIdHandling.cs @@ -0,0 +1,56 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; + +namespace Newtonsoft.Json.Schema +{ + /// + /// + /// Specifies undefined schema Id handling options for the . + /// + /// + /// JSON Schema validation has been moved to its own package. See http://www.newtonsoft.com/jsonschema for more details. + /// + /// + [Obsolete("JSON Schema validation has been moved to its own package. See http://www.newtonsoft.com/jsonschema for more details.")] + public enum UndefinedSchemaIdHandling + { + /// + /// Do not infer a schema Id. + /// + None = 0, + + /// + /// Use the .NET type name as the schema Id. + /// + UseTypeName = 1, + + /// + /// Use the assembly qualified .NET type name as the schema Id. + /// + UseAssemblyQualifiedName = 2, + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Schema/ValidationEventArgs.cs b/Common/00-1Json8.3/Json8.3/Schema/ValidationEventArgs.cs new file mode 100644 index 0000000..b144459 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Schema/ValidationEventArgs.cs @@ -0,0 +1,77 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using Newtonsoft.Json.Utilities; + +namespace Newtonsoft.Json.Schema +{ + /// + /// + /// Returns detailed information related to the . + /// + /// + /// JSON Schema validation has been moved to its own package. See http://www.newtonsoft.com/jsonschema for more details. + /// + /// + [Obsolete("JSON Schema validation has been moved to its own package. See http://www.newtonsoft.com/jsonschema for more details.")] + public class ValidationEventArgs : EventArgs + { + private readonly JsonSchemaException _ex; + + internal ValidationEventArgs(JsonSchemaException ex) + { + ValidationUtils.ArgumentNotNull(ex, nameof(ex)); + _ex = ex; + } + + /// + /// Gets the associated with the validation error. + /// + /// The JsonSchemaException associated with the validation error. + public JsonSchemaException Exception + { + get { return _ex; } + } + + /// + /// Gets the path of the JSON location where the validation error occurred. + /// + /// The path of the JSON location where the validation error occurred. + public string Path + { + get { return _ex.Path; } + } + + /// + /// Gets the text description corresponding to the validation error. + /// + /// The text description. + public string Message + { + get { return _ex.Message; } + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Schema/ValidationEventHandler.cs b/Common/00-1Json8.3/Json8.3/Schema/ValidationEventHandler.cs new file mode 100644 index 0000000..408d8c5 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Schema/ValidationEventHandler.cs @@ -0,0 +1,40 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; + +namespace Newtonsoft.Json.Schema +{ + /// + /// + /// Represents the callback method that will handle JSON schema validation events and the . + /// + /// + /// JSON Schema validation has been moved to its own package. See http://www.newtonsoft.com/jsonschema for more details. + /// + /// + [Obsolete("JSON Schema validation has been moved to its own package. See http://www.newtonsoft.com/jsonschema for more details.")] + public delegate void ValidationEventHandler(object sender, ValidationEventArgs e); +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Serialization/CachedAttributeGetter.cs b/Common/00-1Json8.3/Json8.3/Serialization/CachedAttributeGetter.cs new file mode 100644 index 0000000..0645631 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Serialization/CachedAttributeGetter.cs @@ -0,0 +1,41 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Reflection; +using Newtonsoft.Json.Utilities; + +namespace Newtonsoft.Json.Serialization +{ + internal static class CachedAttributeGetter where T : Attribute + { + private static readonly ThreadSafeStore TypeAttributeCache = new ThreadSafeStore(JsonTypeReflector.GetAttribute); + + public static T GetAttribute(object type) + { + return TypeAttributeCache.Get(type); + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Serialization/CamelCasePropertyNamesContractResolver.cs b/Common/00-1Json8.3/Json8.3/Serialization/CamelCasePropertyNamesContractResolver.cs new file mode 100644 index 0000000..ea9ee82 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Serialization/CamelCasePropertyNamesContractResolver.cs @@ -0,0 +1,57 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System.Globalization; +using Newtonsoft.Json.Utilities; + +namespace Newtonsoft.Json.Serialization +{ + /// + /// Resolves member mappings for a type, camel casing property names. + /// + public class CamelCasePropertyNamesContractResolver : DefaultContractResolver + { + /// + /// Initializes a new instance of the class. + /// + public CamelCasePropertyNamesContractResolver() +#pragma warning disable 612,618 + : base(true) +#pragma warning restore 612,618 + { + } + + /// + /// Resolves the name of the property. + /// + /// Name of the property. + /// The property name camel cased. + protected override string ResolvePropertyName(string propertyName) + { + // lower case the first letter (or more) of the passed in name + return StringUtils.ToCamelCase(propertyName); + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Serialization/DefaultContractResolver.cs b/Common/00-1Json8.3/Json8.3/Serialization/DefaultContractResolver.cs new file mode 100644 index 0000000..bf97033 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Serialization/DefaultContractResolver.cs @@ -0,0 +1,1571 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Collections; +using Newtonsoft.Json.Schema; +#if !(NET35 || NET20 || PORTABLE || PORTABLE40) +using System.Collections.Concurrent; +#endif +using System.Collections.Generic; +using System.ComponentModel; +#if !(NET35 || NET20 || PORTABLE40) +using System.Dynamic; +#endif +using System.Globalization; +using System.Reflection; +using System.Runtime.Serialization; +#if !(DOTNET || PORTABLE || PORTABLE40) +using System.Security.Permissions; +#endif +using System.Xml.Serialization; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Utilities; +using Newtonsoft.Json.Linq; +using System.Runtime.CompilerServices; +#if NET20 +using Newtonsoft.Json.Utilities.LinqBridge; +#else +using System.Linq; + +#endif + +namespace Newtonsoft.Json.Serialization +{ + internal struct ResolverContractKey : IEquatable + { + private readonly Type _resolverType; + private readonly Type _contractType; + + public ResolverContractKey(Type resolverType, Type contractType) + { + _resolverType = resolverType; + _contractType = contractType; + } + + public override int GetHashCode() + { + return _resolverType.GetHashCode() ^ _contractType.GetHashCode(); + } + + public override bool Equals(object obj) + { + if (!(obj is ResolverContractKey)) + { + return false; + } + + return Equals((ResolverContractKey)obj); + } + + public bool Equals(ResolverContractKey other) + { + return (_resolverType == other._resolverType && _contractType == other._contractType); + } + } + + internal class DefaultContractResolverState + { + public Dictionary ContractCache; + public PropertyNameTable NameTable = new PropertyNameTable(); + } + + /// + /// Used by to resolves a for a given . + /// + public class DefaultContractResolver : IContractResolver + { +#pragma warning disable 612,618 + private static readonly IContractResolver _instance = new DefaultContractResolver(true); +#pragma warning restore 612,618 + + internal static IContractResolver Instance + { + get { return _instance; } + } + + private static readonly JsonConverter[] BuiltInConverters = + { +#if !(NET20 || DOTNET || PORTABLE40 || PORTABLE) + new EntityKeyMemberConverter(), +#endif +#if !(NET35 || NET20 || PORTABLE40) + new ExpandoObjectConverter(), +#endif +#if !(PORTABLE40) + new XmlNodeConverter(), +#endif +#if !(DOTNET || PORTABLE40 || PORTABLE) + new BinaryConverter(), + new DataSetConverter(), + new DataTableConverter(), +#endif +#if !(NET35 || NET20) + new DiscriminatedUnionConverter(), +#endif + new KeyValuePairConverter(), + new BsonObjectIdConverter(), + new RegexConverter() + }; + + private static readonly object TypeContractCacheLock = new object(); + + private static readonly DefaultContractResolverState _sharedState = new DefaultContractResolverState(); + private readonly DefaultContractResolverState _instanceState = new DefaultContractResolverState(); + private readonly bool _sharedCache; + + /// + /// Gets a value indicating whether members are being get and set using dynamic code generation. + /// This value is determined by the runtime permissions available. + /// + /// + /// true if using dynamic code generation; otherwise, false. + /// + public bool DynamicCodeGeneration + { + get { return JsonTypeReflector.DynamicCodeGeneration; } + } + +#if !PORTABLE + /// + /// Gets or sets the default members search flags. + /// + /// The default members search flags. + [ObsoleteAttribute("DefaultMembersSearchFlags is obsolete. To modify the members serialized inherit from DefaultContractResolver and override the GetSerializableMembers method instead.")] + public BindingFlags DefaultMembersSearchFlags { get; set; } +#else + private BindingFlags DefaultMembersSearchFlags; +#endif + + /// + /// Gets or sets a value indicating whether compiler generated members should be serialized. + /// + /// + /// true if serialized compiler generated members; otherwise, false. + /// + public bool SerializeCompilerGeneratedMembers { get; set; } + +#if !(DOTNET || PORTABLE || PORTABLE40) + /// + /// Gets or sets a value indicating whether to ignore the interface when serializing and deserializing types. + /// + /// + /// true if the interface will be ignored when serializing and deserializing types; otherwise, false. + /// + public bool IgnoreSerializableInterface { get; set; } + + /// + /// Gets or sets a value indicating whether to ignore the attribute when serializing and deserializing types. + /// + /// + /// true if the attribute will be ignored when serializing and deserializing types; otherwise, false. + /// + public bool IgnoreSerializableAttribute { get; set; } +#endif + + /// + /// Initializes a new instance of the class. + /// + public DefaultContractResolver() + { +#if !(DOTNET || PORTABLE || PORTABLE40) + IgnoreSerializableAttribute = true; +#endif + +#pragma warning disable 618 + DefaultMembersSearchFlags = BindingFlags.Instance | BindingFlags.Public; +#pragma warning restore 618 + } + + /// + /// Initializes a new instance of the class. + /// + /// + /// If set to true the will use a cached shared with other resolvers of the same type. + /// Sharing the cache will significantly improve performance with multiple resolver instances because expensive reflection will only + /// happen once. This setting can cause unexpected behavior if different instances of the resolver are suppose to produce different + /// results. When set to false it is highly recommended to reuse instances with the . + /// + [ObsoleteAttribute("DefaultContractResolver(bool) is obsolete. Use the parameterless constructor and cache instances of the contract resolver within your application for optimal performance.")] + public DefaultContractResolver(bool shareCache) + : this() + { + _sharedCache = shareCache; + } + + internal DefaultContractResolverState GetState() + { + if (_sharedCache) + { + return _sharedState; + } + else + { + return _instanceState; + } + } + + /// + /// Resolves the contract for a given type. + /// + /// The type to resolve a contract for. + /// The contract for a given type. + public virtual JsonContract ResolveContract(Type type) + { + if (type == null) + { + throw new ArgumentNullException(nameof(type)); + } + + DefaultContractResolverState state = GetState(); + + JsonContract contract; + ResolverContractKey key = new ResolverContractKey(GetType(), type); + Dictionary cache = state.ContractCache; + if (cache == null || !cache.TryGetValue(key, out contract)) + { + contract = CreateContract(type); + + // avoid the possibility of modifying the cache dictionary while another thread is accessing it + lock (TypeContractCacheLock) + { + cache = state.ContractCache; + Dictionary updatedCache = (cache != null) + ? new Dictionary(cache) + : new Dictionary(); + updatedCache[key] = contract; + + state.ContractCache = updatedCache; + } + } + + return contract; + } + + /// + /// Gets the serializable members for the type. + /// + /// The type to get serializable members for. + /// The serializable members for the type. + protected virtual List GetSerializableMembers(Type objectType) + { + bool ignoreSerializableAttribute; +#if !(DOTNET || PORTABLE || PORTABLE40) + ignoreSerializableAttribute = IgnoreSerializableAttribute; +#else + ignoreSerializableAttribute = true; +#endif + + MemberSerialization memberSerialization = JsonTypeReflector.GetObjectMemberSerialization(objectType, ignoreSerializableAttribute); + + List allMembers = ReflectionUtils.GetFieldsAndProperties(objectType, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static) + .Where(m => !ReflectionUtils.IsIndexedProperty(m)).ToList(); + + List serializableMembers = new List(); + + if (memberSerialization != MemberSerialization.Fields) + { +#if !NET20 + DataContractAttribute dataContractAttribute = JsonTypeReflector.GetDataContractAttribute(objectType); +#endif + +#pragma warning disable 618 + List defaultMembers = ReflectionUtils.GetFieldsAndProperties(objectType, DefaultMembersSearchFlags) + .Where(m => !ReflectionUtils.IsIndexedProperty(m)).ToList(); +#pragma warning restore 618 + + foreach (MemberInfo member in allMembers) + { + // exclude members that are compiler generated if set + if (SerializeCompilerGeneratedMembers || !member.IsDefined(typeof(CompilerGeneratedAttribute), true)) + { + if (defaultMembers.Contains(member)) + { + // add all members that are found by default member search + serializableMembers.Add(member); + } + else + { + // add members that are explicitly marked with JsonProperty/DataMember attribute + // or are a field if serializing just fields + if (JsonTypeReflector.GetAttribute(member) != null) + { + serializableMembers.Add(member); + } + else if (JsonTypeReflector.GetAttribute(member) != null) + { + serializableMembers.Add(member); + } +#if !NET20 + else if (dataContractAttribute != null && JsonTypeReflector.GetAttribute(member) != null) + { + serializableMembers.Add(member); + } +#endif + else if (memberSerialization == MemberSerialization.Fields && member.MemberType() == MemberTypes.Field) + { + serializableMembers.Add(member); + } + } + } + } + +#if !NET20 + Type match; + // don't include EntityKey on entities objects... this is a bit hacky + if (objectType.AssignableToTypeName("System.Data.Objects.DataClasses.EntityObject", out match)) + { + serializableMembers = serializableMembers.Where(ShouldSerializeEntityMember).ToList(); + } +#endif + } + else + { + // serialize all fields + foreach (MemberInfo member in allMembers) + { + FieldInfo field = member as FieldInfo; + if (field != null && !field.IsStatic) + { + serializableMembers.Add(member); + } + } + } + + return serializableMembers; + } + +#if !NET20 + private bool ShouldSerializeEntityMember(MemberInfo memberInfo) + { + PropertyInfo propertyInfo = memberInfo as PropertyInfo; + if (propertyInfo != null) + { + if (propertyInfo.PropertyType.IsGenericType() && propertyInfo.PropertyType.GetGenericTypeDefinition().FullName == "System.Data.Objects.DataClasses.EntityReference`1") + { + return false; + } + } + + return true; + } +#endif + + /// + /// Creates a for the given type. + /// + /// Type of the object. + /// A for the given type. + protected virtual JsonObjectContract CreateObjectContract(Type objectType) + { + JsonObjectContract contract = new JsonObjectContract(objectType); + InitializeContract(contract); + + bool ignoreSerializableAttribute; +#if !(DOTNET || PORTABLE || PORTABLE40) + ignoreSerializableAttribute = IgnoreSerializableAttribute; +#else + ignoreSerializableAttribute = true; +#endif + + contract.MemberSerialization = JsonTypeReflector.GetObjectMemberSerialization(contract.NonNullableUnderlyingType, ignoreSerializableAttribute); + contract.Properties.AddRange(CreateProperties(contract.NonNullableUnderlyingType, contract.MemberSerialization)); + + JsonObjectAttribute attribute = JsonTypeReflector.GetCachedAttribute(contract.NonNullableUnderlyingType); + if (attribute != null) + { + contract.ItemRequired = attribute._itemRequired; + } + + if (contract.IsInstantiable) + { + ConstructorInfo overrideConstructor = GetAttributeConstructor(contract.NonNullableUnderlyingType); + + // check if a JsonConstructorAttribute has been defined and use that + if (overrideConstructor != null) + { +#pragma warning disable 618 + contract.OverrideConstructor = overrideConstructor; +#pragma warning restore 618 + contract.CreatorParameters.AddRange(CreateConstructorParameters(overrideConstructor, contract.Properties)); + } + else if (contract.MemberSerialization == MemberSerialization.Fields) + { +#if !(DOTNET || PORTABLE40 || PORTABLE) + // mimic DataContractSerializer behaviour when populating fields by overriding default creator to create an uninitialized object + // note that this is only possible when the application is fully trusted so fall back to using the default constructor (if available) in partial trust + if (JsonTypeReflector.FullyTrusted) + { + contract.DefaultCreator = contract.GetUninitializedObject; + } +#endif + } + else if (contract.DefaultCreator == null || contract.DefaultCreatorNonPublic) + { + ConstructorInfo constructor = GetParameterizedConstructor(contract.NonNullableUnderlyingType); + if (constructor != null) + { +#pragma warning disable 618 + contract.ParametrizedConstructor = constructor; +#pragma warning restore 618 + contract.CreatorParameters.AddRange(CreateConstructorParameters(constructor, contract.Properties)); + } + } + } + + MemberInfo extensionDataMember = GetExtensionDataMemberForType(contract.NonNullableUnderlyingType); + if (extensionDataMember != null) + { + SetExtensionDataDelegates(contract, extensionDataMember); + } + + return contract; + } + + private MemberInfo GetExtensionDataMemberForType(Type type) + { + IEnumerable members = GetClassHierarchyForType(type).SelectMany(baseType => + { + IList m = new List(); + m.AddRange(baseType.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly)); + m.AddRange(baseType.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly)); + + return m; + }); + + MemberInfo extensionDataMember = members.LastOrDefault(m => + { + MemberTypes memberType = m.MemberType(); + if (memberType != MemberTypes.Property && memberType != MemberTypes.Field) + { + return false; + } + + // last instance of attribute wins on type if there are multiple + if (!m.IsDefined(typeof(JsonExtensionDataAttribute), false)) + { + return false; + } + + if (!ReflectionUtils.CanReadMemberValue(m, true)) + { + throw new JsonException("Invalid extension data attribute on '{0}'. Member '{1}' must have a getter.".FormatWith(CultureInfo.InvariantCulture, GetClrTypeFullName(m.DeclaringType), m.Name)); + } + + Type t = ReflectionUtils.GetMemberUnderlyingType(m); + + Type dictionaryType; + if (ReflectionUtils.ImplementsGenericDefinition(t, typeof(IDictionary<,>), out dictionaryType)) + { + Type keyType = dictionaryType.GetGenericArguments()[0]; + Type valueType = dictionaryType.GetGenericArguments()[1]; + + if (keyType.IsAssignableFrom(typeof(string)) && valueType.IsAssignableFrom(typeof(JToken))) + { + return true; + } + } + + throw new JsonException("Invalid extension data attribute on '{0}'. Member '{1}' type must implement IDictionary.".FormatWith(CultureInfo.InvariantCulture, GetClrTypeFullName(m.DeclaringType), m.Name)); + }); + + return extensionDataMember; + } + + private static void SetExtensionDataDelegates(JsonObjectContract contract, MemberInfo member) + { + JsonExtensionDataAttribute extensionDataAttribute = ReflectionUtils.GetAttribute(member); + if (extensionDataAttribute == null) + { + return; + } + + Type t = ReflectionUtils.GetMemberUnderlyingType(member); + + Type dictionaryType; + ReflectionUtils.ImplementsGenericDefinition(t, typeof(IDictionary<,>), out dictionaryType); + + Type keyType = dictionaryType.GetGenericArguments()[0]; + Type valueType = dictionaryType.GetGenericArguments()[1]; + + Type createdType; + + // change type to a class if it is the base interface so it can be instantiated if needed + if (ReflectionUtils.IsGenericDefinition(t, typeof(IDictionary<,>))) + { + createdType = typeof(Dictionary<,>).MakeGenericType(keyType, valueType); + } + else + { + createdType = t; + } + + Func getExtensionDataDictionary = JsonTypeReflector.ReflectionDelegateFactory.CreateGet(member); + + if (extensionDataAttribute.ReadData) + { + Action setExtensionDataDictionary = (ReflectionUtils.CanSetMemberValue(member, true, false)) + ? JsonTypeReflector.ReflectionDelegateFactory.CreateSet(member) + : null; + Func createExtensionDataDictionary = JsonTypeReflector.ReflectionDelegateFactory.CreateDefaultConstructor(createdType); + MethodInfo addMethod = t.GetMethod("Add", new[] { keyType, valueType }); + MethodCall setExtensionDataDictionaryValue = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall(addMethod); + + ExtensionDataSetter extensionDataSetter = (o, key, value) => + { + object dictionary = getExtensionDataDictionary(o); + if (dictionary == null) + { + if (setExtensionDataDictionary == null) + { + throw new JsonSerializationException("Cannot set value onto extension data member '{0}'. The extension data collection is null and it cannot be set.".FormatWith(CultureInfo.InvariantCulture, member.Name)); + } + + dictionary = createExtensionDataDictionary(); + setExtensionDataDictionary(o, dictionary); + } + + setExtensionDataDictionaryValue(dictionary, key, value); + }; + + contract.ExtensionDataSetter = extensionDataSetter; + } + + if (extensionDataAttribute.WriteData) + { + Type enumerableWrapper = typeof(EnumerableDictionaryWrapper<,>).MakeGenericType(keyType, valueType); + ConstructorInfo constructors = enumerableWrapper.GetConstructors().First(); + ObjectConstructor createEnumerableWrapper = JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(constructors); + + ExtensionDataGetter extensionDataGetter = o => + { + object dictionary = getExtensionDataDictionary(o); + if (dictionary == null) + { + return null; + } + + return (IEnumerable>)createEnumerableWrapper(dictionary); + }; + + contract.ExtensionDataGetter = extensionDataGetter; + } + + contract.ExtensionDataValueType = valueType; + } + + // leave as class instead of struct + // will be always return as an interface and boxed + internal class EnumerableDictionaryWrapper : IEnumerable> + { + private readonly IEnumerable> _e; + + public EnumerableDictionaryWrapper(IEnumerable> e) + { + ValidationUtils.ArgumentNotNull(e, nameof(e)); + _e = e; + } + + public IEnumerator> GetEnumerator() + { + foreach (KeyValuePair item in _e) + { + yield return new KeyValuePair(item.Key, item.Value); + } + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + } + + private ConstructorInfo GetAttributeConstructor(Type objectType) + { + IList markedConstructors = objectType.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Where(c => c.IsDefined(typeof(JsonConstructorAttribute), true)).ToList(); + + if (markedConstructors.Count > 1) + { + throw new JsonException("Multiple constructors with the JsonConstructorAttribute."); + } + else if (markedConstructors.Count == 1) + { + return markedConstructors[0]; + } + + // little hack to get Version objects to deserialize correctly + if (objectType == typeof(Version)) + { + return objectType.GetConstructor(new[] { typeof(int), typeof(int), typeof(int), typeof(int) }); + } + + return null; + } + + private ConstructorInfo GetParameterizedConstructor(Type objectType) + { + IList constructors = objectType.GetConstructors(BindingFlags.Public | BindingFlags.Instance).ToList(); + + if (constructors.Count == 1) + { + return constructors[0]; + } + else + { + return null; + } + } + + /// + /// Creates the constructor parameters. + /// + /// The constructor to create properties for. + /// The type's member properties. + /// Properties for the given . + protected virtual IList CreateConstructorParameters(ConstructorInfo constructor, JsonPropertyCollection memberProperties) + { + var constructorParameters = constructor.GetParameters(); + + JsonPropertyCollection parameterCollection = new JsonPropertyCollection(constructor.DeclaringType); + + foreach (ParameterInfo parameterInfo in constructorParameters) + { + // it is possible to generate a ParameterInfo with a null name using Reflection.Emit + // protect against an ArgumentNullException from GetClosestMatchProperty by testing for null here + JsonProperty matchingMemberProperty = (parameterInfo.Name != null) ? memberProperties.GetClosestMatchProperty(parameterInfo.Name) : null; + + // type must match as well as name + if (matchingMemberProperty != null && matchingMemberProperty.PropertyType != parameterInfo.ParameterType) + { + matchingMemberProperty = null; + } + + // ensure that property will have a name from matching property or from parameterinfo + // parameterinfo could have no name if generated by a proxy (I'm looking at you Castle) + if (matchingMemberProperty != null || parameterInfo.Name != null) + { + JsonProperty property = CreatePropertyFromConstructorParameter(matchingMemberProperty, parameterInfo); + + if (property != null) + { + parameterCollection.AddProperty(property); + } + } + } + + return parameterCollection; + } + + /// + /// Creates a for the given . + /// + /// The matching member property. + /// The constructor parameter. + /// A created for the given . + protected virtual JsonProperty CreatePropertyFromConstructorParameter(JsonProperty matchingMemberProperty, ParameterInfo parameterInfo) + { + JsonProperty property = new JsonProperty(); + property.PropertyType = parameterInfo.ParameterType; + property.AttributeProvider = new ReflectionAttributeProvider(parameterInfo); + + bool allowNonPublicAccess; + SetPropertySettingsFromAttributes(property, parameterInfo, parameterInfo.Name, parameterInfo.Member.DeclaringType, MemberSerialization.OptOut, out allowNonPublicAccess); + + property.Readable = false; + property.Writable = true; + + // "inherit" values from matching member property if unset on parameter + if (matchingMemberProperty != null) + { + property.PropertyName = (property.PropertyName != parameterInfo.Name) ? property.PropertyName : matchingMemberProperty.PropertyName; + property.Converter = property.Converter ?? matchingMemberProperty.Converter; + property.MemberConverter = property.MemberConverter ?? matchingMemberProperty.MemberConverter; + + if (!property._hasExplicitDefaultValue && matchingMemberProperty._hasExplicitDefaultValue) + { + property.DefaultValue = matchingMemberProperty.DefaultValue; + } + + property._required = property._required ?? matchingMemberProperty._required; + property.IsReference = property.IsReference ?? matchingMemberProperty.IsReference; + property.NullValueHandling = property.NullValueHandling ?? matchingMemberProperty.NullValueHandling; + property.DefaultValueHandling = property.DefaultValueHandling ?? matchingMemberProperty.DefaultValueHandling; + property.ReferenceLoopHandling = property.ReferenceLoopHandling ?? matchingMemberProperty.ReferenceLoopHandling; + property.ObjectCreationHandling = property.ObjectCreationHandling ?? matchingMemberProperty.ObjectCreationHandling; + property.TypeNameHandling = property.TypeNameHandling ?? matchingMemberProperty.TypeNameHandling; + } + + return property; + } + + /// + /// Resolves the default for the contract. + /// + /// Type of the object. + /// The contract's default . + protected virtual JsonConverter ResolveContractConverter(Type objectType) + { + return JsonTypeReflector.GetJsonConverter(objectType); + } + + private Func GetDefaultCreator(Type createdType) + { + return JsonTypeReflector.ReflectionDelegateFactory.CreateDefaultConstructor(createdType); + } + +#if NET35 + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Portability", "CA1903:UseOnlyApiFromTargetedFramework", MessageId = "System.Runtime.Serialization.DataContractAttribute.#get_IsReference()")] +#endif + + private void InitializeContract(JsonContract contract) + { + JsonContainerAttribute containerAttribute = JsonTypeReflector.GetCachedAttribute(contract.NonNullableUnderlyingType); + if (containerAttribute != null) + { + contract.IsReference = containerAttribute._isReference; + } +#if !NET20 + else + { + DataContractAttribute dataContractAttribute = JsonTypeReflector.GetDataContractAttribute(contract.NonNullableUnderlyingType); + // doesn't have a null value + if (dataContractAttribute != null && dataContractAttribute.IsReference) + { + contract.IsReference = true; + } + } +#endif + + contract.Converter = ResolveContractConverter(contract.NonNullableUnderlyingType); + + // then see whether object is compadible with any of the built in converters + contract.InternalConverter = JsonSerializer.GetMatchingConverter(BuiltInConverters, contract.NonNullableUnderlyingType); + + if (contract.IsInstantiable + && (ReflectionUtils.HasDefaultConstructor(contract.CreatedType, true) || contract.CreatedType.IsValueType())) + { + contract.DefaultCreator = GetDefaultCreator(contract.CreatedType); + + contract.DefaultCreatorNonPublic = (!contract.CreatedType.IsValueType() && + ReflectionUtils.GetDefaultConstructor(contract.CreatedType) == null); + } + + ResolveCallbackMethods(contract, contract.NonNullableUnderlyingType); + } + + private void ResolveCallbackMethods(JsonContract contract, Type t) + { + List onSerializing; + List onSerialized; + List onDeserializing; + List onDeserialized; + List onError; + + GetCallbackMethodsForType(t, out onSerializing, out onSerialized, out onDeserializing, out onDeserialized, out onError); + + if (onSerializing != null) + { + contract.OnSerializingCallbacks.AddRange(onSerializing); + } + + if (onSerialized != null) + { + contract.OnSerializedCallbacks.AddRange(onSerialized); + } + + if (onDeserializing != null) + { + contract.OnDeserializingCallbacks.AddRange(onDeserializing); + } + + if (onDeserialized != null) + { + contract.OnDeserializedCallbacks.AddRange(onDeserialized); + } + + if (onError != null) + { + contract.OnErrorCallbacks.AddRange(onError); + } + } + + private void GetCallbackMethodsForType(Type type, out List onSerializing, out List onSerialized, out List onDeserializing, out List onDeserialized, out List onError) + { + onSerializing = null; + onSerialized = null; + onDeserializing = null; + onDeserialized = null; + onError = null; + + foreach (Type baseType in GetClassHierarchyForType(type)) + { + // while we allow more than one OnSerialized total, only one can be defined per class + MethodInfo currentOnSerializing = null; + MethodInfo currentOnSerialized = null; + MethodInfo currentOnDeserializing = null; + MethodInfo currentOnDeserialized = null; + MethodInfo currentOnError = null; + + bool skipSerializing = ShouldSkipSerializing(baseType); + bool skipDeserialized = ShouldSkipDeserialized(baseType); + + foreach (MethodInfo method in baseType.GetMethods(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)) + { + // compact framework errors when getting parameters for a generic method + // lame, but generic methods should not be callbacks anyway + if (method.ContainsGenericParameters) + { + continue; + } + + Type prevAttributeType = null; + ParameterInfo[] parameters = method.GetParameters(); + + if (!skipSerializing && IsValidCallback(method, parameters, typeof(OnSerializingAttribute), currentOnSerializing, ref prevAttributeType)) + { + onSerializing = onSerializing ?? new List(); + onSerializing.Add(JsonContract.CreateSerializationCallback(method)); + currentOnSerializing = method; + } + if (IsValidCallback(method, parameters, typeof(OnSerializedAttribute), currentOnSerialized, ref prevAttributeType)) + { + onSerialized = onSerialized ?? new List(); + onSerialized.Add(JsonContract.CreateSerializationCallback(method)); + currentOnSerialized = method; + } + if (IsValidCallback(method, parameters, typeof(OnDeserializingAttribute), currentOnDeserializing, ref prevAttributeType)) + { + onDeserializing = onDeserializing ?? new List(); + onDeserializing.Add(JsonContract.CreateSerializationCallback(method)); + currentOnDeserializing = method; + } + if (!skipDeserialized && IsValidCallback(method, parameters, typeof(OnDeserializedAttribute), currentOnDeserialized, ref prevAttributeType)) + { + onDeserialized = onDeserialized ?? new List(); + onDeserialized.Add(JsonContract.CreateSerializationCallback(method)); + currentOnDeserialized = method; + } + if (IsValidCallback(method, parameters, typeof(OnErrorAttribute), currentOnError, ref prevAttributeType)) + { + onError = onError ?? new List(); + onError.Add(JsonContract.CreateSerializationErrorCallback(method)); + currentOnError = method; + } + } + } + } + + private static bool ShouldSkipDeserialized(Type t) + { +#if !(NET35 || NET20 || PORTABLE || PORTABLE40) + // ConcurrentDictionary throws an error in its OnDeserialized so ignore - http://json.codeplex.com/discussions/257093 + if (t.IsGenericType() && t.GetGenericTypeDefinition() == typeof(ConcurrentDictionary<,>)) + { + return true; + } +#endif +#if !(NET35 || NET20) + if (t.Name == FSharpUtils.FSharpSetTypeName || t.Name == FSharpUtils.FSharpMapTypeName) + { + return true; + } +#endif + + return false; + } + + private static bool ShouldSkipSerializing(Type t) + { +#if !(NET35 || NET20) + if (t.Name == FSharpUtils.FSharpSetTypeName || t.Name == FSharpUtils.FSharpMapTypeName) + { + return true; + } +#endif +#if DOTNET + if (t.IsGenericType() && t.GetGenericTypeDefinition() == typeof(ConcurrentDictionary<,>)) + return true; +#endif + + return false; + } + + private List GetClassHierarchyForType(Type type) + { + List ret = new List(); + + Type current = type; + while (current != null && current != typeof(object)) + { + ret.Add(current); + current = current.BaseType(); + } + + // Return the class list in order of simple => complex + ret.Reverse(); + return ret; + } + + /// + /// Creates a for the given type. + /// + /// Type of the object. + /// A for the given type. + protected virtual JsonDictionaryContract CreateDictionaryContract(Type objectType) + { + JsonDictionaryContract contract = new JsonDictionaryContract(objectType); + InitializeContract(contract); + + contract.DictionaryKeyResolver = ResolveDictionaryKey; + + ConstructorInfo overrideConstructor = GetAttributeConstructor(contract.NonNullableUnderlyingType); + + if (overrideConstructor != null) + { + ParameterInfo[] parameters = overrideConstructor.GetParameters(); + Type expectedParameterType = (contract.DictionaryKeyType != null && contract.DictionaryValueType != null) + ? typeof(IEnumerable<>).MakeGenericType(typeof(KeyValuePair<,>).MakeGenericType(contract.DictionaryKeyType, contract.DictionaryValueType)) + : typeof(IDictionary); + + if (parameters.Length == 0) + { + contract.HasParameterizedCreator = false; + } + else if (parameters.Length == 1 && expectedParameterType.IsAssignableFrom(parameters[0].ParameterType)) + { + contract.HasParameterizedCreator = true; + } + else + { + throw new JsonException("Constructor for '{0}' must have no parameters or a single parameter that implements '{1}'.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType, expectedParameterType)); + } + + contract.OverrideCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(overrideConstructor); + } + + return contract; + } + + /// + /// Creates a for the given type. + /// + /// Type of the object. + /// A for the given type. + protected virtual JsonArrayContract CreateArrayContract(Type objectType) + { + JsonArrayContract contract = new JsonArrayContract(objectType); + InitializeContract(contract); + + ConstructorInfo overrideConstructor = GetAttributeConstructor(contract.NonNullableUnderlyingType); + + if (overrideConstructor != null) + { + ParameterInfo[] parameters = overrideConstructor.GetParameters(); + Type expectedParameterType = (contract.CollectionItemType != null) + ? typeof(IEnumerable<>).MakeGenericType(contract.CollectionItemType) + : typeof(IEnumerable); + + if (parameters.Length == 0) + { + contract.HasParameterizedCreator = false; + } + else if (parameters.Length == 1 && expectedParameterType.IsAssignableFrom(parameters[0].ParameterType)) + { + contract.HasParameterizedCreator = true; + } + else + { + throw new JsonException("Constructor for '{0}' must have no parameters or a single parameter that implements '{1}'.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType, expectedParameterType)); + } + + contract.OverrideCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(overrideConstructor); + } + + return contract; + } + + /// + /// Creates a for the given type. + /// + /// Type of the object. + /// A for the given type. + protected virtual JsonPrimitiveContract CreatePrimitiveContract(Type objectType) + { + JsonPrimitiveContract contract = new JsonPrimitiveContract(objectType); + InitializeContract(contract); + + return contract; + } + + /// + /// Creates a for the given type. + /// + /// Type of the object. + /// A for the given type. + protected virtual JsonLinqContract CreateLinqContract(Type objectType) + { + JsonLinqContract contract = new JsonLinqContract(objectType); + InitializeContract(contract); + + return contract; + } + +#if !(DOTNET || PORTABLE40 || PORTABLE) + /// + /// Creates a for the given type. + /// + /// Type of the object. + /// A for the given type. + protected virtual JsonISerializableContract CreateISerializableContract(Type objectType) + { + JsonISerializableContract contract = new JsonISerializableContract(objectType); + InitializeContract(contract); + + ConstructorInfo constructorInfo = contract.NonNullableUnderlyingType.GetConstructor(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, new[] { typeof(SerializationInfo), typeof(StreamingContext) }, null); + if (constructorInfo != null) + { + ObjectConstructor creator = JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(constructorInfo); + + contract.ISerializableCreator = creator; + } + + return contract; + } +#endif + +#if !(NET35 || NET20 || PORTABLE40) + /// + /// Creates a for the given type. + /// + /// Type of the object. + /// A for the given type. + protected virtual JsonDynamicContract CreateDynamicContract(Type objectType) + { + JsonDynamicContract contract = new JsonDynamicContract(objectType); + InitializeContract(contract); + + contract.PropertyNameResolver = ResolvePropertyName; + contract.Properties.AddRange(CreateProperties(objectType, MemberSerialization.OptOut)); + + return contract; + } +#endif + + /// + /// Creates a for the given type. + /// + /// Type of the object. + /// A for the given type. + protected virtual JsonStringContract CreateStringContract(Type objectType) + { + JsonStringContract contract = new JsonStringContract(objectType); + InitializeContract(contract); + + return contract; + } + + /// + /// Determines which contract type is created for the given type. + /// + /// Type of the object. + /// A for the given type. + protected virtual JsonContract CreateContract(Type objectType) + { + if (IsJsonPrimitiveType(objectType)) + { + return CreatePrimitiveContract(objectType); + } + + Type t = ReflectionUtils.EnsureNotNullableType(objectType); + JsonContainerAttribute containerAttribute = JsonTypeReflector.GetCachedAttribute(t); + + if (containerAttribute is JsonObjectAttribute) + { + return CreateObjectContract(objectType); + } + + if (containerAttribute is JsonArrayAttribute) + { + return CreateArrayContract(objectType); + } + + if (containerAttribute is JsonDictionaryAttribute) + { + return CreateDictionaryContract(objectType); + } + + if (t == typeof(JToken) || t.IsSubclassOf(typeof(JToken))) + { + return CreateLinqContract(objectType); + } + + if (CollectionUtils.IsDictionaryType(t)) + { + return CreateDictionaryContract(objectType); + } + + if (typeof(IEnumerable).IsAssignableFrom(t)) + { + return CreateArrayContract(objectType); + } + + if (CanConvertToString(t)) + { + return CreateStringContract(objectType); + } + +#if !(DOTNET || PORTABLE40 || PORTABLE) + if (!IgnoreSerializableInterface && typeof(ISerializable).IsAssignableFrom(t)) + { + return CreateISerializableContract(objectType); + } +#endif + +#if !(NET35 || NET20 || PORTABLE40) + if (typeof(IDynamicMetaObjectProvider).IsAssignableFrom(t)) + { + return CreateDynamicContract(objectType); + } +#endif + +#if !PORTABLE + // tested last because it is not possible to automatically deserialize custom IConvertible types + if (IsIConvertible(t)) + { + return CreatePrimitiveContract(t); + } +#endif + + return CreateObjectContract(objectType); + } + + internal static bool IsJsonPrimitiveType(Type t) + { + PrimitiveTypeCode typeCode = ConvertUtils.GetTypeCode(t); + + return (typeCode != PrimitiveTypeCode.Empty && typeCode != PrimitiveTypeCode.Object); + } + +#if !PORTABLE + internal static bool IsIConvertible(Type t) + { + if (typeof(IConvertible).IsAssignableFrom(t) + || (ReflectionUtils.IsNullableType(t) && typeof(IConvertible).IsAssignableFrom(Nullable.GetUnderlyingType(t)))) + { + return !typeof(JToken).IsAssignableFrom(t); + } + + return false; + } +#endif + + internal static bool CanConvertToString(Type type) + { +#if !(DOTNET || PORTABLE40 || PORTABLE) + TypeConverter converter = ConvertUtils.GetConverter(type); + + // use the objectType's TypeConverter if it has one and can convert to a string + if (converter != null + && !(converter is ComponentConverter) + && !(converter is ReferenceConverter) + && converter.GetType() != typeof(TypeConverter)) + { + if (converter.CanConvertTo(typeof(string))) + { + return true; + } + } +#endif + + if (type == typeof(Type) || type.IsSubclassOf(typeof(Type))) + { + return true; + } + + return false; + } + + private static bool IsValidCallback(MethodInfo method, ParameterInfo[] parameters, Type attributeType, MethodInfo currentCallback, ref Type prevAttributeType) + { + if (!method.IsDefined(attributeType, false)) + { + return false; + } + + if (currentCallback != null) + { + throw new JsonException("Invalid attribute. Both '{0}' and '{1}' in type '{2}' have '{3}'.".FormatWith(CultureInfo.InvariantCulture, method, currentCallback, GetClrTypeFullName(method.DeclaringType), attributeType)); + } + + if (prevAttributeType != null) + { + throw new JsonException("Invalid Callback. Method '{3}' in type '{2}' has both '{0}' and '{1}'.".FormatWith(CultureInfo.InvariantCulture, prevAttributeType, attributeType, GetClrTypeFullName(method.DeclaringType), method)); + } + + if (method.IsVirtual) + { + throw new JsonException("Virtual Method '{0}' of type '{1}' cannot be marked with '{2}' attribute.".FormatWith(CultureInfo.InvariantCulture, method, GetClrTypeFullName(method.DeclaringType), attributeType)); + } + + if (method.ReturnType != typeof(void)) + { + throw new JsonException("Serialization Callback '{1}' in type '{0}' must return void.".FormatWith(CultureInfo.InvariantCulture, GetClrTypeFullName(method.DeclaringType), method)); + } + + if (attributeType == typeof(OnErrorAttribute)) + { + if (parameters == null || parameters.Length != 2 || parameters[0].ParameterType != typeof(StreamingContext) || parameters[1].ParameterType != typeof(ErrorContext)) + { + throw new JsonException("Serialization Error Callback '{1}' in type '{0}' must have two parameters of type '{2}' and '{3}'.".FormatWith(CultureInfo.InvariantCulture, GetClrTypeFullName(method.DeclaringType), method, typeof(StreamingContext), typeof(ErrorContext))); + } + } + else + { + if (parameters == null || parameters.Length != 1 || parameters[0].ParameterType != typeof(StreamingContext)) + { + throw new JsonException("Serialization Callback '{1}' in type '{0}' must have a single parameter of type '{2}'.".FormatWith(CultureInfo.InvariantCulture, GetClrTypeFullName(method.DeclaringType), method, typeof(StreamingContext))); + } + } + + prevAttributeType = attributeType; + + return true; + } + + internal static string GetClrTypeFullName(Type type) + { + if (type.IsGenericTypeDefinition() || !type.ContainsGenericParameters()) + { + return type.FullName; + } + + return string.Format(CultureInfo.InvariantCulture, "{0}.{1}", new object[] { type.Namespace, type.Name }); + } + + /// + /// Creates properties for the given . + /// + /// The type to create properties for. + /// /// The member serialization mode for the type. + /// Properties for the given . + protected virtual IList CreateProperties(Type type, MemberSerialization memberSerialization) + { + List members = GetSerializableMembers(type); + if (members == null) + { + throw new JsonSerializationException("Null collection of seralizable members returned."); + } + + JsonPropertyCollection properties = new JsonPropertyCollection(type); + + foreach (MemberInfo member in members) + { + JsonProperty property = CreateProperty(member, memberSerialization); + + if (property != null) + { + DefaultContractResolverState state = GetState(); + + // nametable is not thread-safe for multiple writers + lock (state.NameTable) + { + property.PropertyName = state.NameTable.Add(property.PropertyName); + } + + properties.AddProperty(property); + } + } + + IList orderedProperties = properties.OrderBy(p => p.Order ?? -1).ToList(); + return orderedProperties; + } + + /// + /// Creates the used by the serializer to get and set values from a member. + /// + /// The member. + /// The used by the serializer to get and set values from a member. + protected virtual IValueProvider CreateMemberValueProvider(MemberInfo member) + { + // warning - this method use to cause errors with Intellitrace. Retest in VS Ultimate after changes + IValueProvider valueProvider; + +#if !(PORTABLE40 || PORTABLE || DOTNET) + if (DynamicCodeGeneration) + { + valueProvider = new DynamicValueProvider(member); + } + else + { + valueProvider = new ReflectionValueProvider(member); + } +#elif !(PORTABLE40) + valueProvider = new ExpressionValueProvider(member); +#else + valueProvider = new ReflectionValueProvider(member); +#endif + + return valueProvider; + } + + /// + /// Creates a for the given . + /// + /// The member's parent . + /// The member to create a for. + /// A created for the given . + protected virtual JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization) + { + JsonProperty property = new JsonProperty(); + property.PropertyType = ReflectionUtils.GetMemberUnderlyingType(member); + property.DeclaringType = member.DeclaringType; + property.ValueProvider = CreateMemberValueProvider(member); + property.AttributeProvider = new ReflectionAttributeProvider(member); + + bool allowNonPublicAccess; + SetPropertySettingsFromAttributes(property, member, member.Name, member.DeclaringType, memberSerialization, out allowNonPublicAccess); + + if (memberSerialization != MemberSerialization.Fields) + { + property.Readable = ReflectionUtils.CanReadMemberValue(member, allowNonPublicAccess); + property.Writable = ReflectionUtils.CanSetMemberValue(member, allowNonPublicAccess, property.HasMemberAttribute); + } + else + { + // write to readonly fields + property.Readable = true; + property.Writable = true; + } + property.ShouldSerialize = CreateShouldSerializeTest(member); + + SetIsSpecifiedActions(property, member, allowNonPublicAccess); + + return property; + } + + private void SetPropertySettingsFromAttributes(JsonProperty property, object attributeProvider, string name, Type declaringType, MemberSerialization memberSerialization, out bool allowNonPublicAccess) + { +#if !NET20 + DataContractAttribute dataContractAttribute = JsonTypeReflector.GetDataContractAttribute(declaringType); + + MemberInfo memberInfo = attributeProvider as MemberInfo; + + DataMemberAttribute dataMemberAttribute; + if (dataContractAttribute != null && memberInfo != null) + { + dataMemberAttribute = JsonTypeReflector.GetDataMemberAttribute((MemberInfo)memberInfo); + } + else + { + dataMemberAttribute = null; + } +#endif + + JsonPropertyAttribute propertyAttribute = JsonTypeReflector.GetAttribute(attributeProvider); + JsonRequiredAttribute requiredAttribute = JsonTypeReflector.GetAttribute(attributeProvider); + + string mappedName; + if (propertyAttribute != null && propertyAttribute.PropertyName != null) + { + mappedName = propertyAttribute.PropertyName; + } +#if !NET20 + else if (dataMemberAttribute != null && dataMemberAttribute.Name != null) + { + mappedName = dataMemberAttribute.Name; + } +#endif + else + { + mappedName = name; + } + + property.PropertyName = ResolvePropertyName(mappedName); + property.UnderlyingName = name; + + bool hasMemberAttribute = false; + if (propertyAttribute != null) + { + property._required = propertyAttribute._required; + property.Order = propertyAttribute._order; + property.DefaultValueHandling = propertyAttribute._defaultValueHandling; + hasMemberAttribute = true; + } +#if !NET20 + else if (dataMemberAttribute != null) + { + property._required = (dataMemberAttribute.IsRequired) ? Required.AllowNull : Required.Default; + property.Order = (dataMemberAttribute.Order != -1) ? (int?)dataMemberAttribute.Order : null; + property.DefaultValueHandling = (!dataMemberAttribute.EmitDefaultValue) ? (DefaultValueHandling?)DefaultValueHandling.Ignore : null; + hasMemberAttribute = true; + } +#endif + if (requiredAttribute != null) + { + property._required = Required.Always; + hasMemberAttribute = true; + } + + property.HasMemberAttribute = hasMemberAttribute; + + bool hasJsonIgnoreAttribute = + JsonTypeReflector.GetAttribute(attributeProvider) != null + // automatically ignore extension data dictionary property if it is public + || JsonTypeReflector.GetAttribute(attributeProvider) != null +#if !(DOTNET || PORTABLE40 || PORTABLE) + || JsonTypeReflector.GetAttribute(attributeProvider) != null +#endif + ; + + if (memberSerialization != MemberSerialization.OptIn) + { + bool hasIgnoreDataMemberAttribute = false; + +#if !(NET20 || NET35) + hasIgnoreDataMemberAttribute = (JsonTypeReflector.GetAttribute(attributeProvider) != null); +#endif + + // ignored if it has JsonIgnore or NonSerialized or IgnoreDataMember attributes + property.Ignored = (hasJsonIgnoreAttribute || hasIgnoreDataMemberAttribute); + } + else + { + // ignored if it has JsonIgnore/NonSerialized or does not have DataMember or JsonProperty attributes + property.Ignored = (hasJsonIgnoreAttribute || !hasMemberAttribute); + } + + // resolve converter for property + // the class type might have a converter but the property converter takes presidence + property.Converter = JsonTypeReflector.GetJsonConverter(attributeProvider); + property.MemberConverter = JsonTypeReflector.GetJsonConverter(attributeProvider); + + DefaultValueAttribute defaultValueAttribute = JsonTypeReflector.GetAttribute(attributeProvider); + if (defaultValueAttribute != null) + { + property.DefaultValue = defaultValueAttribute.Value; + } + + property.NullValueHandling = (propertyAttribute != null) ? propertyAttribute._nullValueHandling : null; + property.ReferenceLoopHandling = (propertyAttribute != null) ? propertyAttribute._referenceLoopHandling : null; + property.ObjectCreationHandling = (propertyAttribute != null) ? propertyAttribute._objectCreationHandling : null; + property.TypeNameHandling = (propertyAttribute != null) ? propertyAttribute._typeNameHandling : null; + property.IsReference = (propertyAttribute != null) ? propertyAttribute._isReference : null; + + property.ItemIsReference = (propertyAttribute != null) ? propertyAttribute._itemIsReference : null; + property.ItemConverter = + (propertyAttribute != null && propertyAttribute.ItemConverterType != null) + ? JsonTypeReflector.CreateJsonConverterInstance(propertyAttribute.ItemConverterType, propertyAttribute.ItemConverterParameters) + : null; + property.ItemReferenceLoopHandling = (propertyAttribute != null) ? propertyAttribute._itemReferenceLoopHandling : null; + property.ItemTypeNameHandling = (propertyAttribute != null) ? propertyAttribute._itemTypeNameHandling : null; + + allowNonPublicAccess = false; +#pragma warning disable 618 + if ((DefaultMembersSearchFlags & BindingFlags.NonPublic) == BindingFlags.NonPublic) + { + allowNonPublicAccess = true; + } +#pragma warning restore 618 + if (hasMemberAttribute) + { + allowNonPublicAccess = true; + } + if (memberSerialization == MemberSerialization.Fields) + { + allowNonPublicAccess = true; + } + } + + private Predicate CreateShouldSerializeTest(MemberInfo member) + { + MethodInfo shouldSerializeMethod = member.DeclaringType.GetMethod(JsonTypeReflector.ShouldSerializePrefix + member.Name, ReflectionUtils.EmptyTypes); + + if (shouldSerializeMethod == null || shouldSerializeMethod.ReturnType != typeof(bool)) + { + return null; + } + + MethodCall shouldSerializeCall = + JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall(shouldSerializeMethod); + + return o => (bool)shouldSerializeCall(o); + } + + private void SetIsSpecifiedActions(JsonProperty property, MemberInfo member, bool allowNonPublicAccess) + { + MemberInfo specifiedMember = member.DeclaringType.GetProperty(member.Name + JsonTypeReflector.SpecifiedPostfix); + if (specifiedMember == null) + { + specifiedMember = member.DeclaringType.GetField(member.Name + JsonTypeReflector.SpecifiedPostfix); + } + + if (specifiedMember == null || ReflectionUtils.GetMemberUnderlyingType(specifiedMember) != typeof(bool)) + { + return; + } + + Func specifiedPropertyGet = JsonTypeReflector.ReflectionDelegateFactory.CreateGet(specifiedMember); + + property.GetIsSpecified = o => (bool)specifiedPropertyGet(o); + + if (ReflectionUtils.CanSetMemberValue(specifiedMember, allowNonPublicAccess, false)) + { + property.SetIsSpecified = JsonTypeReflector.ReflectionDelegateFactory.CreateSet(specifiedMember); + } + } + + /// + /// Resolves the name of the property. + /// + /// Name of the property. + /// Resolved name of the property. + protected virtual string ResolvePropertyName(string propertyName) + { + return propertyName; + } + + /// + /// Resolves the key of the dictionary. By default is used to resolve dictionary keys. + /// + /// Key of the dictionary. + /// Resolved key of the dictionary. + protected virtual string ResolveDictionaryKey(string dictionaryKey) + { + return ResolvePropertyName(dictionaryKey); + } + + /// + /// Gets the resolved name of the property. + /// + /// Name of the property. + /// Name of the property. + public string GetResolvedPropertyName(string propertyName) + { + // this is a new method rather than changing the visibility of ResolvePropertyName to avoid + // a breaking change for anyone who has overidden the method + return ResolvePropertyName(propertyName); + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Serialization/DefaultReferenceResolver.cs b/Common/00-1Json8.3/Json8.3/Serialization/DefaultReferenceResolver.cs new file mode 100644 index 0000000..885ccfc --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Serialization/DefaultReferenceResolver.cs @@ -0,0 +1,89 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using Newtonsoft.Json.Utilities; +using System.Globalization; + +namespace Newtonsoft.Json.Serialization +{ + internal class DefaultReferenceResolver : IReferenceResolver + { + private int _referenceCount; + + private BidirectionalDictionary GetMappings(object context) + { + JsonSerializerInternalBase internalSerializer; + + if (context is JsonSerializerInternalBase) + { + internalSerializer = (JsonSerializerInternalBase)context; + } + else if (context is JsonSerializerProxy) + { + internalSerializer = ((JsonSerializerProxy)context).GetInternalSerializer(); + } + else + { + throw new JsonException("The DefaultReferenceResolver can only be used internally."); + } + + return internalSerializer.DefaultReferenceMappings; + } + + public object ResolveReference(object context, string reference) + { + object value; + GetMappings(context).TryGetByFirst(reference, out value); + return value; + } + + public string GetReference(object context, object value) + { + var mappings = GetMappings(context); + + string reference; + if (!mappings.TryGetBySecond(value, out reference)) + { + _referenceCount++; + reference = _referenceCount.ToString(CultureInfo.InvariantCulture); + mappings.Set(reference, value); + } + + return reference; + } + + public void AddReference(object context, string reference, object value) + { + GetMappings(context).Set(reference, value); + } + + public bool IsReferenced(object context, object value) + { + string reference; + return GetMappings(context).TryGetBySecond(value, out reference); + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Serialization/DefaultSerializationBinder.cs b/Common/00-1Json8.3/Json8.3/Serialization/DefaultSerializationBinder.cs new file mode 100644 index 0000000..5df55dc --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Serialization/DefaultSerializationBinder.cs @@ -0,0 +1,164 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Runtime.Serialization; +using System.Reflection; +using System.Globalization; +using Newtonsoft.Json.Utilities; + +namespace Newtonsoft.Json.Serialization +{ + /// + /// The default serialization binder used when resolving and loading classes from type names. + /// + public class DefaultSerializationBinder : SerializationBinder + { + internal static readonly DefaultSerializationBinder Instance = new DefaultSerializationBinder(); + + private readonly ThreadSafeStore _typeCache = new ThreadSafeStore(GetTypeFromTypeNameKey); + + private static Type GetTypeFromTypeNameKey(TypeNameKey typeNameKey) + { + string assemblyName = typeNameKey.AssemblyName; + string typeName = typeNameKey.TypeName; + + if (assemblyName != null) + { + Assembly assembly; + +#if !(DOTNET || PORTABLE40 || PORTABLE) + // look, I don't like using obsolete methods as much as you do but this is the only way + // Assembly.Load won't check the GAC for a partial name +#pragma warning disable 618,612 + assembly = Assembly.LoadWithPartialName(assemblyName); +#pragma warning restore 618,612 +#elif DOTNET || PORTABLE + assembly = Assembly.Load(new AssemblyName(assemblyName)); +#else + assembly = Assembly.Load(assemblyName); +#endif + +#if !(PORTABLE40 || PORTABLE || DOTNET) + if (assembly == null) + { + // will find assemblies loaded with Assembly.LoadFile outside of the main directory + Assembly[] loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies(); + foreach (Assembly a in loadedAssemblies) + { + if (a.FullName == assemblyName) + { + assembly = a; + break; + } + } + } +#endif + + if (assembly == null) + { + throw new JsonSerializationException("Could not load assembly '{0}'.".FormatWith(CultureInfo.InvariantCulture, assemblyName)); + } + + Type type = assembly.GetType(typeName); + if (type == null) + { + throw new JsonSerializationException("Could not find type '{0}' in assembly '{1}'.".FormatWith(CultureInfo.InvariantCulture, typeName, assembly.FullName)); + } + + return type; + } + else + { + return Type.GetType(typeName); + } + } + + internal struct TypeNameKey : IEquatable + { + internal readonly string AssemblyName; + internal readonly string TypeName; + + public TypeNameKey(string assemblyName, string typeName) + { + AssemblyName = assemblyName; + TypeName = typeName; + } + + public override int GetHashCode() + { + return ((AssemblyName != null) ? AssemblyName.GetHashCode() : 0) + ^ ((TypeName != null) ? TypeName.GetHashCode() : 0); + } + + public override bool Equals(object obj) + { + if (!(obj is TypeNameKey)) + { + return false; + } + + return Equals((TypeNameKey)obj); + } + + public bool Equals(TypeNameKey other) + { + return (AssemblyName == other.AssemblyName && TypeName == other.TypeName); + } + } + + /// + /// When overridden in a derived class, controls the binding of a serialized object to a type. + /// + /// Specifies the name of the serialized object. + /// Specifies the name of the serialized object. + /// + /// The type of the object the formatter creates a new instance of. + /// + public override Type BindToType(string assemblyName, string typeName) + { + return _typeCache.Get(new TypeNameKey(assemblyName, typeName)); + } + +#if !(NET35 || NET20) + /// + /// When overridden in a derived class, controls the binding of a serialized object to a type. + /// + /// The type of the object the formatter creates a new instance of. + /// Specifies the name of the serialized object. + /// Specifies the name of the serialized object. + public override void BindToName(Type serializedType, out string assemblyName, out string typeName) + { +#if (DOTNET || PORTABLE) + assemblyName = serializedType.GetTypeInfo().Assembly.FullName; + typeName = serializedType.FullName; +#else + assemblyName = serializedType.Assembly.FullName; + typeName = serializedType.FullName; +#endif + } +#endif + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Serialization/DiagnosticsTraceWriter.cs b/Common/00-1Json8.3/Json8.3/Serialization/DiagnosticsTraceWriter.cs new file mode 100644 index 0000000..b029338 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Serialization/DiagnosticsTraceWriter.cs @@ -0,0 +1,79 @@ +#if !(PORTABLE40 || PORTABLE || DOTNET) +using System; +using System.Diagnostics; +using DiagnosticsTrace = System.Diagnostics.Trace; + +namespace Newtonsoft.Json.Serialization +{ + /// + /// Represents a trace writer that writes to the application's instances. + /// + public class DiagnosticsTraceWriter : ITraceWriter + { + /// + /// Gets the that will be used to filter the trace messages passed to the writer. + /// For example a filter level of Info will exclude Verbose messages and include Info, + /// Warning and Error messages. + /// + /// + /// The that will be used to filter the trace messages passed to the writer. + /// + public TraceLevel LevelFilter { get; set; } + + private TraceEventType GetTraceEventType(TraceLevel level) + { + switch (level) + { + case TraceLevel.Error: + return TraceEventType.Error; + case TraceLevel.Warning: + return TraceEventType.Warning; + case TraceLevel.Info: + return TraceEventType.Information; + case TraceLevel.Verbose: + return TraceEventType.Verbose; + default: + throw new ArgumentOutOfRangeException(nameof(level)); + } + } + + /// + /// Writes the specified trace level, message and optional exception. + /// + /// The at which to write this trace. + /// The trace message. + /// The trace exception. This parameter is optional. + public void Trace(TraceLevel level, string message, Exception ex) + { + if (level == TraceLevel.Off) + { + return; + } + + TraceEventCache eventCache = new TraceEventCache(); + TraceEventType traceEventType = GetTraceEventType(level); + + foreach (TraceListener listener in DiagnosticsTrace.Listeners) + { + if (!listener.IsThreadSafe) + { + lock (listener) + { + listener.TraceEvent(eventCache, "Newtonsoft.Json", traceEventType, 0, message); + } + } + else + { + listener.TraceEvent(eventCache, "Newtonsoft.Json", traceEventType, 0, message); + } + + if (DiagnosticsTrace.AutoFlush) + { + listener.Flush(); + } + } + } + } +} + +#endif \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Serialization/DynamicValueProvider.cs b/Common/00-1Json8.3/Json8.3/Serialization/DynamicValueProvider.cs new file mode 100644 index 0000000..dd9dce7 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Serialization/DynamicValueProvider.cs @@ -0,0 +1,120 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +#if !(PORTABLE40 || PORTABLE || DOTNET) +using System; +using System.Collections.Generic; +#if NET20 +using Newtonsoft.Json.Utilities.LinqBridge; +#endif +using System.Text; +using System.Reflection; +using Newtonsoft.Json.Utilities; +using System.Globalization; + +namespace Newtonsoft.Json.Serialization +{ + /// + /// Get and set values for a using dynamic methods. + /// + public class DynamicValueProvider : IValueProvider + { + private readonly MemberInfo _memberInfo; + private Func _getter; + private Action _setter; + + /// + /// Initializes a new instance of the class. + /// + /// The member info. + public DynamicValueProvider(MemberInfo memberInfo) + { + ValidationUtils.ArgumentNotNull(memberInfo, nameof(memberInfo)); + _memberInfo = memberInfo; + } + + /// + /// Sets the value. + /// + /// The target to set the value on. + /// The value to set on the target. + public void SetValue(object target, object value) + { + try + { + if (_setter == null) + { + _setter = DynamicReflectionDelegateFactory.Instance.CreateSet(_memberInfo); + } + +#if DEBUG + // dynamic method doesn't check whether the type is 'legal' to set + // add this check for unit tests + if (value == null) + { + if (!ReflectionUtils.IsNullable(ReflectionUtils.GetMemberUnderlyingType(_memberInfo))) + { + throw new JsonSerializationException("Incompatible value. Cannot set {0} to null.".FormatWith(CultureInfo.InvariantCulture, _memberInfo)); + } + } + else if (!ReflectionUtils.GetMemberUnderlyingType(_memberInfo).IsAssignableFrom(value.GetType())) + { + throw new JsonSerializationException("Incompatible value. Cannot set {0} to type {1}.".FormatWith(CultureInfo.InvariantCulture, _memberInfo, value.GetType())); + } +#endif + + _setter(target, value); + } + catch (Exception ex) + { + throw new JsonSerializationException("Error setting value to '{0}' on '{1}'.".FormatWith(CultureInfo.InvariantCulture, _memberInfo.Name, target.GetType()), ex); + } + } + + /// + /// Gets the value. + /// + /// The target to get the value from. + /// The value. + public object GetValue(object target) + { + try + { + if (_getter == null) + { + _getter = DynamicReflectionDelegateFactory.Instance.CreateGet(_memberInfo); + } + + return _getter(target); + } + catch (Exception ex) + { + throw new JsonSerializationException("Error getting value from '{0}' on '{1}'.".FormatWith(CultureInfo.InvariantCulture, _memberInfo.Name, target.GetType()), ex); + } + } + } +} + +#endif \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Serialization/ErrorContext.cs b/Common/00-1Json8.3/Json8.3/Serialization/ErrorContext.cs new file mode 100644 index 0000000..bcb2fbb --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Serialization/ErrorContext.cs @@ -0,0 +1,75 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; + +namespace Newtonsoft.Json.Serialization +{ + /// + /// Provides information surrounding an error. + /// + public class ErrorContext + { + internal ErrorContext(object originalObject, object member, string path, Exception error) + { + OriginalObject = originalObject; + Member = member; + Error = error; + Path = path; + } + + internal bool Traced { get; set; } + + /// + /// Gets the error. + /// + /// The error. + public Exception Error { get; private set; } + + /// + /// Gets the original object that caused the error. + /// + /// The original object that caused the error. + public object OriginalObject { get; private set; } + + /// + /// Gets the member that caused the error. + /// + /// The member that caused the error. + public object Member { get; private set; } + + /// + /// Gets the path of the JSON location where the error occurred. + /// + /// The path of the JSON location where the error occurred. + public string Path { get; private set; } + + /// + /// Gets or sets a value indicating whether this is handled. + /// + /// true if handled; otherwise, false. + public bool Handled { get; set; } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Serialization/ErrorEventArgs.cs b/Common/00-1Json8.3/Json8.3/Serialization/ErrorEventArgs.cs new file mode 100644 index 0000000..cae7d03 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Serialization/ErrorEventArgs.cs @@ -0,0 +1,58 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; + +namespace Newtonsoft.Json.Serialization +{ + /// + /// Provides data for the Error event. + /// + public class ErrorEventArgs : EventArgs + { + /// + /// Gets the current object the error event is being raised against. + /// + /// The current object the error event is being raised against. + public object CurrentObject { get; private set; } + + /// + /// Gets the error context. + /// + /// The error context. + public ErrorContext ErrorContext { get; private set; } + + /// + /// Initializes a new instance of the class. + /// + /// The current object. + /// The error context. + public ErrorEventArgs(object currentObject, ErrorContext errorContext) + { + CurrentObject = currentObject; + ErrorContext = errorContext; + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Serialization/ExpressionValueProvider.cs b/Common/00-1Json8.3/Json8.3/Serialization/ExpressionValueProvider.cs new file mode 100644 index 0000000..9774740 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Serialization/ExpressionValueProvider.cs @@ -0,0 +1,120 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +#if !(NET20 || NET35) +using System; +using System.Collections.Generic; +#if NET20 +using Newtonsoft.Json.Utilities.LinqBridge; +#endif +using System.Text; +using System.Reflection; +using Newtonsoft.Json.Utilities; +using System.Globalization; + +namespace Newtonsoft.Json.Serialization +{ + /// + /// Get and set values for a using dynamic methods. + /// + public class ExpressionValueProvider : IValueProvider + { + private readonly MemberInfo _memberInfo; + private Func _getter; + private Action _setter; + + /// + /// Initializes a new instance of the class. + /// + /// The member info. + public ExpressionValueProvider(MemberInfo memberInfo) + { + ValidationUtils.ArgumentNotNull(memberInfo, nameof(memberInfo)); + _memberInfo = memberInfo; + } + + /// + /// Sets the value. + /// + /// The target to set the value on. + /// The value to set on the target. + public void SetValue(object target, object value) + { + try + { + if (_setter == null) + { + _setter = ExpressionReflectionDelegateFactory.Instance.CreateSet(_memberInfo); + } + +#if DEBUG + // dynamic method doesn't check whether the type is 'legal' to set + // add this check for unit tests + if (value == null) + { + if (!ReflectionUtils.IsNullable(ReflectionUtils.GetMemberUnderlyingType(_memberInfo))) + { + throw new JsonSerializationException("Incompatible value. Cannot set {0} to null.".FormatWith(CultureInfo.InvariantCulture, _memberInfo)); + } + } + else if (!ReflectionUtils.GetMemberUnderlyingType(_memberInfo).IsAssignableFrom(value.GetType())) + { + throw new JsonSerializationException("Incompatible value. Cannot set {0} to type {1}.".FormatWith(CultureInfo.InvariantCulture, _memberInfo, value.GetType())); + } +#endif + + _setter(target, value); + } + catch (Exception ex) + { + throw new JsonSerializationException("Error setting value to '{0}' on '{1}'.".FormatWith(CultureInfo.InvariantCulture, _memberInfo.Name, target.GetType()), ex); + } + } + + /// + /// Gets the value. + /// + /// The target to get the value from. + /// The value. + public object GetValue(object target) + { + try + { + if (_getter == null) + { + _getter = ExpressionReflectionDelegateFactory.Instance.CreateGet(_memberInfo); + } + + return _getter(target); + } + catch (Exception ex) + { + throw new JsonSerializationException("Error getting value from '{0}' on '{1}'.".FormatWith(CultureInfo.InvariantCulture, _memberInfo.Name, target.GetType()), ex); + } + } + } +} + +#endif \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Serialization/IAttributeProvider.cs b/Common/00-1Json8.3/Json8.3/Serialization/IAttributeProvider.cs new file mode 100644 index 0000000..97a6469 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Serialization/IAttributeProvider.cs @@ -0,0 +1,51 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Collections.Generic; + +namespace Newtonsoft.Json.Serialization +{ + /// + /// Provides methods to get attributes. + /// + public interface IAttributeProvider + { + /// + /// Returns a collection of all of the attributes, or an empty collection if there are no attributes. + /// + /// When true, look up the hierarchy chain for the inherited custom attribute. + /// A collection of s, or an empty collection. + IList GetAttributes(bool inherit); + + /// + /// Returns a collection of attributes, identified by type, or an empty collection if there are no attributes. + /// + /// The type of the attributes. + /// When true, look up the hierarchy chain for the inherited custom attribute. + /// A collection of s, or an empty collection. + IList GetAttributes(Type attributeType, bool inherit); + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Serialization/IContractResolver.cs b/Common/00-1Json8.3/Json8.3/Serialization/IContractResolver.cs new file mode 100644 index 0000000..10f44ba --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Serialization/IContractResolver.cs @@ -0,0 +1,46 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; + +namespace Newtonsoft.Json.Serialization +{ + /// + /// Used by to resolves a for a given . + /// + /// + /// + /// + /// + public interface IContractResolver + { + /// + /// Resolves the contract for a given type. + /// + /// The type to resolve a contract for. + /// The contract for a given type. + JsonContract ResolveContract(Type type); + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Serialization/IReferenceResolver.cs b/Common/00-1Json8.3/Json8.3/Serialization/IReferenceResolver.cs new file mode 100644 index 0000000..271e307 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Serialization/IReferenceResolver.cs @@ -0,0 +1,67 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +namespace Newtonsoft.Json.Serialization +{ + /// + /// Used to resolve references when serializing and deserializing JSON by the . + /// + public interface IReferenceResolver + { + /// + /// Resolves a reference to its object. + /// + /// The serialization context. + /// The reference to resolve. + /// The object that + object ResolveReference(object context, string reference); + + /// + /// Gets the reference for the sepecified object. + /// + /// The serialization context. + /// The object to get a reference for. + /// The reference to the object. + string GetReference(object context, object value); + + /// + /// Determines whether the specified object is referenced. + /// + /// The serialization context. + /// The object to test for a reference. + /// + /// true if the specified object is referenced; otherwise, false. + /// + bool IsReferenced(object context, object value); + + /// + /// Adds a reference to the specified object. + /// + /// The serialization context. + /// The reference. + /// The object to reference. + void AddReference(object context, string reference, object value); + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Serialization/ITraceWriter.cs b/Common/00-1Json8.3/Json8.3/Serialization/ITraceWriter.cs new file mode 100644 index 0000000..46ed784 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Serialization/ITraceWriter.cs @@ -0,0 +1,28 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; + +namespace Newtonsoft.Json.Serialization +{ + /// + /// Represents a trace writer. + /// + public interface ITraceWriter + { + /// + /// Gets the that will be used to filter the trace messages passed to the writer. + /// For example a filter level of Info will exclude Verbose messages and include Info, + /// Warning and Error messages. + /// + /// The that will be used to filter the trace messages passed to the writer. + TraceLevel LevelFilter { get; } + + /// + /// Writes the specified trace level, message and optional exception. + /// + /// The at which to write this trace. + /// The trace message. + /// The trace exception. This parameter is optional. + void Trace(TraceLevel level, string message, Exception ex); + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Serialization/IValueProvider.cs b/Common/00-1Json8.3/Json8.3/Serialization/IValueProvider.cs new file mode 100644 index 0000000..921724f --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Serialization/IValueProvider.cs @@ -0,0 +1,47 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +namespace Newtonsoft.Json.Serialization +{ + /// + /// Provides methods to get and set values. + /// + public interface IValueProvider + { + /// + /// Sets the value. + /// + /// The target to set the value on. + /// The value to set on the target. + void SetValue(object target, object value); + + /// + /// Gets the value. + /// + /// The target to get the value from. + /// The value. + object GetValue(object target); + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Serialization/JsonArrayContract.cs b/Common/00-1Json8.3/Json8.3/Serialization/JsonArrayContract.cs new file mode 100644 index 0000000..b39ca77 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Serialization/JsonArrayContract.cs @@ -0,0 +1,310 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Globalization; +using System.Reflection; +using Newtonsoft.Json.Utilities; +using System.Collections; +#if NET20 +using Newtonsoft.Json.Utilities.LinqBridge; +#else +using System.Linq; + +#endif + +namespace Newtonsoft.Json.Serialization +{ + /// + /// Contract details for a used by the . + /// + public class JsonArrayContract : JsonContainerContract + { + /// + /// Gets the of the collection items. + /// + /// The of the collection items. + public Type CollectionItemType { get; private set; } + + /// + /// Gets a value indicating whether the collection type is a multidimensional array. + /// + /// true if the collection type is a multidimensional array; otherwise, false. + public bool IsMultidimensionalArray { get; private set; } + + private readonly Type _genericCollectionDefinitionType; + + private Type _genericWrapperType; + private ObjectConstructor _genericWrapperCreator; + private Func _genericTemporaryCollectionCreator; + + internal bool IsArray { get; private set; } + internal bool ShouldCreateWrapper { get; private set; } + internal bool CanDeserialize { get; private set; } + + private readonly ConstructorInfo _parameterizedConstructor; + + private ObjectConstructor _parameterizedCreator; + private ObjectConstructor _overrideCreator; + + internal ObjectConstructor ParameterizedCreator + { + get + { + if (_parameterizedCreator == null) + { + _parameterizedCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(_parameterizedConstructor); + } + + return _parameterizedCreator; + } + } + + /// + /// Gets or sets the function used to create the object. When set this function will override . + /// + /// The function used to create the object. + public ObjectConstructor OverrideCreator + { + get { return _overrideCreator; } + set + { + _overrideCreator = value; + // hacky + CanDeserialize = true; + } + } + + /// + /// Gets a value indicating whether the creator has a parameter with the collection values. + /// + /// true if the creator has a parameter with the collection values; otherwise, false. + public bool HasParameterizedCreator { get; set; } + + internal bool HasParameterizedCreatorInternal + { + get { return (HasParameterizedCreator || _parameterizedCreator != null || _parameterizedConstructor != null); } + } + + /// + /// Initializes a new instance of the class. + /// + /// The underlying type for the contract. + public JsonArrayContract(Type underlyingType) + : base(underlyingType) + { + ContractType = JsonContractType.Array; + IsArray = CreatedType.IsArray; + + bool canDeserialize; + + Type tempCollectionType; + if (IsArray) + { + CollectionItemType = ReflectionUtils.GetCollectionItemType(UnderlyingType); + IsReadOnlyOrFixedSize = true; + _genericCollectionDefinitionType = typeof(List<>).MakeGenericType(CollectionItemType); + + canDeserialize = true; + IsMultidimensionalArray = (IsArray && UnderlyingType.GetArrayRank() > 1); + } + else if (typeof(IList).IsAssignableFrom(underlyingType)) + { + if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(ICollection<>), out _genericCollectionDefinitionType)) + { + CollectionItemType = _genericCollectionDefinitionType.GetGenericArguments()[0]; + } + else + { + CollectionItemType = ReflectionUtils.GetCollectionItemType(underlyingType); + } + + if (underlyingType == typeof(IList)) + { + CreatedType = typeof(List); + } + + if (CollectionItemType != null) + { + _parameterizedConstructor = CollectionUtils.ResolveEnumerableCollectionConstructor(underlyingType, CollectionItemType); + } + + IsReadOnlyOrFixedSize = ReflectionUtils.InheritsGenericDefinition(underlyingType, typeof(ReadOnlyCollection<>)); + canDeserialize = true; + } + else if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(ICollection<>), out _genericCollectionDefinitionType)) + { + CollectionItemType = _genericCollectionDefinitionType.GetGenericArguments()[0]; + + if (ReflectionUtils.IsGenericDefinition(underlyingType, typeof(ICollection<>)) + || ReflectionUtils.IsGenericDefinition(underlyingType, typeof(IList<>))) + { + CreatedType = typeof(List<>).MakeGenericType(CollectionItemType); + } + +#if !(NET20 || NET35) + if (ReflectionUtils.IsGenericDefinition(underlyingType, typeof(ISet<>))) + { + CreatedType = typeof(HashSet<>).MakeGenericType(CollectionItemType); + } +#endif + + _parameterizedConstructor = CollectionUtils.ResolveEnumerableCollectionConstructor(underlyingType, CollectionItemType); + canDeserialize = true; + ShouldCreateWrapper = true; + } +#if !(NET40 || NET35 || NET20 || PORTABLE40) + else if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(IReadOnlyCollection<>), out tempCollectionType)) + { + CollectionItemType = tempCollectionType.GetGenericArguments()[0]; + + if (ReflectionUtils.IsGenericDefinition(underlyingType, typeof(IReadOnlyCollection<>)) + || ReflectionUtils.IsGenericDefinition(underlyingType, typeof(IReadOnlyList<>))) + { + CreatedType = typeof(ReadOnlyCollection<>).MakeGenericType(CollectionItemType); + } + + _genericCollectionDefinitionType = typeof(List<>).MakeGenericType(CollectionItemType); + _parameterizedConstructor = CollectionUtils.ResolveEnumerableCollectionConstructor(CreatedType, CollectionItemType); + IsReadOnlyOrFixedSize = true; + canDeserialize = HasParameterizedCreatorInternal; + } +#endif + else if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(IEnumerable<>), out tempCollectionType)) + { + CollectionItemType = tempCollectionType.GetGenericArguments()[0]; + + if (ReflectionUtils.IsGenericDefinition(UnderlyingType, typeof(IEnumerable<>))) + { + CreatedType = typeof(List<>).MakeGenericType(CollectionItemType); + } + + _parameterizedConstructor = CollectionUtils.ResolveEnumerableCollectionConstructor(underlyingType, CollectionItemType); + +#if !(NET35 || NET20) + if (!HasParameterizedCreatorInternal && underlyingType.Name == FSharpUtils.FSharpListTypeName) + { + FSharpUtils.EnsureInitialized(underlyingType.Assembly()); + _parameterizedCreator = FSharpUtils.CreateSeq(CollectionItemType); + } +#endif + + if (underlyingType.IsGenericType() && underlyingType.GetGenericTypeDefinition() == typeof(IEnumerable<>)) + { + _genericCollectionDefinitionType = tempCollectionType; + + IsReadOnlyOrFixedSize = false; + ShouldCreateWrapper = false; + canDeserialize = true; + } + else + { + _genericCollectionDefinitionType = typeof(List<>).MakeGenericType(CollectionItemType); + + IsReadOnlyOrFixedSize = true; + ShouldCreateWrapper = true; + canDeserialize = HasParameterizedCreatorInternal; + } + } + else + { + // types that implement IEnumerable and nothing else + canDeserialize = false; + ShouldCreateWrapper = true; + } + + CanDeserialize = canDeserialize; + +#if (NET20 || NET35) + if (CollectionItemType != null && ReflectionUtils.IsNullableType(CollectionItemType)) + { + // bug in .NET 2.0 & 3.5 that List> throws an error when adding null via IList.Add(object) + // wrapper will handle calling Add(T) instead + if (ReflectionUtils.InheritsGenericDefinition(CreatedType, typeof(List<>), out tempCollectionType) + || (IsArray && !IsMultidimensionalArray)) + { + ShouldCreateWrapper = true; + } + } +#endif + +#if !(NET20 || NET35 || NET40) + Type immutableCreatedType; + ObjectConstructor immutableParameterizedCreator; + if (ImmutableCollectionsUtils.TryBuildImmutableForArrayContract(underlyingType, CollectionItemType, out immutableCreatedType, out immutableParameterizedCreator)) + { + CreatedType = immutableCreatedType; + _parameterizedCreator = immutableParameterizedCreator; + IsReadOnlyOrFixedSize = true; + CanDeserialize = true; + } +#endif + } + + internal IWrappedCollection CreateWrapper(object list) + { + if (_genericWrapperCreator == null) + { + _genericWrapperType = typeof(CollectionWrapper<>).MakeGenericType(CollectionItemType); + + Type constructorArgument; + + if (ReflectionUtils.InheritsGenericDefinition(_genericCollectionDefinitionType, typeof(List<>)) + || _genericCollectionDefinitionType.GetGenericTypeDefinition() == typeof(IEnumerable<>)) + { + constructorArgument = typeof(ICollection<>).MakeGenericType(CollectionItemType); + } + else + { + constructorArgument = _genericCollectionDefinitionType; + } + + ConstructorInfo genericWrapperConstructor = _genericWrapperType.GetConstructor(new[] { constructorArgument }); + _genericWrapperCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(genericWrapperConstructor); + } + + return (IWrappedCollection)_genericWrapperCreator(list); + } + + internal IList CreateTemporaryCollection() + { + if (_genericTemporaryCollectionCreator == null) + { + // multidimensional array will also have array instances in it + Type collectionItemType = (IsMultidimensionalArray || CollectionItemType == null) + ? typeof(object) + : CollectionItemType; + + Type temporaryListType = typeof(List<>).MakeGenericType(collectionItemType); + _genericTemporaryCollectionCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateDefaultConstructor(temporaryListType); + } + + return (IList)_genericTemporaryCollectionCreator(); + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Serialization/JsonContainerContract.cs b/Common/00-1Json8.3/Json8.3/Serialization/JsonContainerContract.cs new file mode 100644 index 0000000..ef91743 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Serialization/JsonContainerContract.cs @@ -0,0 +1,120 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Collections.Generic; +using System.Reflection; +using Newtonsoft.Json.Utilities; +using System.Collections; +#if NET20 +using Newtonsoft.Json.Utilities.LinqBridge; +#else +using System.Linq; + +#endif + +namespace Newtonsoft.Json.Serialization +{ + /// + /// Contract details for a used by the . + /// + public class JsonContainerContract : JsonContract + { + private JsonContract _itemContract; + private JsonContract _finalItemContract; + + // will be null for containers that don't have an item type (e.g. IList) or for complex objects + internal JsonContract ItemContract + { + get { return _itemContract; } + set + { + _itemContract = value; + if (_itemContract != null) + { + _finalItemContract = (_itemContract.UnderlyingType.IsSealed()) ? _itemContract : null; + } + else + { + _finalItemContract = null; + } + } + } + + // the final (i.e. can't be inherited from like a sealed class or valuetype) item contract + internal JsonContract FinalItemContract + { + get { return _finalItemContract; } + } + + /// + /// Gets or sets the default collection items . + /// + /// The converter. + public JsonConverter ItemConverter { get; set; } + + /// + /// Gets or sets a value indicating whether the collection items preserve object references. + /// + /// true if collection items preserve object references; otherwise, false. + public bool? ItemIsReference { get; set; } + + /// + /// Gets or sets the collection item reference loop handling. + /// + /// The reference loop handling. + public ReferenceLoopHandling? ItemReferenceLoopHandling { get; set; } + + /// + /// Gets or sets the collection item type name handling. + /// + /// The type name handling. + public TypeNameHandling? ItemTypeNameHandling { get; set; } + + /// + /// Initializes a new instance of the class. + /// + /// The underlying type for the contract. + internal JsonContainerContract(Type underlyingType) + : base(underlyingType) + { + JsonContainerAttribute jsonContainerAttribute = JsonTypeReflector.GetCachedAttribute(underlyingType); + + if (jsonContainerAttribute != null) + { + if (jsonContainerAttribute.ItemConverterType != null) + { + ItemConverter = JsonTypeReflector.CreateJsonConverterInstance( + jsonContainerAttribute.ItemConverterType, + jsonContainerAttribute.ItemConverterParameters); + } + + ItemIsReference = jsonContainerAttribute._itemIsReference; + ItemReferenceLoopHandling = jsonContainerAttribute._itemReferenceLoopHandling; + ItemTypeNameHandling = jsonContainerAttribute._itemTypeNameHandling; + } + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Serialization/JsonContract.cs b/Common/00-1Json8.3/Json8.3/Serialization/JsonContract.cs new file mode 100644 index 0000000..6d0b2c3 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Serialization/JsonContract.cs @@ -0,0 +1,392 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Reflection; +using System.Runtime.Serialization; +using Newtonsoft.Json.Linq; +using Newtonsoft.Json.Utilities; + +namespace Newtonsoft.Json.Serialization +{ + internal enum JsonContractType + { + None = 0, + Object = 1, + Array = 2, + Primitive = 3, + String = 4, + Dictionary = 5, + Dynamic = 6, + Serializable = 7, + Linq = 8 + } + + /// + /// Handles serialization callback events. + /// + /// The object that raised the callback event. + /// The streaming context. + public delegate void SerializationCallback(object o, StreamingContext context); + + /// + /// Handles serialization error callback events. + /// + /// The object that raised the callback event. + /// The streaming context. + /// The error context. + public delegate void SerializationErrorCallback(object o, StreamingContext context, ErrorContext errorContext); + + /// + /// Sets extension data for an object during deserialization. + /// + /// The object to set extension data on. + /// The extension data key. + /// The extension data value. + public delegate void ExtensionDataSetter(object o, string key, object value); + + /// + /// Gets extension data for an object during serialization. + /// + /// The object to set extension data on. + public delegate IEnumerable> ExtensionDataGetter(object o); + + /// + /// Contract details for a used by the . + /// + public abstract class JsonContract + { + internal bool IsNullable; + internal bool IsConvertable; + internal bool IsEnum; + internal Type NonNullableUnderlyingType; + internal ReadType InternalReadType; + internal JsonContractType ContractType; + internal bool IsReadOnlyOrFixedSize; + internal bool IsSealed; + internal bool IsInstantiable; + + private List _onDeserializedCallbacks; + private IList _onDeserializingCallbacks; + private IList _onSerializedCallbacks; + private IList _onSerializingCallbacks; + private IList _onErrorCallbacks; + private Type _createdType; + + /// + /// Gets the underlying type for the contract. + /// + /// The underlying type for the contract. + public Type UnderlyingType { get; private set; } + + /// + /// Gets or sets the type created during deserialization. + /// + /// The type created during deserialization. + public Type CreatedType + { + get { return _createdType; } + set + { + _createdType = value; + + IsSealed = _createdType.IsSealed(); + IsInstantiable = !(_createdType.IsInterface() || _createdType.IsAbstract()); + } + } + + /// + /// Gets or sets whether this type contract is serialized as a reference. + /// + /// Whether this type contract is serialized as a reference. + public bool? IsReference { get; set; } + + /// + /// Gets or sets the default for this contract. + /// + /// The converter. + public JsonConverter Converter { get; set; } + + // internally specified JsonConverter's to override default behavour + // checked for after passed in converters and attribute specified converters + internal JsonConverter InternalConverter { get; set; } + + /// + /// Gets or sets all methods called immediately after deserialization of the object. + /// + /// The methods called immediately after deserialization of the object. + public IList OnDeserializedCallbacks + { + get + { + if (_onDeserializedCallbacks == null) + { + _onDeserializedCallbacks = new List(); + } + + return _onDeserializedCallbacks; + } + } + + /// + /// Gets or sets all methods called during deserialization of the object. + /// + /// The methods called during deserialization of the object. + public IList OnDeserializingCallbacks + { + get + { + if (_onDeserializingCallbacks == null) + { + _onDeserializingCallbacks = new List(); + } + + return _onDeserializingCallbacks; + } + } + + /// + /// Gets or sets all methods called after serialization of the object graph. + /// + /// The methods called after serialization of the object graph. + public IList OnSerializedCallbacks + { + get + { + if (_onSerializedCallbacks == null) + { + _onSerializedCallbacks = new List(); + } + + return _onSerializedCallbacks; + } + } + + /// + /// Gets or sets all methods called before serialization of the object. + /// + /// The methods called before serialization of the object. + public IList OnSerializingCallbacks + { + get + { + if (_onSerializingCallbacks == null) + { + _onSerializingCallbacks = new List(); + } + + return _onSerializingCallbacks; + } + } + + /// + /// Gets or sets all method called when an error is thrown during the serialization of the object. + /// + /// The methods called when an error is thrown during the serialization of the object. + public IList OnErrorCallbacks + { + get + { + if (_onErrorCallbacks == null) + { + _onErrorCallbacks = new List(); + } + + return _onErrorCallbacks; + } + } + + /// + /// Gets or sets the method called immediately after deserialization of the object. + /// + /// The method called immediately after deserialization of the object. + [Obsolete("This property is obsolete and has been replaced by the OnDeserializedCallbacks collection.")] + public MethodInfo OnDeserialized + { + get { return (OnDeserializedCallbacks.Count > 0) ? OnDeserializedCallbacks[0].Method() : null; } + set + { + OnDeserializedCallbacks.Clear(); + OnDeserializedCallbacks.Add(CreateSerializationCallback(value)); + } + } + + /// + /// Gets or sets the method called during deserialization of the object. + /// + /// The method called during deserialization of the object. + [Obsolete("This property is obsolete and has been replaced by the OnDeserializingCallbacks collection.")] + public MethodInfo OnDeserializing + { + get { return (OnDeserializingCallbacks.Count > 0) ? OnDeserializingCallbacks[0].Method() : null; } + set + { + OnDeserializingCallbacks.Clear(); + OnDeserializingCallbacks.Add(CreateSerializationCallback(value)); + } + } + + /// + /// Gets or sets the method called after serialization of the object graph. + /// + /// The method called after serialization of the object graph. + [Obsolete("This property is obsolete and has been replaced by the OnSerializedCallbacks collection.")] + public MethodInfo OnSerialized + { + get { return (OnSerializedCallbacks.Count > 0) ? OnSerializedCallbacks[0].Method() : null; } + set + { + OnSerializedCallbacks.Clear(); + OnSerializedCallbacks.Add(CreateSerializationCallback(value)); + } + } + + /// + /// Gets or sets the method called before serialization of the object. + /// + /// The method called before serialization of the object. + [Obsolete("This property is obsolete and has been replaced by the OnSerializingCallbacks collection.")] + public MethodInfo OnSerializing + { + get { return (OnSerializingCallbacks.Count > 0) ? OnSerializingCallbacks[0].Method() : null; } + set + { + OnSerializingCallbacks.Clear(); + OnSerializingCallbacks.Add(CreateSerializationCallback(value)); + } + } + + /// + /// Gets or sets the method called when an error is thrown during the serialization of the object. + /// + /// The method called when an error is thrown during the serialization of the object. + [Obsolete("This property is obsolete and has been replaced by the OnErrorCallbacks collection.")] + public MethodInfo OnError + { + get { return (OnErrorCallbacks.Count > 0) ? OnErrorCallbacks[0].Method() : null; } + set + { + OnErrorCallbacks.Clear(); + OnErrorCallbacks.Add(CreateSerializationErrorCallback(value)); + } + } + + /// + /// Gets or sets the default creator method used to create the object. + /// + /// The default creator method used to create the object. + public Func DefaultCreator { get; set; } + + /// + /// Gets or sets a value indicating whether the default creator is non public. + /// + /// true if the default object creator is non-public; otherwise, false. + public bool DefaultCreatorNonPublic { get; set; } + + internal JsonContract(Type underlyingType) + { + ValidationUtils.ArgumentNotNull(underlyingType, nameof(underlyingType)); + + UnderlyingType = underlyingType; + + IsNullable = ReflectionUtils.IsNullable(underlyingType); + NonNullableUnderlyingType = (IsNullable && ReflectionUtils.IsNullableType(underlyingType)) ? Nullable.GetUnderlyingType(underlyingType) : underlyingType; + + CreatedType = NonNullableUnderlyingType; + + IsConvertable = ConvertUtils.IsConvertible(NonNullableUnderlyingType); + IsEnum = NonNullableUnderlyingType.IsEnum(); + + InternalReadType = ReadType.Read; + } + + internal void InvokeOnSerializing(object o, StreamingContext context) + { + if (_onSerializingCallbacks != null) + { + foreach (SerializationCallback callback in _onSerializingCallbacks) + { + callback(o, context); + } + } + } + + internal void InvokeOnSerialized(object o, StreamingContext context) + { + if (_onSerializedCallbacks != null) + { + foreach (SerializationCallback callback in _onSerializedCallbacks) + { + callback(o, context); + } + } + } + + internal void InvokeOnDeserializing(object o, StreamingContext context) + { + if (_onDeserializingCallbacks != null) + { + foreach (SerializationCallback callback in _onDeserializingCallbacks) + { + callback(o, context); + } + } + } + + internal void InvokeOnDeserialized(object o, StreamingContext context) + { + if (_onDeserializedCallbacks != null) + { + foreach (SerializationCallback callback in _onDeserializedCallbacks) + { + callback(o, context); + } + } + } + + internal void InvokeOnError(object o, StreamingContext context, ErrorContext errorContext) + { + if (_onErrorCallbacks != null) + { + foreach (SerializationErrorCallback callback in _onErrorCallbacks) + { + callback(o, context, errorContext); + } + } + } + + internal static SerializationCallback CreateSerializationCallback(MethodInfo callbackMethodInfo) + { + return (o, context) => callbackMethodInfo.Invoke(o, new object[] { context }); + } + + internal static SerializationErrorCallback CreateSerializationErrorCallback(MethodInfo callbackMethodInfo) + { + return (o, context, econtext) => callbackMethodInfo.Invoke(o, new object[] { context, econtext }); + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Serialization/JsonDictionaryContract.cs b/Common/00-1Json8.3/Json8.3/Serialization/JsonDictionaryContract.cs new file mode 100644 index 0000000..ab3829c --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Serialization/JsonDictionaryContract.cs @@ -0,0 +1,242 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Reflection; +using Newtonsoft.Json.Utilities; +using System.Collections; + +#if NET20 +using Newtonsoft.Json.Utilities.LinqBridge; +#endif + +namespace Newtonsoft.Json.Serialization +{ + /// + /// Contract details for a used by the . + /// + public class JsonDictionaryContract : JsonContainerContract + { + /// + /// Gets or sets the property name resolver. + /// + /// The property name resolver. + [Obsolete("PropertyNameResolver is obsolete. Use DictionaryKeyResolver instead.")] + public Func PropertyNameResolver + { + get { return DictionaryKeyResolver; } + set { DictionaryKeyResolver = value; } + } + + /// + /// Gets or sets the dictionary key resolver. + /// + /// The dictionary key resolver. + public Func DictionaryKeyResolver { get; set; } + + /// + /// Gets the of the dictionary keys. + /// + /// The of the dictionary keys. + public Type DictionaryKeyType { get; private set; } + + /// + /// Gets the of the dictionary values. + /// + /// The of the dictionary values. + public Type DictionaryValueType { get; private set; } + + internal JsonContract KeyContract { get; set; } + + private readonly Type _genericCollectionDefinitionType; + + private Type _genericWrapperType; + private ObjectConstructor _genericWrapperCreator; + + private Func _genericTemporaryDictionaryCreator; + + internal bool ShouldCreateWrapper { get; private set; } + + private readonly ConstructorInfo _parameterizedConstructor; + + private ObjectConstructor _overrideCreator; + private ObjectConstructor _parameterizedCreator; + + internal ObjectConstructor ParameterizedCreator + { + get + { + if (_parameterizedCreator == null) + { + _parameterizedCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(_parameterizedConstructor); + } + + return _parameterizedCreator; + } + } + + /// + /// Gets or sets the function used to create the object. When set this function will override . + /// + /// The function used to create the object. + public ObjectConstructor OverrideCreator + { + get { return _overrideCreator; } + set { _overrideCreator = value; } + } + + /// + /// Gets a value indicating whether the creator has a parameter with the dictionary values. + /// + /// true if the creator has a parameter with the dictionary values; otherwise, false. + public bool HasParameterizedCreator { get; set; } + + internal bool HasParameterizedCreatorInternal + { + get { return (HasParameterizedCreator || _parameterizedCreator != null || _parameterizedConstructor != null); } + } + + /// + /// Initializes a new instance of the class. + /// + /// The underlying type for the contract. + public JsonDictionaryContract(Type underlyingType) + : base(underlyingType) + { + ContractType = JsonContractType.Dictionary; + + Type keyType; + Type valueType; + + if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(IDictionary<,>), out _genericCollectionDefinitionType)) + { + keyType = _genericCollectionDefinitionType.GetGenericArguments()[0]; + valueType = _genericCollectionDefinitionType.GetGenericArguments()[1]; + + if (ReflectionUtils.IsGenericDefinition(UnderlyingType, typeof(IDictionary<,>))) + { + CreatedType = typeof(Dictionary<,>).MakeGenericType(keyType, valueType); + } + +#if !(NET40 || NET35 || NET20 || PORTABLE40) + IsReadOnlyOrFixedSize = ReflectionUtils.InheritsGenericDefinition(underlyingType, typeof(ReadOnlyDictionary<,>)); +#endif + } +#if !(NET40 || NET35 || NET20 || PORTABLE40) + else if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(IReadOnlyDictionary<,>), out _genericCollectionDefinitionType)) + { + keyType = _genericCollectionDefinitionType.GetGenericArguments()[0]; + valueType = _genericCollectionDefinitionType.GetGenericArguments()[1]; + + if (ReflectionUtils.IsGenericDefinition(UnderlyingType, typeof(IReadOnlyDictionary<,>))) + { + CreatedType = typeof(ReadOnlyDictionary<,>).MakeGenericType(keyType, valueType); + } + + IsReadOnlyOrFixedSize = true; + } +#endif + else + { + ReflectionUtils.GetDictionaryKeyValueTypes(UnderlyingType, out keyType, out valueType); + + if (UnderlyingType == typeof(IDictionary)) + { + CreatedType = typeof(Dictionary); + } + } + + if (keyType != null && valueType != null) + { + _parameterizedConstructor = CollectionUtils.ResolveEnumerableCollectionConstructor(CreatedType, typeof(KeyValuePair<,>).MakeGenericType(keyType, valueType)); + +#if !(NET35 || NET20) + if (!HasParameterizedCreatorInternal && underlyingType.Name == FSharpUtils.FSharpMapTypeName) + { + FSharpUtils.EnsureInitialized(underlyingType.Assembly()); + _parameterizedCreator = FSharpUtils.CreateMap(keyType, valueType); + } +#endif + } + + ShouldCreateWrapper = !typeof(IDictionary).IsAssignableFrom(CreatedType); + + DictionaryKeyType = keyType; + DictionaryValueType = valueType; + +#if (NET20 || NET35) + if (DictionaryValueType != null && ReflectionUtils.IsNullableType(DictionaryValueType)) + { + Type tempDictioanryType; + + // bug in .NET 2.0 & 3.5 that Dictionary> throws an error when adding null via IDictionary[key] = object + // wrapper will handle calling Add(T) instead + if (ReflectionUtils.InheritsGenericDefinition(CreatedType, typeof(Dictionary<,>), out tempDictioanryType)) + { + ShouldCreateWrapper = true; + } + } +#endif + +#if !(NET20 || NET35 || NET40) + Type immutableCreatedType; + ObjectConstructor immutableParameterizedCreator; + if (ImmutableCollectionsUtils.TryBuildImmutableForDictionaryContract(underlyingType, DictionaryKeyType, DictionaryValueType, out immutableCreatedType, out immutableParameterizedCreator)) + { + CreatedType = immutableCreatedType; + _parameterizedCreator = immutableParameterizedCreator; + IsReadOnlyOrFixedSize = true; + } +#endif + } + + internal IWrappedDictionary CreateWrapper(object dictionary) + { + if (_genericWrapperCreator == null) + { + _genericWrapperType = typeof(DictionaryWrapper<,>).MakeGenericType(DictionaryKeyType, DictionaryValueType); + + ConstructorInfo genericWrapperConstructor = _genericWrapperType.GetConstructor(new[] { _genericCollectionDefinitionType }); + _genericWrapperCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(genericWrapperConstructor); + } + + return (IWrappedDictionary)_genericWrapperCreator(dictionary); + } + + internal IDictionary CreateTemporaryDictionary() + { + if (_genericTemporaryDictionaryCreator == null) + { + Type temporaryDictionaryType = typeof(Dictionary<,>).MakeGenericType(DictionaryKeyType ?? typeof(object), DictionaryValueType ?? typeof(object)); + + _genericTemporaryDictionaryCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateDefaultConstructor(temporaryDictionaryType); + } + + return (IDictionary)_genericTemporaryDictionaryCreator(); + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Serialization/JsonDynamicContract.cs b/Common/00-1Json8.3/Json8.3/Serialization/JsonDynamicContract.cs new file mode 100644 index 0000000..f4cbfc1 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Serialization/JsonDynamicContract.cs @@ -0,0 +1,119 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +#if !(NET35 || NET20 || PORTABLE40) +using System; +using System.Collections.Generic; +using System.Dynamic; +using System.Reflection; +using System.Runtime.CompilerServices; +using Newtonsoft.Json.Utilities; +using System.Collections; + +namespace Newtonsoft.Json.Serialization +{ + /// + /// Contract details for a used by the . + /// + public class JsonDynamicContract : JsonContainerContract + { + /// + /// Gets the object's properties. + /// + /// The object's properties. + public JsonPropertyCollection Properties { get; private set; } + + /// + /// Gets or sets the property name resolver. + /// + /// The property name resolver. + public Func PropertyNameResolver { get; set; } + + private readonly ThreadSafeStore>> _callSiteGetters = + new ThreadSafeStore>>(CreateCallSiteGetter); + + private readonly ThreadSafeStore>> _callSiteSetters = + new ThreadSafeStore>>(CreateCallSiteSetter); + + private static CallSite> CreateCallSiteGetter(string name) + { + GetMemberBinder getMemberBinder = (GetMemberBinder)DynamicUtils.BinderWrapper.GetMember(name, typeof(DynamicUtils)); + + return CallSite>.Create(new NoThrowGetBinderMember(getMemberBinder)); + } + + private static CallSite> CreateCallSiteSetter(string name) + { + SetMemberBinder binder = (SetMemberBinder)DynamicUtils.BinderWrapper.SetMember(name, typeof(DynamicUtils)); + + return CallSite>.Create(new NoThrowSetBinderMember(binder)); + } + + /// + /// Initializes a new instance of the class. + /// + /// The underlying type for the contract. + public JsonDynamicContract(Type underlyingType) + : base(underlyingType) + { + ContractType = JsonContractType.Dynamic; + + Properties = new JsonPropertyCollection(UnderlyingType); + } + + internal bool TryGetMember(IDynamicMetaObjectProvider dynamicProvider, string name, out object value) + { + ValidationUtils.ArgumentNotNull(dynamicProvider, nameof(dynamicProvider)); + + CallSite> callSite = _callSiteGetters.Get(name); + + object result = callSite.Target(callSite, dynamicProvider); + + if (!ReferenceEquals(result, NoThrowExpressionVisitor.ErrorResult)) + { + value = result; + return true; + } + else + { + value = null; + return false; + } + } + + internal bool TrySetMember(IDynamicMetaObjectProvider dynamicProvider, string name, object value) + { + ValidationUtils.ArgumentNotNull(dynamicProvider, nameof(dynamicProvider)); + + CallSite> callSite = _callSiteSetters.Get(name); + + object result = callSite.Target(callSite, dynamicProvider, value); + + return !ReferenceEquals(result, NoThrowExpressionVisitor.ErrorResult); + } + } +} + +#endif \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Serialization/JsonFormatterConverter.cs b/Common/00-1Json8.3/Json8.3/Serialization/JsonFormatterConverter.cs new file mode 100644 index 0000000..df83357 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Serialization/JsonFormatterConverter.cs @@ -0,0 +1,161 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +#if !(DOTNET || PORTABLE40 || PORTABLE) +using System; +using System.Globalization; +using System.Runtime.Serialization; +using Newtonsoft.Json.Utilities; +using Newtonsoft.Json.Linq; + +namespace Newtonsoft.Json.Serialization +{ + internal class JsonFormatterConverter : IFormatterConverter + { + private readonly JsonSerializerInternalReader _reader; + private readonly JsonISerializableContract _contract; + private readonly JsonProperty _member; + + public JsonFormatterConverter(JsonSerializerInternalReader reader, JsonISerializableContract contract, JsonProperty member) + { + ValidationUtils.ArgumentNotNull(reader, nameof(reader)); + ValidationUtils.ArgumentNotNull(contract, nameof(contract)); + + _reader = reader; + _contract = contract; + _member = member; + } + + private T GetTokenValue(object value) + { + ValidationUtils.ArgumentNotNull(value, nameof(value)); + + JValue v = (JValue)value; + return (T)System.Convert.ChangeType(v.Value, typeof(T), CultureInfo.InvariantCulture); + } + + public object Convert(object value, Type type) + { + ValidationUtils.ArgumentNotNull(value, nameof(value)); + + JToken token = value as JToken; + if (token == null) + { + throw new ArgumentException("Value is not a JToken.", nameof(value)); + } + + return _reader.CreateISerializableItem(token, type, _contract, _member); + } + + public object Convert(object value, TypeCode typeCode) + { + ValidationUtils.ArgumentNotNull(value, nameof(value)); + + if (value is JValue) + { + value = ((JValue)value).Value; + } + + return System.Convert.ChangeType(value, typeCode, CultureInfo.InvariantCulture); + } + + public bool ToBoolean(object value) + { + return GetTokenValue(value); + } + + public byte ToByte(object value) + { + return GetTokenValue(value); + } + + public char ToChar(object value) + { + return GetTokenValue(value); + } + + public DateTime ToDateTime(object value) + { + return GetTokenValue(value); + } + + public decimal ToDecimal(object value) + { + return GetTokenValue(value); + } + + public double ToDouble(object value) + { + return GetTokenValue(value); + } + + public short ToInt16(object value) + { + return GetTokenValue(value); + } + + public int ToInt32(object value) + { + return GetTokenValue(value); + } + + public long ToInt64(object value) + { + return GetTokenValue(value); + } + + public sbyte ToSByte(object value) + { + return GetTokenValue(value); + } + + public float ToSingle(object value) + { + return GetTokenValue(value); + } + + public string ToString(object value) + { + return GetTokenValue(value); + } + + public ushort ToUInt16(object value) + { + return GetTokenValue(value); + } + + public uint ToUInt32(object value) + { + return GetTokenValue(value); + } + + public ulong ToUInt64(object value) + { + return GetTokenValue(value); + } + } +} + +#endif \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Serialization/JsonISerializableContract.cs b/Common/00-1Json8.3/Json8.3/Serialization/JsonISerializableContract.cs new file mode 100644 index 0000000..0e8dc09 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Serialization/JsonISerializableContract.cs @@ -0,0 +1,55 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +#if !(DOTNET || PORTABLE || PORTABLE40) +using System; +using System.Runtime.Serialization; + +namespace Newtonsoft.Json.Serialization +{ + /// + /// Contract details for a used by the . + /// + public class JsonISerializableContract : JsonContainerContract + { + /// + /// Gets or sets the ISerializable object constructor. + /// + /// The ISerializable object constructor. + public ObjectConstructor ISerializableCreator { get; set; } + + /// + /// Initializes a new instance of the class. + /// + /// The underlying type for the contract. + public JsonISerializableContract(Type underlyingType) + : base(underlyingType) + { + ContractType = JsonContractType.Serializable; + } + } +} + +#endif \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Serialization/JsonLinqContract.cs b/Common/00-1Json8.3/Json8.3/Serialization/JsonLinqContract.cs new file mode 100644 index 0000000..c91b3f0 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Serialization/JsonLinqContract.cs @@ -0,0 +1,45 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; + +namespace Newtonsoft.Json.Serialization +{ + /// + /// Contract details for a used by the . + /// + public class JsonLinqContract : JsonContract + { + /// + /// Initializes a new instance of the class. + /// + /// The underlying type for the contract. + public JsonLinqContract(Type underlyingType) + : base(underlyingType) + { + ContractType = JsonContractType.Linq; + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Serialization/JsonObjectContract.cs b/Common/00-1Json8.3/Json8.3/Serialization/JsonObjectContract.cs new file mode 100644 index 0000000..ff81d12 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Serialization/JsonObjectContract.cs @@ -0,0 +1,227 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Globalization; +using System.Reflection; +using System.Runtime.Serialization; +using System.Security; +using Newtonsoft.Json.Linq; +using Newtonsoft.Json.Utilities; + +namespace Newtonsoft.Json.Serialization +{ + /// + /// Contract details for a used by the . + /// + public class JsonObjectContract : JsonContainerContract + { + /// + /// Gets or sets the object member serialization. + /// + /// The member object serialization. + public MemberSerialization MemberSerialization { get; set; } + + /// + /// Gets or sets a value that indicates whether the object's properties are required. + /// + /// + /// A value indicating whether the object's properties are required. + /// + public Required? ItemRequired { get; set; } + + /// + /// Gets the object's properties. + /// + /// The object's properties. + public JsonPropertyCollection Properties { get; private set; } + + /// + /// Gets the constructor parameters required for any non-default constructor + /// + [Obsolete("ConstructorParameters is obsolete. Use CreatorParameters instead.")] + public JsonPropertyCollection ConstructorParameters + { + get { return CreatorParameters; } + } + + /// + /// Gets a collection of instances that define the parameters used with . + /// + public JsonPropertyCollection CreatorParameters + { + get + { + if (_creatorParameters == null) + { + _creatorParameters = new JsonPropertyCollection(UnderlyingType); + } + + return _creatorParameters; + } + } + + /// + /// Gets or sets the override constructor used to create the object. + /// This is set when a constructor is marked up using the + /// JsonConstructor attribute. + /// + /// The override constructor. + [Obsolete("OverrideConstructor is obsolete. Use OverrideCreator instead.")] + public ConstructorInfo OverrideConstructor + { + get { return _overrideConstructor; } + set + { + _overrideConstructor = value; + _overrideCreator = (value != null) ? JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(value) : null; + } + } + + /// + /// Gets or sets the parametrized constructor used to create the object. + /// + /// The parametrized constructor. + [Obsolete("ParametrizedConstructor is obsolete. Use OverrideCreator instead.")] + public ConstructorInfo ParametrizedConstructor + { + get { return _parametrizedConstructor; } + set + { + _parametrizedConstructor = value; + _parameterizedCreator = (value != null) ? JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(value) : null; + } + } + + /// + /// Gets or sets the function used to create the object. When set this function will override . + /// This function is called with a collection of arguments which are defined by the collection. + /// + /// The function used to create the object. + public ObjectConstructor OverrideCreator + { + get { return _overrideCreator; } + set + { + _overrideCreator = value; + _overrideConstructor = null; + } + } + + internal ObjectConstructor ParameterizedCreator + { + get { return _parameterizedCreator; } + } + + /// + /// Gets or sets the extension data setter. + /// + public ExtensionDataSetter ExtensionDataSetter { get; set; } + + /// + /// Gets or sets the extension data getter. + /// + public ExtensionDataGetter ExtensionDataGetter { get; set; } + + /// + /// Gets or sets the extension data value type. + /// + public Type ExtensionDataValueType + { + get { return _extensionDataValueType; } + set + { + _extensionDataValueType = value; + ExtensionDataIsJToken = (value != null && typeof(JToken).IsAssignableFrom(value)); + } + } + + internal bool ExtensionDataIsJToken; + private bool? _hasRequiredOrDefaultValueProperties; + private ConstructorInfo _parametrizedConstructor; + private ConstructorInfo _overrideConstructor; + private ObjectConstructor _overrideCreator; + private ObjectConstructor _parameterizedCreator; + private JsonPropertyCollection _creatorParameters; + private Type _extensionDataValueType; + + internal bool HasRequiredOrDefaultValueProperties + { + get + { + if (_hasRequiredOrDefaultValueProperties == null) + { + _hasRequiredOrDefaultValueProperties = false; + + if (ItemRequired.GetValueOrDefault(Required.Default) != Required.Default) + { + _hasRequiredOrDefaultValueProperties = true; + } + else + { + foreach (JsonProperty property in Properties) + { + if (property.Required != Required.Default || (property.DefaultValueHandling & DefaultValueHandling.Populate) == DefaultValueHandling.Populate) + { + _hasRequiredOrDefaultValueProperties = true; + break; + } + } + } + } + + return _hasRequiredOrDefaultValueProperties.GetValueOrDefault(); + } + } + + /// + /// Initializes a new instance of the class. + /// + /// The underlying type for the contract. + public JsonObjectContract(Type underlyingType) + : base(underlyingType) + { + ContractType = JsonContractType.Object; + + Properties = new JsonPropertyCollection(UnderlyingType); + } + +#if !(DOTNET || PORTABLE40 || PORTABLE) +#if !(NET20 || NET35) + [SecuritySafeCritical] +#endif + internal object GetUninitializedObject() + { + // we should never get here if the environment is not fully trusted, check just in case + if (!JsonTypeReflector.FullyTrusted) + { + throw new JsonException("Insufficient permissions. Creating an uninitialized '{0}' type requires full trust.".FormatWith(CultureInfo.InvariantCulture, NonNullableUnderlyingType)); + } + + return FormatterServices.GetUninitializedObject(NonNullableUnderlyingType); + } +#endif + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Serialization/JsonPrimitiveContract.cs b/Common/00-1Json8.3/Json8.3/Serialization/JsonPrimitiveContract.cs new file mode 100644 index 0000000..8130868 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Serialization/JsonPrimitiveContract.cs @@ -0,0 +1,75 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Collections.Generic; +using Newtonsoft.Json.Utilities; + +namespace Newtonsoft.Json.Serialization +{ + /// + /// Contract details for a used by the . + /// + public class JsonPrimitiveContract : JsonContract + { + internal PrimitiveTypeCode TypeCode { get; set; } + + /// + /// Initializes a new instance of the class. + /// + /// The underlying type for the contract. + public JsonPrimitiveContract(Type underlyingType) + : base(underlyingType) + { + ContractType = JsonContractType.Primitive; + + TypeCode = ConvertUtils.GetTypeCode(underlyingType); + IsReadOnlyOrFixedSize = true; + + ReadType readType; + if (ReadTypeMap.TryGetValue(NonNullableUnderlyingType, out readType)) + { + InternalReadType = readType; + } + } + + private static readonly Dictionary ReadTypeMap = new Dictionary + { + [typeof(byte[])] = ReadType.ReadAsBytes, + [typeof(byte)] = ReadType.ReadAsInt32, + [typeof(short)] = ReadType.ReadAsInt32, + [typeof(int)] = ReadType.ReadAsInt32, + [typeof(decimal)] = ReadType.ReadAsDecimal, + [typeof(bool)] = ReadType.ReadAsBoolean, + [typeof(string)] = ReadType.ReadAsString, + [typeof(DateTime)] = ReadType.ReadAsDateTime, +#if !NET20 + [typeof(DateTimeOffset)] = ReadType.ReadAsDateTimeOffset, +#endif + [typeof(float)] = ReadType.ReadAsDouble, + [typeof(double)] = ReadType.ReadAsDouble + }; + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Serialization/JsonProperty.cs b/Common/00-1Json8.3/Json8.3/Serialization/JsonProperty.cs new file mode 100644 index 0000000..9b0ab58 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Serialization/JsonProperty.cs @@ -0,0 +1,308 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Reflection; +using Newtonsoft.Json.Utilities; + +#if NET20 +using Newtonsoft.Json.Utilities.LinqBridge; +#endif + +namespace Newtonsoft.Json.Serialization +{ + /// + /// Maps a JSON property to a .NET member or constructor parameter. + /// + public class JsonProperty + { + internal Required? _required; + internal bool _hasExplicitDefaultValue; + + private object _defaultValue; + private bool _hasGeneratedDefaultValue; + private string _propertyName; + internal bool _skipPropertyNameEscape; + private Type _propertyType; + + // use to cache contract during deserialization + internal JsonContract PropertyContract { get; set; } + + /// + /// Gets or sets the name of the property. + /// + /// The name of the property. + public string PropertyName + { + get { return _propertyName; } + set + { + _propertyName = value; + _skipPropertyNameEscape = !JavaScriptUtils.ShouldEscapeJavaScriptString(_propertyName, JavaScriptUtils.HtmlCharEscapeFlags); + } + } + + /// + /// Gets or sets the type that declared this property. + /// + /// The type that declared this property. + public Type DeclaringType { get; set; } + + /// + /// Gets or sets the order of serialization of a member. + /// + /// The numeric order of serialization. + public int? Order { get; set; } + + /// + /// Gets or sets the name of the underlying member or parameter. + /// + /// The name of the underlying member or parameter. + public string UnderlyingName { get; set; } + + /// + /// Gets the that will get and set the during serialization. + /// + /// The that will get and set the during serialization. + public IValueProvider ValueProvider { get; set; } + + /// + /// Gets or sets the for this property. + /// + /// The for this property. + public IAttributeProvider AttributeProvider { get; set; } + + /// + /// Gets or sets the type of the property. + /// + /// The type of the property. + public Type PropertyType + { + get { return _propertyType; } + set + { + if (_propertyType != value) + { + _propertyType = value; + _hasGeneratedDefaultValue = false; + } + } + } + + /// + /// Gets or sets the for the property. + /// If set this converter takes presidence over the contract converter for the property type. + /// + /// The converter. + public JsonConverter Converter { get; set; } + + /// + /// Gets or sets the member converter. + /// + /// The member converter. + public JsonConverter MemberConverter { get; set; } + + /// + /// Gets or sets a value indicating whether this is ignored. + /// + /// true if ignored; otherwise, false. + public bool Ignored { get; set; } + + /// + /// Gets or sets a value indicating whether this is readable. + /// + /// true if readable; otherwise, false. + public bool Readable { get; set; } + + /// + /// Gets or sets a value indicating whether this is writable. + /// + /// true if writable; otherwise, false. + public bool Writable { get; set; } + + /// + /// Gets or sets a value indicating whether this has a member attribute. + /// + /// true if has a member attribute; otherwise, false. + public bool HasMemberAttribute { get; set; } + + /// + /// Gets the default value. + /// + /// The default value. + public object DefaultValue + { + get + { + if (!_hasExplicitDefaultValue) + { + return null; + } + + return _defaultValue; + } + set + { + _hasExplicitDefaultValue = true; + _defaultValue = value; + } + } + + internal object GetResolvedDefaultValue() + { + if (_propertyType == null) + { + return null; + } + + if (!_hasExplicitDefaultValue && !_hasGeneratedDefaultValue) + { + _defaultValue = ReflectionUtils.GetDefaultValue(PropertyType); + _hasGeneratedDefaultValue = true; + } + + return _defaultValue; + } + + /// + /// Gets or sets a value indicating whether this is required. + /// + /// A value indicating whether this is required. + public Required Required + { + get { return _required ?? Required.Default; } + set { _required = value; } + } + + /// + /// Gets or sets a value indicating whether this property preserves object references. + /// + /// + /// true if this instance is reference; otherwise, false. + /// + public bool? IsReference { get; set; } + + /// + /// Gets or sets the property null value handling. + /// + /// The null value handling. + public NullValueHandling? NullValueHandling { get; set; } + + /// + /// Gets or sets the property default value handling. + /// + /// The default value handling. + public DefaultValueHandling? DefaultValueHandling { get; set; } + + /// + /// Gets or sets the property reference loop handling. + /// + /// The reference loop handling. + public ReferenceLoopHandling? ReferenceLoopHandling { get; set; } + + /// + /// Gets or sets the property object creation handling. + /// + /// The object creation handling. + public ObjectCreationHandling? ObjectCreationHandling { get; set; } + + /// + /// Gets or sets or sets the type name handling. + /// + /// The type name handling. + public TypeNameHandling? TypeNameHandling { get; set; } + + /// + /// Gets or sets a predicate used to determine whether the property should be serialize. + /// + /// A predicate used to determine whether the property should be serialize. + public Predicate ShouldSerialize { get; set; } + + /// + /// Gets or sets a predicate used to determine whether the property should be deserialized. + /// + /// A predicate used to determine whether the property should be deserialized. + public Predicate ShouldDeserialize { get; set; } + + /// + /// Gets or sets a predicate used to determine whether the property should be serialized. + /// + /// A predicate used to determine whether the property should be serialized. + public Predicate GetIsSpecified { get; set; } + + /// + /// Gets or sets an action used to set whether the property has been deserialized. + /// + /// An action used to set whether the property has been deserialized. + public Action SetIsSpecified { get; set; } + + /// + /// Returns a that represents this instance. + /// + /// + /// A that represents this instance. + /// + public override string ToString() + { + return PropertyName; + } + + /// + /// Gets or sets the converter used when serializing the property's collection items. + /// + /// The collection's items converter. + public JsonConverter ItemConverter { get; set; } + + /// + /// Gets or sets whether this property's collection items are serialized as a reference. + /// + /// Whether this property's collection items are serialized as a reference. + public bool? ItemIsReference { get; set; } + + /// + /// Gets or sets the the type name handling used when serializing the property's collection items. + /// + /// The collection's items type name handling. + public TypeNameHandling? ItemTypeNameHandling { get; set; } + + /// + /// Gets or sets the the reference loop handling used when serializing the property's collection items. + /// + /// The collection's items reference loop handling. + public ReferenceLoopHandling? ItemReferenceLoopHandling { get; set; } + + internal void WritePropertyName(JsonWriter writer) + { + if (_skipPropertyNameEscape) + { + writer.WritePropertyName(PropertyName, false); + } + else + { + writer.WritePropertyName(PropertyName); + } + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Serialization/JsonPropertyCollection.cs b/Common/00-1Json8.3/Json8.3/Serialization/JsonPropertyCollection.cs new file mode 100644 index 0000000..3da2518 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Serialization/JsonPropertyCollection.cs @@ -0,0 +1,180 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Collections.Generic; +using System.Text; +using System.Collections.ObjectModel; +using Newtonsoft.Json.Utilities; +using System.Globalization; + +namespace Newtonsoft.Json.Serialization +{ + /// + /// A collection of objects. + /// + public class JsonPropertyCollection : KeyedCollection + { + private readonly Type _type; + private readonly List _list; + + /// + /// Initializes a new instance of the class. + /// + /// The type. + public JsonPropertyCollection(Type type) + : base(StringComparer.Ordinal) + { + ValidationUtils.ArgumentNotNull(type, "type"); + _type = type; + + // foreach over List to avoid boxing the Enumerator + _list = (List)Items; + } + + /// + /// When implemented in a derived class, extracts the key from the specified element. + /// + /// The element from which to extract the key. + /// The key for the specified element. + protected override string GetKeyForItem(JsonProperty item) + { + return item.PropertyName; + } + + /// + /// Adds a object. + /// + /// The property to add to the collection. + public void AddProperty(JsonProperty property) + { + if (Contains(property.PropertyName)) + { + // don't overwrite existing property with ignored property + if (property.Ignored) + { + return; + } + + JsonProperty existingProperty = this[property.PropertyName]; + bool duplicateProperty = true; + + if (existingProperty.Ignored) + { + // remove ignored property so it can be replaced in collection + Remove(existingProperty); + duplicateProperty = false; + } + else + { + if (property.DeclaringType != null && existingProperty.DeclaringType != null) + { + if (property.DeclaringType.IsSubclassOf(existingProperty.DeclaringType) + || (existingProperty.DeclaringType.IsInterface() && property.DeclaringType.ImplementInterface(existingProperty.DeclaringType))) + { + // current property is on a derived class and hides the existing + Remove(existingProperty); + duplicateProperty = false; + } + if (existingProperty.DeclaringType.IsSubclassOf(property.DeclaringType) + || (property.DeclaringType.IsInterface() && existingProperty.DeclaringType.ImplementInterface(property.DeclaringType))) + { + // current property is hidden by the existing so don't add it + return; + } + } + } + + if (duplicateProperty) + { + throw new JsonSerializationException("A member with the name '{0}' already exists on '{1}'. Use the JsonPropertyAttribute to specify another name.".FormatWith(CultureInfo.InvariantCulture, property.PropertyName, _type)); + } + } + + Add(property); + } + + /// + /// Gets the closest matching object. + /// First attempts to get an exact case match of propertyName and then + /// a case insensitive match. + /// + /// Name of the property. + /// A matching property if found. + public JsonProperty GetClosestMatchProperty(string propertyName) + { + JsonProperty property = GetProperty(propertyName, StringComparison.Ordinal); + if (property == null) + { + property = GetProperty(propertyName, StringComparison.OrdinalIgnoreCase); + } + + return property; + } + + private bool TryGetValue(string key, out JsonProperty item) + { + if (Dictionary == null) + { + item = default(JsonProperty); + return false; + } + + return Dictionary.TryGetValue(key, out item); + } + + /// + /// Gets a property by property name. + /// + /// The name of the property to get. + /// Type property name string comparison. + /// A matching property if found. + public JsonProperty GetProperty(string propertyName, StringComparison comparisonType) + { + // KeyedCollection has an ordinal comparer + if (comparisonType == StringComparison.Ordinal) + { + JsonProperty property; + if (TryGetValue(propertyName, out property)) + { + return property; + } + + return null; + } + + for (int i = 0; i < _list.Count; i++) + { + JsonProperty property = _list[i]; + if (string.Equals(propertyName, property.PropertyName, comparisonType)) + { + return property; + } + } + + return null; + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Serialization/JsonSerializerInternalBase.cs b/Common/00-1Json8.3/Json8.3/Serialization/JsonSerializerInternalBase.cs new file mode 100644 index 0000000..f7e09fa --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Serialization/JsonSerializerInternalBase.cs @@ -0,0 +1,149 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using Newtonsoft.Json.Utilities; + +namespace Newtonsoft.Json.Serialization +{ + internal abstract class JsonSerializerInternalBase + { + private class ReferenceEqualsEqualityComparer : IEqualityComparer + { + bool IEqualityComparer.Equals(object x, object y) + { + return ReferenceEquals(x, y); + } + + int IEqualityComparer.GetHashCode(object obj) + { + // put objects in a bucket based on their reference + return RuntimeHelpers.GetHashCode(obj); + } + } + + private ErrorContext _currentErrorContext; + private BidirectionalDictionary _mappings; + + internal readonly JsonSerializer Serializer; + internal readonly ITraceWriter TraceWriter; + protected JsonSerializerProxy InternalSerializer; + + protected JsonSerializerInternalBase(JsonSerializer serializer) + { + ValidationUtils.ArgumentNotNull(serializer, nameof(serializer)); + + Serializer = serializer; + TraceWriter = serializer.TraceWriter; + } + + internal BidirectionalDictionary DefaultReferenceMappings + { + get + { + // override equality comparer for object key dictionary + // object will be modified as it deserializes and might have mutable hashcode + if (_mappings == null) + { + _mappings = new BidirectionalDictionary( + EqualityComparer.Default, + new ReferenceEqualsEqualityComparer(), + "A different value already has the Id '{0}'.", + "A different Id has already been assigned for value '{0}'."); + } + + return _mappings; + } + } + + private ErrorContext GetErrorContext(object currentObject, object member, string path, Exception error) + { + if (_currentErrorContext == null) + { + _currentErrorContext = new ErrorContext(currentObject, member, path, error); + } + + if (_currentErrorContext.Error != error) + { + throw new InvalidOperationException("Current error context error is different to requested error."); + } + + return _currentErrorContext; + } + + protected void ClearErrorContext() + { + if (_currentErrorContext == null) + { + throw new InvalidOperationException("Could not clear error context. Error context is already null."); + } + + _currentErrorContext = null; + } + + protected bool IsErrorHandled(object currentObject, JsonContract contract, object keyValue, IJsonLineInfo lineInfo, string path, Exception ex) + { + ErrorContext errorContext = GetErrorContext(currentObject, keyValue, path, ex); + + if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Error && !errorContext.Traced) + { + // only write error once + errorContext.Traced = true; + + // kind of a hack but meh. might clean this up later + string message = (GetType() == typeof(JsonSerializerInternalWriter)) ? "Error serializing" : "Error deserializing"; + if (contract != null) + { + message += " " + contract.UnderlyingType; + } + message += ". " + ex.Message; + + // add line information to non-json.net exception message + if (!(ex is JsonException)) + { + message = JsonPosition.FormatMessage(lineInfo, path, message); + } + + TraceWriter.Trace(TraceLevel.Error, message, ex); + } + + // attribute method is non-static so don't invoke if no object + if (contract != null && currentObject != null) + { + contract.InvokeOnError(currentObject, Serializer.Context, errorContext); + } + + if (!errorContext.Handled) + { + Serializer.OnError(new ErrorEventArgs(currentObject, errorContext)); + } + + return errorContext.Handled; + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Serialization/JsonSerializerInternalReader.cs b/Common/00-1Json8.3/Json8.3/Serialization/JsonSerializerInternalReader.cs new file mode 100644 index 0000000..8cea1f6 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Serialization/JsonSerializerInternalReader.cs @@ -0,0 +1,2585 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +#if !(NET35 || NET20 || PORTABLE40) +using System.ComponentModel; +using System.Dynamic; +#endif +using System.Diagnostics; +using System.Globalization; +#if !(PORTABLE || PORTABLE40 || NET35 || NET20) +using System.Numerics; +#endif +using System.Reflection; +using System.Runtime.Serialization; +using Newtonsoft.Json.Linq; +using Newtonsoft.Json.Utilities; +#if NET20 +using Newtonsoft.Json.Utilities.LinqBridge; +#else +using System.Linq; + +#endif + +namespace Newtonsoft.Json.Serialization +{ + internal class JsonSerializerInternalReader : JsonSerializerInternalBase + { + internal enum PropertyPresence + { + None = 0, + Null = 1, + Value = 2 + } + + public JsonSerializerInternalReader(JsonSerializer serializer) + : base(serializer) + { + } + + public void Populate(JsonReader reader, object target) + { + ValidationUtils.ArgumentNotNull(target, nameof(target)); + + Type objectType = target.GetType(); + + JsonContract contract = Serializer._contractResolver.ResolveContract(objectType); + + if (!reader.MoveToContent()) + { + throw JsonSerializationException.Create(reader, "No JSON content found."); + } + + if (reader.TokenType == JsonToken.StartArray) + { + if (contract.ContractType == JsonContractType.Array) + { + JsonArrayContract arrayContract = (JsonArrayContract)contract; + + PopulateList((arrayContract.ShouldCreateWrapper) ? arrayContract.CreateWrapper(target) : (IList)target, reader, arrayContract, null, null); + } + else + { + throw JsonSerializationException.Create(reader, "Cannot populate JSON array onto type '{0}'.".FormatWith(CultureInfo.InvariantCulture, objectType)); + } + } + else if (reader.TokenType == JsonToken.StartObject) + { + reader.ReadAndAssert(); + + string id = null; + if (Serializer.MetadataPropertyHandling != MetadataPropertyHandling.Ignore + && reader.TokenType == JsonToken.PropertyName + && string.Equals(reader.Value.ToString(), JsonTypeReflector.IdPropertyName, StringComparison.Ordinal)) + { + reader.ReadAndAssert(); + id = (reader.Value != null) ? reader.Value.ToString() : null; + reader.ReadAndAssert(); + } + + if (contract.ContractType == JsonContractType.Dictionary) + { + JsonDictionaryContract dictionaryContract = (JsonDictionaryContract)contract; + PopulateDictionary((dictionaryContract.ShouldCreateWrapper) ? dictionaryContract.CreateWrapper(target) : (IDictionary)target, reader, dictionaryContract, null, id); + } + else if (contract.ContractType == JsonContractType.Object) + { + PopulateObject(target, reader, (JsonObjectContract)contract, null, id); + } + else + { + throw JsonSerializationException.Create(reader, "Cannot populate JSON object onto type '{0}'.".FormatWith(CultureInfo.InvariantCulture, objectType)); + } + } + else + { + throw JsonSerializationException.Create(reader, "Unexpected initial token '{0}' when populating object. Expected JSON object or array.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); + } + } + + private JsonContract GetContractSafe(Type type) + { + if (type == null) + { + return null; + } + + return Serializer._contractResolver.ResolveContract(type); + } + + public object Deserialize(JsonReader reader, Type objectType, bool checkAdditionalContent) + { + if (reader == null) + { + throw new ArgumentNullException(nameof(reader)); + } + + JsonContract contract = GetContractSafe(objectType); + + try + { + JsonConverter converter = GetConverter(contract, null, null, null); + + if (reader.TokenType == JsonToken.None && !ReadForType(reader, contract, converter != null)) + { + if (contract != null && !contract.IsNullable) + { + throw JsonSerializationException.Create(reader, "No JSON content found and type '{0}' is not nullable.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)); + } + + return null; + } + + object deserializedValue; + + if (converter != null && converter.CanRead) + { + deserializedValue = DeserializeConvertable(converter, reader, objectType, null); + } + else + { + deserializedValue = CreateValueInternal(reader, objectType, contract, null, null, null, null); + } + + if (checkAdditionalContent) + { + if (reader.Read() && reader.TokenType != JsonToken.Comment) + { + throw new JsonSerializationException("Additional text found in JSON string after finishing deserializing object."); + } + } + + return deserializedValue; + } + catch (Exception ex) + { + //if (IsErrorHandled(null, contract, null, reader as IJsonLineInfo, reader.Path, ex)) + //{ + // HandleError(reader, false, 0); + // return null; + //} + //else + //{ + // // clear context in case serializer is being used inside a converter + // // if the converter wraps the error then not clearing the context will cause this error: + // // "Current error context error is different to requested error." + // ClearErrorContext(); + // throw; + //} + return null; + } + } + + private JsonSerializerProxy GetInternalSerializer() + { + if (InternalSerializer == null) + { + InternalSerializer = new JsonSerializerProxy(this); + } + + return InternalSerializer; + } + + private JToken CreateJToken(JsonReader reader, JsonContract contract) + { + ValidationUtils.ArgumentNotNull(reader, nameof(reader)); + + if (contract != null) + { + if (contract.UnderlyingType == typeof(JRaw)) + { + return JRaw.Create(reader); + } + if (reader.TokenType == JsonToken.Null + && !(contract.UnderlyingType == typeof(JValue) || contract.UnderlyingType == typeof(JToken))) + { + return null; + } + } + + JToken token; + using (JTokenWriter writer = new JTokenWriter()) + { + writer.WriteToken(reader); + token = writer.Token; + } + + return token; + } + + private JToken CreateJObject(JsonReader reader) + { + ValidationUtils.ArgumentNotNull(reader, nameof(reader)); + + // this is needed because we've already read inside the object, looking for metadata properties + using (JTokenWriter writer = new JTokenWriter()) + { + writer.WriteStartObject(); + + do + { + if (reader.TokenType == JsonToken.PropertyName) + { + string propertyName = (string)reader.Value; + if (!reader.ReadAndMoveToContent()) + { + break; + } + + if (CheckPropertyName(reader, propertyName)) + { + continue; + } + + writer.WritePropertyName(propertyName); + writer.WriteToken(reader, true, true, false); + } + else if (reader.TokenType == JsonToken.Comment) + { + // eat + } + else + { + writer.WriteEndObject(); + return writer.Token; + } + } while (reader.Read()); + + throw JsonSerializationException.Create(reader, "Unexpected end when deserializing object."); + } + } + + private object CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, object existingValue) + { + if (contract != null && contract.ContractType == JsonContractType.Linq) + { + return CreateJToken(reader, contract); + } + + do + { + switch (reader.TokenType) + { + // populate a typed object or generic dictionary/array + // depending upon whether an objectType was supplied + case JsonToken.StartObject: + return CreateObject(reader, objectType, contract, member, containerContract, containerMember, existingValue); + case JsonToken.StartArray: + return CreateList(reader, objectType, contract, member, existingValue, null); + case JsonToken.Integer: + case JsonToken.Float: + case JsonToken.Boolean: + case JsonToken.Date: + case JsonToken.Bytes: + return EnsureType(reader, reader.Value, CultureInfo.InvariantCulture, contract, objectType); + case JsonToken.String: + string s = (string)reader.Value; + + // convert empty string to null automatically for nullable types + if (CoerceEmptyStringToNull(objectType, contract, s)) + { + return null; + } + + // string that needs to be returned as a byte array should be base 64 decoded + if (objectType == typeof(byte[])) + { + return Convert.FromBase64String(s); + } + + return EnsureType(reader, s, CultureInfo.InvariantCulture, contract, objectType); + case JsonToken.StartConstructor: + string constructorName = reader.Value.ToString(); + + return EnsureType(reader, constructorName, CultureInfo.InvariantCulture, contract, objectType); + case JsonToken.Null: + case JsonToken.Undefined: +#if !(DOTNET || PORTABLE40 || PORTABLE) + if (objectType == typeof(DBNull)) + { + return DBNull.Value; + } +#endif + + return EnsureType(reader, reader.Value, CultureInfo.InvariantCulture, contract, objectType); + case JsonToken.Raw: + return new JRaw((string)reader.Value); + case JsonToken.Comment: + // ignore + break; + default: + throw JsonSerializationException.Create(reader, "Unexpected token while deserializing object: " + reader.TokenType); + } + } while (reader.Read()); + + throw JsonSerializationException.Create(reader, "Unexpected end when deserializing object."); + } + + private static bool CoerceEmptyStringToNull(Type objectType, JsonContract contract, string s) + { + return string.IsNullOrEmpty(s) && objectType != null && objectType != typeof(string) && objectType != typeof(object) && contract != null && contract.IsNullable; + } + + internal string GetExpectedDescription(JsonContract contract) + { + switch (contract.ContractType) + { + case JsonContractType.Object: + case JsonContractType.Dictionary: +#if !(DOTNET || PORTABLE || PORTABLE40) + case JsonContractType.Serializable: +#endif +#if !(NET35 || NET20 || PORTABLE40) + case JsonContractType.Dynamic: +#endif + return @"JSON object (e.g. {""name"":""value""})"; + case JsonContractType.Array: + return @"JSON array (e.g. [1,2,3])"; + case JsonContractType.Primitive: + return @"JSON primitive value (e.g. string, number, boolean, null)"; + case JsonContractType.String: + return @"JSON string value"; + default: + throw new ArgumentOutOfRangeException(); + } + } + + private JsonConverter GetConverter(JsonContract contract, JsonConverter memberConverter, JsonContainerContract containerContract, JsonProperty containerProperty) + { + JsonConverter converter = null; + if (memberConverter != null) + { + // member attribute converter + converter = memberConverter; + } + else if (containerProperty != null && containerProperty.ItemConverter != null) + { + converter = containerProperty.ItemConverter; + } + else if (containerContract != null && containerContract.ItemConverter != null) + { + converter = containerContract.ItemConverter; + } + else if (contract != null) + { + JsonConverter matchingConverter; + if (contract.Converter != null) + { + // class attribute converter + converter = contract.Converter; + } + else if ((matchingConverter = Serializer.GetMatchingConverter(contract.UnderlyingType)) != null) + { + // passed in converters + converter = matchingConverter; + } + else if (contract.InternalConverter != null) + { + // internally specified converter + converter = contract.InternalConverter; + } + } + return converter; + } + + private object CreateObject(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, object existingValue) + { + string id; + Type resolvedObjectType = objectType; + + if (Serializer.MetadataPropertyHandling == MetadataPropertyHandling.Ignore) + { + // don't look for metadata properties + reader.ReadAndAssert(); + id = null; + } + else if (Serializer.MetadataPropertyHandling == MetadataPropertyHandling.ReadAhead) + { + JTokenReader tokenReader = reader as JTokenReader; + if (tokenReader == null) + { + JToken t = JToken.ReadFrom(reader); + tokenReader = (JTokenReader)t.CreateReader(); + tokenReader.Culture = reader.Culture; + tokenReader.DateFormatString = reader.DateFormatString; + tokenReader.DateParseHandling = reader.DateParseHandling; + tokenReader.DateTimeZoneHandling = reader.DateTimeZoneHandling; + tokenReader.FloatParseHandling = reader.FloatParseHandling; + tokenReader.SupportMultipleContent = reader.SupportMultipleContent; + + // start + tokenReader.ReadAndAssert(); + + reader = tokenReader; + } + + object newValue; + if (ReadMetadataPropertiesToken(tokenReader, ref resolvedObjectType, ref contract, member, containerContract, containerMember, existingValue, out newValue, out id)) + { + return newValue; + } + } + else + { + reader.ReadAndAssert(); + object newValue; + if (ReadMetadataProperties(reader, ref resolvedObjectType, ref contract, member, containerContract, containerMember, existingValue, out newValue, out id)) + { + return newValue; + } + } + + if (HasNoDefinedType(contract)) + { + return CreateJObject(reader); + } + + switch (contract.ContractType) + { + case JsonContractType.Object: + { + bool createdFromNonDefaultCreator = false; + JsonObjectContract objectContract = (JsonObjectContract)contract; + object targetObject; + // check that if type name handling is being used that the existing value is compatible with the specified type + if (existingValue != null && (resolvedObjectType == objectType || resolvedObjectType.IsAssignableFrom(existingValue.GetType()))) + { + targetObject = existingValue; + } + else + { + targetObject = CreateNewObject(reader, objectContract, member, containerMember, id, out createdFromNonDefaultCreator); + } + + // don't populate if read from non-default creator because the object has already been read + if (createdFromNonDefaultCreator) + { + return targetObject; + } + + return PopulateObject(targetObject, reader, objectContract, member, id); + } + case JsonContractType.Primitive: + { + JsonPrimitiveContract primitiveContract = (JsonPrimitiveContract)contract; + // if the content is inside $value then read past it + if (Serializer.MetadataPropertyHandling != MetadataPropertyHandling.Ignore + && reader.TokenType == JsonToken.PropertyName + && string.Equals(reader.Value.ToString(), JsonTypeReflector.ValuePropertyName, StringComparison.Ordinal)) + { + reader.ReadAndAssert(); + + // the token should not be an object because the $type value could have been included in the object + // without needing the $value property + if (reader.TokenType == JsonToken.StartObject) + { + throw JsonSerializationException.Create(reader, "Unexpected token when deserializing primitive value: " + reader.TokenType); + } + + object value = CreateValueInternal(reader, resolvedObjectType, primitiveContract, member, null, null, existingValue); + + reader.ReadAndAssert(); + return value; + } + break; + } + case JsonContractType.Dictionary: + { + JsonDictionaryContract dictionaryContract = (JsonDictionaryContract)contract; + object targetDictionary; + + if (existingValue == null) + { + bool createdFromNonDefaultCreator; + IDictionary dictionary = CreateNewDictionary(reader, dictionaryContract, out createdFromNonDefaultCreator); + + if (createdFromNonDefaultCreator) + { + if (id != null) + { + throw JsonSerializationException.Create(reader, "Cannot preserve reference to readonly dictionary, or dictionary created from a non-default constructor: {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)); + } + + if (contract.OnSerializingCallbacks.Count > 0) + { + throw JsonSerializationException.Create(reader, "Cannot call OnSerializing on readonly dictionary, or dictionary created from a non-default constructor: {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)); + } + + if (contract.OnErrorCallbacks.Count > 0) + { + throw JsonSerializationException.Create(reader, "Cannot call OnError on readonly list, or dictionary created from a non-default constructor: {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)); + } + + if (!dictionaryContract.HasParameterizedCreatorInternal) + { + throw JsonSerializationException.Create(reader, "Cannot deserialize readonly or fixed size dictionary: {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)); + } + } + + PopulateDictionary(dictionary, reader, dictionaryContract, member, id); + + if (createdFromNonDefaultCreator) + { + ObjectConstructor creator = dictionaryContract.OverrideCreator ?? dictionaryContract.ParameterizedCreator; + + return creator(dictionary); + } + else if (dictionary is IWrappedDictionary) + { + return ((IWrappedDictionary)dictionary).UnderlyingDictionary; + } + + targetDictionary = dictionary; + } + else + { + targetDictionary = PopulateDictionary(dictionaryContract.ShouldCreateWrapper ? dictionaryContract.CreateWrapper(existingValue) : (IDictionary)existingValue, reader, dictionaryContract, member, id); + } + + return targetDictionary; + } +#if !(NET35 || NET20 || PORTABLE40) + case JsonContractType.Dynamic: + JsonDynamicContract dynamicContract = (JsonDynamicContract)contract; + return CreateDynamic(reader, dynamicContract, member, id); +#endif +#if !(DOTNET || PORTABLE40 || PORTABLE) + case JsonContractType.Serializable: + JsonISerializableContract serializableContract = (JsonISerializableContract)contract; + return CreateISerializable(reader, serializableContract, member, id); +#endif + } + + string message = @"Cannot deserialize the current JSON object (e.g. {{""name"":""value""}}) into type '{0}' because the type requires a {1} to deserialize correctly." + Environment.NewLine + + @"To fix this error either change the JSON to a {1} or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object." + Environment.NewLine; + message = message.FormatWith(CultureInfo.InvariantCulture, resolvedObjectType, GetExpectedDescription(contract)); + + throw JsonSerializationException.Create(reader, message); + } + + private bool ReadMetadataPropertiesToken(JTokenReader reader, ref Type objectType, ref JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, object existingValue, out object newValue, out string id) + { + id = null; + newValue = null; + + if (reader.TokenType == JsonToken.StartObject) + { + JObject current = (JObject)reader.CurrentToken; + + JToken refToken = current[JsonTypeReflector.RefPropertyName]; + if (refToken != null) + { + if (refToken.Type != JTokenType.String && refToken.Type != JTokenType.Null) + { + throw JsonSerializationException.Create(refToken, refToken.Path, "JSON reference {0} property must have a string or null value.".FormatWith(CultureInfo.InvariantCulture, JsonTypeReflector.RefPropertyName), null); + } + + JToken property = refToken.Parent; + JToken additionalContent = null; + if (property.Next != null) + { + additionalContent = property.Next; + } + else if (property.Previous != null) + { + additionalContent = property.Previous; + } + + string reference = (string)refToken; + + if (reference != null) + { + if (additionalContent != null) + { + throw JsonSerializationException.Create(additionalContent, additionalContent.Path, "Additional content found in JSON reference object. A JSON reference object should only have a {0} property.".FormatWith(CultureInfo.InvariantCulture, JsonTypeReflector.RefPropertyName), null); + } + + newValue = Serializer.GetReferenceResolver().ResolveReference(this, reference); + + if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info) + { + TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(reader as IJsonLineInfo, reader.Path, "Resolved object reference '{0}' to {1}.".FormatWith(CultureInfo.InvariantCulture, reference, newValue.GetType())), null); + } + + reader.Skip(); + return true; + } + } + JToken typeToken = current[JsonTypeReflector.TypePropertyName]; + if (typeToken != null) + { + string qualifiedTypeName = (string)typeToken; + JsonReader typeTokenReader = typeToken.CreateReader(); + typeTokenReader.ReadAndAssert(); + ResolveTypeName(typeTokenReader, ref objectType, ref contract, member, containerContract, containerMember, qualifiedTypeName); + + JToken valueToken = current[JsonTypeReflector.ValuePropertyName]; + if (valueToken != null) + { + while (true) + { + reader.ReadAndAssert(); + if (reader.TokenType == JsonToken.PropertyName) + { + if ((string)reader.Value == JsonTypeReflector.ValuePropertyName) + { + return false; + } + } + + reader.ReadAndAssert(); + reader.Skip(); + } + } + } + JToken idToken = current[JsonTypeReflector.IdPropertyName]; + if (idToken != null) + { + id = (string)idToken; + } + JToken valuesToken = current[JsonTypeReflector.ArrayValuesPropertyName]; + if (valuesToken != null) + { + JsonReader listReader = valuesToken.CreateReader(); + listReader.ReadAndAssert(); + newValue = CreateList(listReader, objectType, contract, member, existingValue, id); + + reader.Skip(); + return true; + } + } + + reader.ReadAndAssert(); + return false; + } + + private bool ReadMetadataProperties(JsonReader reader, ref Type objectType, ref JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, object existingValue, out object newValue, out string id) + { + id = null; + newValue = null; + + if (reader.TokenType == JsonToken.PropertyName) + { + string propertyName = reader.Value.ToString(); + + if (propertyName.Length > 0 && propertyName[0] == '$') + { + // read metadata properties + // $type, $id, $ref, etc + bool metadataProperty; + + do + { + propertyName = reader.Value.ToString(); + + if (string.Equals(propertyName, JsonTypeReflector.RefPropertyName, StringComparison.Ordinal)) + { + reader.ReadAndAssert(); + if (reader.TokenType != JsonToken.String && reader.TokenType != JsonToken.Null) + { + throw JsonSerializationException.Create(reader, "JSON reference {0} property must have a string or null value.".FormatWith(CultureInfo.InvariantCulture, JsonTypeReflector.RefPropertyName)); + } + + string reference = (reader.Value != null) ? reader.Value.ToString() : null; + + reader.ReadAndAssert(); + + if (reference != null) + { + if (reader.TokenType == JsonToken.PropertyName) + { + throw JsonSerializationException.Create(reader, "Additional content found in JSON reference object. A JSON reference object should only have a {0} property.".FormatWith(CultureInfo.InvariantCulture, JsonTypeReflector.RefPropertyName)); + } + + newValue = Serializer.GetReferenceResolver().ResolveReference(this, reference); + + if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info) + { + TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(reader as IJsonLineInfo, reader.Path, "Resolved object reference '{0}' to {1}.".FormatWith(CultureInfo.InvariantCulture, reference, newValue.GetType())), null); + } + + return true; + } + else + { + metadataProperty = true; + } + } + else if (string.Equals(propertyName, JsonTypeReflector.TypePropertyName, StringComparison.Ordinal)) + { + reader.ReadAndAssert(); + string qualifiedTypeName = reader.Value.ToString(); + + ResolveTypeName(reader, ref objectType, ref contract, member, containerContract, containerMember, qualifiedTypeName); + + reader.ReadAndAssert(); + + metadataProperty = true; + } + else if (string.Equals(propertyName, JsonTypeReflector.IdPropertyName, StringComparison.Ordinal)) + { + reader.ReadAndAssert(); + + id = (reader.Value != null) ? reader.Value.ToString() : null; + + reader.ReadAndAssert(); + metadataProperty = true; + } + else if (string.Equals(propertyName, JsonTypeReflector.ArrayValuesPropertyName, StringComparison.Ordinal)) + { + reader.ReadAndAssert(); + object list = CreateList(reader, objectType, contract, member, existingValue, id); + reader.ReadAndAssert(); + newValue = list; + return true; + } + else + { + metadataProperty = false; + } + } while (metadataProperty && reader.TokenType == JsonToken.PropertyName); + } + } + return false; + } + + private void ResolveTypeName(JsonReader reader, ref Type objectType, ref JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, string qualifiedTypeName) + { + TypeNameHandling resolvedTypeNameHandling = + ((member != null) ? member.TypeNameHandling : null) + ?? ((containerContract != null) ? containerContract.ItemTypeNameHandling : null) + ?? ((containerMember != null) ? containerMember.ItemTypeNameHandling : null) + ?? Serializer._typeNameHandling; + + if (resolvedTypeNameHandling != TypeNameHandling.None) + { + string typeName; + string assemblyName; + ReflectionUtils.SplitFullyQualifiedTypeName(qualifiedTypeName, out typeName, out assemblyName); + + Type specifiedType; + try + { + specifiedType = Serializer._binder.BindToType(assemblyName, typeName); + } + catch (Exception ex) + { + throw JsonSerializationException.Create(reader, "Error resolving type specified in JSON '{0}'.".FormatWith(CultureInfo.InvariantCulture, qualifiedTypeName), ex); + } + + if (specifiedType == null) + { + throw JsonSerializationException.Create(reader, "Type specified in JSON '{0}' was not resolved.".FormatWith(CultureInfo.InvariantCulture, qualifiedTypeName)); + } + + if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) + { + TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(reader as IJsonLineInfo, reader.Path, "Resolved type '{0}' to {1}.".FormatWith(CultureInfo.InvariantCulture, qualifiedTypeName, specifiedType)), null); + } + + if (objectType != null +#if !(NET35 || NET20 || PORTABLE40) + && objectType != typeof(IDynamicMetaObjectProvider) +#endif + && !objectType.IsAssignableFrom(specifiedType)) + { + throw JsonSerializationException.Create(reader, "Type specified in JSON '{0}' is not compatible with '{1}'.".FormatWith(CultureInfo.InvariantCulture, specifiedType.AssemblyQualifiedName, objectType.AssemblyQualifiedName)); + } + + objectType = specifiedType; + contract = GetContractSafe(specifiedType); + } + } + + private JsonArrayContract EnsureArrayContract(JsonReader reader, Type objectType, JsonContract contract) + { + if (contract == null) + { + throw JsonSerializationException.Create(reader, "Could not resolve type '{0}' to a JsonContract.".FormatWith(CultureInfo.InvariantCulture, objectType)); + } + + JsonArrayContract arrayContract = contract as JsonArrayContract; + if (arrayContract == null) + { + string message = @"Cannot deserialize the current JSON array (e.g. [1,2,3]) into type '{0}' because the type requires a {1} to deserialize correctly." + Environment.NewLine + + @"To fix this error either change the JSON to a {1} or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array." + Environment.NewLine; + message = message.FormatWith(CultureInfo.InvariantCulture, objectType, GetExpectedDescription(contract)); + + throw JsonSerializationException.Create(reader, message); + } + + return arrayContract; + } + + private object CreateList(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, object existingValue, string id) + { + object value; + + if (HasNoDefinedType(contract)) + { + return CreateJToken(reader, contract); + } + + JsonArrayContract arrayContract = EnsureArrayContract(reader, objectType, contract); + + if (existingValue == null) + { + bool createdFromNonDefaultCreator; + IList list = CreateNewList(reader, arrayContract, out createdFromNonDefaultCreator); + + if (createdFromNonDefaultCreator) + { + if (id != null) + { + throw JsonSerializationException.Create(reader, "Cannot preserve reference to array or readonly list, or list created from a non-default constructor: {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)); + } + + if (contract.OnSerializingCallbacks.Count > 0) + { + throw JsonSerializationException.Create(reader, "Cannot call OnSerializing on an array or readonly list, or list created from a non-default constructor: {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)); + } + + if (contract.OnErrorCallbacks.Count > 0) + { + throw JsonSerializationException.Create(reader, "Cannot call OnError on an array or readonly list, or list created from a non-default constructor: {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)); + } + + if (!arrayContract.HasParameterizedCreatorInternal && !arrayContract.IsArray) + { + throw JsonSerializationException.Create(reader, "Cannot deserialize readonly or fixed size list: {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)); + } + } + + if (!arrayContract.IsMultidimensionalArray) + { + PopulateList(list, reader, arrayContract, member, id); + } + else + { + PopulateMultidimensionalArray(list, reader, arrayContract, member, id); + } + + if (createdFromNonDefaultCreator) + { + if (arrayContract.IsMultidimensionalArray) + { + list = CollectionUtils.ToMultidimensionalArray(list, arrayContract.CollectionItemType, contract.CreatedType.GetArrayRank()); + } + else if (arrayContract.IsArray) + { + Array a = Array.CreateInstance(arrayContract.CollectionItemType, list.Count); + list.CopyTo(a, 0); + list = a; + } + else + { + ObjectConstructor creator = arrayContract.OverrideCreator ?? arrayContract.ParameterizedCreator; + + return creator(list); + } + } + else if (list is IWrappedCollection) + { + return ((IWrappedCollection)list).UnderlyingCollection; + } + + value = list; + } + else + { + if (!arrayContract.CanDeserialize) + { + throw JsonSerializationException.Create(reader, "Cannot populate list type {0}.".FormatWith(CultureInfo.InvariantCulture, contract.CreatedType)); + } + + value = PopulateList((arrayContract.ShouldCreateWrapper) ? arrayContract.CreateWrapper(existingValue) : (IList)existingValue, reader, arrayContract, member, id); + } + + return value; + } + + private bool HasNoDefinedType(JsonContract contract) + { + return (contract == null || contract.UnderlyingType == typeof(object) || contract.ContractType == JsonContractType.Linq +#if !(NET35 || NET20 || PORTABLE40) + || contract.UnderlyingType == typeof(IDynamicMetaObjectProvider) +#endif + ); + } + + private object EnsureType(JsonReader reader, object value, CultureInfo culture, JsonContract contract, Type targetType) + { + if (targetType == null) + { + return value; + } + + Type valueType = ReflectionUtils.GetObjectType(value); + + // type of value and type of target don't match + // attempt to convert value's type to target's type + if (valueType != targetType) + { + if (value == null && contract.IsNullable) + { + return null; + } + + try + { + if (contract.IsConvertable) + { + JsonPrimitiveContract primitiveContract = (JsonPrimitiveContract)contract; + + if (contract.IsEnum) + { + if (value is string) + { + return Enum.Parse(contract.NonNullableUnderlyingType, value.ToString(), true); + } + if (ConvertUtils.IsInteger(primitiveContract.TypeCode)) + { + return Enum.ToObject(contract.NonNullableUnderlyingType, value); + } + } + +#if !(PORTABLE || PORTABLE40 || NET35 || NET20) + if (value is BigInteger) + { + return ConvertUtils.FromBigInteger((BigInteger)value, contract.NonNullableUnderlyingType); + } +#endif + + // this won't work when converting to a custom IConvertible + return Convert.ChangeType(value, contract.NonNullableUnderlyingType, culture); + } + + return ConvertUtils.ConvertOrCast(value, culture, contract.NonNullableUnderlyingType); + } + catch (Exception ex) + { + throw JsonSerializationException.Create(reader, "Error converting value {0} to type '{1}'.".FormatWith(CultureInfo.InvariantCulture, MiscellaneousUtils.FormatValueForPrint(value), targetType), ex); + } + } + + return value; + } + + private bool SetPropertyValue(JsonProperty property, JsonConverter propertyConverter, JsonContainerContract containerContract, JsonProperty containerProperty, JsonReader reader, object target) + { + object currentValue; + bool useExistingValue; + JsonContract propertyContract; + bool gottenCurrentValue; + + if (CalculatePropertyDetails(property, ref propertyConverter, containerContract, containerProperty, reader, target, out useExistingValue, out currentValue, out propertyContract, out gottenCurrentValue)) + { + return false; + } + + object value; + + if (propertyConverter != null && propertyConverter.CanRead) + { + if (!gottenCurrentValue && target != null && property.Readable) + { + currentValue = property.ValueProvider.GetValue(target); + } + + value = DeserializeConvertable(propertyConverter, reader, property.PropertyType, currentValue); + } + else + { + value = CreateValueInternal(reader, property.PropertyType, propertyContract, property, containerContract, containerProperty, (useExistingValue) ? currentValue : null); + } + + // always set the value if useExistingValue is false, + // otherwise also set it if CreateValue returns a new value compared to the currentValue + // this could happen because of a JsonConverter against the type + if ((!useExistingValue || value != currentValue) + && ShouldSetPropertyValue(property, value)) + { + property.ValueProvider.SetValue(target, value); + + if (property.SetIsSpecified != null) + { + if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) + { + TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(reader as IJsonLineInfo, reader.Path, "IsSpecified for property '{0}' on {1} set to true.".FormatWith(CultureInfo.InvariantCulture, property.PropertyName, property.DeclaringType)), null); + } + + property.SetIsSpecified(target, true); + } + + return true; + } + + // the value wasn't set be JSON was populated onto the existing value + return useExistingValue; + } + + private bool CalculatePropertyDetails(JsonProperty property, ref JsonConverter propertyConverter, JsonContainerContract containerContract, JsonProperty containerProperty, JsonReader reader, object target, out bool useExistingValue, out object currentValue, out JsonContract propertyContract, out bool gottenCurrentValue) + { + currentValue = null; + useExistingValue = false; + propertyContract = null; + gottenCurrentValue = false; + + if (property.Ignored) + { + return true; + } + + JsonToken tokenType = reader.TokenType; + + if (property.PropertyContract == null) + { + property.PropertyContract = GetContractSafe(property.PropertyType); + } + + ObjectCreationHandling objectCreationHandling = + property.ObjectCreationHandling.GetValueOrDefault(Serializer._objectCreationHandling); + + if ((objectCreationHandling != ObjectCreationHandling.Replace) + && (tokenType == JsonToken.StartArray || tokenType == JsonToken.StartObject) + && property.Readable) + { + currentValue = property.ValueProvider.GetValue(target); + gottenCurrentValue = true; + + if (currentValue != null) + { + propertyContract = GetContractSafe(currentValue.GetType()); + + useExistingValue = (!propertyContract.IsReadOnlyOrFixedSize && !propertyContract.UnderlyingType.IsValueType()); + } + } + + if (!property.Writable && !useExistingValue) + { + return true; + } + + // test tokentype here because null might not be convertable to some types, e.g. ignoring null when applied to DateTime + if (property.NullValueHandling.GetValueOrDefault(Serializer._nullValueHandling) == NullValueHandling.Ignore && tokenType == JsonToken.Null) + { + return true; + } + + // test tokentype here because default value might not be convertable to actual type, e.g. default of "" for DateTime + if (HasFlag(property.DefaultValueHandling.GetValueOrDefault(Serializer._defaultValueHandling), DefaultValueHandling.Ignore) + && !HasFlag(property.DefaultValueHandling.GetValueOrDefault(Serializer._defaultValueHandling), DefaultValueHandling.Populate) + && JsonTokenUtils.IsPrimitiveToken(tokenType) + && MiscellaneousUtils.ValueEquals(reader.Value, property.GetResolvedDefaultValue())) + { + return true; + } + + if (currentValue == null) + { + propertyContract = property.PropertyContract; + } + else + { + propertyContract = GetContractSafe(currentValue.GetType()); + + if (propertyContract != property.PropertyContract) + { + propertyConverter = GetConverter(propertyContract, property.MemberConverter, containerContract, containerProperty); + } + } + + return false; + } + + private void AddReference(JsonReader reader, string id, object value) + { + try + { + if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) + { + TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(reader as IJsonLineInfo, reader.Path, "Read object reference Id '{0}' for {1}.".FormatWith(CultureInfo.InvariantCulture, id, value.GetType())), null); + } + + Serializer.GetReferenceResolver().AddReference(this, id, value); + } + catch (Exception ex) + { + throw JsonSerializationException.Create(reader, "Error reading object reference '{0}'.".FormatWith(CultureInfo.InvariantCulture, id), ex); + } + } + + private bool HasFlag(DefaultValueHandling value, DefaultValueHandling flag) + { + return ((value & flag) == flag); + } + + private bool ShouldSetPropertyValue(JsonProperty property, object value) + { + if (property.NullValueHandling.GetValueOrDefault(Serializer._nullValueHandling) == NullValueHandling.Ignore && value == null) + { + return false; + } + + if (HasFlag(property.DefaultValueHandling.GetValueOrDefault(Serializer._defaultValueHandling), DefaultValueHandling.Ignore) + && !HasFlag(property.DefaultValueHandling.GetValueOrDefault(Serializer._defaultValueHandling), DefaultValueHandling.Populate) + && MiscellaneousUtils.ValueEquals(value, property.GetResolvedDefaultValue())) + { + return false; + } + + if (!property.Writable) + { + return false; + } + + return true; + } + + private IList CreateNewList(JsonReader reader, JsonArrayContract contract, out bool createdFromNonDefaultCreator) + { + // some types like non-generic IEnumerable can be serialized but not deserialized + if (!contract.CanDeserialize) + { + throw JsonSerializationException.Create(reader, "Cannot create and populate list type {0}.".FormatWith(CultureInfo.InvariantCulture, contract.CreatedType)); + } + + if (contract.OverrideCreator != null) + { + if (contract.HasParameterizedCreator) + { + createdFromNonDefaultCreator = true; + return contract.CreateTemporaryCollection(); + } + else + { + createdFromNonDefaultCreator = false; + return (IList)contract.OverrideCreator(); + } + } + else if (contract.IsReadOnlyOrFixedSize) + { + createdFromNonDefaultCreator = true; + IList list = contract.CreateTemporaryCollection(); + + if (contract.ShouldCreateWrapper) + { + list = contract.CreateWrapper(list); + } + + return list; + } + else if (contract.DefaultCreator != null && (!contract.DefaultCreatorNonPublic || Serializer._constructorHandling == ConstructorHandling.AllowNonPublicDefaultConstructor)) + { + object list = contract.DefaultCreator(); + + if (contract.ShouldCreateWrapper) + { + list = contract.CreateWrapper(list); + } + + createdFromNonDefaultCreator = false; + return (IList)list; + } + else if (contract.HasParameterizedCreatorInternal) + { + createdFromNonDefaultCreator = true; + return contract.CreateTemporaryCollection(); + } + else + { + if (!contract.IsInstantiable) + { + throw JsonSerializationException.Create(reader, "Could not create an instance of type {0}. Type is an interface or abstract class and cannot be instantiated.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)); + } + + throw JsonSerializationException.Create(reader, "Unable to find a constructor to use for type {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)); + } + } + + private IDictionary CreateNewDictionary(JsonReader reader, JsonDictionaryContract contract, out bool createdFromNonDefaultCreator) + { + if (contract.OverrideCreator != null) + { + if (contract.HasParameterizedCreator) + { + createdFromNonDefaultCreator = true; + return contract.CreateTemporaryDictionary(); + } + else + { + createdFromNonDefaultCreator = false; + return (IDictionary)contract.OverrideCreator(); + } + } + else if (contract.IsReadOnlyOrFixedSize) + { + createdFromNonDefaultCreator = true; + return contract.CreateTemporaryDictionary(); + } + else if (contract.DefaultCreator != null && (!contract.DefaultCreatorNonPublic || Serializer._constructorHandling == ConstructorHandling.AllowNonPublicDefaultConstructor)) + { + object dictionary = contract.DefaultCreator(); + + if (contract.ShouldCreateWrapper) + { + dictionary = contract.CreateWrapper(dictionary); + } + + createdFromNonDefaultCreator = false; + return (IDictionary)dictionary; + } + else if (contract.HasParameterizedCreatorInternal) + { + createdFromNonDefaultCreator = true; + return contract.CreateTemporaryDictionary(); + } + else + { + if (!contract.IsInstantiable) + { + throw JsonSerializationException.Create(reader, "Could not create an instance of type {0}. Type is an interface or abstract class and cannot be instantiated.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)); + } + + throw JsonSerializationException.Create(reader, "Unable to find a default constructor to use for type {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)); + } + } + + private void OnDeserializing(JsonReader reader, JsonContract contract, object value) + { + if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info) + { + TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(reader as IJsonLineInfo, reader.Path, "Started deserializing {0}".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)), null); + } + + contract.InvokeOnDeserializing(value, Serializer._context); + } + + private void OnDeserialized(JsonReader reader, JsonContract contract, object value) + { + if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info) + { + TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(reader as IJsonLineInfo, reader.Path, "Finished deserializing {0}".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)), null); + } + + contract.InvokeOnDeserialized(value, Serializer._context); + } + + private object PopulateDictionary(IDictionary dictionary, JsonReader reader, JsonDictionaryContract contract, JsonProperty containerProperty, string id) + { + IWrappedDictionary wrappedDictionary = dictionary as IWrappedDictionary; + object underlyingDictionary = wrappedDictionary != null ? wrappedDictionary.UnderlyingDictionary : dictionary; + + if (id != null) + { + AddReference(reader, id, underlyingDictionary); + } + + OnDeserializing(reader, contract, underlyingDictionary); + + int initialDepth = reader.Depth; + + if (contract.KeyContract == null) + { + contract.KeyContract = GetContractSafe(contract.DictionaryKeyType); + } + + if (contract.ItemContract == null) + { + contract.ItemContract = GetContractSafe(contract.DictionaryValueType); + } + + JsonConverter dictionaryValueConverter = contract.ItemConverter ?? GetConverter(contract.ItemContract, null, contract, containerProperty); + PrimitiveTypeCode keyTypeCode = (contract.KeyContract is JsonPrimitiveContract) ? ((JsonPrimitiveContract)contract.KeyContract).TypeCode : PrimitiveTypeCode.Empty; + + bool finished = false; + do + { + switch (reader.TokenType) + { + case JsonToken.PropertyName: + object keyValue = reader.Value; + if (CheckPropertyName(reader, keyValue.ToString())) + { + continue; + } + + try + { + try + { + // this is for correctly reading ISO and MS formatted dictionary keys + switch (keyTypeCode) + { + case PrimitiveTypeCode.DateTime: + case PrimitiveTypeCode.DateTimeNullable: + { + DateTime dt; + if (DateTimeUtils.TryParseDateTime(keyValue.ToString(), reader.DateTimeZoneHandling, reader.DateFormatString, reader.Culture, out dt)) + { + keyValue = dt; + } + else + { + keyValue = EnsureType(reader, keyValue, CultureInfo.InvariantCulture, contract.KeyContract, contract.DictionaryKeyType); + } + break; + } +#if !NET20 + case PrimitiveTypeCode.DateTimeOffset: + case PrimitiveTypeCode.DateTimeOffsetNullable: + { + DateTimeOffset dt; + if (DateTimeUtils.TryParseDateTimeOffset(keyValue.ToString(), reader.DateFormatString, reader.Culture, out dt)) + { + keyValue = dt; + } + else + { + keyValue = EnsureType(reader, keyValue, CultureInfo.InvariantCulture, contract.KeyContract, contract.DictionaryKeyType); + } + break; + } +#endif + default: + keyValue = EnsureType(reader, keyValue, CultureInfo.InvariantCulture, contract.KeyContract, contract.DictionaryKeyType); + break; + } + } + catch (Exception ex) + { + throw JsonSerializationException.Create(reader, "Could not convert string '{0}' to dictionary key type '{1}'. Create a TypeConverter to convert from the string to the key type object.".FormatWith(CultureInfo.InvariantCulture, reader.Value, contract.DictionaryKeyType), ex); + } + + if (!ReadForType(reader, contract.ItemContract, dictionaryValueConverter != null)) + { + throw JsonSerializationException.Create(reader, "Unexpected end when deserializing object."); + } + + object itemValue; + if (dictionaryValueConverter != null && dictionaryValueConverter.CanRead) + { + itemValue = DeserializeConvertable(dictionaryValueConverter, reader, contract.DictionaryValueType, null); + } + else + { + itemValue = CreateValueInternal(reader, contract.DictionaryValueType, contract.ItemContract, null, contract, containerProperty, null); + } + + dictionary[keyValue] = itemValue; + } + catch (Exception ex) + { + if (IsErrorHandled(underlyingDictionary, contract, keyValue, reader as IJsonLineInfo, reader.Path, ex)) + { + HandleError(reader, true, initialDepth); + } + else + { + throw; + } + } + break; + case JsonToken.Comment: + break; + case JsonToken.EndObject: + finished = true; + break; + default: + throw JsonSerializationException.Create(reader, "Unexpected token when deserializing object: " + reader.TokenType); + } + } while (!finished && reader.Read()); + + if (!finished) + { + ThrowUnexpectedEndException(reader, contract, underlyingDictionary, "Unexpected end when deserializing object."); + } + + OnDeserialized(reader, contract, underlyingDictionary); + return underlyingDictionary; + } + + private object PopulateMultidimensionalArray(IList list, JsonReader reader, JsonArrayContract contract, JsonProperty containerProperty, string id) + { + int rank = contract.UnderlyingType.GetArrayRank(); + + if (id != null) + { + AddReference(reader, id, list); + } + + OnDeserializing(reader, contract, list); + + JsonContract collectionItemContract = GetContractSafe(contract.CollectionItemType); + JsonConverter collectionItemConverter = GetConverter(collectionItemContract, null, contract, containerProperty); + + int? previousErrorIndex = null; + Stack listStack = new Stack(); + listStack.Push(list); + IList currentList = list; + + bool finished = false; + do + { + int initialDepth = reader.Depth; + + if (listStack.Count == rank) + { + try + { + if (ReadForType(reader, collectionItemContract, collectionItemConverter != null)) + { + switch (reader.TokenType) + { + case JsonToken.EndArray: + listStack.Pop(); + currentList = listStack.Peek(); + previousErrorIndex = null; + break; + default: + object value; + + if (collectionItemConverter != null && collectionItemConverter.CanRead) + { + value = DeserializeConvertable(collectionItemConverter, reader, contract.CollectionItemType, null); + } + else + { + value = CreateValueInternal(reader, contract.CollectionItemType, collectionItemContract, null, contract, containerProperty, null); + } + + currentList.Add(value); + break; + } + } + else + { + break; + } + } + catch (Exception ex) + { + JsonPosition errorPosition = reader.GetPosition(initialDepth); + + if (IsErrorHandled(list, contract, errorPosition.Position, reader as IJsonLineInfo, reader.Path, ex)) + { + HandleError(reader, true, initialDepth); + + if (previousErrorIndex != null && previousErrorIndex == errorPosition.Position) + { + // reader index has not moved since previous error handling + // break out of reading array to prevent infinite loop + throw JsonSerializationException.Create(reader, "Infinite loop detected from error handling.", ex); + } + else + { + previousErrorIndex = errorPosition.Position; + } + } + else + { + throw; + } + } + } + else + { + if (reader.Read()) + { + switch (reader.TokenType) + { + case JsonToken.StartArray: + IList newList = new List(); + currentList.Add(newList); + listStack.Push(newList); + currentList = newList; + break; + case JsonToken.EndArray: + listStack.Pop(); + + if (listStack.Count > 0) + { + currentList = listStack.Peek(); + } + else + { + finished = true; + } + break; + case JsonToken.Comment: + break; + default: + throw JsonSerializationException.Create(reader, "Unexpected token when deserializing multidimensional array: " + reader.TokenType); + } + } + else + { + break; + } + } + } while (!finished); + + if (!finished) + { + ThrowUnexpectedEndException(reader, contract, list, "Unexpected end when deserializing array."); + } + + OnDeserialized(reader, contract, list); + return list; + } + + private void ThrowUnexpectedEndException(JsonReader reader, JsonContract contract, object currentObject, string message) + { + try + { + throw JsonSerializationException.Create(reader, message); + } + catch (Exception ex) + { + if (IsErrorHandled(currentObject, contract, null, reader as IJsonLineInfo, reader.Path, ex)) + { + HandleError(reader, false, 0); + } + else + { + throw; + } + } + } + + private object PopulateList(IList list, JsonReader reader, JsonArrayContract contract, JsonProperty containerProperty, string id) + { + IWrappedCollection wrappedCollection = list as IWrappedCollection; + object underlyingList = wrappedCollection != null ? wrappedCollection.UnderlyingCollection : list; + + if (id != null) + { + AddReference(reader, id, underlyingList); + } + + // can't populate an existing array + if (list.IsFixedSize) + { + reader.Skip(); + return underlyingList; + } + + OnDeserializing(reader, contract, underlyingList); + + int initialDepth = reader.Depth; + + if (contract.ItemContract == null) + { + contract.ItemContract = GetContractSafe(contract.CollectionItemType); + } + + JsonConverter collectionItemConverter = GetConverter(contract.ItemContract, null, contract, containerProperty); + + int? previousErrorIndex = null; + + bool finished = false; + do + { + try + { + if (ReadForType(reader, contract.ItemContract, collectionItemConverter != null)) + { + switch (reader.TokenType) + { + case JsonToken.EndArray: + finished = true; + break; + default: + object value; + + if (collectionItemConverter != null && collectionItemConverter.CanRead) + { + value = DeserializeConvertable(collectionItemConverter, reader, contract.CollectionItemType, null); + } + else + { + value = CreateValueInternal(reader, contract.CollectionItemType, contract.ItemContract, null, contract, containerProperty, null); + } + + list.Add(value); + break; + } + } + else + { + break; + } + } + catch (Exception ex) + { + JsonPosition errorPosition = reader.GetPosition(initialDepth); + + if (IsErrorHandled(underlyingList, contract, errorPosition.Position, reader as IJsonLineInfo, reader.Path, ex)) + { + HandleError(reader, true, initialDepth); + + if (previousErrorIndex != null && previousErrorIndex == errorPosition.Position) + { + // reader index has not moved since previous error handling + // break out of reading array to prevent infinite loop + throw JsonSerializationException.Create(reader, "Infinite loop detected from error handling.", ex); + } + else + { + previousErrorIndex = errorPosition.Position; + } + } + else + { + throw; + } + } + } while (!finished); + + if (!finished) + { + ThrowUnexpectedEndException(reader, contract, underlyingList, "Unexpected end when deserializing array."); + } + + OnDeserialized(reader, contract, underlyingList); + return underlyingList; + } + +#if !(DOTNET || PORTABLE40 || PORTABLE) + private object CreateISerializable(JsonReader reader, JsonISerializableContract contract, JsonProperty member, string id) + { + Type objectType = contract.UnderlyingType; + + if (!JsonTypeReflector.FullyTrusted) + { + string message = @"Type '{0}' implements ISerializable but cannot be deserialized using the ISerializable interface because the current application is not fully trusted and ISerializable can expose secure data." + Environment.NewLine + + @"To fix this error either change the environment to be fully trusted, change the application to not deserialize the type, add JsonObjectAttribute to the type or change the JsonSerializer setting ContractResolver to use a new DefaultContractResolver with IgnoreSerializableInterface set to true." + Environment.NewLine; + message = message.FormatWith(CultureInfo.InvariantCulture, objectType); + + throw JsonSerializationException.Create(reader, message); + } + + if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info) + { + TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(reader as IJsonLineInfo, reader.Path, "Deserializing {0} using ISerializable constructor.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)), null); + } + + SerializationInfo serializationInfo = new SerializationInfo(contract.UnderlyingType, new JsonFormatterConverter(this, contract, member)); + + bool finished = false; + do + { + switch (reader.TokenType) + { + case JsonToken.PropertyName: + string memberName = reader.Value.ToString(); + if (!reader.Read()) + { + throw JsonSerializationException.Create(reader, "Unexpected end when setting {0}'s value.".FormatWith(CultureInfo.InvariantCulture, memberName)); + } + serializationInfo.AddValue(memberName, JToken.ReadFrom(reader)); + break; + case JsonToken.Comment: + break; + case JsonToken.EndObject: + finished = true; + break; + default: + throw JsonSerializationException.Create(reader, "Unexpected token when deserializing object: " + reader.TokenType); + } + } while (!finished && reader.Read()); + + if (!finished) + { + ThrowUnexpectedEndException(reader, contract, serializationInfo, "Unexpected end when deserializing object."); + } + + if (contract.ISerializableCreator == null) + { + throw JsonSerializationException.Create(reader, "ISerializable type '{0}' does not have a valid constructor. To correctly implement ISerializable a constructor that takes SerializationInfo and StreamingContext parameters should be present.".FormatWith(CultureInfo.InvariantCulture, objectType)); + } + + object createdObject = contract.ISerializableCreator(serializationInfo, Serializer._context); + + if (id != null) + { + AddReference(reader, id, createdObject); + } + + // these are together because OnDeserializing takes an object but for an ISerializable the object is fully created in the constructor + OnDeserializing(reader, contract, createdObject); + OnDeserialized(reader, contract, createdObject); + + return createdObject; + } + + internal object CreateISerializableItem(JToken token, Type type, JsonISerializableContract contract, JsonProperty member) + { + JsonContract itemContract = GetContractSafe(type); + JsonConverter itemConverter = GetConverter(itemContract, null, contract, member); + + JsonReader tokenReader = token.CreateReader(); + tokenReader.ReadAndAssert(); // Move to first token + + object result; + if (itemConverter != null && itemConverter.CanRead) + { + result = DeserializeConvertable(itemConverter, tokenReader, type, null); + } + else + { + result = CreateValueInternal(tokenReader, type, itemContract, null, contract, member, null); + } + + return result; + } +#endif + +#if !(NET35 || NET20 || PORTABLE40) + private object CreateDynamic(JsonReader reader, JsonDynamicContract contract, JsonProperty member, string id) + { + IDynamicMetaObjectProvider newObject; + + if (!contract.IsInstantiable) + { + throw JsonSerializationException.Create(reader, "Could not create an instance of type {0}. Type is an interface or abstract class and cannot be instantiated.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)); + } + + if (contract.DefaultCreator != null && + (!contract.DefaultCreatorNonPublic || Serializer._constructorHandling == ConstructorHandling.AllowNonPublicDefaultConstructor)) + { + newObject = (IDynamicMetaObjectProvider)contract.DefaultCreator(); + } + else + { + throw JsonSerializationException.Create(reader, "Unable to find a default constructor to use for type {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)); + } + + if (id != null) + { + AddReference(reader, id, newObject); + } + + OnDeserializing(reader, contract, newObject); + + int initialDepth = reader.Depth; + + bool finished = false; + do + { + switch (reader.TokenType) + { + case JsonToken.PropertyName: + string memberName = reader.Value.ToString(); + + try + { + if (!reader.Read()) + { + throw JsonSerializationException.Create(reader, "Unexpected end when setting {0}'s value.".FormatWith(CultureInfo.InvariantCulture, memberName)); + } + + // first attempt to find a settable property, otherwise fall back to a dynamic set without type + JsonProperty property = contract.Properties.GetClosestMatchProperty(memberName); + + if (property != null && property.Writable && !property.Ignored) + { + if (property.PropertyContract == null) + { + property.PropertyContract = GetContractSafe(property.PropertyType); + } + + JsonConverter propertyConverter = GetConverter(property.PropertyContract, property.MemberConverter, null, null); + + if (!SetPropertyValue(property, propertyConverter, null, member, reader, newObject)) + { + reader.Skip(); + } + } + else + { + Type t = (JsonTokenUtils.IsPrimitiveToken(reader.TokenType)) ? reader.ValueType : typeof(IDynamicMetaObjectProvider); + + JsonContract dynamicMemberContract = GetContractSafe(t); + JsonConverter dynamicMemberConverter = GetConverter(dynamicMemberContract, null, null, member); + + object value; + if (dynamicMemberConverter != null && dynamicMemberConverter.CanRead) + { + value = DeserializeConvertable(dynamicMemberConverter, reader, t, null); + } + else + { + value = CreateValueInternal(reader, t, dynamicMemberContract, null, null, member, null); + } + + contract.TrySetMember(newObject, memberName, value); + } + } + catch (Exception ex) + { + if (IsErrorHandled(newObject, contract, memberName, reader as IJsonLineInfo, reader.Path, ex)) + { + HandleError(reader, true, initialDepth); + } + else + { + throw; + } + } + break; + case JsonToken.EndObject: + finished = true; + break; + default: + throw JsonSerializationException.Create(reader, "Unexpected token when deserializing object: " + reader.TokenType); + } + } while (!finished && reader.Read()); + + if (!finished) + { + ThrowUnexpectedEndException(reader, contract, newObject, "Unexpected end when deserializing object."); + } + + OnDeserialized(reader, contract, newObject); + + return newObject; + } +#endif + + internal class CreatorPropertyContext + { + public string Name; + public JsonProperty Property; + public JsonProperty ConstructorProperty; + public PropertyPresence? Presence; + public object Value; + public bool Used; + } + + private object CreateObjectUsingCreatorWithParameters(JsonReader reader, JsonObjectContract contract, JsonProperty containerProperty, ObjectConstructor creator, string id) + { + ValidationUtils.ArgumentNotNull(creator, nameof(creator)); + + // only need to keep a track of properies presence if they are required or a value should be defaulted if missing + bool trackPresence = (contract.HasRequiredOrDefaultValueProperties || HasFlag(Serializer._defaultValueHandling, DefaultValueHandling.Populate)); + + Type objectType = contract.UnderlyingType; + + if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info) + { + string parameters = string.Join(", ", contract.CreatorParameters.Select(p => p.PropertyName).ToArray()); + TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(reader as IJsonLineInfo, reader.Path, "Deserializing {0} using creator with parameters: {1}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType, parameters)), null); + } + + List propertyContexts = ResolvePropertyAndCreatorValues(contract, containerProperty, reader, objectType); + if (trackPresence) + { + foreach (JsonProperty property in contract.Properties) + { + if (propertyContexts.All(p => p.Property != property)) + { + propertyContexts.Add(new CreatorPropertyContext + { + Property = property, + Name = property.PropertyName, + Presence = PropertyPresence.None + }); + } + } + } + + object[] creatorParameterValues = new object[contract.CreatorParameters.Count]; + + foreach (CreatorPropertyContext context in propertyContexts) + { + // set presence of read values + if (trackPresence) + { + if (context.Property != null && context.Presence == null) + { + object v = context.Value; + PropertyPresence propertyPresence; + if (v == null) + { + propertyPresence = PropertyPresence.Null; + } + else if (v is string) + { + propertyPresence = CoerceEmptyStringToNull(context.Property.PropertyType, context.Property.PropertyContract, (string)v) + ? PropertyPresence.Null + : PropertyPresence.Value; + } + else + { + propertyPresence = PropertyPresence.Value; + } + + context.Presence = propertyPresence; + } + } + + JsonProperty constructorProperty = context.ConstructorProperty; + if (constructorProperty == null && context.Property != null) + { + constructorProperty = contract.CreatorParameters.ForgivingCaseSensitiveFind(p => p.PropertyName, context.Property.UnderlyingName); + } + + if (constructorProperty != null && !constructorProperty.Ignored) + { + // handle giving default values to creator parameters + // this needs to happen before the call to creator + if (trackPresence) + { + if (context.Presence == PropertyPresence.None || context.Presence == PropertyPresence.Null) + { + if (constructorProperty.PropertyContract == null) + { + constructorProperty.PropertyContract = GetContractSafe(constructorProperty.PropertyType); + } + + if (HasFlag(constructorProperty.DefaultValueHandling.GetValueOrDefault(Serializer._defaultValueHandling), DefaultValueHandling.Populate)) + { + context.Value = EnsureType( + reader, + constructorProperty.GetResolvedDefaultValue(), + CultureInfo.InvariantCulture, + constructorProperty.PropertyContract, + constructorProperty.PropertyType); + } + } + } + + int i = contract.CreatorParameters.IndexOf(constructorProperty); + creatorParameterValues[i] = context.Value; + + context.Used = true; + } + } + + object createdObject = creator(creatorParameterValues); + + if (id != null) + { + AddReference(reader, id, createdObject); + } + + OnDeserializing(reader, contract, createdObject); + + // go through unused values and set the newly created object's properties + foreach (CreatorPropertyContext context in propertyContexts) + { + if (context.Used || + context.Property == null || + context.Property.Ignored || + context.Presence == PropertyPresence.None) + { + continue; + } + + JsonProperty property = context.Property; + object value = context.Value; + + if (ShouldSetPropertyValue(property, value)) + { + property.ValueProvider.SetValue(createdObject, value); + context.Used = true; + } + else if (!property.Writable && value != null) + { + // handle readonly collection/dictionary properties + JsonContract propertyContract = Serializer._contractResolver.ResolveContract(property.PropertyType); + + if (propertyContract.ContractType == JsonContractType.Array) + { + JsonArrayContract propertyArrayContract = (JsonArrayContract)propertyContract; + + object createdObjectCollection = property.ValueProvider.GetValue(createdObject); + if (createdObjectCollection != null) + { + IWrappedCollection createdObjectCollectionWrapper = propertyArrayContract.CreateWrapper(createdObjectCollection); + IWrappedCollection newValues = propertyArrayContract.CreateWrapper(value); + + foreach (object newValue in newValues) + { + createdObjectCollectionWrapper.Add(newValue); + } + } + } + else if (propertyContract.ContractType == JsonContractType.Dictionary) + { + JsonDictionaryContract dictionaryContract = (JsonDictionaryContract)propertyContract; + + object createdObjectDictionary = property.ValueProvider.GetValue(createdObject); + if (createdObjectDictionary != null) + { + IDictionary targetDictionary = (dictionaryContract.ShouldCreateWrapper) ? dictionaryContract.CreateWrapper(createdObjectDictionary) : (IDictionary)createdObjectDictionary; + IDictionary newValues = (dictionaryContract.ShouldCreateWrapper) ? dictionaryContract.CreateWrapper(value) : (IDictionary)value; + + foreach (DictionaryEntry newValue in newValues) + { + targetDictionary.Add(newValue.Key, newValue.Value); + } + } + } + + context.Used = true; + } + } + + if (contract.ExtensionDataSetter != null) + { + foreach (CreatorPropertyContext propertyValue in propertyContexts) + { + if (!propertyValue.Used) + { + contract.ExtensionDataSetter(createdObject, propertyValue.Name, propertyValue.Value); + } + } + } + + if (trackPresence) + { + foreach (CreatorPropertyContext context in propertyContexts) + { + if (context.Property == null) + { + continue; + } + + EndProcessProperty( + createdObject, + reader, + contract, + reader.Depth, + context.Property, + context.Presence.GetValueOrDefault(), + !context.Used); + } + } + + OnDeserialized(reader, contract, createdObject); + return createdObject; + } + + private object DeserializeConvertable(JsonConverter converter, JsonReader reader, Type objectType, object existingValue) + { + if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info) + { + TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(reader as IJsonLineInfo, reader.Path, "Started deserializing {0} with converter {1}.".FormatWith(CultureInfo.InvariantCulture, objectType, converter.GetType())), null); + } + + object value = converter.ReadJson(reader, objectType, existingValue, GetInternalSerializer()); + + if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info) + { + TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(reader as IJsonLineInfo, reader.Path, "Finished deserializing {0} with converter {1}.".FormatWith(CultureInfo.InvariantCulture, objectType, converter.GetType())), null); + } + + return value; + } + + private List ResolvePropertyAndCreatorValues(JsonObjectContract contract, JsonProperty containerProperty, JsonReader reader, Type objectType) + { + List propertyValues = new List(); + bool exit = false; + do + { + switch (reader.TokenType) + { + case JsonToken.PropertyName: + string memberName = reader.Value.ToString(); + + CreatorPropertyContext creatorPropertyContext = new CreatorPropertyContext + { + Name = reader.Value.ToString(), + ConstructorProperty = contract.CreatorParameters.GetClosestMatchProperty(memberName), + Property = contract.Properties.GetClosestMatchProperty(memberName) + }; + propertyValues.Add(creatorPropertyContext); + + JsonProperty property = creatorPropertyContext.ConstructorProperty ?? creatorPropertyContext.Property; + if (property != null && !property.Ignored) + { + if (property.PropertyContract == null) + { + property.PropertyContract = GetContractSafe(property.PropertyType); + } + + JsonConverter propertyConverter = GetConverter(property.PropertyContract, property.MemberConverter, contract, containerProperty); + + if (!ReadForType(reader, property.PropertyContract, propertyConverter != null)) + { + throw JsonSerializationException.Create(reader, "Unexpected end when setting {0}'s value.".FormatWith(CultureInfo.InvariantCulture, memberName)); + } + + if (propertyConverter != null && propertyConverter.CanRead) + { + creatorPropertyContext.Value = DeserializeConvertable(propertyConverter, reader, property.PropertyType, null); + } + else + { + creatorPropertyContext.Value = CreateValueInternal(reader, property.PropertyType, property.PropertyContract, property, contract, containerProperty, null); + } + + continue; + } + else + { + if (!reader.Read()) + { + throw JsonSerializationException.Create(reader, "Unexpected end when setting {0}'s value.".FormatWith(CultureInfo.InvariantCulture, memberName)); + } + + if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) + { + TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(reader as IJsonLineInfo, reader.Path, "Could not find member '{0}' on {1}.".FormatWith(CultureInfo.InvariantCulture, memberName, contract.UnderlyingType)), null); + } + + if (Serializer._missingMemberHandling == MissingMemberHandling.Error) + { + throw JsonSerializationException.Create(reader, "Could not find member '{0}' on object of type '{1}'".FormatWith(CultureInfo.InvariantCulture, memberName, objectType.Name)); + } + } + + if (contract.ExtensionDataSetter != null) + { + creatorPropertyContext.Value = ReadExtensionDataValue(contract, containerProperty, reader); + } + else + { + reader.Skip(); + } + break; + case JsonToken.Comment: + break; + case JsonToken.EndObject: + exit = true; + break; + default: + throw JsonSerializationException.Create(reader, "Unexpected token when deserializing object: " + reader.TokenType); + } + } while (!exit && reader.Read()); + + return propertyValues; + } + + private bool ReadForType(JsonReader reader, JsonContract contract, bool hasConverter) + { + // don't read properties with converters as a specific value + // the value might be a string which will then get converted which will error if read as date for example + if (hasConverter) + { + return reader.Read(); + } + + ReadType t = (contract != null) ? contract.InternalReadType : ReadType.Read; + + switch (t) + { + case ReadType.Read: + return reader.ReadAndMoveToContent(); + case ReadType.ReadAsInt32: + reader.ReadAsInt32(); + break; + case ReadType.ReadAsDecimal: + reader.ReadAsDecimal(); + break; + case ReadType.ReadAsDouble: + reader.ReadAsDouble(); + break; + case ReadType.ReadAsBytes: + reader.ReadAsBytes(); + break; + case ReadType.ReadAsBoolean: + reader.ReadAsBoolean(); + break; + case ReadType.ReadAsString: + reader.ReadAsString(); + break; + case ReadType.ReadAsDateTime: + reader.ReadAsDateTime(); + break; +#if !NET20 + case ReadType.ReadAsDateTimeOffset: + reader.ReadAsDateTimeOffset(); + break; +#endif + default: + throw new ArgumentOutOfRangeException(); + } + + return (reader.TokenType != JsonToken.None); + } + + public object CreateNewObject(JsonReader reader, JsonObjectContract objectContract, JsonProperty containerMember, JsonProperty containerProperty, string id, out bool createdFromNonDefaultCreator) + { + object newObject = null; + + if (objectContract.OverrideCreator != null) + { + if (objectContract.CreatorParameters.Count > 0) + { + createdFromNonDefaultCreator = true; + return CreateObjectUsingCreatorWithParameters(reader, objectContract, containerMember, objectContract.OverrideCreator, id); + } + + newObject = objectContract.OverrideCreator(new object[0]); + } + else if (objectContract.DefaultCreator != null && + (!objectContract.DefaultCreatorNonPublic || Serializer._constructorHandling == ConstructorHandling.AllowNonPublicDefaultConstructor || objectContract.ParameterizedCreator == null)) + { + // use the default constructor if it is... + // public + // non-public and the user has change constructor handling settings + // non-public and there is no other creator + newObject = objectContract.DefaultCreator(); + } + else if (objectContract.ParameterizedCreator != null) + { + createdFromNonDefaultCreator = true; + return CreateObjectUsingCreatorWithParameters(reader, objectContract, containerMember, objectContract.ParameterizedCreator, id); + } + + if (newObject == null) + { + if (!objectContract.IsInstantiable) + { + throw JsonSerializationException.Create(reader, "Could not create an instance of type {0}. Type is an interface or abstract class and cannot be instantiated.".FormatWith(CultureInfo.InvariantCulture, objectContract.UnderlyingType)); + } + + throw JsonSerializationException.Create(reader, "Unable to find a constructor to use for type {0}. A class should either have a default constructor, one constructor with arguments or a constructor marked with the JsonConstructor attribute.".FormatWith(CultureInfo.InvariantCulture, objectContract.UnderlyingType)); + } + + createdFromNonDefaultCreator = false; + return newObject; + } + + private object PopulateObject(object newObject, JsonReader reader, JsonObjectContract contract, JsonProperty member, string id) + { + OnDeserializing(reader, contract, newObject); + + // only need to keep a track of properies presence if they are required or a value should be defaulted if missing + Dictionary propertiesPresence = (contract.HasRequiredOrDefaultValueProperties || HasFlag(Serializer._defaultValueHandling, DefaultValueHandling.Populate)) + ? contract.Properties.ToDictionary(m => m, m => PropertyPresence.None) + : null; + + if (id != null) + { + AddReference(reader, id, newObject); + } + + int initialDepth = reader.Depth; + + bool finished = false; + do + { + switch (reader.TokenType) + { + case JsonToken.PropertyName: + { + string memberName = reader.Value.ToString(); + + if (CheckPropertyName(reader, memberName)) + { + continue; + } + + try + { + // attempt exact case match first + // then try match ignoring case + JsonProperty property = contract.Properties.GetClosestMatchProperty(memberName); + + if (property == null) + { + if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) + { + TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(reader as IJsonLineInfo, reader.Path, "Could not find member '{0}' on {1}".FormatWith(CultureInfo.InvariantCulture, memberName, contract.UnderlyingType)), null); + } + + if (Serializer._missingMemberHandling == MissingMemberHandling.Error) + { + throw JsonSerializationException.Create(reader, "Could not find member '{0}' on object of type '{1}'".FormatWith(CultureInfo.InvariantCulture, memberName, contract.UnderlyingType.Name)); + } + + if (!reader.Read()) + { + break; + } + + SetExtensionData(contract, member, reader, memberName, newObject); + continue; + } + + if (property.Ignored || !ShouldDeserialize(reader, property, newObject)) + { + if (!reader.Read()) + { + break; + } + + SetPropertyPresence(reader, property, propertiesPresence); + SetExtensionData(contract, member, reader, memberName, newObject); + } + else + { + if (property.PropertyContract == null) + { + property.PropertyContract = GetContractSafe(property.PropertyType); + } + + JsonConverter propertyConverter = GetConverter(property.PropertyContract, property.MemberConverter, contract, member); + + if (!ReadForType(reader, property.PropertyContract, propertyConverter != null)) + { + throw JsonSerializationException.Create(reader, "Unexpected end when setting {0}'s value.".FormatWith(CultureInfo.InvariantCulture, memberName)); + } + + SetPropertyPresence(reader, property, propertiesPresence); + + // set extension data if property is ignored or readonly + if (!SetPropertyValue(property, propertyConverter, contract, member, reader, newObject)) + { + SetExtensionData(contract, member, reader, memberName, newObject); + } + } + } + catch (Exception ex) + { + if (IsErrorHandled(newObject, contract, memberName, reader as IJsonLineInfo, reader.Path, ex)) + { + HandleError(reader, true, initialDepth); + } + else + { + throw; + } + } + break; + } + case JsonToken.EndObject: + finished = true; + break; + case JsonToken.Comment: + // ignore + break; + default: + throw JsonSerializationException.Create(reader, "Unexpected token when deserializing object: " + reader.TokenType); + } + } while (!finished && reader.Read()); + + if (!finished) + { + ThrowUnexpectedEndException(reader, contract, newObject, "Unexpected end when deserializing object."); + } + + if (propertiesPresence != null) + { + foreach (KeyValuePair propertyPresence in propertiesPresence) + { + JsonProperty property = propertyPresence.Key; + PropertyPresence presence = propertyPresence.Value; + + EndProcessProperty(newObject, reader, contract, initialDepth, property, presence, true); + } + } + + OnDeserialized(reader, contract, newObject); + return newObject; + } + + private bool ShouldDeserialize(JsonReader reader, JsonProperty property, object target) + { + if (property.ShouldDeserialize == null) + { + return true; + } + + bool shouldDeserialize = property.ShouldDeserialize(target); + + if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) + { + TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, reader.Path, "ShouldDeserialize result for property '{0}' on {1}: {2}".FormatWith(CultureInfo.InvariantCulture, property.PropertyName, property.DeclaringType, shouldDeserialize)), null); + } + + return shouldDeserialize; + } + + private bool CheckPropertyName(JsonReader reader, string memberName) + { + if (Serializer.MetadataPropertyHandling == MetadataPropertyHandling.ReadAhead) + { + switch (memberName) + { + case JsonTypeReflector.IdPropertyName: + case JsonTypeReflector.RefPropertyName: + case JsonTypeReflector.TypePropertyName: + case JsonTypeReflector.ArrayValuesPropertyName: + reader.Skip(); + return true; + } + } + return false; + } + + private void SetExtensionData(JsonObjectContract contract, JsonProperty member, JsonReader reader, string memberName, object o) + { + if (contract.ExtensionDataSetter != null) + { + try + { + object value = ReadExtensionDataValue(contract, member, reader); + + contract.ExtensionDataSetter(o, memberName, value); + } + catch (Exception ex) + { + throw JsonSerializationException.Create(reader, "Error setting value in extension data for type '{0}'.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType), ex); + } + } + else + { + reader.Skip(); + } + } + + private object ReadExtensionDataValue(JsonObjectContract contract, JsonProperty member, JsonReader reader) + { + object value; + if (contract.ExtensionDataIsJToken) + { + value = JToken.ReadFrom(reader); + } + else + { + value = CreateValueInternal(reader, null, null, null, contract, member, null); + } + return value; + } + + private void EndProcessProperty(object newObject, JsonReader reader, JsonObjectContract contract, int initialDepth, JsonProperty property, PropertyPresence presence, bool setDefaultValue) + { + if (presence == PropertyPresence.None || presence == PropertyPresence.Null) + { + try + { + Required resolvedRequired = property._required ?? contract.ItemRequired ?? Required.Default; + + switch (presence) + { + case PropertyPresence.None: + if (resolvedRequired == Required.AllowNull || resolvedRequired == Required.Always) + { + throw JsonSerializationException.Create(reader, "Required property '{0}' not found in JSON.".FormatWith(CultureInfo.InvariantCulture, property.PropertyName)); + } + + if (setDefaultValue && !property.Ignored) + { + if (property.PropertyContract == null) + { + property.PropertyContract = GetContractSafe(property.PropertyType); + } + + if (HasFlag(property.DefaultValueHandling.GetValueOrDefault(Serializer._defaultValueHandling), DefaultValueHandling.Populate) && property.Writable) + { + property.ValueProvider.SetValue(newObject, EnsureType(reader, property.GetResolvedDefaultValue(), CultureInfo.InvariantCulture, property.PropertyContract, property.PropertyType)); + } + } + break; + case PropertyPresence.Null: + if (resolvedRequired == Required.Always) + { + throw JsonSerializationException.Create(reader, "Required property '{0}' expects a value but got null.".FormatWith(CultureInfo.InvariantCulture, property.PropertyName)); + } + if (resolvedRequired == Required.DisallowNull) + { + throw JsonSerializationException.Create(reader, "Required property '{0}' expects a non-null value.".FormatWith(CultureInfo.InvariantCulture, property.PropertyName)); + } + break; + } + } + catch (Exception ex) + { + if (IsErrorHandled(newObject, contract, property.PropertyName, reader as IJsonLineInfo, reader.Path, ex)) + { + HandleError(reader, true, initialDepth); + } + else + { + throw; + } + } + } + } + + private void SetPropertyPresence(JsonReader reader, JsonProperty property, Dictionary requiredProperties) + { + if (property != null && requiredProperties != null) + { + PropertyPresence propertyPresence; + switch (reader.TokenType) + { + case JsonToken.String: + propertyPresence = (CoerceEmptyStringToNull(property.PropertyType, property.PropertyContract, (string)reader.Value)) + ? PropertyPresence.Null + : PropertyPresence.Value; + break; + case JsonToken.Null: + case JsonToken.Undefined: + propertyPresence = PropertyPresence.Null; + break; + default: + propertyPresence = PropertyPresence.Value; + break; + } + + requiredProperties[property] = propertyPresence; + } + } + + private void HandleError(JsonReader reader, bool readPastError, int initialDepth) + { + ClearErrorContext(); + + if (readPastError) + { + reader.Skip(); + + while (reader.Depth > (initialDepth + 1)) + { + if (!reader.Read()) + { + break; + } + } + } + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Serialization/JsonSerializerInternalWriter.cs b/Common/00-1Json8.3/Json8.3/Serialization/JsonSerializerInternalWriter.cs new file mode 100644 index 0000000..d5b8496 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Serialization/JsonSerializerInternalWriter.cs @@ -0,0 +1,1196 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel; +#if !(NET35 || NET20 || PORTABLE40) +using System.Dynamic; +#endif +using System.Diagnostics; +using System.Globalization; +using System.IO; +using System.Security; +using Newtonsoft.Json.Linq; +using Newtonsoft.Json.Utilities; +using System.Runtime.Serialization; +#if NET20 +using Newtonsoft.Json.Utilities.LinqBridge; +#else +using System.Linq; + +#endif + +namespace Newtonsoft.Json.Serialization +{ + internal class JsonSerializerInternalWriter : JsonSerializerInternalBase + { + private Type _rootType; + private int _rootLevel; + private readonly List _serializeStack = new List(); + + public JsonSerializerInternalWriter(JsonSerializer serializer) + : base(serializer) + { + } + + public void Serialize(JsonWriter jsonWriter, object value, Type objectType) + { + if (jsonWriter == null) + { + throw new ArgumentNullException(nameof(jsonWriter)); + } + + _rootType = objectType; + _rootLevel = _serializeStack.Count + 1; + + JsonContract contract = GetContractSafe(value); + + try + { + if (ShouldWriteReference(value, null, contract, null, null)) + { + WriteReference(jsonWriter, value); + } + else + { + SerializeValue(jsonWriter, value, contract, null, null, null); + } + } + catch (Exception ex) + { + if (IsErrorHandled(null, contract, null, null, jsonWriter.Path, ex)) + { + HandleError(jsonWriter, 0); + } + else + { + // clear context in case serializer is being used inside a converter + // if the converter wraps the error then not clearing the context will cause this error: + // "Current error context error is different to requested error." + ClearErrorContext(); + throw; + } + } + finally + { + // clear root contract to ensure that if level was > 1 then it won't + // accidently be used for non root values + _rootType = null; + } + } + + private JsonSerializerProxy GetInternalSerializer() + { + if (InternalSerializer == null) + { + InternalSerializer = new JsonSerializerProxy(this); + } + + return InternalSerializer; + } + + private JsonContract GetContractSafe(object value) + { + if (value == null) + { + return null; + } + + return Serializer._contractResolver.ResolveContract(value.GetType()); + } + + private void SerializePrimitive(JsonWriter writer, object value, JsonPrimitiveContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty) + { + if (contract.TypeCode == PrimitiveTypeCode.Bytes) + { + // if type name handling is enabled then wrap the base64 byte string in an object with the type name + bool includeTypeDetails = ShouldWriteType(TypeNameHandling.Objects, contract, member, containerContract, containerProperty); + if (includeTypeDetails) + { + writer.WriteStartObject(); + WriteTypeProperty(writer, contract.CreatedType); + writer.WritePropertyName(JsonTypeReflector.ValuePropertyName, false); + + JsonWriter.WriteValue(writer, contract.TypeCode, value); + + writer.WriteEndObject(); + return; + } + } + + JsonWriter.WriteValue(writer, contract.TypeCode, value); + } + + private void SerializeValue(JsonWriter writer, object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty) + { + if (value == null) + { + writer.WriteNull(); + return; + } + + JsonConverter converter = + ((member != null) ? member.Converter : null) ?? + ((containerProperty != null) ? containerProperty.ItemConverter : null) ?? + ((containerContract != null) ? containerContract.ItemConverter : null) ?? + valueContract.Converter ?? + Serializer.GetMatchingConverter(valueContract.UnderlyingType) ?? + valueContract.InternalConverter; + + if (converter != null && converter.CanWrite) + { + SerializeConvertable(writer, converter, value, valueContract, containerContract, containerProperty); + return; + } + + switch (valueContract.ContractType) + { + case JsonContractType.Object: + SerializeObject(writer, value, (JsonObjectContract)valueContract, member, containerContract, containerProperty); + break; + case JsonContractType.Array: + JsonArrayContract arrayContract = (JsonArrayContract)valueContract; + if (!arrayContract.IsMultidimensionalArray) + { + SerializeList(writer, (IEnumerable)value, arrayContract, member, containerContract, containerProperty); + } + else + { + SerializeMultidimensionalArray(writer, (Array)value, arrayContract, member, containerContract, containerProperty); + } + break; + case JsonContractType.Primitive: + SerializePrimitive(writer, value, (JsonPrimitiveContract)valueContract, member, containerContract, containerProperty); + break; + case JsonContractType.String: + SerializeString(writer, value, (JsonStringContract)valueContract); + break; + case JsonContractType.Dictionary: + JsonDictionaryContract dictionaryContract = (JsonDictionaryContract)valueContract; + SerializeDictionary(writer, (value is IDictionary) ? (IDictionary)value : dictionaryContract.CreateWrapper(value), dictionaryContract, member, containerContract, containerProperty); + break; +#if !(NET35 || NET20 || PORTABLE40) + case JsonContractType.Dynamic: + SerializeDynamic(writer, (IDynamicMetaObjectProvider)value, (JsonDynamicContract)valueContract, member, containerContract, containerProperty); + break; +#endif +#if !(DOTNET || PORTABLE40 || PORTABLE) + case JsonContractType.Serializable: + SerializeISerializable(writer, (ISerializable)value, (JsonISerializableContract)valueContract, member, containerContract, containerProperty); + break; +#endif + case JsonContractType.Linq: + ((JToken)value).WriteTo(writer, Serializer.Converters.ToArray()); + break; + } + } + + private bool? ResolveIsReference(JsonContract contract, JsonProperty property, JsonContainerContract collectionContract, JsonProperty containerProperty) + { + bool? isReference = null; + + // value could be coming from a dictionary or array and not have a property + if (property != null) + { + isReference = property.IsReference; + } + + if (isReference == null && containerProperty != null) + { + isReference = containerProperty.ItemIsReference; + } + + if (isReference == null && collectionContract != null) + { + isReference = collectionContract.ItemIsReference; + } + + if (isReference == null) + { + isReference = contract.IsReference; + } + + return isReference; + } + + private bool ShouldWriteReference(object value, JsonProperty property, JsonContract valueContract, JsonContainerContract collectionContract, JsonProperty containerProperty) + { + if (value == null) + { + return false; + } + if (valueContract.ContractType == JsonContractType.Primitive || valueContract.ContractType == JsonContractType.String) + { + return false; + } + + bool? isReference = ResolveIsReference(valueContract, property, collectionContract, containerProperty); + + if (isReference == null) + { + if (valueContract.ContractType == JsonContractType.Array) + { + isReference = HasFlag(Serializer._preserveReferencesHandling, PreserveReferencesHandling.Arrays); + } + else + { + isReference = HasFlag(Serializer._preserveReferencesHandling, PreserveReferencesHandling.Objects); + } + } + + if (!isReference.GetValueOrDefault()) + { + return false; + } + + return Serializer.GetReferenceResolver().IsReferenced(this, value); + } + + private bool ShouldWriteProperty(object memberValue, JsonProperty property) + { + if (property.NullValueHandling.GetValueOrDefault(Serializer._nullValueHandling) == NullValueHandling.Ignore && + memberValue == null) + { + return false; + } + + if (HasFlag(property.DefaultValueHandling.GetValueOrDefault(Serializer._defaultValueHandling), DefaultValueHandling.Ignore) + && MiscellaneousUtils.ValueEquals(memberValue, property.GetResolvedDefaultValue())) + { + return false; + } + + return true; + } + + private bool CheckForCircularReference(JsonWriter writer, object value, JsonProperty property, JsonContract contract, JsonContainerContract containerContract, JsonProperty containerProperty) + { + if (value == null || contract.ContractType == JsonContractType.Primitive || contract.ContractType == JsonContractType.String) + { + return true; + } + + ReferenceLoopHandling? referenceLoopHandling = null; + + if (property != null) + { + referenceLoopHandling = property.ReferenceLoopHandling; + } + + if (referenceLoopHandling == null && containerProperty != null) + { + referenceLoopHandling = containerProperty.ItemReferenceLoopHandling; + } + + if (referenceLoopHandling == null && containerContract != null) + { + referenceLoopHandling = containerContract.ItemReferenceLoopHandling; + } + + bool exists = (Serializer._equalityComparer != null) + ? _serializeStack.Contains(value, Serializer._equalityComparer) + : _serializeStack.Contains(value); + + if (exists) + { + string message = "Self referencing loop detected"; + if (property != null) + { + message += " for property '{0}'".FormatWith(CultureInfo.InvariantCulture, property.PropertyName); + } + message += " with type '{0}'.".FormatWith(CultureInfo.InvariantCulture, value.GetType()); + + switch (referenceLoopHandling.GetValueOrDefault(Serializer._referenceLoopHandling)) + { + case ReferenceLoopHandling.Error: + throw JsonSerializationException.Create(null, writer.ContainerPath, message, null); + case ReferenceLoopHandling.Ignore: + if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) + { + TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, message + ". Skipping serializing self referenced value."), null); + } + + return false; + case ReferenceLoopHandling.Serialize: + if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) + { + TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, message + ". Serializing self referenced value."), null); + } + + return true; + } + } + + return true; + } + + private void WriteReference(JsonWriter writer, object value) + { + string reference = GetReference(writer, value); + + if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info) + { + TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Writing object reference to Id '{0}' for {1}.".FormatWith(CultureInfo.InvariantCulture, reference, value.GetType())), null); + } + + writer.WriteStartObject(); + writer.WritePropertyName(JsonTypeReflector.RefPropertyName, false); + writer.WriteValue(reference); + writer.WriteEndObject(); + } + + private string GetReference(JsonWriter writer, object value) + { + try + { + string reference = Serializer.GetReferenceResolver().GetReference(this, value); + + return reference; + } + catch (Exception ex) + { + throw JsonSerializationException.Create(null, writer.ContainerPath, "Error writing object reference for '{0}'.".FormatWith(CultureInfo.InvariantCulture, value.GetType()), ex); + } + } + + internal static bool TryConvertToString(object value, Type type, out string s) + { +#if !(DOTNET || PORTABLE40 || PORTABLE) + TypeConverter converter = ConvertUtils.GetConverter(type); + + // use the objectType's TypeConverter if it has one and can convert to a string + if (converter != null + && !(converter is ComponentConverter) + && converter.GetType() != typeof(TypeConverter)) + { + if (converter.CanConvertTo(typeof(string))) + { + s = converter.ConvertToInvariantString(value); + return true; + } + } +#endif + +#if (DOTNET || PORTABLE) + if (value is Guid || value is Uri || value is TimeSpan) + { + s = value.ToString(); + return true; + } +#endif + + if (value is Type) + { + s = ((Type)value).AssemblyQualifiedName; + return true; + } + + s = null; + return false; + } + + private void SerializeString(JsonWriter writer, object value, JsonStringContract contract) + { + OnSerializing(writer, contract, value); + + string s; + TryConvertToString(value, contract.UnderlyingType, out s); + writer.WriteValue(s); + + OnSerialized(writer, contract, value); + } + + private void OnSerializing(JsonWriter writer, JsonContract contract, object value) + { + if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info) + { + TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Started serializing {0}".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)), null); + } + + contract.InvokeOnSerializing(value, Serializer._context); + } + + private void OnSerialized(JsonWriter writer, JsonContract contract, object value) + { + if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info) + { + TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Finished serializing {0}".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)), null); + } + + contract.InvokeOnSerialized(value, Serializer._context); + } + + private void SerializeObject(JsonWriter writer, object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty) + { + OnSerializing(writer, contract, value); + + _serializeStack.Add(value); + + WriteObjectStart(writer, value, contract, member, collectionContract, containerProperty); + + int initialDepth = writer.Top; + + for (int index = 0; index < contract.Properties.Count; index++) + { + JsonProperty property = contract.Properties[index]; + try + { + object memberValue; + JsonContract memberContract; + + if (!CalculatePropertyValues(writer, value, contract, member, property, out memberContract, out memberValue)) + { + continue; + } + + property.WritePropertyName(writer); + SerializeValue(writer, memberValue, memberContract, property, contract, member); + } + catch (Exception ex) + { + if (IsErrorHandled(value, contract, property.PropertyName, null, writer.ContainerPath, ex)) + { + HandleError(writer, initialDepth); + } + else + { + throw; + } + } + } + + if (contract.ExtensionDataGetter != null) + { + IEnumerable> extensionData = contract.ExtensionDataGetter(value); + if (extensionData != null) + { + foreach (KeyValuePair e in extensionData) + { + JsonContract keyContract = GetContractSafe(e.Key); + JsonContract valueContract = GetContractSafe(e.Value); + + bool escape; + string propertyName = GetPropertyName(writer, e.Key, keyContract, out escape); + + if (ShouldWriteReference(e.Value, null, valueContract, contract, member)) + { + writer.WritePropertyName(propertyName); + WriteReference(writer, e.Value); + } + else + { + if (!CheckForCircularReference(writer, e.Value, null, valueContract, contract, member)) + { + continue; + } + + writer.WritePropertyName(propertyName); + + SerializeValue(writer, e.Value, valueContract, null, contract, member); + } + } + } + } + + writer.WriteEndObject(); + + _serializeStack.RemoveAt(_serializeStack.Count - 1); + + OnSerialized(writer, contract, value); + } + + private bool CalculatePropertyValues(JsonWriter writer, object value, JsonContainerContract contract, JsonProperty member, JsonProperty property, out JsonContract memberContract, out object memberValue) + { + if (!property.Ignored && property.Readable && ShouldSerialize(writer, property, value) && IsSpecified(writer, property, value)) + { + if (property.PropertyContract == null) + { + property.PropertyContract = Serializer._contractResolver.ResolveContract(property.PropertyType); + } + + memberValue = property.ValueProvider.GetValue(value); + memberContract = (property.PropertyContract.IsSealed) ? property.PropertyContract : GetContractSafe(memberValue); + + if (ShouldWriteProperty(memberValue, property)) + { + if (ShouldWriteReference(memberValue, property, memberContract, contract, member)) + { + property.WritePropertyName(writer); + WriteReference(writer, memberValue); + return false; + } + + if (!CheckForCircularReference(writer, memberValue, property, memberContract, contract, member)) + { + return false; + } + + if (memberValue == null) + { + JsonObjectContract objectContract = contract as JsonObjectContract; + Required resolvedRequired = property._required ?? ((objectContract != null) ? objectContract.ItemRequired : null) ?? Required.Default; + if (resolvedRequired == Required.Always) + { + throw JsonSerializationException.Create(null, writer.ContainerPath, "Cannot write a null value for property '{0}'. Property requires a value.".FormatWith(CultureInfo.InvariantCulture, property.PropertyName), null); + } + if (resolvedRequired == Required.DisallowNull) + { + throw JsonSerializationException.Create(null, writer.ContainerPath, "Cannot write a null value for property '{0}'. Property requires a non-null value.".FormatWith(CultureInfo.InvariantCulture, property.PropertyName), null); + } + } + + return true; + } + } + + memberContract = null; + memberValue = null; + return false; + } + + private void WriteObjectStart(JsonWriter writer, object value, JsonContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty) + { + writer.WriteStartObject(); + + bool isReference = ResolveIsReference(contract, member, collectionContract, containerProperty) ?? HasFlag(Serializer._preserveReferencesHandling, PreserveReferencesHandling.Objects); + // don't make readonly fields the referenced value because they can't be deserialized to + if (isReference && (member == null || member.Writable)) + { + WriteReferenceIdProperty(writer, contract.UnderlyingType, value); + } + if (ShouldWriteType(TypeNameHandling.Objects, contract, member, collectionContract, containerProperty)) + { + WriteTypeProperty(writer, contract.UnderlyingType); + } + } + + private void WriteReferenceIdProperty(JsonWriter writer, Type type, object value) + { + string reference = GetReference(writer, value); + + if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) + { + TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, "Writing object reference Id '{0}' for {1}.".FormatWith(CultureInfo.InvariantCulture, reference, type)), null); + } + + writer.WritePropertyName(JsonTypeReflector.IdPropertyName, false); + writer.WriteValue(reference); + } + + private void WriteTypeProperty(JsonWriter writer, Type type) + { + string typeName = ReflectionUtils.GetTypeName(type, Serializer._typeNameAssemblyFormat, Serializer._binder); + + if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) + { + TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, "Writing type name '{0}' for {1}.".FormatWith(CultureInfo.InvariantCulture, typeName, type)), null); + } + + writer.WritePropertyName(JsonTypeReflector.TypePropertyName, false); + writer.WriteValue(typeName); + } + + private bool HasFlag(DefaultValueHandling value, DefaultValueHandling flag) + { + return ((value & flag) == flag); + } + + private bool HasFlag(PreserveReferencesHandling value, PreserveReferencesHandling flag) + { + return ((value & flag) == flag); + } + + private bool HasFlag(TypeNameHandling value, TypeNameHandling flag) + { + return ((value & flag) == flag); + } + + private void SerializeConvertable(JsonWriter writer, JsonConverter converter, object value, JsonContract contract, JsonContainerContract collectionContract, JsonProperty containerProperty) + { + if (ShouldWriteReference(value, null, contract, collectionContract, containerProperty)) + { + WriteReference(writer, value); + } + else + { + if (!CheckForCircularReference(writer, value, null, contract, collectionContract, containerProperty)) + { + return; + } + + _serializeStack.Add(value); + + if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info) + { + TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Started serializing {0} with converter {1}.".FormatWith(CultureInfo.InvariantCulture, value.GetType(), converter.GetType())), null); + } + + converter.WriteJson(writer, value, GetInternalSerializer()); + + if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info) + { + TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Finished serializing {0} with converter {1}.".FormatWith(CultureInfo.InvariantCulture, value.GetType(), converter.GetType())), null); + } + + _serializeStack.RemoveAt(_serializeStack.Count - 1); + } + } + + private void SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty) + { + IWrappedCollection wrappedCollection = values as IWrappedCollection; + object underlyingList = wrappedCollection != null ? wrappedCollection.UnderlyingCollection : values; + + OnSerializing(writer, contract, underlyingList); + + _serializeStack.Add(underlyingList); + + bool hasWrittenMetadataObject = WriteStartArray(writer, underlyingList, contract, member, collectionContract, containerProperty); + + writer.WriteStartArray(); + + int initialDepth = writer.Top; + + int index = 0; + // note that an error in the IEnumerable won't be caught + foreach (object value in values) + { + try + { + JsonContract valueContract = contract.FinalItemContract ?? GetContractSafe(value); + + if (ShouldWriteReference(value, null, valueContract, contract, member)) + { + WriteReference(writer, value); + } + else + { + if (CheckForCircularReference(writer, value, null, valueContract, contract, member)) + { + SerializeValue(writer, value, valueContract, null, contract, member); + } + } + } + catch (Exception ex) + { + if (IsErrorHandled(underlyingList, contract, index, null, writer.ContainerPath, ex)) + { + HandleError(writer, initialDepth); + } + else + { + throw; + } + } + finally + { + index++; + } + } + + writer.WriteEndArray(); + + if (hasWrittenMetadataObject) + { + writer.WriteEndObject(); + } + + _serializeStack.RemoveAt(_serializeStack.Count - 1); + + OnSerialized(writer, contract, underlyingList); + } + + private void SerializeMultidimensionalArray(JsonWriter writer, Array values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty) + { + OnSerializing(writer, contract, values); + + _serializeStack.Add(values); + + bool hasWrittenMetadataObject = WriteStartArray(writer, values, contract, member, collectionContract, containerProperty); + + SerializeMultidimensionalArray(writer, values, contract, member, writer.Top, new int[0]); + + if (hasWrittenMetadataObject) + { + writer.WriteEndObject(); + } + + _serializeStack.RemoveAt(_serializeStack.Count - 1); + + OnSerialized(writer, contract, values); + } + + private void SerializeMultidimensionalArray(JsonWriter writer, Array values, JsonArrayContract contract, JsonProperty member, int initialDepth, int[] indices) + { + int dimension = indices.Length; + int[] newIndices = new int[dimension + 1]; + for (int i = 0; i < dimension; i++) + { + newIndices[i] = indices[i]; + } + + writer.WriteStartArray(); + + for (int i = values.GetLowerBound(dimension); i <= values.GetUpperBound(dimension); i++) + { + newIndices[dimension] = i; + bool isTopLevel = (newIndices.Length == values.Rank); + + if (isTopLevel) + { + object value = values.GetValue(newIndices); + + try + { + JsonContract valueContract = contract.FinalItemContract ?? GetContractSafe(value); + + if (ShouldWriteReference(value, null, valueContract, contract, member)) + { + WriteReference(writer, value); + } + else + { + if (CheckForCircularReference(writer, value, null, valueContract, contract, member)) + { + SerializeValue(writer, value, valueContract, null, contract, member); + } + } + } + catch (Exception ex) + { + if (IsErrorHandled(values, contract, i, null, writer.ContainerPath, ex)) + { + HandleError(writer, initialDepth + 1); + } + else + { + throw; + } + } + } + else + { + SerializeMultidimensionalArray(writer, values, contract, member, initialDepth + 1, newIndices); + } + } + + writer.WriteEndArray(); + } + + private bool WriteStartArray(JsonWriter writer, object values, JsonArrayContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty) + { + bool isReference = ResolveIsReference(contract, member, containerContract, containerProperty) ?? HasFlag(Serializer._preserveReferencesHandling, PreserveReferencesHandling.Arrays); + // don't make readonly fields the referenced value because they can't be deserialized to + isReference = (isReference && (member == null || member.Writable)); + + bool includeTypeDetails = ShouldWriteType(TypeNameHandling.Arrays, contract, member, containerContract, containerProperty); + bool writeMetadataObject = isReference || includeTypeDetails; + + if (writeMetadataObject) + { + writer.WriteStartObject(); + + if (isReference) + { + WriteReferenceIdProperty(writer, contract.UnderlyingType, values); + } + if (includeTypeDetails) + { + WriteTypeProperty(writer, values.GetType()); + } + writer.WritePropertyName(JsonTypeReflector.ArrayValuesPropertyName, false); + } + + if (contract.ItemContract == null) + { + contract.ItemContract = Serializer._contractResolver.ResolveContract(contract.CollectionItemType ?? typeof(object)); + } + + return writeMetadataObject; + } + +#if !(DOTNET || PORTABLE40 || PORTABLE) +#if !(NET20 || NET35) + [SecuritySafeCritical] +#endif + private void SerializeISerializable(JsonWriter writer, ISerializable value, JsonISerializableContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty) + { + if (!JsonTypeReflector.FullyTrusted) + { + string message = @"Type '{0}' implements ISerializable but cannot be serialized using the ISerializable interface because the current application is not fully trusted and ISerializable can expose secure data." + Environment.NewLine + + @"To fix this error either change the environment to be fully trusted, change the application to not deserialize the type, add JsonObjectAttribute to the type or change the JsonSerializer setting ContractResolver to use a new DefaultContractResolver with IgnoreSerializableInterface set to true." + Environment.NewLine; + message = message.FormatWith(CultureInfo.InvariantCulture, value.GetType()); + + throw JsonSerializationException.Create(null, writer.ContainerPath, message, null); + } + + OnSerializing(writer, contract, value); + _serializeStack.Add(value); + + WriteObjectStart(writer, value, contract, member, collectionContract, containerProperty); + + SerializationInfo serializationInfo = new SerializationInfo(contract.UnderlyingType, new FormatterConverter()); + value.GetObjectData(serializationInfo, Serializer._context); + + foreach (SerializationEntry serializationEntry in serializationInfo) + { + JsonContract valueContract = GetContractSafe(serializationEntry.Value); + + if (ShouldWriteReference(serializationEntry.Value, null, valueContract, contract, member)) + { + writer.WritePropertyName(serializationEntry.Name); + WriteReference(writer, serializationEntry.Value); + } + else if (CheckForCircularReference(writer, serializationEntry.Value, null, valueContract, contract, member)) + { + writer.WritePropertyName(serializationEntry.Name); + SerializeValue(writer, serializationEntry.Value, valueContract, null, contract, member); + } + } + + writer.WriteEndObject(); + + _serializeStack.RemoveAt(_serializeStack.Count - 1); + OnSerialized(writer, contract, value); + } +#endif + +#if !(NET35 || NET20 || PORTABLE40) + private void SerializeDynamic(JsonWriter writer, IDynamicMetaObjectProvider value, JsonDynamicContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty) + { + OnSerializing(writer, contract, value); + _serializeStack.Add(value); + + WriteObjectStart(writer, value, contract, member, collectionContract, containerProperty); + + int initialDepth = writer.Top; + + for (int index = 0; index < contract.Properties.Count; index++) + { + JsonProperty property = contract.Properties[index]; + + // only write non-dynamic properties that have an explicit attribute + if (property.HasMemberAttribute) + { + try + { + object memberValue; + JsonContract memberContract; + + if (!CalculatePropertyValues(writer, value, contract, member, property, out memberContract, out memberValue)) + { + continue; + } + + property.WritePropertyName(writer); + SerializeValue(writer, memberValue, memberContract, property, contract, member); + } + catch (Exception ex) + { + if (IsErrorHandled(value, contract, property.PropertyName, null, writer.ContainerPath, ex)) + { + HandleError(writer, initialDepth); + } + else + { + throw; + } + } + } + } + + foreach (string memberName in value.GetDynamicMemberNames()) + { + object memberValue; + if (contract.TryGetMember(value, memberName, out memberValue)) + { + try + { + JsonContract valueContract = GetContractSafe(memberValue); + + if (!ShouldWriteDynamicProperty(memberValue)) + { + continue; + } + + if (CheckForCircularReference(writer, memberValue, null, valueContract, contract, member)) + { + string resolvedPropertyName = (contract.PropertyNameResolver != null) + ? contract.PropertyNameResolver(memberName) + : memberName; + + writer.WritePropertyName(resolvedPropertyName); + SerializeValue(writer, memberValue, valueContract, null, contract, member); + } + } + catch (Exception ex) + { + if (IsErrorHandled(value, contract, memberName, null, writer.ContainerPath, ex)) + { + HandleError(writer, initialDepth); + } + else + { + throw; + } + } + } + } + + writer.WriteEndObject(); + + _serializeStack.RemoveAt(_serializeStack.Count - 1); + OnSerialized(writer, contract, value); + } +#endif + + private bool ShouldWriteDynamicProperty(object memberValue) + { + if (Serializer._nullValueHandling == NullValueHandling.Ignore && memberValue == null) + { + return false; + } + + if (HasFlag(Serializer._defaultValueHandling, DefaultValueHandling.Ignore) && + (memberValue == null || MiscellaneousUtils.ValueEquals(memberValue, ReflectionUtils.GetDefaultValue(memberValue.GetType())))) + { + return false; + } + + return true; + } + + private bool ShouldWriteType(TypeNameHandling typeNameHandlingFlag, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty) + { + TypeNameHandling resolvedTypeNameHandling = + ((member != null) ? member.TypeNameHandling : null) + ?? ((containerProperty != null) ? containerProperty.ItemTypeNameHandling : null) + ?? ((containerContract != null) ? containerContract.ItemTypeNameHandling : null) + ?? Serializer._typeNameHandling; + + if (HasFlag(resolvedTypeNameHandling, typeNameHandlingFlag)) + { + return true; + } + + // instance type and the property's type's contract default type are different (no need to put the type in JSON because the type will be created by default) + if (HasFlag(resolvedTypeNameHandling, TypeNameHandling.Auto)) + { + if (member != null) + { + if (contract.UnderlyingType != member.PropertyContract.CreatedType) + { + return true; + } + } + else if (containerContract != null) + { + if (containerContract.ItemContract == null || contract.UnderlyingType != containerContract.ItemContract.CreatedType) + { + return true; + } + } + else if (_rootType != null && _serializeStack.Count == _rootLevel) + { + JsonContract rootContract = Serializer._contractResolver.ResolveContract(_rootType); + + if (contract.UnderlyingType != rootContract.CreatedType) + { + return true; + } + } + } + + return false; + } + + private void SerializeDictionary(JsonWriter writer, IDictionary values, JsonDictionaryContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty) + { + IWrappedDictionary wrappedDictionary = values as IWrappedDictionary; + object underlyingDictionary = wrappedDictionary != null ? wrappedDictionary.UnderlyingDictionary : values; + + OnSerializing(writer, contract, underlyingDictionary); + _serializeStack.Add(underlyingDictionary); + + WriteObjectStart(writer, underlyingDictionary, contract, member, collectionContract, containerProperty); + + if (contract.ItemContract == null) + { + contract.ItemContract = Serializer._contractResolver.ResolveContract(contract.DictionaryValueType ?? typeof(object)); + } + + if (contract.KeyContract == null) + { + contract.KeyContract = Serializer._contractResolver.ResolveContract(contract.DictionaryKeyType ?? typeof(object)); + } + + int initialDepth = writer.Top; + + foreach (DictionaryEntry entry in values) + { + bool escape; + string propertyName = GetPropertyName(writer, entry.Key, contract.KeyContract, out escape); + + propertyName = (contract.DictionaryKeyResolver != null) + ? contract.DictionaryKeyResolver(propertyName) + : propertyName; + + try + { + object value = entry.Value; + JsonContract valueContract = contract.FinalItemContract ?? GetContractSafe(value); + + if (ShouldWriteReference(value, null, valueContract, contract, member)) + { + writer.WritePropertyName(propertyName, escape); + WriteReference(writer, value); + } + else + { + if (!CheckForCircularReference(writer, value, null, valueContract, contract, member)) + { + continue; + } + + writer.WritePropertyName(propertyName, escape); + + SerializeValue(writer, value, valueContract, null, contract, member); + } + } + catch (Exception ex) + { + if (IsErrorHandled(underlyingDictionary, contract, propertyName, null, writer.ContainerPath, ex)) + { + HandleError(writer, initialDepth); + } + else + { + throw; + } + } + } + + writer.WriteEndObject(); + + _serializeStack.RemoveAt(_serializeStack.Count - 1); + + OnSerialized(writer, contract, underlyingDictionary); + } + + private string GetPropertyName(JsonWriter writer, object name, JsonContract contract, out bool escape) + { + string propertyName; + + if (contract.ContractType == JsonContractType.Primitive) + { + JsonPrimitiveContract primitiveContract = (JsonPrimitiveContract)contract; + if (primitiveContract.TypeCode == PrimitiveTypeCode.DateTime || primitiveContract.TypeCode == PrimitiveTypeCode.DateTimeNullable) + { + DateTime dt = DateTimeUtils.EnsureDateTime((DateTime)name, writer.DateTimeZoneHandling); + + escape = false; + StringWriter sw = new StringWriter(CultureInfo.InvariantCulture); + DateTimeUtils.WriteDateTimeString(sw, dt, writer.DateFormatHandling, writer.DateFormatString, writer.Culture); + return sw.ToString(); + } +#if !NET20 + else if (primitiveContract.TypeCode == PrimitiveTypeCode.DateTimeOffset || primitiveContract.TypeCode == PrimitiveTypeCode.DateTimeOffsetNullable) + { + escape = false; + StringWriter sw = new StringWriter(CultureInfo.InvariantCulture); + DateTimeUtils.WriteDateTimeOffsetString(sw, (DateTimeOffset)name, writer.DateFormatHandling, writer.DateFormatString, writer.Culture); + return sw.ToString(); + } +#endif + else + { + escape = true; + return Convert.ToString(name, CultureInfo.InvariantCulture); + } + } + else if (TryConvertToString(name, name.GetType(), out propertyName)) + { + escape = true; + return propertyName; + } + else + { + escape = true; + return name.ToString(); + } + } + + private void HandleError(JsonWriter writer, int initialDepth) + { + ClearErrorContext(); + + if (writer.WriteState == WriteState.Property) + { + writer.WriteNull(); + } + + while (writer.Top > initialDepth) + { + writer.WriteEnd(); + } + } + + private bool ShouldSerialize(JsonWriter writer, JsonProperty property, object target) + { + if (property.ShouldSerialize == null) + { + return true; + } + + bool shouldSerialize = property.ShouldSerialize(target); + + if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) + { + TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, "ShouldSerialize result for property '{0}' on {1}: {2}".FormatWith(CultureInfo.InvariantCulture, property.PropertyName, property.DeclaringType, shouldSerialize)), null); + } + + return shouldSerialize; + } + + private bool IsSpecified(JsonWriter writer, JsonProperty property, object target) + { + if (property.GetIsSpecified == null) + { + return true; + } + + bool isSpecified = property.GetIsSpecified(target); + + if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) + { + TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, "IsSpecified result for property '{0}' on {1}: {2}".FormatWith(CultureInfo.InvariantCulture, property.PropertyName, property.DeclaringType, isSpecified)), null); + } + + return isSpecified; + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Serialization/JsonSerializerProxy.cs b/Common/00-1Json8.3/Json8.3/Serialization/JsonSerializerProxy.cs new file mode 100644 index 0000000..cd1c910 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Serialization/JsonSerializerProxy.cs @@ -0,0 +1,278 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Collections; +using System.Globalization; +using System.Runtime.Serialization.Formatters; +using Newtonsoft.Json.Utilities; +using System.Runtime.Serialization; + +namespace Newtonsoft.Json.Serialization +{ + internal class JsonSerializerProxy : JsonSerializer + { + private readonly JsonSerializerInternalReader _serializerReader; + private readonly JsonSerializerInternalWriter _serializerWriter; + private readonly JsonSerializer _serializer; + + public override event EventHandler Error + { + add { _serializer.Error += value; } + remove { _serializer.Error -= value; } + } + + public override IReferenceResolver ReferenceResolver + { + get { return _serializer.ReferenceResolver; } + set { _serializer.ReferenceResolver = value; } + } + + public override ITraceWriter TraceWriter + { + get { return _serializer.TraceWriter; } + set { _serializer.TraceWriter = value; } + } + + public override IEqualityComparer EqualityComparer + { + get { return _serializer.EqualityComparer; } + set { _serializer.EqualityComparer = value; } + } + + public override JsonConverterCollection Converters + { + get { return _serializer.Converters; } + } + + public override DefaultValueHandling DefaultValueHandling + { + get { return _serializer.DefaultValueHandling; } + set { _serializer.DefaultValueHandling = value; } + } + + public override IContractResolver ContractResolver + { + get { return _serializer.ContractResolver; } + set { _serializer.ContractResolver = value; } + } + + public override MissingMemberHandling MissingMemberHandling + { + get { return _serializer.MissingMemberHandling; } + set { _serializer.MissingMemberHandling = value; } + } + + public override NullValueHandling NullValueHandling + { + get { return _serializer.NullValueHandling; } + set { _serializer.NullValueHandling = value; } + } + + public override ObjectCreationHandling ObjectCreationHandling + { + get { return _serializer.ObjectCreationHandling; } + set { _serializer.ObjectCreationHandling = value; } + } + + public override ReferenceLoopHandling ReferenceLoopHandling + { + get { return _serializer.ReferenceLoopHandling; } + set { _serializer.ReferenceLoopHandling = value; } + } + + public override PreserveReferencesHandling PreserveReferencesHandling + { + get { return _serializer.PreserveReferencesHandling; } + set { _serializer.PreserveReferencesHandling = value; } + } + + public override TypeNameHandling TypeNameHandling + { + get { return _serializer.TypeNameHandling; } + set { _serializer.TypeNameHandling = value; } + } + + public override MetadataPropertyHandling MetadataPropertyHandling + { + get { return _serializer.MetadataPropertyHandling; } + set { _serializer.MetadataPropertyHandling = value; } + } + + public override FormatterAssemblyStyle TypeNameAssemblyFormat + { + get { return _serializer.TypeNameAssemblyFormat; } + set { _serializer.TypeNameAssemblyFormat = value; } + } + + public override ConstructorHandling ConstructorHandling + { + get { return _serializer.ConstructorHandling; } + set { _serializer.ConstructorHandling = value; } + } + + public override SerializationBinder Binder + { + get { return _serializer.Binder; } + set { _serializer.Binder = value; } + } + + public override StreamingContext Context + { + get { return _serializer.Context; } + set { _serializer.Context = value; } + } + + public override Formatting Formatting + { + get { return _serializer.Formatting; } + set { _serializer.Formatting = value; } + } + + public override DateFormatHandling DateFormatHandling + { + get { return _serializer.DateFormatHandling; } + set { _serializer.DateFormatHandling = value; } + } + + public override DateTimeZoneHandling DateTimeZoneHandling + { + get { return _serializer.DateTimeZoneHandling; } + set { _serializer.DateTimeZoneHandling = value; } + } + + public override DateParseHandling DateParseHandling + { + get { return _serializer.DateParseHandling; } + set { _serializer.DateParseHandling = value; } + } + + public override FloatFormatHandling FloatFormatHandling + { + get { return _serializer.FloatFormatHandling; } + set { _serializer.FloatFormatHandling = value; } + } + + public override FloatParseHandling FloatParseHandling + { + get { return _serializer.FloatParseHandling; } + set { _serializer.FloatParseHandling = value; } + } + + public override StringEscapeHandling StringEscapeHandling + { + get { return _serializer.StringEscapeHandling; } + set { _serializer.StringEscapeHandling = value; } + } + + public override string DateFormatString + { + get { return _serializer.DateFormatString; } + set { _serializer.DateFormatString = value; } + } + + public override CultureInfo Culture + { + get { return _serializer.Culture; } + set { _serializer.Culture = value; } + } + + public override int? MaxDepth + { + get { return _serializer.MaxDepth; } + set { _serializer.MaxDepth = value; } + } + + public override bool CheckAdditionalContent + { + get { return _serializer.CheckAdditionalContent; } + set { _serializer.CheckAdditionalContent = value; } + } + + internal JsonSerializerInternalBase GetInternalSerializer() + { + if (_serializerReader != null) + { + return _serializerReader; + } + else + { + return _serializerWriter; + } + } + + public JsonSerializerProxy(JsonSerializerInternalReader serializerReader) + { + ValidationUtils.ArgumentNotNull(serializerReader, nameof(serializerReader)); + + _serializerReader = serializerReader; + _serializer = serializerReader.Serializer; + } + + public JsonSerializerProxy(JsonSerializerInternalWriter serializerWriter) + { + ValidationUtils.ArgumentNotNull(serializerWriter, nameof(serializerWriter)); + + _serializerWriter = serializerWriter; + _serializer = serializerWriter.Serializer; + } + + internal override object DeserializeInternal(JsonReader reader, Type objectType) + { + if (_serializerReader != null) + { + return _serializerReader.Deserialize(reader, objectType, false); + } + else + { + return _serializer.Deserialize(reader, objectType); + } + } + + internal override void PopulateInternal(JsonReader reader, object target) + { + if (_serializerReader != null) + { + _serializerReader.Populate(reader, target); + } + else + { + _serializer.Populate(reader, target); + } + } + + internal override void SerializeInternal(JsonWriter jsonWriter, object value, Type rootType) + { + if (_serializerWriter != null) + { + _serializerWriter.Serialize(jsonWriter, value, rootType); + } + else + { + _serializer.Serialize(jsonWriter, value); + } + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Serialization/JsonStringContract.cs b/Common/00-1Json8.3/Json8.3/Serialization/JsonStringContract.cs new file mode 100644 index 0000000..be096bc --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Serialization/JsonStringContract.cs @@ -0,0 +1,45 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; + +namespace Newtonsoft.Json.Serialization +{ + /// + /// Contract details for a used by the . + /// + public class JsonStringContract : JsonPrimitiveContract + { + /// + /// Initializes a new instance of the class. + /// + /// The underlying type for the contract. + public JsonStringContract(Type underlyingType) + : base(underlyingType) + { + ContractType = JsonContractType.String; + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Serialization/JsonTypeReflector.cs b/Common/00-1Json8.3/Json8.3/Serialization/JsonTypeReflector.cs new file mode 100644 index 0000000..0744b94 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Serialization/JsonTypeReflector.cs @@ -0,0 +1,461 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Globalization; +using System.Reflection; +using System.Security; +#if !(DOTNET || PORTABLE || PORTABLE40) +using System.Security.Permissions; +#endif +using Newtonsoft.Json.Utilities; +#if NET20 +using Newtonsoft.Json.Utilities.LinqBridge; +#else +using System.Linq; +#endif +using System.Runtime.Serialization; + +namespace Newtonsoft.Json.Serialization +{ + internal static class JsonTypeReflector + { + private static bool? _dynamicCodeGeneration; + private static bool? _fullyTrusted; + + public const string IdPropertyName = "$id"; + public const string RefPropertyName = "$ref"; + public const string TypePropertyName = "$type"; + public const string ValuePropertyName = "$value"; + public const string ArrayValuesPropertyName = "$values"; + + public const string ShouldSerializePrefix = "ShouldSerialize"; + public const string SpecifiedPostfix = "Specified"; + + private static readonly ThreadSafeStore> JsonConverterCreatorCache = + new ThreadSafeStore>(GetJsonConverterCreator); + +#if !(NET20 || DOTNET) + private static readonly ThreadSafeStore AssociatedMetadataTypesCache = new ThreadSafeStore(GetAssociateMetadataTypeFromAttribute); + private static ReflectionObject _metadataTypeAttributeReflectionObject; +#endif + + public static T GetCachedAttribute(object attributeProvider) where T : Attribute + { + return CachedAttributeGetter.GetAttribute(attributeProvider); + } + +#if !NET20 + public static DataContractAttribute GetDataContractAttribute(Type type) + { + // DataContractAttribute does not have inheritance + Type currentType = type; + + while (currentType != null) + { + DataContractAttribute result = CachedAttributeGetter.GetAttribute(currentType); + if (result != null) + { + return result; + } + + currentType = currentType.BaseType(); + } + + return null; + } + + public static DataMemberAttribute GetDataMemberAttribute(MemberInfo memberInfo) + { + // DataMemberAttribute does not have inheritance + + // can't override a field + if (memberInfo.MemberType() == MemberTypes.Field) + { + return CachedAttributeGetter.GetAttribute(memberInfo); + } + + // search property and then search base properties if nothing is returned and the property is virtual + PropertyInfo propertyInfo = (PropertyInfo)memberInfo; + DataMemberAttribute result = CachedAttributeGetter.GetAttribute(propertyInfo); + if (result == null) + { + if (propertyInfo.IsVirtual()) + { + Type currentType = propertyInfo.DeclaringType; + + while (result == null && currentType != null) + { + PropertyInfo baseProperty = (PropertyInfo)ReflectionUtils.GetMemberInfoFromType(currentType, propertyInfo); + if (baseProperty != null && baseProperty.IsVirtual()) + { + result = CachedAttributeGetter.GetAttribute(baseProperty); + } + + currentType = currentType.BaseType(); + } + } + } + + return result; + } +#endif + + public static MemberSerialization GetObjectMemberSerialization(Type objectType, bool ignoreSerializableAttribute) + { + JsonObjectAttribute objectAttribute = GetCachedAttribute(objectType); + if (objectAttribute != null) + { + return objectAttribute.MemberSerialization; + } + +#if !NET20 + DataContractAttribute dataContractAttribute = GetDataContractAttribute(objectType); + if (dataContractAttribute != null) + { + return MemberSerialization.OptIn; + } +#endif + +#if !(DOTNET || PORTABLE40 || PORTABLE) + if (!ignoreSerializableAttribute) + { + SerializableAttribute serializableAttribute = GetCachedAttribute(objectType); + if (serializableAttribute != null) + { + return MemberSerialization.Fields; + } + } +#endif + + // the default + return MemberSerialization.OptOut; + } + + public static JsonConverter GetJsonConverter(object attributeProvider) + { + JsonConverterAttribute converterAttribute = GetCachedAttribute(attributeProvider); + + if (converterAttribute != null) + { + Func creator = JsonConverterCreatorCache.Get(converterAttribute.ConverterType); + if (creator != null) + { + return creator(converterAttribute.ConverterParameters); + } + } + + return null; + } + + /// + /// Lookup and create an instance of the JsonConverter type described by the argument. + /// + /// The JsonConverter type to create. + /// Optional arguments to pass to an initializing constructor of the JsonConverter. + /// If null, the default constructor is used. + public static JsonConverter CreateJsonConverterInstance(Type converterType, object[] converterArgs) + { + Func converterCreator = JsonConverterCreatorCache.Get(converterType); + return converterCreator(converterArgs); + } + + /// + /// Create a factory function that can be used to create instances of a JsonConverter described by the + /// argument type. The returned function can then be used to either invoke the converter's default ctor, or any + /// parameterized constructors by way of an object array. + /// + private static Func GetJsonConverterCreator(Type converterType) + { + Func defaultConstructor = (ReflectionUtils.HasDefaultConstructor(converterType, false)) + ? ReflectionDelegateFactory.CreateDefaultConstructor(converterType) + : null; + + return (parameters) => + { + try + { + if (parameters != null) + { + ObjectConstructor parameterizedConstructor = null; + Type[] paramTypes = parameters.Select(param => param.GetType()).ToArray(); + ConstructorInfo parameterizedConstructorInfo = converterType.GetConstructor(paramTypes); + + if (null != parameterizedConstructorInfo) + { + parameterizedConstructor = ReflectionDelegateFactory.CreateParameterizedConstructor(parameterizedConstructorInfo); + return (JsonConverter)parameterizedConstructor(parameters); + } + else + { + throw new JsonException("No matching parameterized constructor found for '{0}'.".FormatWith(CultureInfo.InvariantCulture, converterType)); + } + } + + if (defaultConstructor == null) + { + throw new JsonException("No parameterless constructor defined for '{0}'.".FormatWith(CultureInfo.InvariantCulture, converterType)); + } + + return (JsonConverter)defaultConstructor(); + } + catch (Exception ex) + { + throw new JsonException("Error creating '{0}'.".FormatWith(CultureInfo.InvariantCulture, converterType), ex); + } + }; + } + +#if !(PORTABLE40 || PORTABLE) + public static TypeConverter GetTypeConverter(Type type) + { + return TypeDescriptor.GetConverter(type); + } +#endif + +#if !(NET20 || DOTNET) + private static Type GetAssociatedMetadataType(Type type) + { + return AssociatedMetadataTypesCache.Get(type); + } + + private static Type GetAssociateMetadataTypeFromAttribute(Type type) + { + Attribute[] customAttributes = ReflectionUtils.GetAttributes(type, null, true); + + foreach (Attribute attribute in customAttributes) + { + Type attributeType = attribute.GetType(); + + // only test on attribute type name + // attribute assembly could change because of type forwarding, etc + if (string.Equals(attributeType.FullName, "System.ComponentModel.DataAnnotations.MetadataTypeAttribute", StringComparison.Ordinal)) + { + const string metadataClassTypeName = "MetadataClassType"; + + if (_metadataTypeAttributeReflectionObject == null) + { + _metadataTypeAttributeReflectionObject = ReflectionObject.Create(attributeType, metadataClassTypeName); + } + + return (Type)_metadataTypeAttributeReflectionObject.GetValue(attribute, metadataClassTypeName); + } + } + + return null; + } +#endif + + private static T GetAttribute(Type type) where T : Attribute + { + T attribute; + +#if !(NET20 || DOTNET) + Type metadataType = GetAssociatedMetadataType(type); + if (metadataType != null) + { + attribute = ReflectionUtils.GetAttribute(metadataType, true); + if (attribute != null) + { + return attribute; + } + } +#endif + + attribute = ReflectionUtils.GetAttribute(type, true); + if (attribute != null) + { + return attribute; + } + + foreach (Type typeInterface in type.GetInterfaces()) + { + attribute = ReflectionUtils.GetAttribute(typeInterface, true); + if (attribute != null) + { + return attribute; + } + } + + return null; + } + + private static T GetAttribute(MemberInfo memberInfo) where T : Attribute + { + T attribute; + +#if !(NET20 || DOTNET) + Type metadataType = GetAssociatedMetadataType(memberInfo.DeclaringType); + if (metadataType != null) + { + MemberInfo metadataTypeMemberInfo = ReflectionUtils.GetMemberInfoFromType(metadataType, memberInfo); + + if (metadataTypeMemberInfo != null) + { + attribute = ReflectionUtils.GetAttribute(metadataTypeMemberInfo, true); + if (attribute != null) + { + return attribute; + } + } + } +#endif + + attribute = ReflectionUtils.GetAttribute(memberInfo, true); + if (attribute != null) + { + return attribute; + } + + if (memberInfo.DeclaringType != null) + { + foreach (Type typeInterface in memberInfo.DeclaringType.GetInterfaces()) + { + MemberInfo interfaceTypeMemberInfo = ReflectionUtils.GetMemberInfoFromType(typeInterface, memberInfo); + + if (interfaceTypeMemberInfo != null) + { + attribute = ReflectionUtils.GetAttribute(interfaceTypeMemberInfo, true); + if (attribute != null) + { + return attribute; + } + } + } + } + + return null; + } + + public static T GetAttribute(object provider) where T : Attribute + { + Type type = provider as Type; + if (type != null) + { + return GetAttribute(type); + } + + MemberInfo memberInfo = provider as MemberInfo; + if (memberInfo != null) + { + return GetAttribute(memberInfo); + } + + return ReflectionUtils.GetAttribute(provider, true); + } + +#if DEBUG + internal static void SetFullyTrusted(bool fullyTrusted) + { + _fullyTrusted = fullyTrusted; + } + + internal static void SetDynamicCodeGeneration(bool dynamicCodeGeneration) + { + _dynamicCodeGeneration = dynamicCodeGeneration; + } +#endif + + public static bool DynamicCodeGeneration + { +#if !(NET20 || NET35 || PORTABLE) + [SecuritySafeCritical] +#endif + get + { + if (_dynamicCodeGeneration == null) + { +#if !(DOTNET || PORTABLE40 || PORTABLE) + try + { + new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Demand(); + new ReflectionPermission(ReflectionPermissionFlag.RestrictedMemberAccess).Demand(); + new SecurityPermission(SecurityPermissionFlag.SkipVerification).Demand(); + new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand(); + new SecurityPermission(PermissionState.Unrestricted).Demand(); + _dynamicCodeGeneration = true; + } + catch (Exception) + { + _dynamicCodeGeneration = false; + } +#else + _dynamicCodeGeneration = false; +#endif + } + + return _dynamicCodeGeneration.GetValueOrDefault(); + } + } + + public static bool FullyTrusted + { + get + { + if (_fullyTrusted == null) + { +#if (DOTNET || PORTABLE || PORTABLE40) + _fullyTrusted = false; +#elif !(NET20 || NET35 || PORTABLE40) + AppDomain appDomain = AppDomain.CurrentDomain; + + _fullyTrusted = appDomain.IsHomogenous && appDomain.IsFullyTrusted; +#else + try + { + new SecurityPermission(PermissionState.Unrestricted).Demand(); + _fullyTrusted = true; + } + catch (Exception) + { + _fullyTrusted = false; + } +#endif + } + + return _fullyTrusted.GetValueOrDefault(); + } + } + + public static ReflectionDelegateFactory ReflectionDelegateFactory + { + get + { +#if !(PORTABLE40 || PORTABLE || DOTNET) + if (DynamicCodeGeneration) + { + return DynamicReflectionDelegateFactory.Instance; + } + + return LateBoundReflectionDelegateFactory.Instance; +#else + return ExpressionReflectionDelegateFactory.Instance; +#endif + } + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Serialization/MemoryTraceWriter.cs b/Common/00-1Json8.3/Json8.3/Serialization/MemoryTraceWriter.cs new file mode 100644 index 0000000..7581216 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Serialization/MemoryTraceWriter.cs @@ -0,0 +1,90 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Globalization; +using System.Text; + +namespace Newtonsoft.Json.Serialization +{ + /// + /// Represents a trace writer that writes to memory. When the trace message limit is + /// reached then old trace messages will be removed as new messages are added. + /// + public class MemoryTraceWriter : ITraceWriter + { + private readonly Queue _traceMessages; + + /// + /// Gets the that will be used to filter the trace messages passed to the writer. + /// For example a filter level of Info will exclude Verbose messages and include Info, + /// Warning and Error messages. + /// + /// + /// The that will be used to filter the trace messages passed to the writer. + /// + public TraceLevel LevelFilter { get; set; } + + /// + /// Initializes a new instance of the class. + /// + public MemoryTraceWriter() + { + LevelFilter = TraceLevel.Verbose; + _traceMessages = new Queue(); + } + + /// + /// Writes the specified trace level, message and optional exception. + /// + /// The at which to write this trace. + /// The trace message. + /// The trace exception. This parameter is optional. + public void Trace(TraceLevel level, string message, Exception ex) + { + if (_traceMessages.Count >= 1000) + { + _traceMessages.Dequeue(); + } + + StringBuilder sb = new StringBuilder(); + sb.Append(DateTime.Now.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff", CultureInfo.InvariantCulture)); + sb.Append(" "); + sb.Append(level.ToString("g")); + sb.Append(" "); + sb.Append(message); + + _traceMessages.Enqueue(sb.ToString()); + } + + /// + /// Returns an enumeration of the most recent trace messages. + /// + /// An enumeration of the most recent trace messages. + public IEnumerable GetTraceMessages() + { + return _traceMessages; + } + + /// + /// Returns a of the most recent trace messages. + /// + /// + /// A of the most recent trace messages. + /// + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + foreach (string traceMessage in _traceMessages) + { + if (sb.Length > 0) + { + sb.AppendLine(); + } + + sb.Append(traceMessage); + } + + return sb.ToString(); + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Serialization/ObjectConstructor.cs b/Common/00-1Json8.3/Json8.3/Serialization/ObjectConstructor.cs new file mode 100644 index 0000000..380674f --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Serialization/ObjectConstructor.cs @@ -0,0 +1,33 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +namespace Newtonsoft.Json.Serialization +{ + /// + /// Represents a method that constructs an object. + /// + /// The object type to create. + public delegate object ObjectConstructor(params object[] args); +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Serialization/OnErrorAttribute.cs b/Common/00-1Json8.3/Json8.3/Serialization/OnErrorAttribute.cs new file mode 100644 index 0000000..cb33296 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Serialization/OnErrorAttribute.cs @@ -0,0 +1,37 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; + +namespace Newtonsoft.Json.Serialization +{ + /// + /// When applied to a method, specifies that the method is called when an error occurs serializing an object. + /// + [AttributeUsage(AttributeTargets.Method, Inherited = false)] + public sealed class OnErrorAttribute : Attribute + { + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Serialization/ReflectionAttributeProvider.cs b/Common/00-1Json8.3/Json8.3/Serialization/ReflectionAttributeProvider.cs new file mode 100644 index 0000000..5e9bc4e --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Serialization/ReflectionAttributeProvider.cs @@ -0,0 +1,71 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Collections.Generic; +using System.Reflection; +using Newtonsoft.Json.Utilities; + +namespace Newtonsoft.Json.Serialization +{ + /// + /// Provides methods to get attributes from a , , or . + /// + public class ReflectionAttributeProvider : IAttributeProvider + { + private readonly object _attributeProvider; + + /// + /// Initializes a new instance of the class. + /// + /// The instance to get attributes for. This parameter should be a , , or . + public ReflectionAttributeProvider(object attributeProvider) + { + ValidationUtils.ArgumentNotNull(attributeProvider, nameof(attributeProvider)); + _attributeProvider = attributeProvider; + } + + /// + /// Returns a collection of all of the attributes, or an empty collection if there are no attributes. + /// + /// When true, look up the hierarchy chain for the inherited custom attribute. + /// A collection of s, or an empty collection. + public IList GetAttributes(bool inherit) + { + return ReflectionUtils.GetAttributes(_attributeProvider, null, inherit); + } + + /// + /// Returns a collection of attributes, identified by type, or an empty collection if there are no attributes. + /// + /// The type of the attributes. + /// When true, look up the hierarchy chain for the inherited custom attribute. + /// A collection of s, or an empty collection. + public IList GetAttributes(Type attributeType, bool inherit) + { + return ReflectionUtils.GetAttributes(_attributeProvider, attributeType, inherit); + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Serialization/ReflectionValueProvider.cs b/Common/00-1Json8.3/Json8.3/Serialization/ReflectionValueProvider.cs new file mode 100644 index 0000000..93af29e --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Serialization/ReflectionValueProvider.cs @@ -0,0 +1,84 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Reflection; +using Newtonsoft.Json.Utilities; +using System.Globalization; + +namespace Newtonsoft.Json.Serialization +{ + /// + /// Get and set values for a using reflection. + /// + public class ReflectionValueProvider : IValueProvider + { + private readonly MemberInfo _memberInfo; + + /// + /// Initializes a new instance of the class. + /// + /// The member info. + public ReflectionValueProvider(MemberInfo memberInfo) + { + ValidationUtils.ArgumentNotNull(memberInfo, nameof(memberInfo)); + _memberInfo = memberInfo; + } + + /// + /// Sets the value. + /// + /// The target to set the value on. + /// The value to set on the target. + public void SetValue(object target, object value) + { + try + { + ReflectionUtils.SetMemberValue(_memberInfo, target, value); + } + catch (Exception ex) + { + throw new JsonSerializationException("Error setting value to '{0}' on '{1}'.".FormatWith(CultureInfo.InvariantCulture, _memberInfo.Name, target.GetType()), ex); + } + } + + /// + /// Gets the value. + /// + /// The target to get the value from. + /// The value. + public object GetValue(object target) + { + try + { + return ReflectionUtils.GetMemberValue(_memberInfo, target); + } + catch (Exception ex) + { + throw new JsonSerializationException("Error getting value from '{0}' on '{1}'.".FormatWith(CultureInfo.InvariantCulture, _memberInfo.Name, target.GetType()), ex); + } + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Serialization/TraceJsonReader.cs b/Common/00-1Json8.3/Json8.3/Serialization/TraceJsonReader.cs new file mode 100644 index 0000000..78b389e --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Serialization/TraceJsonReader.cs @@ -0,0 +1,157 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Text; + +namespace Newtonsoft.Json.Serialization +{ + internal class TraceJsonReader : JsonReader, IJsonLineInfo + { + private readonly JsonReader _innerReader; + private readonly JsonTextWriter _textWriter; + private readonly StringWriter _sw; + + public TraceJsonReader(JsonReader innerReader) + { + _innerReader = innerReader; + + _sw = new StringWriter(CultureInfo.InvariantCulture); + // prefix the message in the stringwriter to avoid concat with a potentially large JSON string + _sw.Write("Deserialized JSON: " + Environment.NewLine); + + _textWriter = new JsonTextWriter(_sw); + _textWriter.Formatting = Formatting.Indented; + } + + public string GetDeserializedJsonMessage() + { + return _sw.ToString(); + } + + public override bool Read() + { + var value = _innerReader.Read(); + _textWriter.WriteToken(_innerReader, false, false, true); + return value; + } + + public override int? ReadAsInt32() + { + var value = _innerReader.ReadAsInt32(); + _textWriter.WriteToken(_innerReader, false, false, true); + return value; + } + + public override string ReadAsString() + { + var value = _innerReader.ReadAsString(); + _textWriter.WriteToken(_innerReader, false, false, true); + return value; + } + + public override byte[] ReadAsBytes() + { + var value = _innerReader.ReadAsBytes(); + _textWriter.WriteToken(_innerReader, false, false, true); + return value; + } + + public override decimal? ReadAsDecimal() + { + var value = _innerReader.ReadAsDecimal(); + _textWriter.WriteToken(_innerReader, false, false, true); + return value; + } + + public override double? ReadAsDouble() + { + var value = _innerReader.ReadAsDouble(); + _textWriter.WriteToken(_innerReader, false, false, true); + return value; + } + + public override bool? ReadAsBoolean() + { + var value = _innerReader.ReadAsBoolean(); + _textWriter.WriteToken(_innerReader, false, false, true); + return value; + } + + public override DateTime? ReadAsDateTime() + { + var value = _innerReader.ReadAsDateTime(); + _textWriter.WriteToken(_innerReader, false, false, true); + return value; + } + +#if !NET20 + public override DateTimeOffset? ReadAsDateTimeOffset() + { + var value = _innerReader.ReadAsDateTimeOffset(); + _textWriter.WriteToken(_innerReader, false, false, true); + return value; + } +#endif + + public override int Depth + { + get { return _innerReader.Depth; } + } + + public override string Path + { + get { return _innerReader.Path; } + } + + public override char QuoteChar + { + get { return _innerReader.QuoteChar; } + protected internal set { _innerReader.QuoteChar = value; } + } + + public override JsonToken TokenType + { + get { return _innerReader.TokenType; } + } + + public override object Value + { + get { return _innerReader.Value; } + } + + public override Type ValueType + { + get { return _innerReader.ValueType; } + } + + public override void Close() + { + _innerReader.Close(); + } + + bool IJsonLineInfo.HasLineInfo() + { + IJsonLineInfo lineInfo = _innerReader as IJsonLineInfo; + return lineInfo != null && lineInfo.HasLineInfo(); + } + + int IJsonLineInfo.LineNumber + { + get + { + IJsonLineInfo lineInfo = _innerReader as IJsonLineInfo; + return (lineInfo != null) ? lineInfo.LineNumber : 0; + } + } + + int IJsonLineInfo.LinePosition + { + get + { + IJsonLineInfo lineInfo = _innerReader as IJsonLineInfo; + return (lineInfo != null) ? lineInfo.LinePosition : 0; + } + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Serialization/TraceJsonWriter.cs b/Common/00-1Json8.3/Json8.3/Serialization/TraceJsonWriter.cs new file mode 100644 index 0000000..0d38434 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Serialization/TraceJsonWriter.cs @@ -0,0 +1,322 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +#if !(NET20 || NET35 || PORTABLE || PORTABLE40) +using System.Numerics; +#endif +using System.Text; + +namespace Newtonsoft.Json.Serialization +{ + internal class TraceJsonWriter : JsonWriter + { + private readonly JsonWriter _innerWriter; + private readonly JsonTextWriter _textWriter; + private readonly StringWriter _sw; + + public TraceJsonWriter(JsonWriter innerWriter) + { + _innerWriter = innerWriter; + + _sw = new StringWriter(CultureInfo.InvariantCulture); + // prefix the message in the stringwriter to avoid concat with a potentially large JSON string + _sw.Write("Serialized JSON: " + Environment.NewLine); + + _textWriter = new JsonTextWriter(_sw); + _textWriter.Formatting = Formatting.Indented; + _textWriter.Culture = innerWriter.Culture; + _textWriter.DateFormatHandling = innerWriter.DateFormatHandling; + _textWriter.DateFormatString = innerWriter.DateFormatString; + _textWriter.DateTimeZoneHandling = innerWriter.DateTimeZoneHandling; + _textWriter.FloatFormatHandling = innerWriter.FloatFormatHandling; + } + + public string GetSerializedJsonMessage() + { + return _sw.ToString(); + } + + public override void WriteValue(decimal value) + { + _textWriter.WriteValue(value); + _innerWriter.WriteValue(value); + base.WriteValue(value); + } + + public override void WriteValue(bool value) + { + _textWriter.WriteValue(value); + _innerWriter.WriteValue(value); + base.WriteValue(value); + } + + public override void WriteValue(byte value) + { + _textWriter.WriteValue(value); + _innerWriter.WriteValue(value); + base.WriteValue(value); + } + + public override void WriteValue(byte? value) + { + _textWriter.WriteValue(value); + _innerWriter.WriteValue(value); + base.WriteValue(value); + } + + public override void WriteValue(char value) + { + _textWriter.WriteValue(value); + _innerWriter.WriteValue(value); + base.WriteValue(value); + } + + public override void WriteValue(byte[] value) + { + _textWriter.WriteValue(value); + _innerWriter.WriteValue(value); + base.WriteValue(value); + } + + public override void WriteValue(DateTime value) + { + _textWriter.WriteValue(value); + _innerWriter.WriteValue(value); + base.WriteValue(value); + } + +#if !NET20 + public override void WriteValue(DateTimeOffset value) + { + _textWriter.WriteValue(value); + _innerWriter.WriteValue(value); + base.WriteValue(value); + } +#endif + + public override void WriteValue(double value) + { + _textWriter.WriteValue(value); + _innerWriter.WriteValue(value); + base.WriteValue(value); + } + + public override void WriteUndefined() + { + _textWriter.WriteUndefined(); + _innerWriter.WriteUndefined(); + base.WriteUndefined(); + } + + public override void WriteNull() + { + _textWriter.WriteNull(); + _innerWriter.WriteNull(); + base.WriteUndefined(); + } + + public override void WriteValue(float value) + { + _textWriter.WriteValue(value); + _innerWriter.WriteValue(value); + base.WriteValue(value); + } + + public override void WriteValue(Guid value) + { + _textWriter.WriteValue(value); + _innerWriter.WriteValue(value); + base.WriteValue(value); + } + + public override void WriteValue(int value) + { + _textWriter.WriteValue(value); + _innerWriter.WriteValue(value); + base.WriteValue(value); + } + + public override void WriteValue(long value) + { + _textWriter.WriteValue(value); + _innerWriter.WriteValue(value); + base.WriteValue(value); + } + + public override void WriteValue(object value) + { +#if !(NET20 || NET35 || PORTABLE || PORTABLE40) + if (value is BigInteger) + { + _textWriter.WriteValue(value); + _innerWriter.WriteValue(value); + InternalWriteValue(JsonToken.Integer); + } + else +#endif + { + _textWriter.WriteValue(value); + _innerWriter.WriteValue(value); + base.WriteValue(value); + } + } + + public override void WriteValue(sbyte value) + { + _textWriter.WriteValue(value); + _innerWriter.WriteValue(value); + base.WriteValue(value); + } + + public override void WriteValue(short value) + { + _textWriter.WriteValue(value); + _innerWriter.WriteValue(value); + base.WriteValue(value); + } + + public override void WriteValue(string value) + { + _textWriter.WriteValue(value); + _innerWriter.WriteValue(value); + base.WriteValue(value); + } + + public override void WriteValue(TimeSpan value) + { + _textWriter.WriteValue(value); + _innerWriter.WriteValue(value); + base.WriteValue(value); + } + + public override void WriteValue(uint value) + { + _textWriter.WriteValue(value); + _innerWriter.WriteValue(value); + base.WriteValue(value); + } + + public override void WriteValue(ulong value) + { + _textWriter.WriteValue(value); + _innerWriter.WriteValue(value); + base.WriteValue(value); + } + + public override void WriteValue(Uri value) + { + _textWriter.WriteValue(value); + _innerWriter.WriteValue(value); + base.WriteValue(value); + } + + public override void WriteValue(ushort value) + { + _textWriter.WriteValue(value); + _innerWriter.WriteValue(value); + base.WriteValue(value); + } + + public override void WriteWhitespace(string ws) + { + _textWriter.WriteWhitespace(ws); + _innerWriter.WriteWhitespace(ws); + base.WriteWhitespace(ws); + } + + public override void WriteComment(string text) + { + _textWriter.WriteComment(text); + _innerWriter.WriteComment(text); + base.WriteComment(text); + } + + public override void WriteStartArray() + { + _textWriter.WriteStartArray(); + _innerWriter.WriteStartArray(); + base.WriteStartArray(); + } + + public override void WriteEndArray() + { + _textWriter.WriteEndArray(); + _innerWriter.WriteEndArray(); + base.WriteEndArray(); + } + + public override void WriteStartConstructor(string name) + { + _textWriter.WriteStartConstructor(name); + _innerWriter.WriteStartConstructor(name); + base.WriteStartConstructor(name); + } + + public override void WriteEndConstructor() + { + _textWriter.WriteEndConstructor(); + _innerWriter.WriteEndConstructor(); + base.WriteEndConstructor(); + } + + public override void WritePropertyName(string name) + { + _textWriter.WritePropertyName(name); + _innerWriter.WritePropertyName(name); + base.WritePropertyName(name); + } + + public override void WritePropertyName(string name, bool escape) + { + _textWriter.WritePropertyName(name, escape); + _innerWriter.WritePropertyName(name, escape); + + // method with escape will error + base.WritePropertyName(name); + } + + public override void WriteStartObject() + { + _textWriter.WriteStartObject(); + _innerWriter.WriteStartObject(); + base.WriteStartObject(); + } + + public override void WriteEndObject() + { + _textWriter.WriteEndObject(); + _innerWriter.WriteEndObject(); + base.WriteEndObject(); + } + + public override void WriteRawValue(string json) + { + _textWriter.WriteRawValue(json); + _innerWriter.WriteRawValue(json); + + // calling base method will write json twice + InternalWriteValue(JsonToken.Undefined); + } + + public override void WriteRaw(string json) + { + _textWriter.WriteRaw(json); + _innerWriter.WriteRaw(json); + base.WriteRaw(json); + } + + public override void Close() + { + _textWriter.Close(); + _innerWriter.Close(); + base.Close(); + } + + public override void Flush() + { + _textWriter.Flush(); + _innerWriter.Flush(); + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/StringEscapeHandling.cs b/Common/00-1Json8.3/Json8.3/StringEscapeHandling.cs new file mode 100644 index 0000000..4016eb6 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/StringEscapeHandling.cs @@ -0,0 +1,48 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +namespace Newtonsoft.Json +{ + /// + /// Specifies how strings are escaped when writing JSON text. + /// + public enum StringEscapeHandling + { + /// + /// Only control characters (e.g. newline) are escaped. + /// + Default = 0, + + /// + /// All non-ASCII and control characters (e.g. newline) are escaped. + /// + EscapeNonAscii = 1, + + /// + /// HTML (<, >, &, ', ") and control characters (e.g. newline) are escaped. + /// + EscapeHtml = 2 + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/TypeNameHandling.cs b/Common/00-1Json8.3/Json8.3/TypeNameHandling.cs new file mode 100644 index 0000000..9a5a8cf --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/TypeNameHandling.cs @@ -0,0 +1,67 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Runtime.Serialization; + +namespace Newtonsoft.Json +{ + /// + /// Specifies type name handling options for the . + /// + /// + /// should be used with caution when your application deserializes JSON from an external source. + /// Incoming types should be validated with a custom + /// when deserializing with a value other than TypeNameHandling.None. + /// + [Flags] + public enum TypeNameHandling + { + /// + /// Do not include the .NET type name when serializing types. + /// + None = 0, + + /// + /// Include the .NET type name when serializing into a JSON object structure. + /// + Objects = 1, + + /// + /// Include the .NET type name when serializing into a JSON array structure. + /// + Arrays = 2, + + /// + /// Always include the .NET type name when serializing. + /// + All = Objects | Arrays, + + /// + /// Include the .NET type name when the type of the object being serialized is not the same as its declared type. + /// + Auto = 4 + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Utilities/Base64Encoder.cs b/Common/00-1Json8.3/Json8.3/Utilities/Base64Encoder.cs new file mode 100644 index 0000000..8f298d1 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Utilities/Base64Encoder.cs @@ -0,0 +1,128 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.IO; + +namespace Newtonsoft.Json.Utilities +{ + internal class Base64Encoder + { + private const int Base64LineSize = 76; + private const int LineSizeInBytes = 57; + + private readonly char[] _charsLine = new char[Base64LineSize]; + private readonly TextWriter _writer; + + private byte[] _leftOverBytes; + private int _leftOverBytesCount; + + public Base64Encoder(TextWriter writer) + { + ValidationUtils.ArgumentNotNull(writer, nameof(writer)); + _writer = writer; + } + + public void Encode(byte[] buffer, int index, int count) + { + if (buffer == null) + { + throw new ArgumentNullException(nameof(buffer)); + } + + if (index < 0) + { + throw new ArgumentOutOfRangeException(nameof(index)); + } + + if (count < 0) + { + throw new ArgumentOutOfRangeException(nameof(count)); + } + + if (count > (buffer.Length - index)) + { + throw new ArgumentOutOfRangeException(nameof(count)); + } + + if (_leftOverBytesCount > 0) + { + int leftOverBytesCount = _leftOverBytesCount; + while (leftOverBytesCount < 3 && count > 0) + { + _leftOverBytes[leftOverBytesCount++] = buffer[index++]; + count--; + } + if (count == 0 && leftOverBytesCount < 3) + { + _leftOverBytesCount = leftOverBytesCount; + return; + } + int num2 = Convert.ToBase64CharArray(_leftOverBytes, 0, 3, _charsLine, 0); + WriteChars(_charsLine, 0, num2); + } + _leftOverBytesCount = count % 3; + if (_leftOverBytesCount > 0) + { + count -= _leftOverBytesCount; + if (_leftOverBytes == null) + { + _leftOverBytes = new byte[3]; + } + for (int i = 0; i < _leftOverBytesCount; i++) + { + _leftOverBytes[i] = buffer[(index + count) + i]; + } + } + int num4 = index + count; + int length = LineSizeInBytes; + while (index < num4) + { + if ((index + length) > num4) + { + length = num4 - index; + } + int num6 = Convert.ToBase64CharArray(buffer, index, length, _charsLine, 0); + WriteChars(_charsLine, 0, num6); + index += length; + } + } + + public void Flush() + { + if (_leftOverBytesCount > 0) + { + int count = Convert.ToBase64CharArray(_leftOverBytes, 0, _leftOverBytesCount, _charsLine, 0); + WriteChars(_charsLine, 0, count); + _leftOverBytesCount = 0; + } + } + + private void WriteChars(char[] chars, int index, int count) + { + _writer.Write(chars, index, count); + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Utilities/BidirectionalDictionary.cs b/Common/00-1Json8.3/Json8.3/Utilities/BidirectionalDictionary.cs new file mode 100644 index 0000000..b72d56c --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Utilities/BidirectionalDictionary.cs @@ -0,0 +1,97 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Collections.Generic; +using System.Globalization; + +namespace Newtonsoft.Json.Utilities +{ + internal class BidirectionalDictionary + { + private readonly IDictionary _firstToSecond; + private readonly IDictionary _secondToFirst; + private readonly string _duplicateFirstErrorMessage; + private readonly string _duplicateSecondErrorMessage; + + public BidirectionalDictionary() + : this(EqualityComparer.Default, EqualityComparer.Default) + { + } + + public BidirectionalDictionary(IEqualityComparer firstEqualityComparer, IEqualityComparer secondEqualityComparer) + : this( + firstEqualityComparer, + secondEqualityComparer, + "Duplicate item already exists for '{0}'.", + "Duplicate item already exists for '{0}'.") + { + } + + public BidirectionalDictionary(IEqualityComparer firstEqualityComparer, IEqualityComparer secondEqualityComparer, + string duplicateFirstErrorMessage, string duplicateSecondErrorMessage) + { + _firstToSecond = new Dictionary(firstEqualityComparer); + _secondToFirst = new Dictionary(secondEqualityComparer); + _duplicateFirstErrorMessage = duplicateFirstErrorMessage; + _duplicateSecondErrorMessage = duplicateSecondErrorMessage; + } + + public void Set(TFirst first, TSecond second) + { + TFirst existingFirst; + TSecond existingSecond; + + if (_firstToSecond.TryGetValue(first, out existingSecond)) + { + if (!existingSecond.Equals(second)) + { + throw new ArgumentException(_duplicateFirstErrorMessage.FormatWith(CultureInfo.InvariantCulture, first)); + } + } + + if (_secondToFirst.TryGetValue(second, out existingFirst)) + { + if (!existingFirst.Equals(first)) + { + throw new ArgumentException(_duplicateSecondErrorMessage.FormatWith(CultureInfo.InvariantCulture, second)); + } + } + + _firstToSecond.Add(first, second); + _secondToFirst.Add(second, first); + } + + public bool TryGetByFirst(TFirst first, out TSecond second) + { + return _firstToSecond.TryGetValue(first, out second); + } + + public bool TryGetBySecond(TSecond second, out TFirst first) + { + return _secondToFirst.TryGetValue(second, out first); + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Utilities/CollectionUtils.cs b/Common/00-1Json8.3/Json8.3/Utilities/CollectionUtils.cs new file mode 100644 index 0000000..2074b34 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Utilities/CollectionUtils.cs @@ -0,0 +1,348 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Reflection; +using System.Text; +using System.Collections; +#if NET20 +using Newtonsoft.Json.Utilities.LinqBridge; +#else +using System.Linq; +#endif +using System.Globalization; +using Newtonsoft.Json.Serialization; + +namespace Newtonsoft.Json.Utilities +{ + internal static class CollectionUtils + { + /// + /// Determines whether the collection is null or empty. + /// + /// The collection. + /// + /// true if the collection is null or empty; otherwise, false. + /// + public static bool IsNullOrEmpty(ICollection collection) + { + if (collection != null) + { + return (collection.Count == 0); + } + return true; + } + + /// + /// Adds the elements of the specified collection to the specified generic IList. + /// + /// The list to add to. + /// The collection of elements to add. + public static void AddRange(this IList initial, IEnumerable collection) + { + if (initial == null) + { + throw new ArgumentNullException(nameof(initial)); + } + + if (collection == null) + { + return; + } + + foreach (T value in collection) + { + initial.Add(value); + } + } + +#if (NET20 || NET35 || PORTABLE40) + public static void AddRange(this IList initial, IEnumerable collection) + { + ValidationUtils.ArgumentNotNull(initial, nameof(initial)); + + // because earlier versions of .NET didn't support covariant generics + initial.AddRange(collection.Cast()); + } +#endif + + public static bool IsDictionaryType(Type type) + { + ValidationUtils.ArgumentNotNull(type, nameof(type)); + + if (typeof(IDictionary).IsAssignableFrom(type)) + { + return true; + } + if (ReflectionUtils.ImplementsGenericDefinition(type, typeof(IDictionary<,>))) + { + return true; + } +#if !(NET40 || NET35 || NET20 || PORTABLE40) + if (ReflectionUtils.ImplementsGenericDefinition(type, typeof(IReadOnlyDictionary<,>))) + { + return true; + } +#endif + + return false; + } + + public static ConstructorInfo ResolveEnumerableCollectionConstructor(Type collectionType, Type collectionItemType) + { + Type genericEnumerable = typeof(IEnumerable<>).MakeGenericType(collectionItemType); + ConstructorInfo match = null; + + foreach (ConstructorInfo constructor in collectionType.GetConstructors(BindingFlags.Public | BindingFlags.Instance)) + { + IList parameters = constructor.GetParameters(); + + if (parameters.Count == 1) + { + if (genericEnumerable == parameters[0].ParameterType) + { + // exact match + match = constructor; + break; + } + + // incase we can't find an exact match, use first inexact + if (match == null) + { + if (genericEnumerable.IsAssignableFrom(parameters[0].ParameterType)) + { + match = constructor; + } + } + } + } + + return match; + } + + public static bool AddDistinct(this IList list, T value) + { + return list.AddDistinct(value, EqualityComparer.Default); + } + + public static bool AddDistinct(this IList list, T value, IEqualityComparer comparer) + { + if (list.ContainsValue(value, comparer)) + { + return false; + } + + list.Add(value); + return true; + } + + // this is here because LINQ Bridge doesn't support Contains with IEqualityComparer + public static bool ContainsValue(this IEnumerable source, TSource value, IEqualityComparer comparer) + { + if (comparer == null) + { + comparer = EqualityComparer.Default; + } + + if (source == null) + { + throw new ArgumentNullException(nameof(source)); + } + + foreach (TSource local in source) + { + if (comparer.Equals(local, value)) + { + return true; + } + } + + return false; + } + + public static bool AddRangeDistinct(this IList list, IEnumerable values, IEqualityComparer comparer) + { + bool allAdded = true; + foreach (T value in values) + { + if (!list.AddDistinct(value, comparer)) + { + allAdded = false; + } + } + + return allAdded; + } + + public static int IndexOf(this IEnumerable collection, Func predicate) + { + int index = 0; + foreach (T value in collection) + { + if (predicate(value)) + { + return index; + } + + index++; + } + + return -1; + } + + public static bool Contains(this IEnumerable list, object value, IEqualityComparer comparer) + { + foreach (object item in list) + { + if (comparer.Equals(item, value)) + { + return true; + } + } + return false; + } + + /// + /// Returns the index of the first occurrence in a sequence by using a specified IEqualityComparer{TSource}. + /// + /// The type of the elements of source. + /// A sequence in which to locate a value. + /// The object to locate in the sequence + /// An equality comparer to compare values. + /// The zero-based index of the first occurrence of value within the entire sequence, if found; otherwise, ?. + public static int IndexOf(this IEnumerable list, TSource value, IEqualityComparer comparer) + { + int index = 0; + foreach (TSource item in list) + { + if (comparer.Equals(item, value)) + { + return index; + } + index++; + } + return -1; + } + + private static IList GetDimensions(IList values, int dimensionsCount) + { + IList dimensions = new List(); + + IList currentArray = values; + while (true) + { + dimensions.Add(currentArray.Count); + + // don't keep calculating dimensions for arrays inside the value array + if (dimensions.Count == dimensionsCount) + { + break; + } + + if (currentArray.Count == 0) + { + break; + } + + object v = currentArray[0]; + if (v is IList) + { + currentArray = (IList)v; + } + else + { + break; + } + } + + return dimensions; + } + + private static void CopyFromJaggedToMultidimensionalArray(IList values, Array multidimensionalArray, int[] indices) + { + int dimension = indices.Length; + if (dimension == multidimensionalArray.Rank) + { + multidimensionalArray.SetValue(JaggedArrayGetValue(values, indices), indices); + return; + } + + int dimensionLength = multidimensionalArray.GetLength(dimension); + IList list = (IList)JaggedArrayGetValue(values, indices); + int currentValuesLength = list.Count; + if (currentValuesLength != dimensionLength) + { + throw new Exception("Cannot deserialize non-cubical array as multidimensional array."); + } + + int[] newIndices = new int[dimension + 1]; + for (int i = 0; i < dimension; i++) + { + newIndices[i] = indices[i]; + } + + for (int i = 0; i < multidimensionalArray.GetLength(dimension); i++) + { + newIndices[dimension] = i; + CopyFromJaggedToMultidimensionalArray(values, multidimensionalArray, newIndices); + } + } + + private static object JaggedArrayGetValue(IList values, int[] indices) + { + IList currentList = values; + for (int i = 0; i < indices.Length; i++) + { + int index = indices[i]; + if (i == indices.Length - 1) + { + return currentList[index]; + } + else + { + currentList = (IList)currentList[index]; + } + } + return currentList; + } + + public static Array ToMultidimensionalArray(IList values, Type type, int rank) + { + IList dimensions = GetDimensions(values, rank); + + while (dimensions.Count < rank) + { + dimensions.Add(0); + } + + Array multidimensionalArray = Array.CreateInstance(type, dimensions.ToArray()); + CopyFromJaggedToMultidimensionalArray(values, multidimensionalArray, new int[0]); + + return multidimensionalArray; + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Utilities/CollectionWrapper.cs b/Common/00-1Json8.3/Json8.3/Utilities/CollectionWrapper.cs new file mode 100644 index 0000000..6afc9ac --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Utilities/CollectionWrapper.cs @@ -0,0 +1,348 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Threading; +using System.Globalization; +#if NET20 +using Newtonsoft.Json.Utilities.LinqBridge; +#else +using System.Linq; + +#endif + +namespace Newtonsoft.Json.Utilities +{ + internal interface IWrappedCollection : IList + { + object UnderlyingCollection { get; } + } + + internal class CollectionWrapper : ICollection, IWrappedCollection + { + private readonly IList _list; + private readonly ICollection _genericCollection; + private object _syncRoot; + + public CollectionWrapper(IList list) + { + ValidationUtils.ArgumentNotNull(list, nameof(list)); + + if (list is ICollection) + { + _genericCollection = (ICollection)list; + } + else + { + _list = list; + } + } + + public CollectionWrapper(ICollection list) + { + ValidationUtils.ArgumentNotNull(list, nameof(list)); + + _genericCollection = list; + } + + public virtual void Add(T item) + { + if (_genericCollection != null) + { + _genericCollection.Add(item); + } + else + { + _list.Add(item); + } + } + + public virtual void Clear() + { + if (_genericCollection != null) + { + _genericCollection.Clear(); + } + else + { + _list.Clear(); + } + } + + public virtual bool Contains(T item) + { + if (_genericCollection != null) + { + return _genericCollection.Contains(item); + } + else + { + return _list.Contains(item); + } + } + + public virtual void CopyTo(T[] array, int arrayIndex) + { + if (_genericCollection != null) + { + _genericCollection.CopyTo(array, arrayIndex); + } + else + { + _list.CopyTo(array, arrayIndex); + } + } + + public virtual int Count + { + get + { + if (_genericCollection != null) + { + return _genericCollection.Count; + } + else + { + return _list.Count; + } + } + } + + public virtual bool IsReadOnly + { + get + { + if (_genericCollection != null) + { + return _genericCollection.IsReadOnly; + } + else + { + return _list.IsReadOnly; + } + } + } + + public virtual bool Remove(T item) + { + if (_genericCollection != null) + { + return _genericCollection.Remove(item); + } + else + { + bool contains = _list.Contains(item); + + if (contains) + { + _list.Remove(item); + } + + return contains; + } + } + + public virtual IEnumerator GetEnumerator() + { + if (_genericCollection != null) + { + return _genericCollection.GetEnumerator(); + } + + return _list.Cast().GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + if (_genericCollection != null) + { + return _genericCollection.GetEnumerator(); + } + else + { + return _list.GetEnumerator(); + } + } + + int IList.Add(object value) + { + VerifyValueType(value); + Add((T)value); + + return (Count - 1); + } + + bool IList.Contains(object value) + { + if (IsCompatibleObject(value)) + { + return Contains((T)value); + } + + return false; + } + + int IList.IndexOf(object value) + { + if (_genericCollection != null) + { + throw new InvalidOperationException("Wrapped ICollection does not support IndexOf."); + } + + if (IsCompatibleObject(value)) + { + return _list.IndexOf((T)value); + } + + return -1; + } + + void IList.RemoveAt(int index) + { + if (_genericCollection != null) + { + throw new InvalidOperationException("Wrapped ICollection does not support RemoveAt."); + } + + _list.RemoveAt(index); + } + + void IList.Insert(int index, object value) + { + if (_genericCollection != null) + { + throw new InvalidOperationException("Wrapped ICollection does not support Insert."); + } + + VerifyValueType(value); + _list.Insert(index, (T)value); + } + + bool IList.IsFixedSize + { + get + { + if (_genericCollection != null) + { + // ICollection only has IsReadOnly + return _genericCollection.IsReadOnly; + } + else + { + return _list.IsFixedSize; + } + } + } + + void IList.Remove(object value) + { + if (IsCompatibleObject(value)) + { + Remove((T)value); + } + } + + object IList.this[int index] + { + get + { + if (_genericCollection != null) + { + throw new InvalidOperationException("Wrapped ICollection does not support indexer."); + } + + return _list[index]; + } + set + { + if (_genericCollection != null) + { + throw new InvalidOperationException("Wrapped ICollection does not support indexer."); + } + + VerifyValueType(value); + _list[index] = (T)value; + } + } + + void ICollection.CopyTo(Array array, int arrayIndex) + { + CopyTo((T[])array, arrayIndex); + } + + bool ICollection.IsSynchronized + { + get { return false; } + } + + object ICollection.SyncRoot + { + get + { + if (_syncRoot == null) + { + Interlocked.CompareExchange(ref _syncRoot, new object(), null); + } + + return _syncRoot; + } + } + + private static void VerifyValueType(object value) + { + if (!IsCompatibleObject(value)) + { + throw new ArgumentException("The value '{0}' is not of type '{1}' and cannot be used in this generic collection.".FormatWith(CultureInfo.InvariantCulture, value, typeof(T)), nameof(value)); + } + } + + private static bool IsCompatibleObject(object value) + { + if (!(value is T) && (value != null || (typeof(T).IsValueType() && !ReflectionUtils.IsNullableType(typeof(T))))) + { + return false; + } + + return true; + } + + public object UnderlyingCollection + { + get + { + if (_genericCollection != null) + { + return _genericCollection; + } + else + { + return _list; + } + } + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Utilities/ConvertUtils.cs b/Common/00-1Json8.3/Json8.3/Utilities/ConvertUtils.cs new file mode 100644 index 0000000..227db86 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Utilities/ConvertUtils.cs @@ -0,0 +1,987 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.ComponentModel; +#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) +using System.Numerics; +#endif +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json.Serialization; +using System.Reflection; +#if NET20 +using Newtonsoft.Json.Utilities.LinqBridge; +#endif +#if !(DOTNET || PORTABLE40 || PORTABLE) +using System.Data.SqlTypes; + +#endif + +namespace Newtonsoft.Json.Utilities +{ + internal enum PrimitiveTypeCode + { + Empty = 0, + Object = 1, + Char = 2, + CharNullable = 3, + Boolean = 4, + BooleanNullable = 5, + SByte = 6, + SByteNullable = 7, + Int16 = 8, + Int16Nullable = 9, + UInt16 = 10, + UInt16Nullable = 11, + Int32 = 12, + Int32Nullable = 13, + Byte = 14, + ByteNullable = 15, + UInt32 = 16, + UInt32Nullable = 17, + Int64 = 18, + Int64Nullable = 19, + UInt64 = 20, + UInt64Nullable = 21, + Single = 22, + SingleNullable = 23, + Double = 24, + DoubleNullable = 25, + DateTime = 26, + DateTimeNullable = 27, + DateTimeOffset = 28, + DateTimeOffsetNullable = 29, + Decimal = 30, + DecimalNullable = 31, + Guid = 32, + GuidNullable = 33, + TimeSpan = 34, + TimeSpanNullable = 35, + BigInteger = 36, + BigIntegerNullable = 37, + Uri = 38, + String = 39, + Bytes = 40, + DBNull = 41 + } + + internal class TypeInformation + { + public Type Type { get; set; } + public PrimitiveTypeCode TypeCode { get; set; } + } + + internal enum ParseResult + { + None = 0, + Success = 1, + Overflow = 2, + Invalid = 3 + } + + internal static class ConvertUtils + { + private static readonly Dictionary TypeCodeMap = + new Dictionary + { + { typeof(char), PrimitiveTypeCode.Char }, + { typeof(char?), PrimitiveTypeCode.CharNullable }, + { typeof(bool), PrimitiveTypeCode.Boolean }, + { typeof(bool?), PrimitiveTypeCode.BooleanNullable }, + { typeof(sbyte), PrimitiveTypeCode.SByte }, + { typeof(sbyte?), PrimitiveTypeCode.SByteNullable }, + { typeof(short), PrimitiveTypeCode.Int16 }, + { typeof(short?), PrimitiveTypeCode.Int16Nullable }, + { typeof(ushort), PrimitiveTypeCode.UInt16 }, + { typeof(ushort?), PrimitiveTypeCode.UInt16Nullable }, + { typeof(int), PrimitiveTypeCode.Int32 }, + { typeof(int?), PrimitiveTypeCode.Int32Nullable }, + { typeof(byte), PrimitiveTypeCode.Byte }, + { typeof(byte?), PrimitiveTypeCode.ByteNullable }, + { typeof(uint), PrimitiveTypeCode.UInt32 }, + { typeof(uint?), PrimitiveTypeCode.UInt32Nullable }, + { typeof(long), PrimitiveTypeCode.Int64 }, + { typeof(long?), PrimitiveTypeCode.Int64Nullable }, + { typeof(ulong), PrimitiveTypeCode.UInt64 }, + { typeof(ulong?), PrimitiveTypeCode.UInt64Nullable }, + { typeof(float), PrimitiveTypeCode.Single }, + { typeof(float?), PrimitiveTypeCode.SingleNullable }, + { typeof(double), PrimitiveTypeCode.Double }, + { typeof(double?), PrimitiveTypeCode.DoubleNullable }, + { typeof(DateTime), PrimitiveTypeCode.DateTime }, + { typeof(DateTime?), PrimitiveTypeCode.DateTimeNullable }, +#if !NET20 + { typeof(DateTimeOffset), PrimitiveTypeCode.DateTimeOffset }, + { typeof(DateTimeOffset?), PrimitiveTypeCode.DateTimeOffsetNullable }, +#endif + { typeof(decimal), PrimitiveTypeCode.Decimal }, + { typeof(decimal?), PrimitiveTypeCode.DecimalNullable }, + { typeof(Guid), PrimitiveTypeCode.Guid }, + { typeof(Guid?), PrimitiveTypeCode.GuidNullable }, + { typeof(TimeSpan), PrimitiveTypeCode.TimeSpan }, + { typeof(TimeSpan?), PrimitiveTypeCode.TimeSpanNullable }, +#if !(PORTABLE || PORTABLE40 || NET35 || NET20) + { typeof(BigInteger), PrimitiveTypeCode.BigInteger }, + { typeof(BigInteger?), PrimitiveTypeCode.BigIntegerNullable }, +#endif + { typeof(Uri), PrimitiveTypeCode.Uri }, + { typeof(string), PrimitiveTypeCode.String }, + { typeof(byte[]), PrimitiveTypeCode.Bytes }, +#if !(PORTABLE || PORTABLE40 || DOTNET) + { typeof(DBNull), PrimitiveTypeCode.DBNull } +#endif + }; + +#if !PORTABLE + private static readonly TypeInformation[] PrimitiveTypeCodes = + { + // need all of these. lookup against the index with TypeCode value + new TypeInformation { Type = typeof(object), TypeCode = PrimitiveTypeCode.Empty }, + new TypeInformation { Type = typeof(object), TypeCode = PrimitiveTypeCode.Object }, + new TypeInformation { Type = typeof(object), TypeCode = PrimitiveTypeCode.DBNull }, + new TypeInformation { Type = typeof(bool), TypeCode = PrimitiveTypeCode.Boolean }, + new TypeInformation { Type = typeof(char), TypeCode = PrimitiveTypeCode.Char }, + new TypeInformation { Type = typeof(sbyte), TypeCode = PrimitiveTypeCode.SByte }, + new TypeInformation { Type = typeof(byte), TypeCode = PrimitiveTypeCode.Byte }, + new TypeInformation { Type = typeof(short), TypeCode = PrimitiveTypeCode.Int16 }, + new TypeInformation { Type = typeof(ushort), TypeCode = PrimitiveTypeCode.UInt16 }, + new TypeInformation { Type = typeof(int), TypeCode = PrimitiveTypeCode.Int32 }, + new TypeInformation { Type = typeof(uint), TypeCode = PrimitiveTypeCode.UInt32 }, + new TypeInformation { Type = typeof(long), TypeCode = PrimitiveTypeCode.Int64 }, + new TypeInformation { Type = typeof(ulong), TypeCode = PrimitiveTypeCode.UInt64 }, + new TypeInformation { Type = typeof(float), TypeCode = PrimitiveTypeCode.Single }, + new TypeInformation { Type = typeof(double), TypeCode = PrimitiveTypeCode.Double }, + new TypeInformation { Type = typeof(decimal), TypeCode = PrimitiveTypeCode.Decimal }, + new TypeInformation { Type = typeof(DateTime), TypeCode = PrimitiveTypeCode.DateTime }, + new TypeInformation { Type = typeof(object), TypeCode = PrimitiveTypeCode.Empty }, // no 17 in TypeCode for some reason + new TypeInformation { Type = typeof(string), TypeCode = PrimitiveTypeCode.String } + }; +#endif + + public static PrimitiveTypeCode GetTypeCode(Type t) + { + bool isEnum; + return GetTypeCode(t, out isEnum); + } + + public static PrimitiveTypeCode GetTypeCode(Type t, out bool isEnum) + { + PrimitiveTypeCode typeCode; + if (TypeCodeMap.TryGetValue(t, out typeCode)) + { + isEnum = false; + return typeCode; + } + + if (t.IsEnum()) + { + isEnum = true; + return GetTypeCode(Enum.GetUnderlyingType(t)); + } + + // performance? + if (ReflectionUtils.IsNullableType(t)) + { + Type nonNullable = Nullable.GetUnderlyingType(t); + if (nonNullable.IsEnum()) + { + Type nullableUnderlyingType = typeof(Nullable<>).MakeGenericType(Enum.GetUnderlyingType(nonNullable)); + isEnum = true; + return GetTypeCode(nullableUnderlyingType); + } + } + + isEnum = false; + return PrimitiveTypeCode.Object; + } + +#if !PORTABLE + public static TypeInformation GetTypeInformation(IConvertible convertable) + { + TypeInformation typeInformation = PrimitiveTypeCodes[(int)convertable.GetTypeCode()]; + return typeInformation; + } +#endif + + public static bool IsConvertible(Type t) + { +#if !PORTABLE + return typeof(IConvertible).IsAssignableFrom(t); +#else + return ( + t == typeof(bool) || t == typeof(byte) || t == typeof(char) || t == typeof(DateTime) || t == typeof(decimal) || t == typeof(double) || t == typeof(short) || t == typeof(int) || + t == typeof(long) || t == typeof(sbyte) || t == typeof(float) || t == typeof(string) || t == typeof(ushort) || t == typeof(uint) || t == typeof(ulong) || t.IsEnum()); +#endif + } + + public static TimeSpan ParseTimeSpan(string input) + { +#if !(NET35 || NET20) + return TimeSpan.Parse(input, CultureInfo.InvariantCulture); +#else + return TimeSpan.Parse(input); +#endif + } + + internal struct TypeConvertKey : IEquatable + { + private readonly Type _initialType; + private readonly Type _targetType; + + public Type InitialType + { + get { return _initialType; } + } + + public Type TargetType + { + get { return _targetType; } + } + + public TypeConvertKey(Type initialType, Type targetType) + { + _initialType = initialType; + _targetType = targetType; + } + + public override int GetHashCode() + { + return _initialType.GetHashCode() ^ _targetType.GetHashCode(); + } + + public override bool Equals(object obj) + { + if (!(obj is TypeConvertKey)) + { + return false; + } + + return Equals((TypeConvertKey)obj); + } + + public bool Equals(TypeConvertKey other) + { + return (_initialType == other._initialType && _targetType == other._targetType); + } + } + + private static readonly ThreadSafeStore> CastConverters = + new ThreadSafeStore>(CreateCastConverter); + + private static Func CreateCastConverter(TypeConvertKey t) + { + MethodInfo castMethodInfo = t.TargetType.GetMethod("op_Implicit", new[] { t.InitialType }); + if (castMethodInfo == null) + { + castMethodInfo = t.TargetType.GetMethod("op_Explicit", new[] { t.InitialType }); + } + + if (castMethodInfo == null) + { + return null; + } + + MethodCall call = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall(castMethodInfo); + + return o => call(null, o); + } + +#if !(NET20 || NET35 || PORTABLE || PORTABLE40) + internal static BigInteger ToBigInteger(object value) + { + if (value is BigInteger) + { + return (BigInteger)value; + } + if (value is string) + { + return BigInteger.Parse((string)value, CultureInfo.InvariantCulture); + } + if (value is float) + { + return new BigInteger((float)value); + } + if (value is double) + { + return new BigInteger((double)value); + } + if (value is decimal) + { + return new BigInteger((decimal)value); + } + if (value is int) + { + return new BigInteger((int)value); + } + if (value is long) + { + return new BigInteger((long)value); + } + if (value is uint) + { + return new BigInteger((uint)value); + } + if (value is ulong) + { + return new BigInteger((ulong)value); + } + if (value is byte[]) + { + return new BigInteger((byte[])value); + } + + throw new InvalidCastException("Cannot convert {0} to BigInteger.".FormatWith(CultureInfo.InvariantCulture, value.GetType())); + } + + public static object FromBigInteger(BigInteger i, Type targetType) + { + if (targetType == typeof(decimal)) + { + return (decimal)i; + } + if (targetType == typeof(double)) + { + return (double)i; + } + if (targetType == typeof(float)) + { + return (float)i; + } + if (targetType == typeof(ulong)) + { + return (ulong)i; + } + if (targetType == typeof(bool)) + { + return i != 0; + } + + try + { + return System.Convert.ChangeType((long)i, targetType, CultureInfo.InvariantCulture); + } + catch (Exception ex) + { + throw new InvalidOperationException("Can not convert from BigInteger to {0}.".FormatWith(CultureInfo.InvariantCulture, targetType), ex); + } + } +#endif + + #region TryConvert + internal enum ConvertResult + { + Success = 0, + CannotConvertNull = 1, + NotInstantiableType = 2, + NoValidConversion = 3 + } + + public static object Convert(object initialValue, CultureInfo culture, Type targetType) + { + object value; + switch (TryConvertInternal(initialValue, culture, targetType, out value)) + { + case ConvertResult.Success: + return value; + case ConvertResult.CannotConvertNull: + throw new Exception("Can not convert null {0} into non-nullable {1}.".FormatWith(CultureInfo.InvariantCulture, initialValue.GetType(), targetType)); + case ConvertResult.NotInstantiableType: + throw new ArgumentException("Target type {0} is not a value type or a non-abstract class.".FormatWith(CultureInfo.InvariantCulture, targetType), nameof(targetType)); + case ConvertResult.NoValidConversion: + throw new InvalidOperationException("Can not convert from {0} to {1}.".FormatWith(CultureInfo.InvariantCulture, initialValue.GetType(), targetType)); + default: + throw new InvalidOperationException("Unexpected conversion result."); + } + } + + private static bool TryConvert(object initialValue, CultureInfo culture, Type targetType, out object value) + { + try + { + if (TryConvertInternal(initialValue, culture, targetType, out value) == ConvertResult.Success) + { + return true; + } + + value = null; + return false; + } + catch + { + value = null; + return false; + } + } + + private static ConvertResult TryConvertInternal(object initialValue, CultureInfo culture, Type targetType, out object value) + { + if (initialValue == null) + { + throw new ArgumentNullException(nameof(initialValue)); + } + + if (ReflectionUtils.IsNullableType(targetType)) + { + targetType = Nullable.GetUnderlyingType(targetType); + } + + Type initialType = initialValue.GetType(); + + if (targetType == initialType) + { + value = initialValue; + return ConvertResult.Success; + } + + // use Convert.ChangeType if both types are IConvertible + if (ConvertUtils.IsConvertible(initialValue.GetType()) && ConvertUtils.IsConvertible(targetType)) + { + if (targetType.IsEnum()) + { + if (initialValue is string) + { + value = Enum.Parse(targetType, initialValue.ToString(), true); + return ConvertResult.Success; + } + else if (IsInteger(initialValue)) + { + value = Enum.ToObject(targetType, initialValue); + return ConvertResult.Success; + } + } + + value = System.Convert.ChangeType(initialValue, targetType, culture); + return ConvertResult.Success; + } + +#if !NET20 + if (initialValue is DateTime && targetType == typeof(DateTimeOffset)) + { + value = new DateTimeOffset((DateTime)initialValue); + return ConvertResult.Success; + } +#endif + + if (initialValue is byte[] && targetType == typeof(Guid)) + { + value = new Guid((byte[])initialValue); + return ConvertResult.Success; + } + + if (initialValue is Guid && targetType == typeof(byte[])) + { + value = ((Guid)initialValue).ToByteArray(); + return ConvertResult.Success; + } + + string s = initialValue as string; + if (s != null) + { + if (targetType == typeof(Guid)) + { + value = new Guid(s); + return ConvertResult.Success; + } + if (targetType == typeof(Uri)) + { + value = new Uri(s, UriKind.RelativeOrAbsolute); + return ConvertResult.Success; + } + if (targetType == typeof(TimeSpan)) + { + value = ParseTimeSpan(s); + return ConvertResult.Success; + } + if (targetType == typeof(byte[])) + { + value = System.Convert.FromBase64String(s); + return ConvertResult.Success; + } + if (targetType == typeof(Version)) + { + Version result; + if (VersionTryParse(s, out result)) + { + value = result; + return ConvertResult.Success; + } + value = null; + return ConvertResult.NoValidConversion; + } + if (typeof(Type).IsAssignableFrom(targetType)) + { + value = Type.GetType(s, true); + return ConvertResult.Success; + } + } + +#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) + if (targetType == typeof(BigInteger)) + { + value = ToBigInteger(initialValue); + return ConvertResult.Success; + } + if (initialValue is BigInteger) + { + value = FromBigInteger((BigInteger)initialValue, targetType); + return ConvertResult.Success; + } +#endif + +#if !(PORTABLE40 || PORTABLE) + // see if source or target types have a TypeConverter that converts between the two + TypeConverter toConverter = GetConverter(initialType); + + if (toConverter != null && toConverter.CanConvertTo(targetType)) + { + value = toConverter.ConvertTo(null, culture, initialValue, targetType); + return ConvertResult.Success; + } + + TypeConverter fromConverter = GetConverter(targetType); + + if (fromConverter != null && fromConverter.CanConvertFrom(initialType)) + { + value = fromConverter.ConvertFrom(null, culture, initialValue); + return ConvertResult.Success; + } +#endif +#if !(DOTNET || PORTABLE40 || PORTABLE) + // handle DBNull and INullable + if (initialValue == DBNull.Value) + { + if (ReflectionUtils.IsNullable(targetType)) + { + value = EnsureTypeAssignable(null, initialType, targetType); + return ConvertResult.Success; + } + + // cannot convert null to non-nullable + value = null; + return ConvertResult.CannotConvertNull; + } +#endif +#if !(DOTNET || PORTABLE40 || PORTABLE) + if (initialValue is INullable) + { + value = EnsureTypeAssignable(ToValue((INullable)initialValue), initialType, targetType); + return ConvertResult.Success; + } +#endif + + if (targetType.IsInterface() || targetType.IsGenericTypeDefinition() || targetType.IsAbstract()) + { + value = null; + return ConvertResult.NotInstantiableType; + } + + value = null; + return ConvertResult.NoValidConversion; + } + #endregion + + #region ConvertOrCast + /// + /// Converts the value to the specified type. If the value is unable to be converted, the + /// value is checked whether it assignable to the specified type. + /// + /// The value to convert. + /// The culture to use when converting. + /// The type to convert or cast the value to. + /// + /// The converted type. If conversion was unsuccessful, the initial value + /// is returned if assignable to the target type. + /// + public static object ConvertOrCast(object initialValue, CultureInfo culture, Type targetType) + { + object convertedValue; + + if (targetType == typeof(object)) + { + return initialValue; + } + + if (initialValue == null && ReflectionUtils.IsNullable(targetType)) + { + return null; + } + + if (TryConvert(initialValue, culture, targetType, out convertedValue)) + { + return convertedValue; + } + + return EnsureTypeAssignable(initialValue, ReflectionUtils.GetObjectType(initialValue), targetType); + } + #endregion + + private static object EnsureTypeAssignable(object value, Type initialType, Type targetType) + { + Type valueType = (value != null) ? value.GetType() : null; + + if (value != null) + { + if (targetType.IsAssignableFrom(valueType)) + { + return value; + } + + Func castConverter = CastConverters.Get(new TypeConvertKey(valueType, targetType)); + if (castConverter != null) + { + return castConverter(value); + } + } + else + { + if (ReflectionUtils.IsNullable(targetType)) + { + return null; + } + } + + throw new ArgumentException("Could not cast or convert from {0} to {1}.".FormatWith(CultureInfo.InvariantCulture, (initialType != null) ? initialType.ToString() : "{null}", targetType)); + } + +#if !(DOTNET || PORTABLE40 || PORTABLE) + public static object ToValue(INullable nullableValue) + { + if (nullableValue == null) + { + return null; + } + else if (nullableValue is SqlInt32) + { + return ToValue((SqlInt32)nullableValue); + } + else if (nullableValue is SqlInt64) + { + return ToValue((SqlInt64)nullableValue); + } + else if (nullableValue is SqlBoolean) + { + return ToValue((SqlBoolean)nullableValue); + } + else if (nullableValue is SqlString) + { + return ToValue((SqlString)nullableValue); + } + else if (nullableValue is SqlDateTime) + { + return ToValue((SqlDateTime)nullableValue); + } + + throw new ArgumentException("Unsupported INullable type: {0}".FormatWith(CultureInfo.InvariantCulture, nullableValue.GetType())); + } +#endif + +#if !(PORTABLE40 || PORTABLE) + internal static TypeConverter GetConverter(Type t) + { + return JsonTypeReflector.GetTypeConverter(t); + } +#endif + + public static bool VersionTryParse(string input, out Version result) + { +#if !(NET20 || NET35) + return Version.TryParse(input, out result); +#else + // improve failure performance with regex? + try + { + result = new Version(input); + return true; + } + catch + { + result = null; + return false; + } +#endif + } + + public static bool IsInteger(object value) + { + switch (GetTypeCode(value.GetType())) + { + case PrimitiveTypeCode.SByte: + case PrimitiveTypeCode.Byte: + case PrimitiveTypeCode.Int16: + case PrimitiveTypeCode.UInt16: + case PrimitiveTypeCode.Int32: + case PrimitiveTypeCode.UInt32: + case PrimitiveTypeCode.Int64: + case PrimitiveTypeCode.UInt64: + return true; + default: + return false; + } + } + + public static ParseResult Int32TryParse(char[] chars, int start, int length, out int value) + { + value = 0; + + if (length == 0) + { + return ParseResult.Invalid; + } + + bool isNegative = (chars[start] == '-'); + + if (isNegative) + { + // text just a negative sign + if (length == 1) + { + return ParseResult.Invalid; + } + + start++; + length--; + } + + int end = start + length; + + // Int32.MaxValue and MinValue are 10 chars + // Or is 10 chars and start is greater than two + // Need to improve this! + if (length > 10 || (length == 10 && chars[start] - '0' > 2)) + { + // invalid result takes precedence over overflow + for (int i = start; i < end; i++) + { + int c = chars[i] - '0'; + + if (c < 0 || c > 9) + { + return ParseResult.Invalid; + } + } + + return ParseResult.Overflow; + } + + for (int i = start; i < end; i++) + { + int c = chars[i] - '0'; + + if (c < 0 || c > 9) + { + return ParseResult.Invalid; + } + + int newValue = (10 * value) - c; + + // overflow has caused the number to loop around + if (newValue > value) + { + i++; + + // double check the rest of the string that there wasn't anything invalid + // invalid result takes precedence over overflow result + for (; i < end; i++) + { + c = chars[i] - '0'; + + if (c < 0 || c > 9) + { + return ParseResult.Invalid; + } + } + + return ParseResult.Overflow; + } + + value = newValue; + } + + // go from negative to positive to avoids overflow + // negative can be slightly bigger than positive + if (!isNegative) + { + // negative integer can be one bigger than positive + if (value == int.MinValue) + { + return ParseResult.Overflow; + } + + value = -value; + } + + return ParseResult.Success; + } + + public static ParseResult Int64TryParse(char[] chars, int start, int length, out long value) + { + value = 0; + + if (length == 0) + { + return ParseResult.Invalid; + } + + bool isNegative = (chars[start] == '-'); + + if (isNegative) + { + // text just a negative sign + if (length == 1) + { + return ParseResult.Invalid; + } + + start++; + length--; + } + + int end = start + length; + + // Int64.MaxValue and MinValue are 19 chars + if (length > 19) + { + // invalid result takes precedence over overflow + for (int i = start; i < end; i++) + { + int c = chars[i] - '0'; + + if (c < 0 || c > 9) + { + return ParseResult.Invalid; + } + } + + return ParseResult.Overflow; + } + + for (int i = start; i < end; i++) + { + int c = chars[i] - '0'; + + if (c < 0 || c > 9) + { + return ParseResult.Invalid; + } + + long newValue = (10 * value) - c; + + // overflow has caused the number to loop around + if (newValue > value) + { + i++; + + // double check the rest of the string that there wasn't anything invalid + // invalid result takes precedence over overflow result + for (; i < end; i++) + { + c = chars[i] - '0'; + + if (c < 0 || c > 9) + { + return ParseResult.Invalid; + } + } + + return ParseResult.Overflow; + } + + value = newValue; + } + + // go from negative to positive to avoids overflow + // negative can be slightly bigger than positive + if (!isNegative) + { + // negative integer can be one bigger than positive + if (value == long.MinValue) + { + return ParseResult.Overflow; + } + + value = -value; + } + + return ParseResult.Success; + } + + public static bool TryConvertGuid(string s, out Guid g) + { + // GUID has to have format 00000000-0000-0000-0000-000000000000 +#if NET20 || NET35 + if (s == null) + { + throw new ArgumentNullException("s"); + } + + Regex format = new Regex("^[A-Fa-f0-9]{8}-([A-Fa-f0-9]{4}-){3}[A-Fa-f0-9]{12}$"); + Match match = format.Match(s); + if (match.Success) + { + g = new Guid(s); + return true; + } + + g = Guid.Empty; + return false; +#else + return Guid.TryParseExact(s, "D", out g); +#endif + } + + public static int HexTextToInt(char[] text, int start, int end) + { + int value = 0; + for (int i = start; i < end; i++) + { + value += HexCharToInt(text[i]) << ((end - 1 - i) * 4); + } + return value; + } + + private static int HexCharToInt(char ch) + { + if (ch <= 57 && ch >= 48) + { + return ch - 48; + } + + if (ch <= 70 && ch >= 65) + { + return ch - 55; + } + + if (ch <= 102 && ch >= 97) + { + return ch - 87; + } + + throw new FormatException("Invalid hex character: " + ch); + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Utilities/DateTimeParser.cs b/Common/00-1Json8.3/Json8.3/Utilities/DateTimeParser.cs new file mode 100644 index 0000000..9addb98 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Utilities/DateTimeParser.cs @@ -0,0 +1,277 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; + +namespace Newtonsoft.Json.Utilities +{ + internal enum ParserTimeZone + { + Unspecified = 0, + Utc = 1, + LocalWestOfUtc = 2, + LocalEastOfUtc = 3 + } + + internal struct DateTimeParser + { + static DateTimeParser() + { + Power10 = new[] { -1, 10, 100, 1000, 10000, 100000, 1000000 }; + + Lzyyyy = "yyyy".Length; + Lzyyyy_ = "yyyy-".Length; + Lzyyyy_MM = "yyyy-MM".Length; + Lzyyyy_MM_ = "yyyy-MM-".Length; + Lzyyyy_MM_dd = "yyyy-MM-dd".Length; + Lzyyyy_MM_ddT = "yyyy-MM-ddT".Length; + LzHH = "HH".Length; + LzHH_ = "HH:".Length; + LzHH_mm = "HH:mm".Length; + LzHH_mm_ = "HH:mm:".Length; + LzHH_mm_ss = "HH:mm:ss".Length; + Lz_ = "-".Length; + Lz_zz = "-zz".Length; + } + + public int Year; + public int Month; + public int Day; + public int Hour; + public int Minute; + public int Second; + public int Fraction; + public int ZoneHour; + public int ZoneMinute; + public ParserTimeZone Zone; + + private char[] _text; + private int _end; + + private static readonly int[] Power10; + + private static readonly int Lzyyyy; + private static readonly int Lzyyyy_; + private static readonly int Lzyyyy_MM; + private static readonly int Lzyyyy_MM_; + private static readonly int Lzyyyy_MM_dd; + private static readonly int Lzyyyy_MM_ddT; + private static readonly int LzHH; + private static readonly int LzHH_; + private static readonly int LzHH_mm; + private static readonly int LzHH_mm_; + private static readonly int LzHH_mm_ss; + private static readonly int Lz_; + private static readonly int Lz_zz; + + private const short MaxFractionDigits = 7; + + public bool Parse(char[] text, int startIndex, int length) + { + _text = text; + _end = startIndex + length; + + if (ParseDate(startIndex) && ParseChar(Lzyyyy_MM_dd + startIndex, 'T') && ParseTimeAndZoneAndWhitespace(Lzyyyy_MM_ddT + startIndex)) + { + return true; + } + + return false; + } + + private bool ParseDate(int start) + { + return (Parse4Digit(start, out Year) + && 1 <= Year + && ParseChar(start + Lzyyyy, '-') + && Parse2Digit(start + Lzyyyy_, out Month) + && 1 <= Month + && Month <= 12 + && ParseChar(start + Lzyyyy_MM, '-') + && Parse2Digit(start + Lzyyyy_MM_, out Day) + && 1 <= Day + && Day <= DateTime.DaysInMonth(Year, Month)); + } + + private bool ParseTimeAndZoneAndWhitespace(int start) + { + return (ParseTime(ref start) && ParseZone(start)); + } + + private bool ParseTime(ref int start) + { + if (!(Parse2Digit(start, out Hour) + && Hour <= 24 + && ParseChar(start + LzHH, ':') + && Parse2Digit(start + LzHH_, out Minute) + && Minute < 60 + && ParseChar(start + LzHH_mm, ':') + && Parse2Digit(start + LzHH_mm_, out Second) + && Second < 60 + && (Hour != 24 || (Minute == 0 && Second == 0)))) // hour can be 24 if minute/second is zero) + { + return false; + } + + start += LzHH_mm_ss; + if (ParseChar(start, '.')) + { + Fraction = 0; + int numberOfDigits = 0; + + while (++start < _end && numberOfDigits < MaxFractionDigits) + { + int digit = _text[start] - '0'; + if (digit < 0 || digit > 9) + { + break; + } + + Fraction = (Fraction * 10) + digit; + + numberOfDigits++; + } + + if (numberOfDigits < MaxFractionDigits) + { + if (numberOfDigits == 0) + { + return false; + } + + Fraction *= Power10[MaxFractionDigits - numberOfDigits]; + } + + if (Hour == 24 && Fraction != 0) + { + return false; + } + } + return true; + } + + private bool ParseZone(int start) + { + if (start < _end) + { + char ch = _text[start]; + if (ch == 'Z' || ch == 'z') + { + Zone = ParserTimeZone.Utc; + start++; + } + else + { + if (start + 2 < _end + && Parse2Digit(start + Lz_, out ZoneHour) + && ZoneHour <= 99) + { + switch (ch) + { + case '-': + Zone = ParserTimeZone.LocalWestOfUtc; + start += Lz_zz; + break; + + case '+': + Zone = ParserTimeZone.LocalEastOfUtc; + start += Lz_zz; + break; + } + } + + if (start < _end) + { + if (ParseChar(start, ':')) + { + start += 1; + + if (start + 1 < _end + && Parse2Digit(start, out ZoneMinute) + && ZoneMinute <= 99) + { + start += 2; + } + } + else + { + if (start + 1 < _end + && Parse2Digit(start, out ZoneMinute) + && ZoneMinute <= 99) + { + start += 2; + } + } + } + } + } + + return (start == _end); + } + + private bool Parse4Digit(int start, out int num) + { + if (start + 3 < _end) + { + int digit1 = _text[start] - '0'; + int digit2 = _text[start + 1] - '0'; + int digit3 = _text[start + 2] - '0'; + int digit4 = _text[start + 3] - '0'; + if (0 <= digit1 && digit1 < 10 + && 0 <= digit2 && digit2 < 10 + && 0 <= digit3 && digit3 < 10 + && 0 <= digit4 && digit4 < 10) + { + num = (((((digit1 * 10) + digit2) * 10) + digit3) * 10) + digit4; + return true; + } + } + num = 0; + return false; + } + + private bool Parse2Digit(int start, out int num) + { + if (start + 1 < _end) + { + int digit1 = _text[start] - '0'; + int digit2 = _text[start + 1] - '0'; + if (0 <= digit1 && digit1 < 10 + && 0 <= digit2 && digit2 < 10) + { + num = (digit1 * 10) + digit2; + return true; + } + } + num = 0; + return false; + } + + private bool ParseChar(int start, char ch) + { + return (start < _end && _text[start] == ch); + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Utilities/DateTimeUtils.cs b/Common/00-1Json8.3/Json8.3/Utilities/DateTimeUtils.cs new file mode 100644 index 0000000..097bfe6 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Utilities/DateTimeUtils.cs @@ -0,0 +1,824 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.IO; +using System.Xml; +using System.Globalization; + +namespace Newtonsoft.Json.Utilities +{ + internal static class DateTimeUtils + { + internal static readonly long InitialJavaScriptDateTicks = 621355968000000000; + private const string IsoDateFormat = "yyyy-MM-ddTHH:mm:ss.FFFFFFFK"; + + private const int DaysPer100Years = 36524; + private const int DaysPer400Years = 146097; + private const int DaysPer4Years = 1461; + private const int DaysPerYear = 365; + private const long TicksPerDay = 864000000000L; + private static readonly int[] DaysToMonth365; + private static readonly int[] DaysToMonth366; + + static DateTimeUtils() + { + DaysToMonth365 = new[] { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 }; + DaysToMonth366 = new[] { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 }; + } + + public static TimeSpan GetUtcOffset(this DateTime d) + { +#if NET20 + return TimeZone.CurrentTimeZone.GetUtcOffset(d); +#else + return TimeZoneInfo.Local.GetUtcOffset(d); +#endif + } + +#if !(PORTABLE40 || PORTABLE) + public static XmlDateTimeSerializationMode ToSerializationMode(DateTimeKind kind) + { + switch (kind) + { + case DateTimeKind.Local: + return XmlDateTimeSerializationMode.Local; + case DateTimeKind.Unspecified: + return XmlDateTimeSerializationMode.Unspecified; + case DateTimeKind.Utc: + return XmlDateTimeSerializationMode.Utc; + default: + throw MiscellaneousUtils.CreateArgumentOutOfRangeException("kind", kind, "Unexpected DateTimeKind value."); + } + } +#endif + + internal static DateTime EnsureDateTime(DateTime value, DateTimeZoneHandling timeZone) + { + switch (timeZone) + { + case DateTimeZoneHandling.Local: + value = SwitchToLocalTime(value); + break; + case DateTimeZoneHandling.Utc: + value = SwitchToUtcTime(value); + break; + case DateTimeZoneHandling.Unspecified: + value = new DateTime(value.Ticks, DateTimeKind.Unspecified); + break; + case DateTimeZoneHandling.RoundtripKind: + break; + default: + throw new ArgumentException("Invalid date time handling value."); + } + + return value; + } + + private static DateTime SwitchToLocalTime(DateTime value) + { + switch (value.Kind) + { + case DateTimeKind.Unspecified: + return new DateTime(value.Ticks, DateTimeKind.Local); + + case DateTimeKind.Utc: + return value.ToLocalTime(); + + case DateTimeKind.Local: + return value; + } + return value; + } + + private static DateTime SwitchToUtcTime(DateTime value) + { + switch (value.Kind) + { + case DateTimeKind.Unspecified: + return new DateTime(value.Ticks, DateTimeKind.Utc); + + case DateTimeKind.Utc: + return value; + + case DateTimeKind.Local: + return value.ToUniversalTime(); + } + return value; + } + + private static long ToUniversalTicks(DateTime dateTime) + { + if (dateTime.Kind == DateTimeKind.Utc) + { + return dateTime.Ticks; + } + + return ToUniversalTicks(dateTime, dateTime.GetUtcOffset()); + } + + private static long ToUniversalTicks(DateTime dateTime, TimeSpan offset) + { + // special case min and max value + // they never have a timezone appended to avoid issues + if (dateTime.Kind == DateTimeKind.Utc || dateTime == DateTime.MaxValue || dateTime == DateTime.MinValue) + { + return dateTime.Ticks; + } + + long ticks = dateTime.Ticks - offset.Ticks; + if (ticks > 3155378975999999999L) + { + return 3155378975999999999L; + } + + if (ticks < 0L) + { + return 0L; + } + + return ticks; + } + + internal static long ConvertDateTimeToJavaScriptTicks(DateTime dateTime, TimeSpan offset) + { + long universialTicks = ToUniversalTicks(dateTime, offset); + + return UniversialTicksToJavaScriptTicks(universialTicks); + } + + internal static long ConvertDateTimeToJavaScriptTicks(DateTime dateTime) + { + return ConvertDateTimeToJavaScriptTicks(dateTime, true); + } + + internal static long ConvertDateTimeToJavaScriptTicks(DateTime dateTime, bool convertToUtc) + { + long ticks = (convertToUtc) ? ToUniversalTicks(dateTime) : dateTime.Ticks; + + return UniversialTicksToJavaScriptTicks(ticks); + } + + private static long UniversialTicksToJavaScriptTicks(long universialTicks) + { + long javaScriptTicks = (universialTicks - InitialJavaScriptDateTicks) / 10000; + + return javaScriptTicks; + } + + internal static DateTime ConvertJavaScriptTicksToDateTime(long javaScriptTicks) + { + DateTime dateTime = new DateTime((javaScriptTicks * 10000) + InitialJavaScriptDateTicks, DateTimeKind.Utc); + + return dateTime; + } + + #region Parse + internal static bool TryParseDateTimeIso(StringReference text, DateTimeZoneHandling dateTimeZoneHandling, out DateTime dt) + { + DateTimeParser dateTimeParser = new DateTimeParser(); + if (!dateTimeParser.Parse(text.Chars, text.StartIndex, text.Length)) + { + dt = default(DateTime); + return false; + } + + DateTime d = CreateDateTime(dateTimeParser); + + long ticks; + + switch (dateTimeParser.Zone) + { + case ParserTimeZone.Utc: + d = new DateTime(d.Ticks, DateTimeKind.Utc); + break; + + case ParserTimeZone.LocalWestOfUtc: + { + TimeSpan offset = new TimeSpan(dateTimeParser.ZoneHour, dateTimeParser.ZoneMinute, 0); + ticks = d.Ticks + offset.Ticks; + if (ticks <= DateTime.MaxValue.Ticks) + { + d = new DateTime(ticks, DateTimeKind.Utc).ToLocalTime(); + } + else + { + ticks += d.GetUtcOffset().Ticks; + if (ticks > DateTime.MaxValue.Ticks) + { + ticks = DateTime.MaxValue.Ticks; + } + + d = new DateTime(ticks, DateTimeKind.Local); + } + break; + } + case ParserTimeZone.LocalEastOfUtc: + { + TimeSpan offset = new TimeSpan(dateTimeParser.ZoneHour, dateTimeParser.ZoneMinute, 0); + ticks = d.Ticks - offset.Ticks; + if (ticks >= DateTime.MinValue.Ticks) + { + d = new DateTime(ticks, DateTimeKind.Utc).ToLocalTime(); + } + else + { + ticks += d.GetUtcOffset().Ticks; + if (ticks < DateTime.MinValue.Ticks) + { + ticks = DateTime.MinValue.Ticks; + } + + d = new DateTime(ticks, DateTimeKind.Local); + } + break; + } + } + + dt = EnsureDateTime(d, dateTimeZoneHandling); + return true; + } + +#if !NET20 + internal static bool TryParseDateTimeOffsetIso(StringReference text, out DateTimeOffset dt) + { + DateTimeParser dateTimeParser = new DateTimeParser(); + if (!dateTimeParser.Parse(text.Chars, text.StartIndex, text.Length)) + { + dt = default(DateTimeOffset); + return false; + } + + DateTime d = CreateDateTime(dateTimeParser); + + TimeSpan offset; + + switch (dateTimeParser.Zone) + { + case ParserTimeZone.Utc: + offset = new TimeSpan(0L); + break; + case ParserTimeZone.LocalWestOfUtc: + offset = new TimeSpan(-dateTimeParser.ZoneHour, -dateTimeParser.ZoneMinute, 0); + break; + case ParserTimeZone.LocalEastOfUtc: + offset = new TimeSpan(dateTimeParser.ZoneHour, dateTimeParser.ZoneMinute, 0); + break; + default: + offset = TimeZoneInfo.Local.GetUtcOffset(d); + break; + } + + long ticks = d.Ticks - offset.Ticks; + if (ticks < 0 || ticks > 3155378975999999999) + { + dt = default(DateTimeOffset); + return false; + } + + dt = new DateTimeOffset(d, offset); + return true; + } +#endif + + private static DateTime CreateDateTime(DateTimeParser dateTimeParser) + { + bool is24Hour; + if (dateTimeParser.Hour == 24) + { + is24Hour = true; + dateTimeParser.Hour = 0; + } + else + { + is24Hour = false; + } + + DateTime d = new DateTime(dateTimeParser.Year, dateTimeParser.Month, dateTimeParser.Day, dateTimeParser.Hour, dateTimeParser.Minute, dateTimeParser.Second); + d = d.AddTicks(dateTimeParser.Fraction); + + if (is24Hour) + { + d = d.AddDays(1); + } + return d; + } + + internal static bool TryParseDateTime(StringReference s, DateTimeZoneHandling dateTimeZoneHandling, string dateFormatString, CultureInfo culture, out DateTime dt) + { + if (s.Length > 0) + { + int i = s.StartIndex; + if (s[i] == '/') + { + if (s.Length >= 9 && s.StartsWith("/Date(") && s.EndsWith(")/")) + { + if (TryParseDateTimeMicrosoft(s, dateTimeZoneHandling, out dt)) + { + return true; + } + } + } + else if (s.Length >= 19 && s.Length <= 40 && char.IsDigit(s[i]) && s[i + 10] == 'T') + { + if (TryParseDateTimeIso(s, dateTimeZoneHandling, out dt)) + { + return true; + } + } + + if (!string.IsNullOrEmpty(dateFormatString)) + { + if (TryParseDateTimeExact(s.ToString(), dateTimeZoneHandling, dateFormatString, culture, out dt)) + { + return true; + } + } + } + + dt = default(DateTime); + return false; + } + + internal static bool TryParseDateTime(string s, DateTimeZoneHandling dateTimeZoneHandling, string dateFormatString, CultureInfo culture, out DateTime dt) + { + if (s.Length > 0) + { + if (s[0] == '/') + { + if (s.Length >= 9 && s.StartsWith("/Date(", StringComparison.Ordinal) && s.EndsWith(")/", StringComparison.Ordinal)) + { + if (TryParseDateTimeMicrosoft(new StringReference(s.ToCharArray(), 0, s.Length), dateTimeZoneHandling, out dt)) + { + return true; + } + } + } + else if (s.Length >= 19 && s.Length <= 40 && char.IsDigit(s[0]) && s[10] == 'T') + { + if (DateTime.TryParseExact(s, IsoDateFormat, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out dt)) + { + dt = EnsureDateTime(dt, dateTimeZoneHandling); + return true; + } + } + + if (!string.IsNullOrEmpty(dateFormatString)) + { + if (TryParseDateTimeExact(s, dateTimeZoneHandling, dateFormatString, culture, out dt)) + { + return true; + } + } + } + + dt = default(DateTime); + return false; + } + +#if !NET20 + internal static bool TryParseDateTimeOffset(StringReference s, string dateFormatString, CultureInfo culture, out DateTimeOffset dt) + { + if (s.Length > 0) + { + int i = s.StartIndex; + if (s[i] == '/') + { + if (s.Length >= 9 && s.StartsWith("/Date(") && s.EndsWith(")/")) + { + if (TryParseDateTimeOffsetMicrosoft(s, out dt)) + { + return true; + } + } + } + else if (s.Length >= 19 && s.Length <= 40 && char.IsDigit(s[i]) && s[i + 10] == 'T') + { + if (TryParseDateTimeOffsetIso(s, out dt)) + { + return true; + } + } + + if (!string.IsNullOrEmpty(dateFormatString)) + { + if (TryParseDateTimeOffsetExact(s.ToString(), dateFormatString, culture, out dt)) + { + return true; + } + } + } + + dt = default(DateTimeOffset); + return false; + } + + internal static bool TryParseDateTimeOffset(string s, string dateFormatString, CultureInfo culture, out DateTimeOffset dt) + { + if (s.Length > 0) + { + if (s[0] == '/') + { + if (s.Length >= 9 && s.StartsWith("/Date(", StringComparison.Ordinal) && s.EndsWith(")/", StringComparison.Ordinal)) + { + if (TryParseDateTimeOffsetMicrosoft(new StringReference(s.ToCharArray(), 0, s.Length), out dt)) + { + return true; + } + } + } + else if (s.Length >= 19 && s.Length <= 40 && char.IsDigit(s[0]) && s[10] == 'T') + { + if (DateTimeOffset.TryParseExact(s, IsoDateFormat, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out dt)) + { + if (TryParseDateTimeOffsetIso(new StringReference(s.ToCharArray(), 0, s.Length), out dt)) + { + return true; + } + } + } + + if (!string.IsNullOrEmpty(dateFormatString)) + { + if (TryParseDateTimeOffsetExact(s, dateFormatString, culture, out dt)) + { + return true; + } + } + } + + dt = default(DateTimeOffset); + return false; + } +#endif + + private static bool TryParseMicrosoftDate(StringReference text, out long ticks, out TimeSpan offset, out DateTimeKind kind) + { + kind = DateTimeKind.Utc; + + int index = text.IndexOf('+', 7, text.Length - 8); + + if (index == -1) + { + index = text.IndexOf('-', 7, text.Length - 8); + } + + if (index != -1) + { + kind = DateTimeKind.Local; + + if (!TryReadOffset(text, index + text.StartIndex, out offset)) + { + ticks = 0; + return false; + } + } + else + { + offset = TimeSpan.Zero; + index = text.Length - 2; + } + + return (ConvertUtils.Int64TryParse(text.Chars, 6 + text.StartIndex, index - 6, out ticks) == ParseResult.Success); + } + + private static bool TryParseDateTimeMicrosoft(StringReference text, DateTimeZoneHandling dateTimeZoneHandling, out DateTime dt) + { + long ticks; + TimeSpan offset; + DateTimeKind kind; + + if (!TryParseMicrosoftDate(text, out ticks, out offset, out kind)) + { + dt = default(DateTime); + return false; + } + + DateTime utcDateTime = ConvertJavaScriptTicksToDateTime(ticks); + + switch (kind) + { + case DateTimeKind.Unspecified: + dt = DateTime.SpecifyKind(utcDateTime.ToLocalTime(), DateTimeKind.Unspecified); + break; + case DateTimeKind.Local: + dt = utcDateTime.ToLocalTime(); + break; + default: + dt = utcDateTime; + break; + } + + dt = EnsureDateTime(dt, dateTimeZoneHandling); + return true; + } + + private static bool TryParseDateTimeExact(string text, DateTimeZoneHandling dateTimeZoneHandling, string dateFormatString, CultureInfo culture, out DateTime dt) + { + DateTime temp; + if (DateTime.TryParseExact(text, dateFormatString, culture, DateTimeStyles.RoundtripKind, out temp)) + { + temp = EnsureDateTime(temp, dateTimeZoneHandling); + dt = temp; + return true; + } + + dt = default(DateTime); + return false; + } + +#if !NET20 + private static bool TryParseDateTimeOffsetMicrosoft(StringReference text, out DateTimeOffset dt) + { + long ticks; + TimeSpan offset; + DateTimeKind kind; + + if (!TryParseMicrosoftDate(text, out ticks, out offset, out kind)) + { + dt = default(DateTime); + return false; + } + + DateTime utcDateTime = ConvertJavaScriptTicksToDateTime(ticks); + + dt = new DateTimeOffset(utcDateTime.Add(offset).Ticks, offset); + return true; + } + + private static bool TryParseDateTimeOffsetExact(string text, string dateFormatString, CultureInfo culture, out DateTimeOffset dt) + { + DateTimeOffset temp; + if (DateTimeOffset.TryParseExact(text, dateFormatString, culture, DateTimeStyles.RoundtripKind, out temp)) + { + dt = temp; + return true; + } + + dt = default(DateTimeOffset); + return false; + } +#endif + + private static bool TryReadOffset(StringReference offsetText, int startIndex, out TimeSpan offset) + { + bool negative = (offsetText[startIndex] == '-'); + + int hours; + if (ConvertUtils.Int32TryParse(offsetText.Chars, startIndex + 1, 2, out hours) != ParseResult.Success) + { + offset = default(TimeSpan); + return false; + } + + int minutes = 0; + if (offsetText.Length - startIndex > 5) + { + if (ConvertUtils.Int32TryParse(offsetText.Chars, startIndex + 3, 2, out minutes) != ParseResult.Success) + { + offset = default(TimeSpan); + return false; + } + } + + offset = TimeSpan.FromHours(hours) + TimeSpan.FromMinutes(minutes); + if (negative) + { + offset = offset.Negate(); + } + + return true; + } + #endregion + + #region Write + internal static void WriteDateTimeString(TextWriter writer, DateTime value, DateFormatHandling format, string formatString, CultureInfo culture) + { + if (string.IsNullOrEmpty(formatString)) + { + char[] chars = new char[64]; + int pos = WriteDateTimeString(chars, 0, value, null, value.Kind, format); + writer.Write(chars, 0, pos); + } + else + { + writer.Write(value.ToString(formatString, culture)); + } + } + + internal static int WriteDateTimeString(char[] chars, int start, DateTime value, TimeSpan? offset, DateTimeKind kind, DateFormatHandling format) + { + int pos = start; + + if (format == DateFormatHandling.MicrosoftDateFormat) + { + TimeSpan o = offset ?? value.GetUtcOffset(); + + long javaScriptTicks = ConvertDateTimeToJavaScriptTicks(value, o); + + @"\/Date(".CopyTo(0, chars, pos, 7); + pos += 7; + + string ticksText = javaScriptTicks.ToString(CultureInfo.InvariantCulture); + ticksText.CopyTo(0, chars, pos, ticksText.Length); + pos += ticksText.Length; + + switch (kind) + { + case DateTimeKind.Unspecified: + if (value != DateTime.MaxValue && value != DateTime.MinValue) + { + pos = WriteDateTimeOffset(chars, pos, o, format); + } + break; + case DateTimeKind.Local: + pos = WriteDateTimeOffset(chars, pos, o, format); + break; + } + + @")\/".CopyTo(0, chars, pos, 3); + pos += 3; + } + else + { + pos = WriteDefaultIsoDate(chars, pos, value); + + switch (kind) + { + case DateTimeKind.Local: + pos = WriteDateTimeOffset(chars, pos, offset ?? value.GetUtcOffset(), format); + break; + case DateTimeKind.Utc: + chars[pos++] = 'Z'; + break; + } + } + + return pos; + } + + internal static int WriteDefaultIsoDate(char[] chars, int start, DateTime dt) + { + int length = 19; + + int year; + int month; + int day; + GetDateValues(dt, out year, out month, out day); + + CopyIntToCharArray(chars, start, year, 4); + chars[start + 4] = '-'; + CopyIntToCharArray(chars, start + 5, month, 2); + chars[start + 7] = '-'; + CopyIntToCharArray(chars, start + 8, day, 2); + chars[start + 10] = 'T'; + CopyIntToCharArray(chars, start + 11, dt.Hour, 2); + chars[start + 13] = ':'; + CopyIntToCharArray(chars, start + 14, dt.Minute, 2); + chars[start + 16] = ':'; + CopyIntToCharArray(chars, start + 17, dt.Second, 2); + + int fraction = (int)(dt.Ticks % 10000000L); + + if (fraction != 0) + { + int digits = 7; + while ((fraction % 10) == 0) + { + digits--; + fraction /= 10; + } + + chars[start + 19] = '.'; + CopyIntToCharArray(chars, start + 20, fraction, digits); + + length += digits + 1; + } + + return start + length; + } + + private static void CopyIntToCharArray(char[] chars, int start, int value, int digits) + { + while (digits-- != 0) + { + chars[start + digits] = (char)((value % 10) + 48); + value /= 10; + } + } + + internal static int WriteDateTimeOffset(char[] chars, int start, TimeSpan offset, DateFormatHandling format) + { + chars[start++] = (offset.Ticks >= 0L) ? '+' : '-'; + + int absHours = Math.Abs(offset.Hours); + CopyIntToCharArray(chars, start, absHours, 2); + start += 2; + + if (format == DateFormatHandling.IsoDateFormat) + { + chars[start++] = ':'; + } + + int absMinutes = Math.Abs(offset.Minutes); + CopyIntToCharArray(chars, start, absMinutes, 2); + start += 2; + + return start; + } + +#if !NET20 + internal static void WriteDateTimeOffsetString(TextWriter writer, DateTimeOffset value, DateFormatHandling format, string formatString, CultureInfo culture) + { + if (string.IsNullOrEmpty(formatString)) + { + char[] chars = new char[64]; + int pos = WriteDateTimeString(chars, 0, (format == DateFormatHandling.IsoDateFormat) ? value.DateTime : value.UtcDateTime, value.Offset, DateTimeKind.Local, format); + + writer.Write(chars, 0, pos); + } + else + { + writer.Write(value.ToString(formatString, culture)); + } + } +#endif + #endregion + + private static void GetDateValues(DateTime td, out int year, out int month, out int day) + { + long ticks = td.Ticks; + // n = number of days since 1/1/0001 + int n = (int)(ticks / TicksPerDay); + // y400 = number of whole 400-year periods since 1/1/0001 + int y400 = n / DaysPer400Years; + // n = day number within 400-year period + n -= y400 * DaysPer400Years; + // y100 = number of whole 100-year periods within 400-year period + int y100 = n / DaysPer100Years; + // Last 100-year period has an extra day, so decrement result if 4 + if (y100 == 4) + { + y100 = 3; + } + // n = day number within 100-year period + n -= y100 * DaysPer100Years; + // y4 = number of whole 4-year periods within 100-year period + int y4 = n / DaysPer4Years; + // n = day number within 4-year period + n -= y4 * DaysPer4Years; + // y1 = number of whole years within 4-year period + int y1 = n / DaysPerYear; + // Last year has an extra day, so decrement result if 4 + if (y1 == 4) + { + y1 = 3; + } + + year = y400 * 400 + y100 * 100 + y4 * 4 + y1 + 1; + + // n = day number within year + n -= y1 * DaysPerYear; + + // Leap year calculation looks different from IsLeapYear since y1, y4, + // and y100 are relative to year 1, not year 0 + bool leapYear = y1 == 3 && (y4 != 24 || y100 == 3); + int[] days = leapYear ? DaysToMonth366 : DaysToMonth365; + // All months have less than 32 days, so n >> 5 is a good conservative + // estimate for the month + int m = n >> 5 + 1; + // m = 1-based month number + while (n >= days[m]) + { + m++; + } + + month = m; + + // Return 1-based day-of-month + day = n - days[m - 1] + 1; + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Utilities/DictionaryWrapper.cs b/Common/00-1Json8.3/Json8.3/Utilities/DictionaryWrapper.cs new file mode 100644 index 0000000..4819c23 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Utilities/DictionaryWrapper.cs @@ -0,0 +1,700 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Collections.Generic; +using System.Collections; +using System.Threading; +#if NET20 +using Newtonsoft.Json.Utilities.LinqBridge; +#else +using System.Linq; + +#endif + +namespace Newtonsoft.Json.Utilities +{ + internal interface IWrappedDictionary + : IDictionary + { + object UnderlyingDictionary { get; } + } + + internal class DictionaryWrapper : IDictionary, IWrappedDictionary + { + private readonly IDictionary _dictionary; + private readonly IDictionary _genericDictionary; +#if !(NET40 || NET35 || NET20 || PORTABLE40) + private readonly IReadOnlyDictionary _readOnlyDictionary; +#endif + private object _syncRoot; + + public DictionaryWrapper(IDictionary dictionary) + { + ValidationUtils.ArgumentNotNull(dictionary, nameof(dictionary)); + + _dictionary = dictionary; + } + + public DictionaryWrapper(IDictionary dictionary) + { + ValidationUtils.ArgumentNotNull(dictionary, nameof(dictionary)); + + _genericDictionary = dictionary; + } + +#if !(NET40 || NET35 || NET20 || PORTABLE40) + public DictionaryWrapper(IReadOnlyDictionary dictionary) + { + ValidationUtils.ArgumentNotNull(dictionary, nameof(dictionary)); + + _readOnlyDictionary = dictionary; + } +#endif + + public void Add(TKey key, TValue value) + { + if (_dictionary != null) + { + _dictionary.Add(key, value); + } + else if (_genericDictionary != null) + { + _genericDictionary.Add(key, value); + } + else + { + throw new NotSupportedException(); + } + } + + public bool ContainsKey(TKey key) + { + if (_dictionary != null) + { + return _dictionary.Contains(key); + } +#if !(NET40 || NET35 || NET20 || PORTABLE40) + else if (_readOnlyDictionary != null) + { + return _readOnlyDictionary.ContainsKey(key); + } +#endif + else + { + return _genericDictionary.ContainsKey(key); + } + } + + public ICollection Keys + { + get + { + if (_dictionary != null) + { + return _dictionary.Keys.Cast().ToList(); + } +#if !(NET40 || NET35 || NET20 || PORTABLE40) + else if (_readOnlyDictionary != null) + { + return _readOnlyDictionary.Keys.ToList(); + } +#endif + else + { + return _genericDictionary.Keys; + } + } + } + + public bool Remove(TKey key) + { + if (_dictionary != null) + { + if (_dictionary.Contains(key)) + { + _dictionary.Remove(key); + return true; + } + else + { + return false; + } + } +#if !(NET40 || NET35 || NET20 || PORTABLE40) + else if (_readOnlyDictionary != null) + { + throw new NotSupportedException(); + } +#endif + else + { + return _genericDictionary.Remove(key); + } + } + + public bool TryGetValue(TKey key, out TValue value) + { + if (_dictionary != null) + { + if (!_dictionary.Contains(key)) + { + value = default(TValue); + return false; + } + else + { + value = (TValue)_dictionary[key]; + return true; + } + } +#if !(NET40 || NET35 || NET20 || PORTABLE40) + else if (_readOnlyDictionary != null) + { + throw new NotSupportedException(); + } +#endif + else + { + return _genericDictionary.TryGetValue(key, out value); + } + } + + public ICollection Values + { + get + { + if (_dictionary != null) + { + return _dictionary.Values.Cast().ToList(); + } +#if !(NET40 || NET35 || NET20 || PORTABLE40) + else if (_readOnlyDictionary != null) + { + return _readOnlyDictionary.Values.ToList(); + } +#endif + else + { + return _genericDictionary.Values; + } + } + } + + public TValue this[TKey key] + { + get + { + if (_dictionary != null) + { + return (TValue)_dictionary[key]; + } +#if !(NET40 || NET35 || NET20 || PORTABLE40) + else if (_readOnlyDictionary != null) + { + return _readOnlyDictionary[key]; + } +#endif + else + { + return _genericDictionary[key]; + } + } + set + { + if (_dictionary != null) + { + _dictionary[key] = value; + } +#if !(NET40 || NET35 || NET20 || PORTABLE40) + else if (_readOnlyDictionary != null) + { + throw new NotSupportedException(); + } +#endif + else + { + _genericDictionary[key] = value; + } + } + } + + public void Add(KeyValuePair item) + { + if (_dictionary != null) + { + ((IList)_dictionary).Add(item); + } +#if !(NET40 || NET35 || NET20 || PORTABLE40) + else if (_readOnlyDictionary != null) + { + throw new NotSupportedException(); + } +#endif + else if (_genericDictionary != null) + { + _genericDictionary.Add(item); + } + } + + public void Clear() + { + if (_dictionary != null) + { + _dictionary.Clear(); + } +#if !(NET40 || NET35 || NET20 || PORTABLE40) + else if (_readOnlyDictionary != null) + { + throw new NotSupportedException(); + } +#endif + else + { + _genericDictionary.Clear(); + } + } + + public bool Contains(KeyValuePair item) + { + if (_dictionary != null) + { + return ((IList)_dictionary).Contains(item); + } +#if !(NET40 || NET35 || NET20 || PORTABLE40) + else if (_readOnlyDictionary != null) + { + return _readOnlyDictionary.Contains(item); + } +#endif + else + { + return _genericDictionary.Contains(item); + } + } + + public void CopyTo(KeyValuePair[] array, int arrayIndex) + { + if (_dictionary != null) + { + foreach (DictionaryEntry item in _dictionary) + { + array[arrayIndex++] = new KeyValuePair((TKey)item.Key, (TValue)item.Value); + } + } +#if !(NET40 || NET35 || NET20 || PORTABLE40) + else if (_readOnlyDictionary != null) + { + throw new NotSupportedException(); + } +#endif + else + { + _genericDictionary.CopyTo(array, arrayIndex); + } + } + + public int Count + { + get + { + if (_dictionary != null) + { + return _dictionary.Count; + } +#if !(NET40 || NET35 || NET20 || PORTABLE40) + else if (_readOnlyDictionary != null) + { + return _readOnlyDictionary.Count; + } +#endif + else + { + return _genericDictionary.Count; + } + } + } + + public bool IsReadOnly + { + get + { + if (_dictionary != null) + { + return _dictionary.IsReadOnly; + } +#if !(NET40 || NET35 || NET20 || PORTABLE40) + else if (_readOnlyDictionary != null) + { + return true; + } +#endif + else + { + return _genericDictionary.IsReadOnly; + } + } + } + + public bool Remove(KeyValuePair item) + { + if (_dictionary != null) + { + if (_dictionary.Contains(item.Key)) + { + object value = _dictionary[item.Key]; + + if (object.Equals(value, item.Value)) + { + _dictionary.Remove(item.Key); + return true; + } + else + { + return false; + } + } + else + { + return true; + } + } +#if !(NET40 || NET35 || NET20 || PORTABLE40) + else if (_readOnlyDictionary != null) + { + throw new NotSupportedException(); + } +#endif + else + { + return _genericDictionary.Remove(item); + } + } + + public IEnumerator> GetEnumerator() + { + if (_dictionary != null) + { + return _dictionary.Cast().Select(de => new KeyValuePair((TKey)de.Key, (TValue)de.Value)).GetEnumerator(); + } +#if !(NET40 || NET35 || NET20 || PORTABLE40) + else if (_readOnlyDictionary != null) + { + return _readOnlyDictionary.GetEnumerator(); + } +#endif + else + { + return _genericDictionary.GetEnumerator(); + } + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + void IDictionary.Add(object key, object value) + { + if (_dictionary != null) + { + _dictionary.Add(key, value); + } +#if !(NET40 || NET35 || NET20 || PORTABLE40) + else if (_readOnlyDictionary != null) + { + throw new NotSupportedException(); + } +#endif + else + { + _genericDictionary.Add((TKey)key, (TValue)value); + } + } + + object IDictionary.this[object key] + { + get + { + if (_dictionary != null) + { + return _dictionary[key]; + } +#if !(NET40 || NET35 || NET20 || PORTABLE40) + else if (_readOnlyDictionary != null) + { + return _readOnlyDictionary[(TKey)key]; + } +#endif + else + { + return _genericDictionary[(TKey)key]; + } + } + set + { + if (_dictionary != null) + { + _dictionary[key] = value; + } +#if !(NET40 || NET35 || NET20 || PORTABLE40) + else if (_readOnlyDictionary != null) + { + throw new NotSupportedException(); + } +#endif + else + { + _genericDictionary[(TKey)key] = (TValue)value; + } + } + } + + private struct DictionaryEnumerator : IDictionaryEnumerator + { + private readonly IEnumerator> _e; + + public DictionaryEnumerator(IEnumerator> e) + { + ValidationUtils.ArgumentNotNull(e, nameof(e)); + _e = e; + } + + public DictionaryEntry Entry + { + get { return (DictionaryEntry)Current; } + } + + public object Key + { + get { return Entry.Key; } + } + + public object Value + { + get { return Entry.Value; } + } + + public object Current + { + get { return new DictionaryEntry(_e.Current.Key, _e.Current.Value); } + } + + public bool MoveNext() + { + return _e.MoveNext(); + } + + public void Reset() + { + _e.Reset(); + } + } + + IDictionaryEnumerator IDictionary.GetEnumerator() + { + if (_dictionary != null) + { + return _dictionary.GetEnumerator(); + } +#if !(NET40 || NET35 || NET20 || PORTABLE40) + else if (_readOnlyDictionary != null) + { + return new DictionaryEnumerator(_readOnlyDictionary.GetEnumerator()); + } +#endif + else + { + return new DictionaryEnumerator(_genericDictionary.GetEnumerator()); + } + } + + bool IDictionary.Contains(object key) + { + if (_genericDictionary != null) + { + return _genericDictionary.ContainsKey((TKey)key); + } +#if !(NET40 || NET35 || NET20 || PORTABLE40) + else if (_readOnlyDictionary != null) + { + return _readOnlyDictionary.ContainsKey((TKey)key); + } +#endif + else + { + return _dictionary.Contains(key); + } + } + + bool IDictionary.IsFixedSize + { + get + { + if (_genericDictionary != null) + { + return false; + } +#if !(NET40 || NET35 || NET20 || PORTABLE40) + else if (_readOnlyDictionary != null) + { + return true; + } +#endif + else + { + return _dictionary.IsFixedSize; + } + } + } + + ICollection IDictionary.Keys + { + get + { + if (_genericDictionary != null) + { + return _genericDictionary.Keys.ToList(); + } +#if !(NET40 || NET35 || NET20 || PORTABLE40) + else if (_readOnlyDictionary != null) + { + return _readOnlyDictionary.Keys.ToList(); + } +#endif + else + { + return _dictionary.Keys; + } + } + } + + public void Remove(object key) + { + if (_dictionary != null) + { + _dictionary.Remove(key); + } +#if !(NET40 || NET35 || NET20 || PORTABLE40) + else if (_readOnlyDictionary != null) + { + throw new NotSupportedException(); + } +#endif + else + { + _genericDictionary.Remove((TKey)key); + } + } + + ICollection IDictionary.Values + { + get + { + if (_genericDictionary != null) + { + return _genericDictionary.Values.ToList(); + } +#if !(NET40 || NET35 || NET20 || PORTABLE40) + else if (_readOnlyDictionary != null) + { + return _readOnlyDictionary.Values.ToList(); + } +#endif + else + { + return _dictionary.Values; + } + } + } + + void ICollection.CopyTo(Array array, int index) + { + if (_dictionary != null) + { + _dictionary.CopyTo(array, index); + } +#if !(NET40 || NET35 || NET20 || PORTABLE40) + else if (_readOnlyDictionary != null) + { + throw new NotSupportedException(); + } +#endif + else + { + _genericDictionary.CopyTo((KeyValuePair[])array, index); + } + } + + bool ICollection.IsSynchronized + { + get + { + if (_dictionary != null) + { + return _dictionary.IsSynchronized; + } + else + { + return false; + } + } + } + + object ICollection.SyncRoot + { + get + { + if (_syncRoot == null) + { + Interlocked.CompareExchange(ref _syncRoot, new object(), null); + } + + return _syncRoot; + } + } + + public object UnderlyingDictionary + { + get + { + if (_dictionary != null) + { + return _dictionary; + } +#if !(NET40 || NET35 || NET20 || PORTABLE40) + else if (_readOnlyDictionary != null) + { + return _readOnlyDictionary; + } +#endif + else + { + return _genericDictionary; + } + } + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Utilities/DynamicProxy.cs b/Common/00-1Json8.3/Json8.3/Utilities/DynamicProxy.cs new file mode 100644 index 0000000..7fb0100 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Utilities/DynamicProxy.cs @@ -0,0 +1,113 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +#if !(NET35 || NET20 || PORTABLE40) +using System; +using System.Collections.Generic; +using System.Dynamic; +using System.Linq; +using System.Linq.Expressions; +using System.Text; + +namespace Newtonsoft.Json.Utilities +{ + internal class DynamicProxy + { + public virtual IEnumerable GetDynamicMemberNames(T instance) + { + return new string[0]; + } + + public virtual bool TryBinaryOperation(T instance, BinaryOperationBinder binder, object arg, out object result) + { + result = null; + return false; + } + + public virtual bool TryConvert(T instance, ConvertBinder binder, out object result) + { + result = null; + return false; + } + + public virtual bool TryCreateInstance(T instance, CreateInstanceBinder binder, object[] args, out object result) + { + result = null; + return false; + } + + public virtual bool TryDeleteIndex(T instance, DeleteIndexBinder binder, object[] indexes) + { + return false; + } + + public virtual bool TryDeleteMember(T instance, DeleteMemberBinder binder) + { + return false; + } + + public virtual bool TryGetIndex(T instance, GetIndexBinder binder, object[] indexes, out object result) + { + result = null; + return false; + } + + public virtual bool TryGetMember(T instance, GetMemberBinder binder, out object result) + { + result = null; + return false; + } + + public virtual bool TryInvoke(T instance, InvokeBinder binder, object[] args, out object result) + { + result = null; + return false; + } + + public virtual bool TryInvokeMember(T instance, InvokeMemberBinder binder, object[] args, out object result) + { + result = null; + return false; + } + + public virtual bool TrySetIndex(T instance, SetIndexBinder binder, object[] indexes, object value) + { + return false; + } + + public virtual bool TrySetMember(T instance, SetMemberBinder binder, object value) + { + return false; + } + + public virtual bool TryUnaryOperation(T instance, UnaryOperationBinder binder, out object result) + { + result = null; + return false; + } + } +} + +#endif \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Utilities/DynamicProxyMetaObject.cs b/Common/00-1Json8.3/Json8.3/Utilities/DynamicProxyMetaObject.cs new file mode 100644 index 0000000..28321d5 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Utilities/DynamicProxyMetaObject.cs @@ -0,0 +1,427 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +#if !(NET35 || NET20 || PORTABLE40) +using System; +using System.Collections.Generic; +using System.Dynamic; +using System.Linq; +using System.Linq.Expressions; +using System.Reflection; + +namespace Newtonsoft.Json.Utilities +{ + internal sealed class DynamicProxyMetaObject : DynamicMetaObject + { + private readonly DynamicProxy _proxy; + private readonly bool _dontFallbackFirst; + + internal DynamicProxyMetaObject(Expression expression, T value, DynamicProxy proxy, bool dontFallbackFirst) + : base(expression, BindingRestrictions.Empty, value) + { + _proxy = proxy; + _dontFallbackFirst = dontFallbackFirst; + } + + private new T Value + { + get { return (T)base.Value; } + } + + private bool IsOverridden(string method) + { + return ReflectionUtils.IsMethodOverridden(_proxy.GetType(), typeof(DynamicProxy), method); + } + + public override DynamicMetaObject BindGetMember(GetMemberBinder binder) + { + return IsOverridden("TryGetMember") + ? CallMethodWithResult("TryGetMember", binder, NoArgs, e => binder.FallbackGetMember(this, e)) + : base.BindGetMember(binder); + } + + public override DynamicMetaObject BindSetMember(SetMemberBinder binder, DynamicMetaObject value) + { + return IsOverridden("TrySetMember") + ? CallMethodReturnLast("TrySetMember", binder, GetArgs(value), e => binder.FallbackSetMember(this, value, e)) + : base.BindSetMember(binder, value); + } + + public override DynamicMetaObject BindDeleteMember(DeleteMemberBinder binder) + { + return IsOverridden("TryDeleteMember") + ? CallMethodNoResult("TryDeleteMember", binder, NoArgs, e => binder.FallbackDeleteMember(this, e)) + : base.BindDeleteMember(binder); + } + + public override DynamicMetaObject BindConvert(ConvertBinder binder) + { + return IsOverridden("TryConvert") + ? CallMethodWithResult("TryConvert", binder, NoArgs, e => binder.FallbackConvert(this, e)) + : base.BindConvert(binder); + } + + public override DynamicMetaObject BindInvokeMember(InvokeMemberBinder binder, DynamicMetaObject[] args) + { + if (!IsOverridden("TryInvokeMember")) + { + return base.BindInvokeMember(binder, args); + } + + // + // Generate a tree like: + // + // { + // object result; + // TryInvokeMember(payload, out result) + // ? result + // : TryGetMember(payload, out result) + // ? FallbackInvoke(result) + // : fallbackResult + // } + // + // Then it calls FallbackInvokeMember with this tree as the + // "error", giving the language the option of using this + // tree or doing .NET binding. + // + Fallback fallback = e => binder.FallbackInvokeMember(this, args, e); + + DynamicMetaObject call = BuildCallMethodWithResult( + "TryInvokeMember", + binder, + GetArgArray(args), + BuildCallMethodWithResult( + "TryGetMember", + new GetBinderAdapter(binder), + NoArgs, + fallback(null), + e => binder.FallbackInvoke(e, args, null) + ), + null + ); + + return _dontFallbackFirst ? call : fallback(call); + } + + public override DynamicMetaObject BindCreateInstance(CreateInstanceBinder binder, DynamicMetaObject[] args) + { + return IsOverridden("TryCreateInstance") + ? CallMethodWithResult("TryCreateInstance", binder, GetArgArray(args), e => binder.FallbackCreateInstance(this, args, e)) + : base.BindCreateInstance(binder, args); + } + + public override DynamicMetaObject BindInvoke(InvokeBinder binder, DynamicMetaObject[] args) + { + return IsOverridden("TryInvoke") + ? CallMethodWithResult("TryInvoke", binder, GetArgArray(args), e => binder.FallbackInvoke(this, args, e)) + : base.BindInvoke(binder, args); + } + + public override DynamicMetaObject BindBinaryOperation(BinaryOperationBinder binder, DynamicMetaObject arg) + { + return IsOverridden("TryBinaryOperation") + ? CallMethodWithResult("TryBinaryOperation", binder, GetArgs(arg), e => binder.FallbackBinaryOperation(this, arg, e)) + : base.BindBinaryOperation(binder, arg); + } + + public override DynamicMetaObject BindUnaryOperation(UnaryOperationBinder binder) + { + return IsOverridden("TryUnaryOperation") + ? CallMethodWithResult("TryUnaryOperation", binder, NoArgs, e => binder.FallbackUnaryOperation(this, e)) + : base.BindUnaryOperation(binder); + } + + public override DynamicMetaObject BindGetIndex(GetIndexBinder binder, DynamicMetaObject[] indexes) + { + return IsOverridden("TryGetIndex") + ? CallMethodWithResult("TryGetIndex", binder, GetArgArray(indexes), e => binder.FallbackGetIndex(this, indexes, e)) + : base.BindGetIndex(binder, indexes); + } + + public override DynamicMetaObject BindSetIndex(SetIndexBinder binder, DynamicMetaObject[] indexes, DynamicMetaObject value) + { + return IsOverridden("TrySetIndex") + ? CallMethodReturnLast("TrySetIndex", binder, GetArgArray(indexes, value), e => binder.FallbackSetIndex(this, indexes, value, e)) + : base.BindSetIndex(binder, indexes, value); + } + + public override DynamicMetaObject BindDeleteIndex(DeleteIndexBinder binder, DynamicMetaObject[] indexes) + { + return IsOverridden("TryDeleteIndex") + ? CallMethodNoResult("TryDeleteIndex", binder, GetArgArray(indexes), e => binder.FallbackDeleteIndex(this, indexes, e)) + : base.BindDeleteIndex(binder, indexes); + } + + private delegate DynamicMetaObject Fallback(DynamicMetaObject errorSuggestion); + + private static readonly Expression[] NoArgs = new Expression[0]; + + private static Expression[] GetArgs(params DynamicMetaObject[] args) + { + return args.Select(arg => Expression.Convert(arg.Expression, typeof(object))).ToArray(); + } + + private static Expression[] GetArgArray(DynamicMetaObject[] args) + { + return new[] { Expression.NewArrayInit(typeof(object), GetArgs(args)) }; + } + + private static Expression[] GetArgArray(DynamicMetaObject[] args, DynamicMetaObject value) + { + return new Expression[] + { + Expression.NewArrayInit(typeof(object), GetArgs(args)), + Expression.Convert(value.Expression, typeof(object)) + }; + } + + private static ConstantExpression Constant(DynamicMetaObjectBinder binder) + { + Type t = binder.GetType(); + while (!t.IsVisible()) + { + t = t.BaseType(); + } + return Expression.Constant(binder, t); + } + + /// + /// Helper method for generating a MetaObject which calls a + /// specific method on Dynamic that returns a result + /// + private DynamicMetaObject CallMethodWithResult(string methodName, DynamicMetaObjectBinder binder, Expression[] args, Fallback fallback, Fallback fallbackInvoke = null) + { + // + // First, call fallback to do default binding + // This produces either an error or a call to a .NET member + // + DynamicMetaObject fallbackResult = fallback(null); + + DynamicMetaObject callDynamic = BuildCallMethodWithResult(methodName, binder, args, fallbackResult, fallbackInvoke); + + // + // Now, call fallback again using our new MO as the error + // When we do this, one of two things can happen: + // 1. Binding will succeed, and it will ignore our call to + // the dynamic method, OR + // 2. Binding will fail, and it will use the MO we created + // above. + // + + return _dontFallbackFirst ? callDynamic : fallback(callDynamic); + } + + private DynamicMetaObject BuildCallMethodWithResult(string methodName, DynamicMetaObjectBinder binder, Expression[] args, DynamicMetaObject fallbackResult, Fallback fallbackInvoke) + { + // + // Build a new expression like: + // { + // object result; + // TryGetMember(payload, out result) ? fallbackInvoke(result) : fallbackResult + // } + // + ParameterExpression result = Expression.Parameter(typeof(object), null); + + IList callArgs = new List(); + callArgs.Add(Expression.Convert(Expression, typeof(T))); + callArgs.Add(Constant(binder)); + callArgs.AddRange(args); + callArgs.Add(result); + + DynamicMetaObject resultMetaObject = new DynamicMetaObject(result, BindingRestrictions.Empty); + + // Need to add a conversion if calling TryConvert + if (binder.ReturnType != typeof(object)) + { + UnaryExpression convert = Expression.Convert(resultMetaObject.Expression, binder.ReturnType); + // will always be a cast or unbox + + resultMetaObject = new DynamicMetaObject(convert, resultMetaObject.Restrictions); + } + + if (fallbackInvoke != null) + { + resultMetaObject = fallbackInvoke(resultMetaObject); + } + + DynamicMetaObject callDynamic = new DynamicMetaObject( + Expression.Block( + new[] { result }, + Expression.Condition( + Expression.Call( + Expression.Constant(_proxy), + typeof(DynamicProxy).GetMethod(methodName), + callArgs + ), + resultMetaObject.Expression, + fallbackResult.Expression, + binder.ReturnType + ) + ), + GetRestrictions().Merge(resultMetaObject.Restrictions).Merge(fallbackResult.Restrictions) + ); + + return callDynamic; + } + + /// + /// Helper method for generating a MetaObject which calls a + /// specific method on Dynamic, but uses one of the arguments for + /// the result. + /// + private DynamicMetaObject CallMethodReturnLast(string methodName, DynamicMetaObjectBinder binder, Expression[] args, Fallback fallback) + { + // + // First, call fallback to do default binding + // This produces either an error or a call to a .NET member + // + DynamicMetaObject fallbackResult = fallback(null); + + // + // Build a new expression like: + // { + // object result; + // TrySetMember(payload, result = value) ? result : fallbackResult + // } + // + ParameterExpression result = Expression.Parameter(typeof(object), null); + + IList callArgs = new List(); + callArgs.Add(Expression.Convert(Expression, typeof(T))); + callArgs.Add(Constant(binder)); + callArgs.AddRange(args); + callArgs[args.Length + 1] = Expression.Assign(result, callArgs[args.Length + 1]); + + DynamicMetaObject callDynamic = new DynamicMetaObject( + Expression.Block( + new[] { result }, + Expression.Condition( + Expression.Call( + Expression.Constant(_proxy), + typeof(DynamicProxy).GetMethod(methodName), + callArgs + ), + result, + fallbackResult.Expression, + typeof(object) + ) + ), + GetRestrictions().Merge(fallbackResult.Restrictions) + ); + + // + // Now, call fallback again using our new MO as the error + // When we do this, one of two things can happen: + // 1. Binding will succeed, and it will ignore our call to + // the dynamic method, OR + // 2. Binding will fail, and it will use the MO we created + // above. + // + return _dontFallbackFirst ? callDynamic : fallback(callDynamic); + } + + /// + /// Helper method for generating a MetaObject which calls a + /// specific method on Dynamic, but uses one of the arguments for + /// the result. + /// + private DynamicMetaObject CallMethodNoResult(string methodName, DynamicMetaObjectBinder binder, Expression[] args, Fallback fallback) + { + // + // First, call fallback to do default binding + // This produces either an error or a call to a .NET member + // + DynamicMetaObject fallbackResult = fallback(null); + + IList callArgs = new List(); + callArgs.Add(Expression.Convert(Expression, typeof(T))); + callArgs.Add(Constant(binder)); + callArgs.AddRange(args); + + // + // Build a new expression like: + // if (TryDeleteMember(payload)) { } else { fallbackResult } + // + DynamicMetaObject callDynamic = new DynamicMetaObject( + Expression.Condition( + Expression.Call( + Expression.Constant(_proxy), + typeof(DynamicProxy).GetMethod(methodName), + callArgs + ), + Expression.Empty(), + fallbackResult.Expression, + typeof(void) + ), + GetRestrictions().Merge(fallbackResult.Restrictions) + ); + + // + // Now, call fallback again using our new MO as the error + // When we do this, one of two things can happen: + // 1. Binding will succeed, and it will ignore our call to + // the dynamic method, OR + // 2. Binding will fail, and it will use the MO we created + // above. + // + return _dontFallbackFirst ? callDynamic : fallback(callDynamic); + } + + /// + /// Returns a Restrictions object which includes our current restrictions merged + /// with a restriction limiting our type + /// + private BindingRestrictions GetRestrictions() + { + return (Value == null && HasValue) + ? BindingRestrictions.GetInstanceRestriction(Expression, null) + : BindingRestrictions.GetTypeRestriction(Expression, LimitType); + } + + public override IEnumerable GetDynamicMemberNames() + { + return _proxy.GetDynamicMemberNames(Value); + } + + // It is okay to throw NotSupported from this binder. This object + // is only used by DynamicObject.GetMember--it is not expected to + // (and cannot) implement binding semantics. It is just so the DO + // can use the Name and IgnoreCase properties. + private sealed class GetBinderAdapter : GetMemberBinder + { + internal GetBinderAdapter(InvokeMemberBinder binder) : + base(binder.Name, binder.IgnoreCase) + { + } + + public override DynamicMetaObject FallbackGetMember(DynamicMetaObject target, DynamicMetaObject errorSuggestion) + { + throw new NotSupportedException(); + } + } + } +} + +#endif \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Utilities/DynamicReflectionDelegateFactory.cs b/Common/00-1Json8.3/Json8.3/Utilities/DynamicReflectionDelegateFactory.cs new file mode 100644 index 0000000..13cfe7b --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Utilities/DynamicReflectionDelegateFactory.cs @@ -0,0 +1,360 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +#if !(DOTNET || PORTABLE || PORTABLE40) +using System; +using System.Collections.Generic; +#if NET20 +using Newtonsoft.Json.Utilities.LinqBridge; +#endif +using System.Reflection; +using System.Reflection.Emit; +using Newtonsoft.Json.Serialization; +using System.Globalization; + +namespace Newtonsoft.Json.Utilities +{ + internal class DynamicReflectionDelegateFactory : ReflectionDelegateFactory + { + public static DynamicReflectionDelegateFactory Instance = new DynamicReflectionDelegateFactory(); + + private static DynamicMethod CreateDynamicMethod(string name, Type returnType, Type[] parameterTypes, Type owner) + { + DynamicMethod dynamicMethod = !owner.IsInterface() + ? new DynamicMethod(name, returnType, parameterTypes, owner, true) + : new DynamicMethod(name, returnType, parameterTypes, owner.Module, true); + + return dynamicMethod; + } + + public override ObjectConstructor CreateParameterizedConstructor(MethodBase method) + { + DynamicMethod dynamicMethod = CreateDynamicMethod(method.ToString(), typeof(object), new[] { typeof(object[]) }, method.DeclaringType); + ILGenerator generator = dynamicMethod.GetILGenerator(); + + GenerateCreateMethodCallIL(method, generator, 0); + + return (ObjectConstructor)dynamicMethod.CreateDelegate(typeof(ObjectConstructor)); + } + + public override MethodCall CreateMethodCall(MethodBase method) + { + DynamicMethod dynamicMethod = CreateDynamicMethod(method.ToString(), typeof(object), new[] { typeof(object), typeof(object[]) }, method.DeclaringType); + ILGenerator generator = dynamicMethod.GetILGenerator(); + + GenerateCreateMethodCallIL(method, generator, 1); + + return (MethodCall)dynamicMethod.CreateDelegate(typeof(MethodCall)); + } + + private void GenerateCreateMethodCallIL(MethodBase method, ILGenerator generator, int argsIndex) + { + ParameterInfo[] args = method.GetParameters(); + + Label argsOk = generator.DefineLabel(); + + // throw an error if the number of argument values doesn't match method parameters + generator.Emit(OpCodes.Ldarg, argsIndex); + generator.Emit(OpCodes.Ldlen); + generator.Emit(OpCodes.Ldc_I4, args.Length); + generator.Emit(OpCodes.Beq, argsOk); + generator.Emit(OpCodes.Newobj, typeof(TargetParameterCountException).GetConstructor(ReflectionUtils.EmptyTypes)); + generator.Emit(OpCodes.Throw); + + generator.MarkLabel(argsOk); + + if (!method.IsConstructor && !method.IsStatic) + { + generator.PushInstance(method.DeclaringType); + } + + int localVariableCount = 0; + + for (int i = 0; i < args.Length; i++) + { + ParameterInfo parameter = args[i]; + Type parameterType = parameter.ParameterType; + + if (parameterType.IsByRef) + { + parameterType = parameterType.GetElementType(); + + LocalBuilder localVariable = generator.DeclareLocal(parameterType); + + // don't need to set variable for 'out' parameter + if (!parameter.IsOut) + { + generator.PushArrayInstance(argsIndex, i); + + if (parameterType.IsValueType()) + { + Label skipSettingDefault = generator.DefineLabel(); + Label finishedProcessingParameter = generator.DefineLabel(); + + // check if parameter is not null + generator.Emit(OpCodes.Brtrue_S, skipSettingDefault); + + // parameter has no value, initialize to default + generator.Emit(OpCodes.Ldloca_S, localVariable); + generator.Emit(OpCodes.Initobj, parameterType); + generator.Emit(OpCodes.Br_S, finishedProcessingParameter); + + // parameter has value, get value from array again and unbox and set to variable + generator.MarkLabel(skipSettingDefault); + generator.PushArrayInstance(argsIndex, i); + generator.UnboxIfNeeded(parameterType); + generator.Emit(OpCodes.Stloc, localVariableCount); + + // parameter finished, we out! + generator.MarkLabel(finishedProcessingParameter); + } + else + { + generator.UnboxIfNeeded(parameterType); + generator.Emit(OpCodes.Stloc, localVariableCount); + } + } + + generator.Emit(OpCodes.Ldloca_S, localVariable); + + localVariableCount++; + } + else if (parameterType.IsValueType()) + { + generator.PushArrayInstance(argsIndex, i); + + // have to check that value type parameters aren't null + // otherwise they will error when unboxed + Label skipSettingDefault = generator.DefineLabel(); + Label finishedProcessingParameter = generator.DefineLabel(); + + // check if parameter is not null + generator.Emit(OpCodes.Brtrue_S, skipSettingDefault); + + // parameter has no value, initialize to default + LocalBuilder localVariable = generator.DeclareLocal(parameterType); + generator.Emit(OpCodes.Ldloca_S, localVariable); + generator.Emit(OpCodes.Initobj, parameterType); + generator.Emit(OpCodes.Ldloc, localVariableCount); + generator.Emit(OpCodes.Br_S, finishedProcessingParameter); + + // parameter has value, get value from array again and unbox + generator.MarkLabel(skipSettingDefault); + generator.PushArrayInstance(argsIndex, i); + generator.UnboxIfNeeded(parameterType); + + // parameter finished, we out! + generator.MarkLabel(finishedProcessingParameter); + localVariableCount++; + } + else + { + generator.PushArrayInstance(argsIndex, i); + + generator.UnboxIfNeeded(parameterType); + } + } + + if (method.IsConstructor) + { + generator.Emit(OpCodes.Newobj, (ConstructorInfo)method); + } + else + { + generator.CallMethod((MethodInfo)method); + } + + Type returnType = method.IsConstructor + ? method.DeclaringType + : ((MethodInfo)method).ReturnType; + + if (returnType != typeof(void)) + { + generator.BoxIfNeeded(returnType); + } + else + { + generator.Emit(OpCodes.Ldnull); + } + + generator.Return(); + } + + public override Func CreateDefaultConstructor(Type type) + { + DynamicMethod dynamicMethod = CreateDynamicMethod("Create" + type.FullName, typeof(T), ReflectionUtils.EmptyTypes, type); + dynamicMethod.InitLocals = true; + ILGenerator generator = dynamicMethod.GetILGenerator(); + + GenerateCreateDefaultConstructorIL(type, generator); + + return (Func)dynamicMethod.CreateDelegate(typeof(Func)); + } + + private void GenerateCreateDefaultConstructorIL(Type type, ILGenerator generator) + { + if (type.IsValueType()) + { + generator.DeclareLocal(type); + generator.Emit(OpCodes.Ldloc_0); + generator.Emit(OpCodes.Box, type); + } + else + { + ConstructorInfo constructorInfo = + type.GetConstructor(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, + ReflectionUtils.EmptyTypes, null); + + if (constructorInfo == null) + { + throw new ArgumentException("Could not get constructor for {0}.".FormatWith(CultureInfo.InvariantCulture, type)); + } + + generator.Emit(OpCodes.Newobj, constructorInfo); + } + + generator.Return(); + } + + public override Func CreateGet(PropertyInfo propertyInfo) + { + DynamicMethod dynamicMethod = CreateDynamicMethod("Get" + propertyInfo.Name, typeof(T), new[] { typeof(object) }, propertyInfo.DeclaringType); + ILGenerator generator = dynamicMethod.GetILGenerator(); + + GenerateCreateGetPropertyIL(propertyInfo, generator); + + return (Func)dynamicMethod.CreateDelegate(typeof(Func)); + } + + private void GenerateCreateGetPropertyIL(PropertyInfo propertyInfo, ILGenerator generator) + { + MethodInfo getMethod = propertyInfo.GetGetMethod(true); + if (getMethod == null) + { + throw new ArgumentException("Property '{0}' does not have a getter.".FormatWith(CultureInfo.InvariantCulture, propertyInfo.Name)); + } + + if (!getMethod.IsStatic) + { + generator.PushInstance(propertyInfo.DeclaringType); + } + + generator.CallMethod(getMethod); + generator.BoxIfNeeded(propertyInfo.PropertyType); + generator.Return(); + } + + public override Func CreateGet(FieldInfo fieldInfo) + { + if (fieldInfo.IsLiteral) + { + object constantValue = fieldInfo.GetValue(null); + Func getter = o => constantValue; + return getter; + } + + DynamicMethod dynamicMethod = CreateDynamicMethod("Get" + fieldInfo.Name, typeof(T), new[] { typeof(object) }, fieldInfo.DeclaringType); + ILGenerator generator = dynamicMethod.GetILGenerator(); + + GenerateCreateGetFieldIL(fieldInfo, generator); + + return (Func)dynamicMethod.CreateDelegate(typeof(Func)); + } + + private void GenerateCreateGetFieldIL(FieldInfo fieldInfo, ILGenerator generator) + { + if (!fieldInfo.IsStatic) + { + generator.PushInstance(fieldInfo.DeclaringType); + generator.Emit(OpCodes.Ldfld, fieldInfo); + } + else + { + generator.Emit(OpCodes.Ldsfld, fieldInfo); + } + + generator.BoxIfNeeded(fieldInfo.FieldType); + generator.Return(); + } + + public override Action CreateSet(FieldInfo fieldInfo) + { + DynamicMethod dynamicMethod = CreateDynamicMethod("Set" + fieldInfo.Name, null, new[] { typeof(T), typeof(object) }, fieldInfo.DeclaringType); + ILGenerator generator = dynamicMethod.GetILGenerator(); + + GenerateCreateSetFieldIL(fieldInfo, generator); + + return (Action)dynamicMethod.CreateDelegate(typeof(Action)); + } + + internal static void GenerateCreateSetFieldIL(FieldInfo fieldInfo, ILGenerator generator) + { + if (!fieldInfo.IsStatic) + { + generator.PushInstance(fieldInfo.DeclaringType); + } + + generator.Emit(OpCodes.Ldarg_1); + generator.UnboxIfNeeded(fieldInfo.FieldType); + + if (!fieldInfo.IsStatic) + { + generator.Emit(OpCodes.Stfld, fieldInfo); + } + else + { + generator.Emit(OpCodes.Stsfld, fieldInfo); + } + + generator.Return(); + } + + public override Action CreateSet(PropertyInfo propertyInfo) + { + DynamicMethod dynamicMethod = CreateDynamicMethod("Set" + propertyInfo.Name, null, new[] { typeof(T), typeof(object) }, propertyInfo.DeclaringType); + ILGenerator generator = dynamicMethod.GetILGenerator(); + + GenerateCreateSetPropertyIL(propertyInfo, generator); + + return (Action)dynamicMethod.CreateDelegate(typeof(Action)); + } + + internal static void GenerateCreateSetPropertyIL(PropertyInfo propertyInfo, ILGenerator generator) + { + MethodInfo setMethod = propertyInfo.GetSetMethod(true); + if (!setMethod.IsStatic) + { + generator.PushInstance(propertyInfo.DeclaringType); + } + + generator.Emit(OpCodes.Ldarg_1); + generator.UnboxIfNeeded(propertyInfo.PropertyType); + generator.CallMethod(setMethod); + generator.Return(); + } + } +} + +#endif \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Utilities/DynamicUtils.cs b/Common/00-1Json8.3/Json8.3/Utilities/DynamicUtils.cs new file mode 100644 index 0000000..a83d311 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Utilities/DynamicUtils.cs @@ -0,0 +1,210 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +#if !(NET35 || NET20 || PORTABLE40) +using System; +using System.Collections.Generic; +using System.Dynamic; +using System.Linq; +using System.Linq.Expressions; +#if !(PORTABLE) +using System.Reflection; +#else +using Microsoft.CSharp.RuntimeBinder; +#endif +using System.Runtime.CompilerServices; +using System.Text; +using System.Globalization; +using Newtonsoft.Json.Serialization; + +namespace Newtonsoft.Json.Utilities +{ + internal static class DynamicUtils + { + internal static class BinderWrapper + { +#if !(PORTABLE) + public const string CSharpAssemblyName = "Microsoft.CSharp, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; + + private const string BinderTypeName = "Microsoft.CSharp.RuntimeBinder.Binder, " + CSharpAssemblyName; + private const string CSharpArgumentInfoTypeName = "Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo, " + CSharpAssemblyName; + private const string CSharpArgumentInfoFlagsTypeName = "Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, " + CSharpAssemblyName; + private const string CSharpBinderFlagsTypeName = "Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, " + CSharpAssemblyName; + + private static object _getCSharpArgumentInfoArray; + private static object _setCSharpArgumentInfoArray; + private static MethodCall _getMemberCall; + private static MethodCall _setMemberCall; + private static bool _init; + + private static void Init() + { + if (!_init) + { + Type binderType = Type.GetType(BinderTypeName, false); + if (binderType == null) + { + throw new InvalidOperationException("Could not resolve type '{0}'. You may need to add a reference to Microsoft.CSharp.dll to work with dynamic types.".FormatWith(CultureInfo.InvariantCulture, BinderTypeName)); + } + + // None + _getCSharpArgumentInfoArray = CreateSharpArgumentInfoArray(0); + // None, Constant | UseCompileTimeType + _setCSharpArgumentInfoArray = CreateSharpArgumentInfoArray(0, 3); + CreateMemberCalls(); + + _init = true; + } + } + + private static object CreateSharpArgumentInfoArray(params int[] values) + { + Type csharpArgumentInfoType = Type.GetType(CSharpArgumentInfoTypeName); + Type csharpArgumentInfoFlags = Type.GetType(CSharpArgumentInfoFlagsTypeName); + + Array a = Array.CreateInstance(csharpArgumentInfoType, values.Length); + + for (int i = 0; i < values.Length; i++) + { + MethodInfo createArgumentInfoMethod = csharpArgumentInfoType.GetMethod("Create", new[] { csharpArgumentInfoFlags, typeof(string) }); + object arg = createArgumentInfoMethod.Invoke(null, new object[] { 0, null }); + a.SetValue(arg, i); + } + + return a; + } + + private static void CreateMemberCalls() + { + Type csharpArgumentInfoType = Type.GetType(CSharpArgumentInfoTypeName, true); + Type csharpBinderFlagsType = Type.GetType(CSharpBinderFlagsTypeName, true); + Type binderType = Type.GetType(BinderTypeName, true); + + Type csharpArgumentInfoTypeEnumerableType = typeof(IEnumerable<>).MakeGenericType(csharpArgumentInfoType); + + MethodInfo getMemberMethod = binderType.GetMethod("GetMember", new[] { csharpBinderFlagsType, typeof(string), typeof(Type), csharpArgumentInfoTypeEnumerableType }); + _getMemberCall = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall(getMemberMethod); + + MethodInfo setMemberMethod = binderType.GetMethod("SetMember", new[] { csharpBinderFlagsType, typeof(string), typeof(Type), csharpArgumentInfoTypeEnumerableType }); + _setMemberCall = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall(setMemberMethod); + } +#endif + + public static CallSiteBinder GetMember(string name, Type context) + { +#if !(PORTABLE) + Init(); + return (CallSiteBinder)_getMemberCall(null, 0, name, context, _getCSharpArgumentInfoArray); +#else + return Binder.GetMember( + CSharpBinderFlags.None, name, context, new[] {CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null)}); +#endif + } + + public static CallSiteBinder SetMember(string name, Type context) + { +#if !(PORTABLE) + Init(); + return (CallSiteBinder)_setMemberCall(null, 0, name, context, _setCSharpArgumentInfoArray); +#else + return Binder.SetMember( + CSharpBinderFlags.None, name, context, new[] + { + CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.UseCompileTimeType, null), + CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.Constant, null) + }); +#endif + } + } + + public static IEnumerable GetDynamicMemberNames(this IDynamicMetaObjectProvider dynamicProvider) + { + DynamicMetaObject metaObject = dynamicProvider.GetMetaObject(Expression.Constant(dynamicProvider)); + return metaObject.GetDynamicMemberNames(); + } + } + + internal class NoThrowGetBinderMember : GetMemberBinder + { + private readonly GetMemberBinder _innerBinder; + + public NoThrowGetBinderMember(GetMemberBinder innerBinder) + : base(innerBinder.Name, innerBinder.IgnoreCase) + { + _innerBinder = innerBinder; + } + + public override DynamicMetaObject FallbackGetMember(DynamicMetaObject target, DynamicMetaObject errorSuggestion) + { + DynamicMetaObject retMetaObject = _innerBinder.Bind(target, new DynamicMetaObject[] { }); + + NoThrowExpressionVisitor noThrowVisitor = new NoThrowExpressionVisitor(); + Expression resultExpression = noThrowVisitor.Visit(retMetaObject.Expression); + + DynamicMetaObject finalMetaObject = new DynamicMetaObject(resultExpression, retMetaObject.Restrictions); + return finalMetaObject; + } + } + + internal class NoThrowSetBinderMember : SetMemberBinder + { + private readonly SetMemberBinder _innerBinder; + + public NoThrowSetBinderMember(SetMemberBinder innerBinder) + : base(innerBinder.Name, innerBinder.IgnoreCase) + { + _innerBinder = innerBinder; + } + + public override DynamicMetaObject FallbackSetMember(DynamicMetaObject target, DynamicMetaObject value, DynamicMetaObject errorSuggestion) + { + DynamicMetaObject retMetaObject = _innerBinder.Bind(target, new DynamicMetaObject[] { value }); + + NoThrowExpressionVisitor noThrowVisitor = new NoThrowExpressionVisitor(); + Expression resultExpression = noThrowVisitor.Visit(retMetaObject.Expression); + + DynamicMetaObject finalMetaObject = new DynamicMetaObject(resultExpression, retMetaObject.Restrictions); + return finalMetaObject; + } + } + + internal class NoThrowExpressionVisitor : ExpressionVisitor + { + internal static readonly object ErrorResult = new object(); + + protected override Expression VisitConditional(ConditionalExpression node) + { + // if the result of a test is to throw an error, rewrite to result an error result value + if (node.IfFalse.NodeType == ExpressionType.Throw) + { + return Expression.Condition(node.Test, node.IfTrue, Expression.Constant(ErrorResult)); + } + + return base.VisitConditional(node); + } + } +} + +#endif \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Utilities/EnumUtils.cs b/Common/00-1Json8.3/Json8.3/Utilities/EnumUtils.cs new file mode 100644 index 0000000..69d33dc --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Utilities/EnumUtils.cs @@ -0,0 +1,257 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Runtime.Serialization; +#if NET20 +using Newtonsoft.Json.Utilities.LinqBridge; +#else +using System.Linq; +#endif +using System.Reflection; + +namespace Newtonsoft.Json.Utilities +{ + internal static class EnumUtils + { + private static readonly ThreadSafeStore> EnumMemberNamesPerType = new ThreadSafeStore>(InitializeEnumType); + + private static BidirectionalDictionary InitializeEnumType(Type type) + { + BidirectionalDictionary map = new BidirectionalDictionary( + StringComparer.OrdinalIgnoreCase, + StringComparer.OrdinalIgnoreCase); + + foreach (FieldInfo f in type.GetFields()) + { + string n1 = f.Name; + string n2; + +#if !NET20 + n2 = f.GetCustomAttributes(typeof(EnumMemberAttribute), true) + .Cast() + .Select(a => a.Value) + .SingleOrDefault() ?? f.Name; +#else + n2 = f.Name; +#endif + + string s; + if (map.TryGetBySecond(n2, out s)) + { + throw new InvalidOperationException("Enum name '{0}' already exists on enum '{1}'.".FormatWith(CultureInfo.InvariantCulture, n2, type.Name)); + } + + map.Set(n1, n2); + } + + return map; + } + + public static IList GetFlagsValues(T value) where T : struct + { + Type enumType = typeof(T); + + if (!enumType.IsDefined(typeof(FlagsAttribute), false)) + { + throw new ArgumentException("Enum type {0} is not a set of flags.".FormatWith(CultureInfo.InvariantCulture, enumType)); + } + + Type underlyingType = Enum.GetUnderlyingType(value.GetType()); + + ulong num = Convert.ToUInt64(value, CultureInfo.InvariantCulture); + IList> enumNameValues = GetNamesAndValues(); + IList selectedFlagsValues = new List(); + + foreach (EnumValue enumNameValue in enumNameValues) + { + if ((num & enumNameValue.Value) == enumNameValue.Value && enumNameValue.Value != 0) + { + selectedFlagsValues.Add((T)Convert.ChangeType(enumNameValue.Value, underlyingType, CultureInfo.CurrentCulture)); + } + } + + if (selectedFlagsValues.Count == 0 && enumNameValues.SingleOrDefault(v => v.Value == 0) != null) + { + selectedFlagsValues.Add(default(T)); + } + + return selectedFlagsValues; + } + + /// + /// Gets a dictionary of the names and values of an Enum type. + /// + /// + public static IList> GetNamesAndValues() where T : struct + { + return GetNamesAndValues(typeof(T)); + } + + /// + /// Gets a dictionary of the names and values of an Enum type. + /// + /// The enum type to get names and values for. + /// + public static IList> GetNamesAndValues(Type enumType) where TUnderlyingType : struct + { + if (enumType == null) + { + throw new ArgumentNullException(nameof(enumType)); + } + + if (!enumType.IsEnum()) + { + throw new ArgumentException("Type {0} is not an Enum.".FormatWith(CultureInfo.InvariantCulture, enumType), nameof(enumType)); + } + + IList enumValues = GetValues(enumType); + IList enumNames = GetNames(enumType); + + IList> nameValues = new List>(); + + for (int i = 0; i < enumValues.Count; i++) + { + try + { + nameValues.Add(new EnumValue(enumNames[i], (TUnderlyingType)Convert.ChangeType(enumValues[i], typeof(TUnderlyingType), CultureInfo.CurrentCulture))); + } + catch (OverflowException e) + { + throw new InvalidOperationException( + string.Format(CultureInfo.InvariantCulture, "Value from enum with the underlying type of {0} cannot be added to dictionary with a value type of {1}. Value was too large: {2}", + Enum.GetUnderlyingType(enumType), typeof(TUnderlyingType), Convert.ToUInt64(enumValues[i], CultureInfo.InvariantCulture)), e); + } + } + + return nameValues; + } + + public static IList GetValues(Type enumType) + { + if (!enumType.IsEnum()) + { + throw new ArgumentException("Type '" + enumType.Name + "' is not an enum."); + } + + List values = new List(); + + var fields = enumType.GetFields().Where(f => f.IsLiteral); + + foreach (FieldInfo field in fields) + { + object value = field.GetValue(enumType); + values.Add(value); + } + + return values; + } + + public static IList GetNames(Type enumType) + { + if (!enumType.IsEnum()) + { + throw new ArgumentException("Type '" + enumType.Name + "' is not an enum."); + } + + List values = new List(); + + var fields = enumType.GetFields().Where(f => f.IsLiteral); + + foreach (FieldInfo field in fields) + { + values.Add(field.Name); + } + + return values; + } + + public static object ParseEnumName(string enumText, bool isNullable, Type t) + { + if (enumText == string.Empty && isNullable) + { + return null; + } + + string finalEnumText; + + BidirectionalDictionary map = EnumMemberNamesPerType.Get(t); + if (enumText.IndexOf(',') != -1) + { + string[] names = enumText.Split(','); + for (int i = 0; i < names.Length; i++) + { + string name = names[i].Trim(); + + names[i] = ResolvedEnumName(map, name); + } + + finalEnumText = string.Join(", ", names); + } + else + { + finalEnumText = ResolvedEnumName(map, enumText); + } + + return Enum.Parse(t, finalEnumText, true); + } + + public static string ToEnumName(Type enumType, string enumText, bool camelCaseText) + { + BidirectionalDictionary map = EnumMemberNamesPerType.Get(enumType); + + string[] names = enumText.Split(','); + for (int i = 0; i < names.Length; i++) + { + string name = names[i].Trim(); + + string resolvedEnumName; + map.TryGetByFirst(name, out resolvedEnumName); + resolvedEnumName = resolvedEnumName ?? name; + + if (camelCaseText) + { + resolvedEnumName = StringUtils.ToCamelCase(resolvedEnumName); + } + + names[i] = resolvedEnumName; + } + + string finalName = string.Join(", ", names); + + return finalName; + } + + private static string ResolvedEnumName(BidirectionalDictionary map, string enumText) + { + string resolvedEnumName; + map.TryGetBySecond(enumText, out resolvedEnumName); + resolvedEnumName = resolvedEnumName ?? enumText; + return resolvedEnumName; + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Utilities/EnumValue.cs b/Common/00-1Json8.3/Json8.3/Utilities/EnumValue.cs new file mode 100644 index 0000000..c672ead --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Utilities/EnumValue.cs @@ -0,0 +1,49 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +namespace Newtonsoft.Json.Utilities +{ + internal class EnumValue where T : struct + { + private readonly string _name; + private readonly T _value; + + public string Name + { + get { return _name; } + } + + public T Value + { + get { return _value; } + } + + public EnumValue(string name, T value) + { + _name = name; + _value = value; + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Utilities/ExpressionReflectionDelegateFactory.cs b/Common/00-1Json8.3/Json8.3/Utilities/ExpressionReflectionDelegateFactory.cs new file mode 100644 index 0000000..0204262 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Utilities/ExpressionReflectionDelegateFactory.cs @@ -0,0 +1,368 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +#if !(NET20 || NET35) +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System; +using System.Linq.Expressions; +using System.Reflection; +using Newtonsoft.Json.Serialization; + +namespace Newtonsoft.Json.Utilities +{ + internal class ExpressionReflectionDelegateFactory : ReflectionDelegateFactory + { + private static readonly ExpressionReflectionDelegateFactory _instance = new ExpressionReflectionDelegateFactory(); + + internal static ReflectionDelegateFactory Instance + { + get { return _instance; } + } + + public override ObjectConstructor CreateParameterizedConstructor(MethodBase method) + { + ValidationUtils.ArgumentNotNull(method, nameof(method)); + + Type type = typeof(object); + + ParameterExpression argsParameterExpression = Expression.Parameter(typeof(object[]), "args"); + + Expression callExpression = BuildMethodCall(method, type, null, argsParameterExpression); + + LambdaExpression lambdaExpression = Expression.Lambda(typeof(ObjectConstructor), callExpression, argsParameterExpression); + + ObjectConstructor compiled = (ObjectConstructor)lambdaExpression.Compile(); + return compiled; + } + + public override MethodCall CreateMethodCall(MethodBase method) + { + ValidationUtils.ArgumentNotNull(method, nameof(method)); + + Type type = typeof(object); + + ParameterExpression targetParameterExpression = Expression.Parameter(type, "target"); + ParameterExpression argsParameterExpression = Expression.Parameter(typeof(object[]), "args"); + + Expression callExpression = BuildMethodCall(method, type, targetParameterExpression, argsParameterExpression); + + LambdaExpression lambdaExpression = Expression.Lambda(typeof(MethodCall), callExpression, targetParameterExpression, argsParameterExpression); + + MethodCall compiled = (MethodCall)lambdaExpression.Compile(); + return compiled; + } + + private class ByRefParameter + { + public Expression Value; + public ParameterExpression Variable; + public bool IsOut; + } + + private Expression BuildMethodCall(MethodBase method, Type type, ParameterExpression targetParameterExpression, ParameterExpression argsParameterExpression) + { + ParameterInfo[] parametersInfo = method.GetParameters(); + + Expression[] argsExpression = new Expression[parametersInfo.Length]; + IList refParameterMap = new List(); + + for (int i = 0; i < parametersInfo.Length; i++) + { + ParameterInfo parameter = parametersInfo[i]; + Type parameterType = parameter.ParameterType; + bool isByRef = false; + if (parameterType.IsByRef) + { + parameterType = parameterType.GetElementType(); + isByRef = true; + } + + Expression indexExpression = Expression.Constant(i); + + Expression paramAccessorExpression = Expression.ArrayIndex(argsParameterExpression, indexExpression); + + Expression argExpression; + + if (parameterType.IsValueType()) + { + BinaryExpression ensureValueTypeNotNull = Expression.Coalesce(paramAccessorExpression, Expression.New(parameterType)); + + argExpression = EnsureCastExpression(ensureValueTypeNotNull, parameterType); + } + else + { + argExpression = EnsureCastExpression(paramAccessorExpression, parameterType); + } + + if (isByRef) + { + ParameterExpression variable = Expression.Variable(parameterType); + refParameterMap.Add(new ByRefParameter + { + Value = argExpression, + Variable = variable, + IsOut = parameter.IsOut + }); + + argExpression = variable; + } + + argsExpression[i] = argExpression; + } + + Expression callExpression; + if (method.IsConstructor) + { + callExpression = Expression.New((ConstructorInfo)method, argsExpression); + } + else if (method.IsStatic) + { + callExpression = Expression.Call((MethodInfo)method, argsExpression); + } + else + { + Expression readParameter = EnsureCastExpression(targetParameterExpression, method.DeclaringType); + + callExpression = Expression.Call(readParameter, (MethodInfo)method, argsExpression); + } + + if (method is MethodInfo) + { + MethodInfo m = (MethodInfo)method; + if (m.ReturnType != typeof(void)) + { + callExpression = EnsureCastExpression(callExpression, type); + } + else + { + callExpression = Expression.Block(callExpression, Expression.Constant(null)); + } + } + else + { + callExpression = EnsureCastExpression(callExpression, type); + } + + if (refParameterMap.Count > 0) + { + IList variableExpressions = new List(); + IList bodyExpressions = new List(); + foreach (ByRefParameter p in refParameterMap) + { + if (!p.IsOut) + { + bodyExpressions.Add(Expression.Assign(p.Variable, p.Value)); + } + + variableExpressions.Add(p.Variable); + } + + bodyExpressions.Add(callExpression); + + callExpression = Expression.Block(variableExpressions, bodyExpressions); + } + + return callExpression; + } + + public override Func CreateDefaultConstructor(Type type) + { + ValidationUtils.ArgumentNotNull(type, "type"); + + // avoid error from expressions compiler because of abstract class + if (type.IsAbstract()) + { + return () => (T)Activator.CreateInstance(type); + } + + try + { + Type resultType = typeof(T); + + Expression expression = Expression.New(type); + + expression = EnsureCastExpression(expression, resultType); + + LambdaExpression lambdaExpression = Expression.Lambda(typeof(Func), expression); + + Func compiled = (Func)lambdaExpression.Compile(); + return compiled; + } + catch + { + // an error can be thrown if constructor is not valid on Win8 + // will have INVOCATION_FLAGS_NON_W8P_FX_API invocation flag + return () => (T)Activator.CreateInstance(type); + } + } + + public override Func CreateGet(PropertyInfo propertyInfo) + { + ValidationUtils.ArgumentNotNull(propertyInfo, nameof(propertyInfo)); + + Type instanceType = typeof(T); + Type resultType = typeof(object); + + ParameterExpression parameterExpression = Expression.Parameter(instanceType, "instance"); + Expression resultExpression; + + MethodInfo getMethod = propertyInfo.GetGetMethod(true); + + if (getMethod.IsStatic) + { + resultExpression = Expression.MakeMemberAccess(null, propertyInfo); + } + else + { + Expression readParameter = EnsureCastExpression(parameterExpression, propertyInfo.DeclaringType); + + resultExpression = Expression.MakeMemberAccess(readParameter, propertyInfo); + } + + resultExpression = EnsureCastExpression(resultExpression, resultType); + + LambdaExpression lambdaExpression = Expression.Lambda(typeof(Func), resultExpression, parameterExpression); + + Func compiled = (Func)lambdaExpression.Compile(); + return compiled; + } + + public override Func CreateGet(FieldInfo fieldInfo) + { + ValidationUtils.ArgumentNotNull(fieldInfo, nameof(fieldInfo)); + + ParameterExpression sourceParameter = Expression.Parameter(typeof(T), "source"); + + Expression fieldExpression; + if (fieldInfo.IsStatic) + { + fieldExpression = Expression.Field(null, fieldInfo); + } + else + { + Expression sourceExpression = EnsureCastExpression(sourceParameter, fieldInfo.DeclaringType); + + fieldExpression = Expression.Field(sourceExpression, fieldInfo); + } + + fieldExpression = EnsureCastExpression(fieldExpression, typeof(object)); + + Func compiled = Expression.Lambda>(fieldExpression, sourceParameter).Compile(); + return compiled; + } + + public override Action CreateSet(FieldInfo fieldInfo) + { + ValidationUtils.ArgumentNotNull(fieldInfo, nameof(fieldInfo)); + + // use reflection for structs + // expression doesn't correctly set value + if (fieldInfo.DeclaringType.IsValueType() || fieldInfo.IsInitOnly) + { + return LateBoundReflectionDelegateFactory.Instance.CreateSet(fieldInfo); + } + + ParameterExpression sourceParameterExpression = Expression.Parameter(typeof(T), "source"); + ParameterExpression valueParameterExpression = Expression.Parameter(typeof(object), "value"); + + Expression fieldExpression; + if (fieldInfo.IsStatic) + { + fieldExpression = Expression.Field(null, fieldInfo); + } + else + { + Expression sourceExpression = EnsureCastExpression(sourceParameterExpression, fieldInfo.DeclaringType); + + fieldExpression = Expression.Field(sourceExpression, fieldInfo); + } + + Expression valueExpression = EnsureCastExpression(valueParameterExpression, fieldExpression.Type); + + BinaryExpression assignExpression = Expression.Assign(fieldExpression, valueExpression); + + LambdaExpression lambdaExpression = Expression.Lambda(typeof(Action), assignExpression, sourceParameterExpression, valueParameterExpression); + + Action compiled = (Action)lambdaExpression.Compile(); + return compiled; + } + + public override Action CreateSet(PropertyInfo propertyInfo) + { + ValidationUtils.ArgumentNotNull(propertyInfo, nameof(propertyInfo)); + + // use reflection for structs + // expression doesn't correctly set value + if (propertyInfo.DeclaringType.IsValueType()) + { + return LateBoundReflectionDelegateFactory.Instance.CreateSet(propertyInfo); + } + + Type instanceType = typeof(T); + Type valueType = typeof(object); + + ParameterExpression instanceParameter = Expression.Parameter(instanceType, "instance"); + + ParameterExpression valueParameter = Expression.Parameter(valueType, "value"); + Expression readValueParameter = EnsureCastExpression(valueParameter, propertyInfo.PropertyType); + + MethodInfo setMethod = propertyInfo.GetSetMethod(true); + + Expression setExpression; + if (setMethod.IsStatic) + { + setExpression = Expression.Call(setMethod, readValueParameter); + } + else + { + Expression readInstanceParameter = EnsureCastExpression(instanceParameter, propertyInfo.DeclaringType); + + setExpression = Expression.Call(readInstanceParameter, setMethod, readValueParameter); + } + + LambdaExpression lambdaExpression = Expression.Lambda(typeof(Action), setExpression, instanceParameter, valueParameter); + + Action compiled = (Action)lambdaExpression.Compile(); + return compiled; + } + + private Expression EnsureCastExpression(Expression expression, Type targetType) + { + Type expressionType = expression.Type; + + // check if a cast or conversion is required + if (expressionType == targetType || (!expressionType.IsValueType() && targetType.IsAssignableFrom(expressionType))) + { + return expression; + } + + return Expression.Convert(expression, targetType); + } + } +} + +#endif \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Utilities/FSharpUtils.cs b/Common/00-1Json8.3/Json8.3/Utilities/FSharpUtils.cs new file mode 100644 index 0000000..f288f1f --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Utilities/FSharpUtils.cs @@ -0,0 +1,195 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +#if !(NET35 || NET20) +using System.Threading; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Text; +using Newtonsoft.Json.Serialization; + +namespace Newtonsoft.Json.Utilities +{ + internal class FSharpFunction + { + private readonly object _instance; + private readonly MethodCall _invoker; + + public FSharpFunction(object instance, MethodCall invoker) + { + _instance = instance; + _invoker = invoker; + } + + public object Invoke(params object[] args) + { + object o = _invoker(_instance, args); + + return o; + } + } + + internal static class FSharpUtils + { + private static readonly object Lock = new object(); + + private static bool _initialized; + private static MethodInfo _ofSeq; + private static Type _mapType; + + public static Assembly FSharpCoreAssembly { get; private set; } + public static MethodCall IsUnion { get; private set; } + public static MethodCall GetUnionCases { get; private set; } + public static MethodCall PreComputeUnionTagReader { get; private set; } + public static MethodCall PreComputeUnionReader { get; private set; } + public static MethodCall PreComputeUnionConstructor { get; private set; } + public static Func GetUnionCaseInfoDeclaringType { get; private set; } + public static Func GetUnionCaseInfoName { get; private set; } + public static Func GetUnionCaseInfoTag { get; private set; } + public static MethodCall GetUnionCaseInfoFields { get; private set; } + + public const string FSharpSetTypeName = "FSharpSet`1"; + public const string FSharpListTypeName = "FSharpList`1"; + public const string FSharpMapTypeName = "FSharpMap`2"; + + public static void EnsureInitialized(Assembly fsharpCoreAssembly) + { + if (!_initialized) + { + lock (Lock) + { + if (!_initialized) + { + FSharpCoreAssembly = fsharpCoreAssembly; + + Type fsharpType = fsharpCoreAssembly.GetType("Microsoft.FSharp.Reflection.FSharpType"); + + MethodInfo isUnionMethodInfo = GetMethodWithNonPublicFallback(fsharpType, "IsUnion", BindingFlags.Public | BindingFlags.Static); + IsUnion = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall(isUnionMethodInfo); + + MethodInfo getUnionCasesMethodInfo = GetMethodWithNonPublicFallback(fsharpType, "GetUnionCases", BindingFlags.Public | BindingFlags.Static); + GetUnionCases = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall(getUnionCasesMethodInfo); + + Type fsharpValue = fsharpCoreAssembly.GetType("Microsoft.FSharp.Reflection.FSharpValue"); + + PreComputeUnionTagReader = CreateFSharpFuncCall(fsharpValue, "PreComputeUnionTagReader"); + PreComputeUnionReader = CreateFSharpFuncCall(fsharpValue, "PreComputeUnionReader"); + PreComputeUnionConstructor = CreateFSharpFuncCall(fsharpValue, "PreComputeUnionConstructor"); + + Type unionCaseInfo = fsharpCoreAssembly.GetType("Microsoft.FSharp.Reflection.UnionCaseInfo"); + + GetUnionCaseInfoName = JsonTypeReflector.ReflectionDelegateFactory.CreateGet(unionCaseInfo.GetProperty("Name")); + GetUnionCaseInfoTag = JsonTypeReflector.ReflectionDelegateFactory.CreateGet(unionCaseInfo.GetProperty("Tag")); + GetUnionCaseInfoDeclaringType = JsonTypeReflector.ReflectionDelegateFactory.CreateGet(unionCaseInfo.GetProperty("DeclaringType")); + GetUnionCaseInfoFields = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall(unionCaseInfo.GetMethod("GetFields")); + + Type listModule = fsharpCoreAssembly.GetType("Microsoft.FSharp.Collections.ListModule"); + _ofSeq = listModule.GetMethod("OfSeq"); + + _mapType = fsharpCoreAssembly.GetType("Microsoft.FSharp.Collections.FSharpMap`2"); + +#if !(DOTNET || PORTABLE) + Thread.MemoryBarrier(); +#endif + _initialized = true; + } + } + } + } + + private static MethodInfo GetMethodWithNonPublicFallback(Type type, string methodName, BindingFlags bindingFlags) + { + MethodInfo methodInfo = type.GetMethod(methodName, bindingFlags); + + // if no matching method then attempt to find with nonpublic flag + // this is required because in WinApps some methods are private but always using NonPublic breaks medium trust + // https://github.com/JamesNK/Newtonsoft.Json/pull/649 + // https://github.com/JamesNK/Newtonsoft.Json/issues/821 + if (methodInfo == null && (bindingFlags & BindingFlags.NonPublic) != BindingFlags.NonPublic) + { + methodInfo = type.GetMethod(methodName, bindingFlags | BindingFlags.NonPublic); + } + + return methodInfo; + } + + private static MethodCall CreateFSharpFuncCall(Type type, string methodName) + { + MethodInfo innerMethodInfo = GetMethodWithNonPublicFallback(type, methodName, BindingFlags.Public | BindingFlags.Static); + MethodInfo invokeFunc = innerMethodInfo.ReturnType.GetMethod("Invoke", BindingFlags.Public | BindingFlags.Instance); + + MethodCall call = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall(innerMethodInfo); + MethodCall invoke = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall(invokeFunc); + + MethodCall createFunction = (target, args) => + { + object result = call(target, args); + + FSharpFunction f = new FSharpFunction(result, invoke); + return f; + }; + + return createFunction; + } + + public static ObjectConstructor CreateSeq(Type t) + { + MethodInfo seqType = _ofSeq.MakeGenericMethod(t); + + return JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(seqType); + } + + public static ObjectConstructor CreateMap(Type keyType, Type valueType) + { + MethodInfo creatorDefinition = typeof(FSharpUtils).GetMethod("BuildMapCreator"); + + MethodInfo creatorGeneric = creatorDefinition.MakeGenericMethod(keyType, valueType); + + return (ObjectConstructor)creatorGeneric.Invoke(null, null); + } + + public static ObjectConstructor BuildMapCreator() + { + Type genericMapType = _mapType.MakeGenericType(typeof(TKey), typeof(TValue)); + ConstructorInfo ctor = genericMapType.GetConstructor(new[] { typeof(IEnumerable>) }); + ObjectConstructor ctorDelegate = JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(ctor); + + ObjectConstructor creator = args => + { + // convert dictionary KeyValuePairs to Tuples + IEnumerable> values = (IEnumerable>)args[0]; + IEnumerable> tupleValues = values.Select(kv => new Tuple(kv.Key, kv.Value)); + + return ctorDelegate(tupleValues); + }; + + return creator; + } + } +} + +#endif \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Utilities/ILGeneratorExtensions.cs b/Common/00-1Json8.3/Json8.3/Utilities/ILGeneratorExtensions.cs new file mode 100644 index 0000000..9173659 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Utilities/ILGeneratorExtensions.cs @@ -0,0 +1,98 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +#if !(DOTNET || PORTABLE40 || PORTABLE) +using System; +using System.Reflection.Emit; +using System.Reflection; + +namespace Newtonsoft.Json.Utilities +{ + internal static class ILGeneratorExtensions + { + public static void PushInstance(this ILGenerator generator, Type type) + { + generator.Emit(OpCodes.Ldarg_0); + if (type.IsValueType()) + { + generator.Emit(OpCodes.Unbox, type); + } + else + { + generator.Emit(OpCodes.Castclass, type); + } + } + + public static void PushArrayInstance(this ILGenerator generator, int argsIndex, int arrayIndex) + { + generator.Emit(OpCodes.Ldarg, argsIndex); + generator.Emit(OpCodes.Ldc_I4, arrayIndex); + generator.Emit(OpCodes.Ldelem_Ref); + } + + public static void BoxIfNeeded(this ILGenerator generator, Type type) + { + if (type.IsValueType()) + { + generator.Emit(OpCodes.Box, type); + } + else + { + generator.Emit(OpCodes.Castclass, type); + } + } + + public static void UnboxIfNeeded(this ILGenerator generator, Type type) + { + if (type.IsValueType()) + { + generator.Emit(OpCodes.Unbox_Any, type); + } + else + { + generator.Emit(OpCodes.Castclass, type); + } + } + + public static void CallMethod(this ILGenerator generator, MethodInfo methodInfo) + { + if (methodInfo.IsFinal || !methodInfo.IsVirtual) + { + generator.Emit(OpCodes.Call, methodInfo); + } + else + { + generator.Emit(OpCodes.Callvirt, methodInfo); + } + } + + public static void Return(this ILGenerator generator) + { + generator.Emit(OpCodes.Ret); + } + } +} + +#endif \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Utilities/ImmutableCollectionsUtils.cs b/Common/00-1Json8.3/Json8.3/Utilities/ImmutableCollectionsUtils.cs new file mode 100644 index 0000000..46faa85 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Utilities/ImmutableCollectionsUtils.cs @@ -0,0 +1,176 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +#if !(NET20 || NET35 || NET40) +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Text; +using System.Threading.Tasks; +using Newtonsoft.Json.Serialization; + +namespace Newtonsoft.Json.Utilities +{ + internal static class ImmutableCollectionsUtils + { + internal class ImmutableCollectionTypeInfo + { + public ImmutableCollectionTypeInfo(string contractTypeName, string createdTypeName, string builderTypeName) + { + ContractTypeName = contractTypeName; + CreatedTypeName = createdTypeName; + BuilderTypeName = builderTypeName; + } + + public string ContractTypeName { get; set; } + public string CreatedTypeName { get; set; } + public string BuilderTypeName { get; set; } + } + + private const string ImmutableListGenericInterfaceTypeName = "System.Collections.Immutable.IImmutableList`1"; + private const string ImmutableQueueGenericInterfaceTypeName = "System.Collections.Immutable.IImmutableQueue`1"; + private const string ImmutableStackGenericInterfaceTypeName = "System.Collections.Immutable.IImmutableStack`1"; + private const string ImmutableSetGenericInterfaceTypeName = "System.Collections.Immutable.IImmutableSet`1"; + + private const string ImmutableArrayTypeName = "System.Collections.Immutable.ImmutableArray"; + private const string ImmutableArrayGenericTypeName = "System.Collections.Immutable.ImmutableArray`1"; + + private const string ImmutableListTypeName = "System.Collections.Immutable.ImmutableList"; + private const string ImmutableListGenericTypeName = "System.Collections.Immutable.ImmutableList`1"; + + private const string ImmutableQueueTypeName = "System.Collections.Immutable.ImmutableQueue"; + private const string ImmutableQueueGenericTypeName = "System.Collections.Immutable.ImmutableQueue`1"; + + private const string ImmutableStackTypeName = "System.Collections.Immutable.ImmutableStack"; + private const string ImmutableStackGenericTypeName = "System.Collections.Immutable.ImmutableStack`1"; + + private const string ImmutableSortedSetTypeName = "System.Collections.Immutable.ImmutableSortedSet"; + private const string ImmutableSortedSetGenericTypeName = "System.Collections.Immutable.ImmutableSortedSet`1"; + + private const string ImmutableHashSetTypeName = "System.Collections.Immutable.ImmutableHashSet"; + private const string ImmutableHashSetGenericTypeName = "System.Collections.Immutable.ImmutableHashSet`1"; + + private static readonly IList ArrayContractImmutableCollectionDefinitions = new List + { + new ImmutableCollectionTypeInfo(ImmutableListGenericInterfaceTypeName, ImmutableListGenericTypeName, ImmutableListTypeName), + new ImmutableCollectionTypeInfo(ImmutableListGenericTypeName, ImmutableListGenericTypeName, ImmutableListTypeName), + new ImmutableCollectionTypeInfo(ImmutableQueueGenericInterfaceTypeName, ImmutableQueueGenericTypeName, ImmutableQueueTypeName), + new ImmutableCollectionTypeInfo(ImmutableQueueGenericTypeName, ImmutableQueueGenericTypeName, ImmutableQueueTypeName), + new ImmutableCollectionTypeInfo(ImmutableStackGenericInterfaceTypeName, ImmutableStackGenericTypeName, ImmutableStackTypeName), + new ImmutableCollectionTypeInfo(ImmutableStackGenericTypeName, ImmutableStackGenericTypeName, ImmutableStackTypeName), + new ImmutableCollectionTypeInfo(ImmutableSetGenericInterfaceTypeName, ImmutableSortedSetGenericTypeName, ImmutableSortedSetTypeName), + new ImmutableCollectionTypeInfo(ImmutableSortedSetGenericTypeName, ImmutableSortedSetGenericTypeName, ImmutableSortedSetTypeName), + new ImmutableCollectionTypeInfo(ImmutableHashSetGenericTypeName, ImmutableHashSetGenericTypeName, ImmutableHashSetTypeName), + new ImmutableCollectionTypeInfo(ImmutableArrayGenericTypeName, ImmutableArrayGenericTypeName, ImmutableArrayTypeName) + }; + + private const string ImmutableDictionaryGenericInterfaceTypeName = "System.Collections.Immutable.IImmutableDictionary`2"; + + private const string ImmutableDictionaryTypeName = "System.Collections.Immutable.ImmutableDictionary"; + private const string ImmutableDictionaryGenericTypeName = "System.Collections.Immutable.ImmutableDictionary`2"; + + private const string ImmutableSortedDictionaryTypeName = "System.Collections.Immutable.ImmutableSortedDictionary"; + private const string ImmutableSortedDictionaryGenericTypeName = "System.Collections.Immutable.ImmutableSortedDictionary`2"; + + private static readonly IList DictionaryContractImmutableCollectionDefinitions = new List + { + new ImmutableCollectionTypeInfo(ImmutableDictionaryGenericInterfaceTypeName, ImmutableSortedDictionaryGenericTypeName, ImmutableSortedDictionaryTypeName), + new ImmutableCollectionTypeInfo(ImmutableSortedDictionaryGenericTypeName, ImmutableSortedDictionaryGenericTypeName, ImmutableSortedDictionaryTypeName), + new ImmutableCollectionTypeInfo(ImmutableDictionaryGenericTypeName, ImmutableDictionaryGenericTypeName, ImmutableDictionaryTypeName) + }; + + internal static bool TryBuildImmutableForArrayContract(Type underlyingType, Type collectionItemType, out Type createdType, out ObjectConstructor parameterizedCreator) + { + if (underlyingType.IsGenericType()) + { + Type underlyingTypeDefinition = underlyingType.GetGenericTypeDefinition(); + string name = underlyingTypeDefinition.FullName; + + ImmutableCollectionTypeInfo definition = ArrayContractImmutableCollectionDefinitions.FirstOrDefault(d => d.ContractTypeName == name); + if (definition != null) + { + Type createdTypeDefinition = underlyingTypeDefinition.Assembly().GetType(definition.CreatedTypeName); + Type builderTypeDefinition = underlyingTypeDefinition.Assembly().GetType(definition.BuilderTypeName); + + if (createdTypeDefinition != null && builderTypeDefinition != null) + { + MethodInfo mb = builderTypeDefinition.GetMethods().FirstOrDefault(m => m.Name == "CreateRange" && m.GetParameters().Length == 1); + if (mb != null) + { + createdType = createdTypeDefinition.MakeGenericType(collectionItemType); + MethodInfo method = mb.MakeGenericMethod(collectionItemType); + parameterizedCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(method); + return true; + } + } + } + } + + createdType = null; + parameterizedCreator = null; + return false; + } + + internal static bool TryBuildImmutableForDictionaryContract(Type underlyingType, Type keyItemType, Type valueItemType, out Type createdType, out ObjectConstructor parameterizedCreator) + { + if (underlyingType.IsGenericType()) + { + Type underlyingTypeDefinition = underlyingType.GetGenericTypeDefinition(); + string name = underlyingTypeDefinition.FullName; + + ImmutableCollectionTypeInfo definition = DictionaryContractImmutableCollectionDefinitions.FirstOrDefault(d => d.ContractTypeName == name); + if (definition != null) + { + Type createdTypeDefinition = underlyingTypeDefinition.Assembly().GetType(definition.CreatedTypeName); + Type builderTypeDefinition = underlyingTypeDefinition.Assembly().GetType(definition.BuilderTypeName); + + if (createdTypeDefinition != null && builderTypeDefinition != null) + { + MethodInfo mb = builderTypeDefinition.GetMethods().FirstOrDefault(m => + { + ParameterInfo[] parameters = m.GetParameters(); + + return m.Name == "CreateRange" && parameters.Length == 1 && parameters[0].ParameterType.IsGenericType() && parameters[0].ParameterType.GetGenericTypeDefinition() == typeof(IEnumerable<>); + }); + if (mb != null) + { + createdType = createdTypeDefinition.MakeGenericType(keyItemType, valueItemType); + MethodInfo method = mb.MakeGenericMethod(keyItemType, valueItemType); + parameterizedCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(method); + return true; + } + } + } + } + + createdType = null; + parameterizedCreator = null; + return false; + } + } +} + +#endif \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Utilities/JavaScriptUtils.cs b/Common/00-1Json8.3/Json8.3/Utilities/JavaScriptUtils.cs new file mode 100644 index 0000000..e8ef53e --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Utilities/JavaScriptUtils.cs @@ -0,0 +1,318 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Collections; +using System.Globalization; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Collections.Generic; +#if NET20 +using Newtonsoft.Json.Utilities.LinqBridge; +#else +using System.Linq; + +#endif + +namespace Newtonsoft.Json.Utilities +{ + internal static class BufferUtils + { + public static char[] RentBuffer(IArrayPool bufferPool, int minSize) + { + if (bufferPool == null) + { + return new char[minSize]; + } + + char[] buffer = bufferPool.Rent(minSize); + return buffer; + } + + public static void ReturnBuffer(IArrayPool bufferPool, char[] buffer) + { + if (bufferPool == null) + { + return; + } + + bufferPool.Return(buffer); + } + + public static char[] EnsureBufferSize(IArrayPool bufferPool, int size, char[] buffer) + { + if (bufferPool == null) + { + return new char[size]; + } + + if (buffer != null) + { + bufferPool.Return(buffer); + } + + return bufferPool.Rent(size); + } + } + + internal static class JavaScriptUtils + { + internal static readonly bool[] SingleQuoteCharEscapeFlags = new bool[128]; + internal static readonly bool[] DoubleQuoteCharEscapeFlags = new bool[128]; + internal static readonly bool[] HtmlCharEscapeFlags = new bool[128]; + + private const int UnicodeTextLength = 6; + + static JavaScriptUtils() + { + IList escapeChars = new List + { + '\n', '\r', '\t', '\\', '\f', '\b', + }; + for (int i = 0; i < ' '; i++) + { + escapeChars.Add((char)i); + } + + foreach (var escapeChar in escapeChars.Union(new[] { '\'' })) + { + SingleQuoteCharEscapeFlags[escapeChar] = true; + } + foreach (var escapeChar in escapeChars.Union(new[] { '"' })) + { + DoubleQuoteCharEscapeFlags[escapeChar] = true; + } + foreach (var escapeChar in escapeChars.Union(new[] { '"', '\'', '<', '>', '&' })) + { + HtmlCharEscapeFlags[escapeChar] = true; + } + } + + private const string EscapedUnicodeText = "!"; + + public static bool[] GetCharEscapeFlags(StringEscapeHandling stringEscapeHandling, char quoteChar) + { + if (stringEscapeHandling == StringEscapeHandling.EscapeHtml) + { + return HtmlCharEscapeFlags; + } + + if (quoteChar == '"') + { + return DoubleQuoteCharEscapeFlags; + } + + return SingleQuoteCharEscapeFlags; + } + + public static bool ShouldEscapeJavaScriptString(string s, bool[] charEscapeFlags) + { + if (s == null) + { + return false; + } + + foreach (char c in s) + { + if (c >= charEscapeFlags.Length || charEscapeFlags[c]) + { + return true; + } + } + + return false; + } + + public static void WriteEscapedJavaScriptString(TextWriter writer, string s, char delimiter, bool appendDelimiters, + bool[] charEscapeFlags, StringEscapeHandling stringEscapeHandling, IArrayPool bufferPool, ref char[] writeBuffer) + { + // leading delimiter + if (appendDelimiters) + { + writer.Write(delimiter); + } + + if (s != null) + { + int lastWritePosition = 0; + + for (int i = 0; i < s.Length; i++) + { + var c = s[i]; + + if (c < charEscapeFlags.Length && !charEscapeFlags[c]) + { + continue; + } + + string escapedValue; + + switch (c) + { + case '\t': + escapedValue = @"\t"; + break; + case '\n': + escapedValue = @"\n"; + break; + case '\r': + escapedValue = @"\r"; + break; + case '\f': + escapedValue = @"\f"; + break; + case '\b': + escapedValue = @"\b"; + break; + case '\\': + escapedValue = @"\\"; + break; + case '\u0085': // Next Line + escapedValue = @"\u0085"; + break; + case '\u2028': // Line Separator + escapedValue = @"\u2028"; + break; + case '\u2029': // Paragraph Separator + escapedValue = @"\u2029"; + break; + default: + if (c < charEscapeFlags.Length || stringEscapeHandling == StringEscapeHandling.EscapeNonAscii) + { + if (c == '\'' && stringEscapeHandling != StringEscapeHandling.EscapeHtml) + { + escapedValue = @"\'"; + } + else if (c == '"' && stringEscapeHandling != StringEscapeHandling.EscapeHtml) + { + escapedValue = @"\"""; + } + else + { + if (writeBuffer == null || writeBuffer.Length < UnicodeTextLength) + { + writeBuffer = BufferUtils.EnsureBufferSize(bufferPool, UnicodeTextLength, writeBuffer); + } + + StringUtils.ToCharAsUnicode(c, writeBuffer); + + // slightly hacky but it saves multiple conditions in if test + escapedValue = EscapedUnicodeText; + } + } + else + { + escapedValue = null; + } + break; + } + + if (escapedValue == null) + { + continue; + } + + bool isEscapedUnicodeText = string.Equals(escapedValue, EscapedUnicodeText); + + if (i > lastWritePosition) + { + int length = i - lastWritePosition + ((isEscapedUnicodeText) ? UnicodeTextLength : 0); + int start = (isEscapedUnicodeText) ? UnicodeTextLength : 0; + + if (writeBuffer == null || writeBuffer.Length < length) + { + char[] newBuffer = BufferUtils.RentBuffer(bufferPool, length); + + // the unicode text is already in the buffer + // copy it over when creating new buffer + if (isEscapedUnicodeText) + { + Array.Copy(writeBuffer, newBuffer, UnicodeTextLength); + } + + BufferUtils.ReturnBuffer(bufferPool, writeBuffer); + + writeBuffer = newBuffer; + } + + s.CopyTo(lastWritePosition, writeBuffer, start, length - start); + + // write unchanged chars before writing escaped text + writer.Write(writeBuffer, start, length - start); + } + + lastWritePosition = i + 1; + if (!isEscapedUnicodeText) + { + writer.Write(escapedValue); + } + else + { + writer.Write(writeBuffer, 0, UnicodeTextLength); + } + } + + if (lastWritePosition == 0) + { + // no escaped text, write entire string + writer.Write(s); + } + else + { + int length = s.Length - lastWritePosition; + + if (writeBuffer == null || writeBuffer.Length < length) + { + writeBuffer = BufferUtils.EnsureBufferSize(bufferPool, length, writeBuffer); + } + + s.CopyTo(lastWritePosition, writeBuffer, 0, length); + + // write remaining text + writer.Write(writeBuffer, 0, length); + } + } + + // trailing delimiter + if (appendDelimiters) + { + writer.Write(delimiter); + } + } + + public static string ToEscapedJavaScriptString(string value, char delimiter, bool appendDelimiters, StringEscapeHandling stringEscapeHandling) + { + bool[] charEscapeFlags = GetCharEscapeFlags(stringEscapeHandling, delimiter); + + using (StringWriter w = StringUtils.CreateStringWriter(StringUtils.GetLength(value) ?? 16)) + { + char[] buffer = null; + WriteEscapedJavaScriptString(w, value, delimiter, appendDelimiters, charEscapeFlags, stringEscapeHandling, null, ref buffer); + return w.ToString(); + } + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Utilities/JsonTokenUtils.cs b/Common/00-1Json8.3/Json8.3/Utilities/JsonTokenUtils.cs new file mode 100644 index 0000000..fa45a5e --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Utilities/JsonTokenUtils.cs @@ -0,0 +1,77 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Text; + +namespace Newtonsoft.Json.Utilities +{ + internal static class JsonTokenUtils + { + internal static bool IsEndToken(JsonToken token) + { + switch (token) + { + case JsonToken.EndObject: + case JsonToken.EndArray: + case JsonToken.EndConstructor: + return true; + default: + return false; + } + } + + internal static bool IsStartToken(JsonToken token) + { + switch (token) + { + case JsonToken.StartObject: + case JsonToken.StartArray: + case JsonToken.StartConstructor: + return true; + default: + return false; + } + } + + internal static bool IsPrimitiveToken(JsonToken token) + { + switch (token) + { + case JsonToken.Integer: + case JsonToken.Float: + case JsonToken.String: + case JsonToken.Boolean: + case JsonToken.Undefined: + case JsonToken.Null: + case JsonToken.Date: + case JsonToken.Bytes: + return true; + default: + return false; + } + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Utilities/LateBoundReflectionDelegateFactory.cs b/Common/00-1Json8.3/Json8.3/Utilities/LateBoundReflectionDelegateFactory.cs new file mode 100644 index 0000000..52e1f5a --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Utilities/LateBoundReflectionDelegateFactory.cs @@ -0,0 +1,119 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using Newtonsoft.Json.Serialization; +using System.Reflection; + +#if NET20 +using Newtonsoft.Json.Utilities.LinqBridge; +#endif + +namespace Newtonsoft.Json.Utilities +{ + internal class LateBoundReflectionDelegateFactory : ReflectionDelegateFactory + { + private static readonly LateBoundReflectionDelegateFactory _instance = new LateBoundReflectionDelegateFactory(); + + internal static ReflectionDelegateFactory Instance + { + get { return _instance; } + } + + public override ObjectConstructor CreateParameterizedConstructor(MethodBase method) + { + ValidationUtils.ArgumentNotNull(method, nameof(method)); + + ConstructorInfo c = method as ConstructorInfo; + if (c != null) + { + // don't convert to method group to avoid medium trust issues + // https://github.com/JamesNK/Newtonsoft.Json/issues/476 + return a => + { + object[] args = a; + return c.Invoke(args); + }; + } + + return a => method.Invoke(null, a); + } + + public override MethodCall CreateMethodCall(MethodBase method) + { + ValidationUtils.ArgumentNotNull(method, nameof(method)); + + ConstructorInfo c = method as ConstructorInfo; + if (c != null) + { + return (o, a) => c.Invoke(a); + } + + return (o, a) => method.Invoke(o, a); + } + + public override Func CreateDefaultConstructor(Type type) + { + ValidationUtils.ArgumentNotNull(type, nameof(type)); + + if (type.IsValueType()) + { + return () => (T)Activator.CreateInstance(type); + } + + ConstructorInfo constructorInfo = ReflectionUtils.GetDefaultConstructor(type, true); + + return () => (T)constructorInfo.Invoke(null); + } + + public override Func CreateGet(PropertyInfo propertyInfo) + { + ValidationUtils.ArgumentNotNull(propertyInfo, nameof(propertyInfo)); + + return o => propertyInfo.GetValue(o, null); + } + + public override Func CreateGet(FieldInfo fieldInfo) + { + ValidationUtils.ArgumentNotNull(fieldInfo, nameof(fieldInfo)); + + return o => fieldInfo.GetValue(o); + } + + public override Action CreateSet(FieldInfo fieldInfo) + { + ValidationUtils.ArgumentNotNull(fieldInfo, nameof(fieldInfo)); + + return (o, v) => fieldInfo.SetValue(o, v); + } + + public override Action CreateSet(PropertyInfo propertyInfo) + { + ValidationUtils.ArgumentNotNull(propertyInfo, nameof(propertyInfo)); + + return (o, v) => propertyInfo.SetValue(o, v, null); + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Utilities/LinqBridge.cs b/Common/00-1Json8.3/Json8.3/Utilities/LinqBridge.cs new file mode 100644 index 0000000..f1a0807 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Utilities/LinqBridge.cs @@ -0,0 +1,3014 @@ + +#if NET20 + +#region License, Terms and Author(s) +// +// LINQBridge +// Copyright (c) 2007-9 Atif Aziz, Joseph Albahari. All rights reserved. +// +// Author(s): +// +// Atif Aziz, http://www.raboof.com +// +// This library is free software; you can redistribute it and/or modify it +// under the terms of the New BSD License, a copy of which should have +// been delivered along with this distribution. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +#endregion + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Diagnostics; +using System.Globalization; +using Newtonsoft.Json.Serialization; + +namespace Newtonsoft.Json.Utilities.LinqBridge +{ + /// + /// Provides a set of static (Shared in Visual Basic) methods for + /// querying objects that implement . + /// + internal static partial class Enumerable + { + /// + /// Returns the input typed as . + /// + + public static IEnumerable AsEnumerable(IEnumerable source) + { + return source; + } + + /// + /// Returns an empty that has the + /// specified type argument. + /// + + public static IEnumerable Empty() + { + return Sequence.Empty; + } + + /// + /// Converts the elements of an to the + /// specified type. + /// + + public static IEnumerable Cast( + this IEnumerable source) + { + CheckNotNull(source, "source"); + + return CastYield(source); + } + + private static IEnumerable CastYield( + IEnumerable source) + { + foreach (var item in source) + yield return (TResult) item; + } + + /// + /// Filters the elements of an based on a specified type. + /// + + public static IEnumerable OfType( + this IEnumerable source) + { + CheckNotNull(source, "source"); + + return OfTypeYield(source); + } + + private static IEnumerable OfTypeYield( + IEnumerable source) + { + foreach (var item in source) + if (item is TResult) + yield return (TResult) item; + } + + /// + /// Generates a sequence of integral numbers within a specified range. + /// + /// The value of the first integer in the sequence. + /// The number of sequential integers to generate. + + public static IEnumerable Range(int start, int count) + { + if (count < 0) + throw new ArgumentOutOfRangeException("count", count, null); + + var end = (long) start + count; + if (end - 1 >= int.MaxValue) + throw new ArgumentOutOfRangeException("count", count, null); + + return RangeYield(start, end); + } + + private static IEnumerable RangeYield(int start, long end) + { + for (var i = start; i < end; i++) + yield return i; + } + + /// + /// Generates a sequence that contains one repeated value. + /// + + public static IEnumerable Repeat(TResult element, int count) + { + if (count < 0) throw new ArgumentOutOfRangeException("count", count, null); + + return RepeatYield(element, count); + } + + private static IEnumerable RepeatYield(TResult element, int count) + { + for (var i = 0; i < count; i++) + yield return element; + } + + /// + /// Filters a sequence of values based on a predicate. + /// + + public static IEnumerable Where( + this IEnumerable source, + Func predicate) + { + CheckNotNull(predicate, "predicate"); + + return source.Where((item, i) => predicate(item)); + } + + /// + /// Filters a sequence of values based on a predicate. + /// Each element's index is used in the logic of the predicate function. + /// + + public static IEnumerable Where( + this IEnumerable source, + Func predicate) + { + CheckNotNull(source, "source"); + CheckNotNull(predicate, "predicate"); + + return WhereYield(source, predicate); + } + + private static IEnumerable WhereYield( + IEnumerable source, + Func predicate) + { + var i = 0; + foreach (var item in source) + if (predicate(item, i++)) + yield return item; + } + + /// + /// Projects each element of a sequence into a new form. + /// + + public static IEnumerable Select( + this IEnumerable source, + Func selector) + { + CheckNotNull(selector, "selector"); + + return source.Select((item, i) => selector(item)); + } + + /// + /// Projects each element of a sequence into a new form by + /// incorporating the element's index. + /// + + public static IEnumerable Select( + this IEnumerable source, + Func selector) + { + CheckNotNull(source, "source"); + CheckNotNull(selector, "selector"); + + return SelectYield(source, selector); + } + + private static IEnumerable SelectYield( + IEnumerable source, + Func selector) + { + var i = 0; + foreach (var item in source) + yield return selector(item, i++); + } + + /// + /// Projects each element of a sequence to an + /// and flattens the resulting sequences into one sequence. + /// + + public static IEnumerable SelectMany( + this IEnumerable source, + Func> selector) + { + CheckNotNull(selector, "selector"); + + return source.SelectMany((item, i) => selector(item)); + } + + /// + /// Projects each element of a sequence to an , + /// and flattens the resulting sequences into one sequence. The + /// index of each source element is used in the projected form of + /// that element. + /// + + public static IEnumerable SelectMany( + this IEnumerable source, + Func> selector) + { + CheckNotNull(selector, "selector"); + + return source.SelectMany(selector, (item, subitem) => subitem); + } + + /// + /// Projects each element of a sequence to an , + /// flattens the resulting sequences into one sequence, and invokes + /// a result selector function on each element therein. + /// + + public static IEnumerable SelectMany( + this IEnumerable source, + Func> collectionSelector, + Func resultSelector) + { + CheckNotNull(collectionSelector, "collectionSelector"); + + return source.SelectMany((item, i) => collectionSelector(item), resultSelector); + } + + /// + /// Projects each element of a sequence to an , + /// flattens the resulting sequences into one sequence, and invokes + /// a result selector function on each element therein. The index of + /// each source element is used in the intermediate projected form + /// of that element. + /// + + public static IEnumerable SelectMany( + this IEnumerable source, + Func> collectionSelector, + Func resultSelector) + { + CheckNotNull(source, "source"); + CheckNotNull(collectionSelector, "collectionSelector"); + CheckNotNull(resultSelector, "resultSelector"); + + return SelectManyYield(source, collectionSelector, resultSelector); + } + + private static IEnumerable SelectManyYield( + this IEnumerable source, + Func> collectionSelector, + Func resultSelector) + { + var i = 0; + foreach (var item in source) + foreach (var subitem in collectionSelector(item, i++)) + yield return resultSelector(item, subitem); + } + + /// + /// Returns elements from a sequence as long as a specified condition is true. + /// + + public static IEnumerable TakeWhile( + this IEnumerable source, + Func predicate) + { + CheckNotNull(predicate, "predicate"); + + return source.TakeWhile((item, i) => predicate(item)); + } + + /// + /// Returns elements from a sequence as long as a specified condition is true. + /// The element's index is used in the logic of the predicate function. + /// + + public static IEnumerable TakeWhile( + this IEnumerable source, + Func predicate) + { + CheckNotNull(source, "source"); + CheckNotNull(predicate, "predicate"); + + return TakeWhileYield(source, predicate); + } + + private static IEnumerable TakeWhileYield( + this IEnumerable source, + Func predicate) + { + var i = 0; + foreach (var item in source) + if (predicate(item, i++)) + yield return item; + else + break; + } + + private static class Futures + { + public static readonly Func Default = () => default(T); + public static readonly Func Undefined = () => { throw new InvalidOperationException(); }; + } + + /// + /// Base implementation of First operator. + /// + + private static TSource FirstImpl( + this IEnumerable source, + Func empty) + { + CheckNotNull(source, "source"); + Debug.Assert(empty != null); + + var list = source as IList; // optimized case for lists + if (list != null) + return list.Count > 0 ? list[0] : empty(); + + using (var e = source.GetEnumerator()) // fallback for enumeration + return e.MoveNext() ? e.Current : empty(); + } + + /// + /// Returns the first element of a sequence. + /// + + public static TSource First( + this IEnumerable source) + { + return source.FirstImpl(Futures.Undefined); + } + + /// + /// Returns the first element in a sequence that satisfies a specified condition. + /// + + public static TSource First( + this IEnumerable source, + Func predicate) + { + return First(source.Where(predicate)); + } + + /// + /// Returns the first element of a sequence, or a default value if + /// the sequence contains no elements. + /// + + public static TSource FirstOrDefault( + this IEnumerable source) + { + return source.FirstImpl(Futures.Default); + } + + /// + /// Returns the first element of the sequence that satisfies a + /// condition or a default value if no such element is found. + /// + + public static TSource FirstOrDefault( + this IEnumerable source, + Func predicate) + { + return FirstOrDefault(source.Where(predicate)); + } + + /// + /// Base implementation of Last operator. + /// + + private static TSource LastImpl( + this IEnumerable source, + Func empty) + { + CheckNotNull(source, "source"); + + var list = source as IList; // optimized case for lists + if (list != null) + return list.Count > 0 ? list[list.Count - 1] : empty(); + + using (var e = source.GetEnumerator()) + { + if (!e.MoveNext()) + return empty(); + + var last = e.Current; + while (e.MoveNext()) + last = e.Current; + + return last; + } + } + + /// + /// Returns the last element of a sequence. + /// + public static TSource Last( + this IEnumerable source) + { + return source.LastImpl(Futures.Undefined); + } + + /// + /// Returns the last element of a sequence that satisfies a + /// specified condition. + /// + + public static TSource Last( + this IEnumerable source, + Func predicate) + { + return Last(source.Where(predicate)); + } + + /// + /// Returns the last element of a sequence, or a default value if + /// the sequence contains no elements. + /// + + public static TSource LastOrDefault( + this IEnumerable source) + { + return source.LastImpl(Futures.Default); + } + + /// + /// Returns the last element of a sequence that satisfies a + /// condition or a default value if no such element is found. + /// + + public static TSource LastOrDefault( + this IEnumerable source, + Func predicate) + { + return LastOrDefault(source.Where(predicate)); + } + + /// + /// Base implementation of Single operator. + /// + + private static TSource SingleImpl( + this IEnumerable source, + Func empty) + { + CheckNotNull(source, "source"); + + using (var e = source.GetEnumerator()) + { + if (e.MoveNext()) + { + var single = e.Current; + if (!e.MoveNext()) + return single; + + throw new InvalidOperationException(); + } + + return empty(); + } + } + + /// + /// Returns the only element of a sequence, and throws an exception + /// if there is not exactly one element in the sequence. + /// + + public static TSource Single( + this IEnumerable source) + { + return source.SingleImpl(Futures.Undefined); + } + + /// + /// Returns the only element of a sequence that satisfies a + /// specified condition, and throws an exception if more than one + /// such element exists. + /// + + public static TSource Single( + this IEnumerable source, + Func predicate) + { + return Single(source.Where(predicate)); + } + + /// + /// Returns the only element of a sequence, or a default value if + /// the sequence is empty; this method throws an exception if there + /// is more than one element in the sequence. + /// + + public static TSource SingleOrDefault( + this IEnumerable source) + { + return source.SingleImpl(Futures.Default); + } + + /// + /// Returns the only element of a sequence that satisfies a + /// specified condition or a default value if no such element + /// exists; this method throws an exception if more than one element + /// satisfies the condition. + /// + + public static TSource SingleOrDefault( + this IEnumerable source, + Func predicate) + { + return SingleOrDefault(source.Where(predicate)); + } + + /// + /// Returns the element at a specified index in a sequence. + /// + + public static TSource ElementAt( + this IEnumerable source, + int index) + { + CheckNotNull(source, "source"); + + if (index < 0) + throw new ArgumentOutOfRangeException("index", index, null); + + var list = source as IList; + if (list != null) + return list[index]; + + try + { + return source.SkipWhile((item, i) => i < index).First(); + } + catch (InvalidOperationException) // if thrown by First + { + throw new ArgumentOutOfRangeException("index", index, null); + } + } + + /// + /// Returns the element at a specified index in a sequence or a + /// default value if the index is out of range. + /// + + public static TSource ElementAtOrDefault( + this IEnumerable source, + int index) + { + CheckNotNull(source, "source"); + + if (index < 0) + return default(TSource); + + var list = source as IList; + if (list != null) + return index < list.Count ? list[index] : default(TSource); + + return source.SkipWhile((item, i) => i < index).FirstOrDefault(); + } + + /// + /// Inverts the order of the elements in a sequence. + /// + + public static IEnumerable Reverse( + this IEnumerable source) + { + CheckNotNull(source, "source"); + + return ReverseYield(source); + } + + private static IEnumerable ReverseYield(IEnumerable source) + { + var stack = new Stack(); + foreach (var item in source) + stack.Push(item); + + foreach (var item in stack) + yield return item; + } + + /// + /// Returns a specified number of contiguous elements from the start + /// of a sequence. + /// + + public static IEnumerable Take( + this IEnumerable source, + int count) + { + return source.Where((item, i) => i < count); + } + + /// + /// Bypasses a specified number of elements in a sequence and then + /// returns the remaining elements. + /// + + public static IEnumerable Skip( + this IEnumerable source, + int count) + { + return source.Where((item, i) => i >= count); + } + + /// + /// Bypasses elements in a sequence as long as a specified condition + /// is true and then returns the remaining elements. + /// + + public static IEnumerable SkipWhile( + this IEnumerable source, + Func predicate) + { + CheckNotNull(predicate, "predicate"); + + return source.SkipWhile((item, i) => predicate(item)); + } + + /// + /// Bypasses elements in a sequence as long as a specified condition + /// is true and then returns the remaining elements. The element's + /// index is used in the logic of the predicate function. + /// + + public static IEnumerable SkipWhile( + this IEnumerable source, + Func predicate) + { + CheckNotNull(source, "source"); + CheckNotNull(predicate, "predicate"); + + return SkipWhileYield(source, predicate); + } + + private static IEnumerable SkipWhileYield( + IEnumerable source, + Func predicate) + { + using (var e = source.GetEnumerator()) + { + for (var i = 0;; i++) + { + if (!e.MoveNext()) + yield break; + + if (!predicate(e.Current, i)) + break; + } + + do + { + yield return e.Current; + } while (e.MoveNext()); + } + } + + /// + /// Returns the number of elements in a sequence. + /// + + public static int Count( + this IEnumerable source) + { + CheckNotNull(source, "source"); + + var collection = source as ICollection; + return collection != null + ? collection.Count + : source.Aggregate(0, (count, item) => checked(count + 1)); + } + + /// + /// Returns a number that represents how many elements in the + /// specified sequence satisfy a condition. + /// + + public static int Count( + this IEnumerable source, + Func predicate) + { + return Count(source.Where(predicate)); + } + + /// + /// Returns an that represents the total number + /// of elements in a sequence. + /// + + public static long LongCount( + this IEnumerable source) + { + CheckNotNull(source, "source"); + + var array = source as Array; + return array != null + ? array.LongLength + : source.Aggregate(0L, (count, item) => count + 1); + } + + /// + /// Returns an that represents how many elements + /// in a sequence satisfy a condition. + /// + + public static long LongCount( + this IEnumerable source, + Func predicate) + { + return LongCount(source.Where(predicate)); + } + + /// + /// Concatenates two sequences. + /// + + public static IEnumerable Concat( + this IEnumerable first, + IEnumerable second) + { + CheckNotNull(first, "first"); + CheckNotNull(second, "second"); + + return ConcatYield(first, second); + } + + private static IEnumerable ConcatYield( + IEnumerable first, + IEnumerable second) + { + foreach (var item in first) + yield return item; + + foreach (var item in second) + yield return item; + } + + /// + /// Creates a from an . + /// + + public static List ToList( + this IEnumerable source) + { + CheckNotNull(source, "source"); + + return new List(source); + } + + /// + /// Creates an array from an . + /// + + public static TSource[] ToArray( + this IEnumerable source) + { + return source.ToList().ToArray(); + } + + /// + /// Returns distinct elements from a sequence by using the default + /// equality comparer to compare values. + /// + + public static IEnumerable Distinct( + this IEnumerable source) + { + return Distinct(source, /* comparer */ null); + } + + /// + /// Returns distinct elements from a sequence by using a specified + /// to compare values. + /// + + public static IEnumerable Distinct( + this IEnumerable source, + IEqualityComparer comparer) + { + CheckNotNull(source, "source"); + + return DistinctYield(source, comparer); + } + + private static IEnumerable DistinctYield( + IEnumerable source, + IEqualityComparer comparer) + { + var set = new Dictionary(comparer); + var gotNull = false; + + foreach (var item in source) + { + if (item == null) + { + if (gotNull) + continue; + gotNull = true; + } + else + { + if (set.ContainsKey(item)) + continue; + set.Add(item, null); + } + + yield return item; + } + } + + /// + /// Creates a from an + /// according to a specified key + /// selector function. + /// + + public static ILookup ToLookup( + this IEnumerable source, + Func keySelector) + { + return ToLookup(source, keySelector, e => e, /* comparer */ null); + } + + /// + /// Creates a from an + /// according to a specified key + /// selector function and a key comparer. + /// + + public static ILookup ToLookup( + this IEnumerable source, + Func keySelector, + IEqualityComparer comparer) + { + return ToLookup(source, keySelector, e => e, comparer); + } + + /// + /// Creates a from an + /// according to specified key + /// and element selector functions. + /// + + public static ILookup ToLookup( + this IEnumerable source, + Func keySelector, + Func elementSelector) + { + return ToLookup(source, keySelector, elementSelector, /* comparer */ null); + } + + /// + /// Creates a from an + /// according to a specified key + /// selector function, a comparer and an element selector function. + /// + + public static ILookup ToLookup( + this IEnumerable source, + Func keySelector, + Func elementSelector, + IEqualityComparer comparer) + { + CheckNotNull(source, "source"); + CheckNotNull(keySelector, "keySelector"); + CheckNotNull(elementSelector, "elementSelector"); + + var lookup = new Lookup(comparer); + + foreach (var item in source) + { + var key = keySelector(item); + + var grouping = (Grouping) lookup.Find(key); + if (grouping == null) + { + grouping = new Grouping(key); + lookup.Add(grouping); + } + + grouping.Add(elementSelector(item)); + } + + return lookup; + } + + /// + /// Groups the elements of a sequence according to a specified key + /// selector function. + /// + + public static IEnumerable> GroupBy( + this IEnumerable source, + Func keySelector) + { + return GroupBy(source, keySelector, /* comparer */ null); + } + + /// + /// Groups the elements of a sequence according to a specified key + /// selector function and compares the keys by using a specified + /// comparer. + /// + + public static IEnumerable> GroupBy( + this IEnumerable source, + Func keySelector, + IEqualityComparer comparer) + { + return GroupBy(source, keySelector, e => e, comparer); + } + + /// + /// Groups the elements of a sequence according to a specified key + /// selector function and projects the elements for each group by + /// using a specified function. + /// + + public static IEnumerable> GroupBy( + this IEnumerable source, + Func keySelector, + Func elementSelector) + { + return GroupBy(source, keySelector, elementSelector, /* comparer */ null); + } + + /// + /// Groups the elements of a sequence according to a specified key + /// selector function and creates a result value from each group and + /// its key. + /// + + public static IEnumerable> GroupBy( + this IEnumerable source, + Func keySelector, + Func elementSelector, + IEqualityComparer comparer) + { + CheckNotNull(source, "source"); + CheckNotNull(keySelector, "keySelector"); + CheckNotNull(elementSelector, "elementSelector"); + + return ToLookup(source, keySelector, elementSelector, comparer); + } + + /// + /// Groups the elements of a sequence according to a key selector + /// function. The keys are compared by using a comparer and each + /// group's elements are projected by using a specified function. + /// + + public static IEnumerable GroupBy( + this IEnumerable source, + Func keySelector, + Func, TResult> resultSelector) + { + return GroupBy(source, keySelector, resultSelector, /* comparer */ null); + } + + /// + /// Groups the elements of a sequence according to a specified key + /// selector function and creates a result value from each group and + /// its key. The elements of each group are projected by using a + /// specified function. + /// + + public static IEnumerable GroupBy( + this IEnumerable source, + Func keySelector, + Func, TResult> resultSelector, + IEqualityComparer comparer) + { + CheckNotNull(source, "source"); + CheckNotNull(keySelector, "keySelector"); + CheckNotNull(resultSelector, "resultSelector"); + + return ToLookup(source, keySelector, comparer).Select(g => resultSelector(g.Key, g)); + } + + /// + /// Groups the elements of a sequence according to a specified key + /// selector function and creates a result value from each group and + /// its key. The keys are compared by using a specified comparer. + /// + + public static IEnumerable GroupBy( + this IEnumerable source, + Func keySelector, + Func elementSelector, + Func, TResult> resultSelector) + { + return GroupBy(source, keySelector, elementSelector, resultSelector, /* comparer */ null); + } + + /// + /// Groups the elements of a sequence according to a specified key + /// selector function and creates a result value from each group and + /// its key. Key values are compared by using a specified comparer, + /// and the elements of each group are projected by using a + /// specified function. + /// + + public static IEnumerable GroupBy( + this IEnumerable source, + Func keySelector, + Func elementSelector, + Func, TResult> resultSelector, + IEqualityComparer comparer) + { + CheckNotNull(source, "source"); + CheckNotNull(keySelector, "keySelector"); + CheckNotNull(elementSelector, "elementSelector"); + CheckNotNull(resultSelector, "resultSelector"); + + return ToLookup(source, keySelector, elementSelector, comparer) + .Select(g => resultSelector(g.Key, g)); + } + + /// + /// Applies an accumulator function over a sequence. + /// + + public static TSource Aggregate( + this IEnumerable source, + Func func) + { + CheckNotNull(source, "source"); + CheckNotNull(func, "func"); + + using (var e = source.GetEnumerator()) + { + if (!e.MoveNext()) + throw new InvalidOperationException(); + + return e.Renumerable().Skip(1).Aggregate(e.Current, func); + } + } + + /// + /// Applies an accumulator function over a sequence. The specified + /// seed value is used as the initial accumulator value. + /// + + public static TAccumulate Aggregate( + this IEnumerable source, + TAccumulate seed, + Func func) + { + return Aggregate(source, seed, func, r => r); + } + + /// + /// Applies an accumulator function over a sequence. The specified + /// seed value is used as the initial accumulator value, and the + /// specified function is used to select the result value. + /// + + public static TResult Aggregate( + this IEnumerable source, + TAccumulate seed, + Func func, + Func resultSelector) + { + CheckNotNull(source, "source"); + CheckNotNull(func, "func"); + CheckNotNull(resultSelector, "resultSelector"); + + var result = seed; + + foreach (var item in source) + result = func(result, item); + + return resultSelector(result); + } + + /// + /// Produces the set union of two sequences by using the default + /// equality comparer. + /// + + public static IEnumerable Union( + this IEnumerable first, + IEnumerable second) + { + return Union(first, second, /* comparer */ null); + } + + /// + /// Produces the set union of two sequences by using a specified + /// . + /// + + public static IEnumerable Union( + this IEnumerable first, + IEnumerable second, + IEqualityComparer comparer) + { + return first.Concat(second).Distinct(comparer); + } + + /// + /// Returns the elements of the specified sequence or the type + /// parameter's default value in a singleton collection if the + /// sequence is empty. + /// + + public static IEnumerable DefaultIfEmpty( + this IEnumerable source) + { + return source.DefaultIfEmpty(default(TSource)); + } + + /// + /// Returns the elements of the specified sequence or the specified + /// value in a singleton collection if the sequence is empty. + /// + + public static IEnumerable DefaultIfEmpty( + this IEnumerable source, + TSource defaultValue) + { + CheckNotNull(source, "source"); + + return DefaultIfEmptyYield(source, defaultValue); + } + + private static IEnumerable DefaultIfEmptyYield( + IEnumerable source, + TSource defaultValue) + { + using (var e = source.GetEnumerator()) + { + if (!e.MoveNext()) + yield return defaultValue; + else + do + { + yield return e.Current; + } while (e.MoveNext()); + } + } + + /// + /// Determines whether all elements of a sequence satisfy a condition. + /// + + public static bool All( + this IEnumerable source, + Func predicate) + { + CheckNotNull(source, "source"); + CheckNotNull(predicate, "predicate"); + + foreach (var item in source) + if (!predicate(item)) + return false; + + return true; + } + + /// + /// Determines whether a sequence contains any elements. + /// + + public static bool Any( + this IEnumerable source) + { + CheckNotNull(source, "source"); + + using (var e = source.GetEnumerator()) + return e.MoveNext(); + } + + /// + /// Determines whether any element of a sequence satisfies a + /// condition. + /// + + public static bool Any( + this IEnumerable source, + Func predicate) + { + return source.Where(predicate).Any(); + } + + /// + /// Determines whether a sequence contains a specified element by + /// using the default equality comparer. + /// + + public static bool Contains( + this IEnumerable source, + TSource value) + { + return source.Contains(value, /* comparer */ null); + } + + /// + /// Determines whether a sequence contains a specified element by + /// using a specified . + /// + + public static bool Contains( + this IEnumerable source, + TSource value, + IEqualityComparer comparer) + { + CheckNotNull(source, "source"); + + if (comparer == null) + { + var collection = source as ICollection; + if (collection != null) + return collection.Contains(value); + } + + comparer = comparer ?? EqualityComparer.Default; + return source.Any(item => comparer.Equals(item, value)); + } + + /// + /// Determines whether two sequences are equal by comparing the + /// elements by using the default equality comparer for their type. + /// + + public static bool SequenceEqual( + this IEnumerable first, + IEnumerable second) + { + return first.SequenceEqual(second, /* comparer */ null); + } + + /// + /// Determines whether two sequences are equal by comparing their + /// elements by using a specified . + /// + + public static bool SequenceEqual( + this IEnumerable first, + IEnumerable second, + IEqualityComparer comparer) + { + CheckNotNull(first, "frist"); + CheckNotNull(second, "second"); + + comparer = comparer ?? EqualityComparer.Default; + + using (IEnumerator lhs = first.GetEnumerator(), + rhs = second.GetEnumerator()) + { + do + { + if (!lhs.MoveNext()) + return !rhs.MoveNext(); + + if (!rhs.MoveNext()) + return false; + } while (comparer.Equals(lhs.Current, rhs.Current)); + } + + return false; + } + + /// + /// Base implementation for Min/Max operator. + /// + + private static TSource MinMaxImpl( + this IEnumerable source, + Func lesser) + { + CheckNotNull(source, "source"); + Debug.Assert(lesser != null); + + return source.Aggregate((a, item) => lesser(a, item) ? a : item); + } + + /// + /// Base implementation for Min/Max operator for nullable types. + /// + + private static TSource? MinMaxImpl( + this IEnumerable source, + TSource? seed, Func lesser) where TSource : struct + { + CheckNotNull(source, "source"); + Debug.Assert(lesser != null); + + return source.Aggregate(seed, (a, item) => lesser(a, item) ? a : item); + // == MinMaxImpl(Repeat(null, 1).Concat(source), lesser); + } + + /// + /// Returns the minimum value in a generic sequence. + /// + + public static TSource Min( + this IEnumerable source) + { + var comparer = Comparer.Default; + return source.MinMaxImpl((x, y) => comparer.Compare(x, y) < 0); + } + + /// + /// Invokes a transform function on each element of a generic + /// sequence and returns the minimum resulting value. + /// + + public static TResult Min( + this IEnumerable source, + Func selector) + { + return source.Select(selector).Min(); + } + + /// + /// Returns the maximum value in a generic sequence. + /// + + public static TSource Max( + this IEnumerable source) + { + var comparer = Comparer.Default; + return source.MinMaxImpl((x, y) => comparer.Compare(x, y) > 0); + } + + /// + /// Invokes a transform function on each element of a generic + /// sequence and returns the maximum resulting value. + /// + + public static TResult Max( + this IEnumerable source, + Func selector) + { + return source.Select(selector).Max(); + } + + /// + /// Makes an enumerator seen as enumerable once more. + /// + /// + /// The supplied enumerator must have been started. The first element + /// returned is the element the enumerator was on when passed in. + /// DO NOT use this method if the caller must be a generator. It is + /// mostly safe among aggregate operations. + /// + + private static IEnumerable Renumerable(this IEnumerator e) + { + Debug.Assert(e != null); + + do + { + yield return e.Current; + } while (e.MoveNext()); + } + + /// + /// Sorts the elements of a sequence in ascending order according to a key. + /// + + public static IOrderedEnumerable OrderBy( + this IEnumerable source, + Func keySelector) + { + return source.OrderBy(keySelector, /* comparer */ null); + } + + /// + /// Sorts the elements of a sequence in ascending order by using a + /// specified comparer. + /// + + public static IOrderedEnumerable OrderBy( + this IEnumerable source, + Func keySelector, + IComparer comparer) + { + CheckNotNull(source, "source"); + CheckNotNull(keySelector, "keySelector"); + + return new OrderedEnumerable(source, keySelector, comparer, /* descending */ false); + } + + /// + /// Sorts the elements of a sequence in descending order according to a key. + /// + + public static IOrderedEnumerable OrderByDescending( + this IEnumerable source, + Func keySelector) + { + return source.OrderByDescending(keySelector, /* comparer */ null); + } + + /// + /// Sorts the elements of a sequence in descending order by using a + /// specified comparer. + /// + + public static IOrderedEnumerable OrderByDescending( + this IEnumerable source, + Func keySelector, + IComparer comparer) + { + CheckNotNull(source, "source"); + CheckNotNull(source, "keySelector"); + + return new OrderedEnumerable(source, keySelector, comparer, /* descending */ true); + } + + /// + /// Performs a subsequent ordering of the elements in a sequence in + /// ascending order according to a key. + /// + + public static IOrderedEnumerable ThenBy( + this IOrderedEnumerable source, + Func keySelector) + { + return source.ThenBy(keySelector, /* comparer */ null); + } + + /// + /// Performs a subsequent ordering of the elements in a sequence in + /// ascending order by using a specified comparer. + /// + + public static IOrderedEnumerable ThenBy( + this IOrderedEnumerable source, + Func keySelector, + IComparer comparer) + { + CheckNotNull(source, "source"); + + return source.CreateOrderedEnumerable(keySelector, comparer, /* descending */ false); + } + + /// + /// Performs a subsequent ordering of the elements in a sequence in + /// descending order, according to a key. + /// + + public static IOrderedEnumerable ThenByDescending( + this IOrderedEnumerable source, + Func keySelector) + { + return source.ThenByDescending(keySelector, /* comparer */ null); + } + + /// + /// Performs a subsequent ordering of the elements in a sequence in + /// descending order by using a specified comparer. + /// + + public static IOrderedEnumerable ThenByDescending( + this IOrderedEnumerable source, + Func keySelector, + IComparer comparer) + { + CheckNotNull(source, "source"); + + return source.CreateOrderedEnumerable(keySelector, comparer, /* descending */ true); + } + + /// + /// Base implementation for Intersect and Except operators. + /// + + private static IEnumerable IntersectExceptImpl( + this IEnumerable first, + IEnumerable second, + IEqualityComparer comparer, + bool flag) + { + CheckNotNull(first, "first"); + CheckNotNull(second, "second"); + + var keys = new List(); + var flags = new Dictionary(comparer); + + foreach (var item in first.Where(k => !flags.ContainsKey(k))) + { + flags.Add(item, !flag); + keys.Add(item); + } + + foreach (var item in second.Where(flags.ContainsKey)) + flags[item] = flag; + + // + // As per docs, "the marked elements are yielded in the order in + // which they were collected. + // + + return keys.Where(item => flags[item]); + } + + /// + /// Produces the set intersection of two sequences by using the + /// default equality comparer to compare values. + /// + + public static IEnumerable Intersect( + this IEnumerable first, + IEnumerable second) + { + return first.Intersect(second, /* comparer */ null); + } + + /// + /// Produces the set intersection of two sequences by using the + /// specified to compare values. + /// + + public static IEnumerable Intersect( + this IEnumerable first, + IEnumerable second, + IEqualityComparer comparer) + { + return IntersectExceptImpl(first, second, comparer, /* flag */ true); + } + + /// + /// Produces the set difference of two sequences by using the + /// default equality comparer to compare values. + /// + + public static IEnumerable Except( + this IEnumerable first, + IEnumerable second) + { + return first.Except(second, /* comparer */ null); + } + + /// + /// Produces the set difference of two sequences by using the + /// specified to compare values. + /// + + public static IEnumerable Except( + this IEnumerable first, + IEnumerable second, + IEqualityComparer comparer) + { + return IntersectExceptImpl(first, second, comparer, /* flag */ false); + } + + /// + /// Creates a from an + /// according to a specified key + /// selector function. + /// + + public static Dictionary ToDictionary( + this IEnumerable source, + Func keySelector) + { + return source.ToDictionary(keySelector, /* comparer */ null); + } + + /// + /// Creates a from an + /// according to a specified key + /// selector function and key comparer. + /// + + public static Dictionary ToDictionary( + this IEnumerable source, + Func keySelector, + IEqualityComparer comparer) + { + return source.ToDictionary(keySelector, e => e); + } + + /// + /// Creates a from an + /// according to specified key + /// selector and element selector functions. + /// + + public static Dictionary ToDictionary( + this IEnumerable source, + Func keySelector, + Func elementSelector) + { + return source.ToDictionary(keySelector, elementSelector, /* comparer */ null); + } + + /// + /// Creates a from an + /// according to a specified key + /// selector function, a comparer, and an element selector function. + /// + + public static Dictionary ToDictionary( + this IEnumerable source, + Func keySelector, + Func elementSelector, + IEqualityComparer comparer) + { + CheckNotNull(source, "source"); + CheckNotNull(keySelector, "keySelector"); + CheckNotNull(elementSelector, "elementSelector"); + + var dict = new Dictionary(comparer); + + foreach (var item in source) + { + // + // ToDictionary is meant to throw ArgumentNullException if + // keySelector produces a key that is null and + // Argument exception if keySelector produces duplicate keys + // for two elements. Incidentally, the doucmentation for + // IDictionary.Add says that the Add method + // throws the same exceptions under the same circumstances + // so we don't need to do any additional checking or work + // here and let the Add implementation do all the heavy + // lifting. + // + + dict.Add(keySelector(item), elementSelector(item)); + } + + return dict; + } + + /// + /// Correlates the elements of two sequences based on matching keys. + /// The default equality comparer is used to compare keys. + /// + + public static IEnumerable Join( + this IEnumerable outer, + IEnumerable inner, + Func outerKeySelector, + Func innerKeySelector, + Func resultSelector) + { + return outer.Join(inner, outerKeySelector, innerKeySelector, resultSelector, /* comparer */ null); + } + + /// + /// Correlates the elements of two sequences based on matching keys. + /// The default equality comparer is used to compare keys. A + /// specified is used to compare keys. + /// + + public static IEnumerable Join( + this IEnumerable outer, + IEnumerable inner, + Func outerKeySelector, + Func innerKeySelector, + Func resultSelector, + IEqualityComparer comparer) + { + CheckNotNull(outer, "outer"); + CheckNotNull(inner, "inner"); + CheckNotNull(outerKeySelector, "outerKeySelector"); + CheckNotNull(innerKeySelector, "innerKeySelector"); + CheckNotNull(resultSelector, "resultSelector"); + + var lookup = inner.ToLookup(innerKeySelector, comparer); + + return + from o in outer + from i in lookup[outerKeySelector(o)] + select resultSelector(o, i); + } + + /// + /// Correlates the elements of two sequences based on equality of + /// keys and groups the results. The default equality comparer is + /// used to compare keys. + /// + + public static IEnumerable GroupJoin( + this IEnumerable outer, + IEnumerable inner, + Func outerKeySelector, + Func innerKeySelector, + Func, TResult> resultSelector) + { + return outer.GroupJoin(inner, outerKeySelector, innerKeySelector, resultSelector, /* comparer */ null); + } + + /// + /// Correlates the elements of two sequences based on equality of + /// keys and groups the results. The default equality comparer is + /// used to compare keys. A specified + /// is used to compare keys. + /// + + public static IEnumerable GroupJoin( + this IEnumerable outer, + IEnumerable inner, + Func outerKeySelector, + Func innerKeySelector, + Func, TResult> resultSelector, + IEqualityComparer comparer) + { + CheckNotNull(outer, "outer"); + CheckNotNull(inner, "inner"); + CheckNotNull(outerKeySelector, "outerKeySelector"); + CheckNotNull(innerKeySelector, "innerKeySelector"); + CheckNotNull(resultSelector, "resultSelector"); + + var lookup = inner.ToLookup(innerKeySelector, comparer); + return outer.Select(o => resultSelector(o, lookup[outerKeySelector(o)])); + } + + [DebuggerStepThrough] + private static void CheckNotNull(T value, string name) where T : class + { + if (value == null) + throw new ArgumentNullException(name); + } + + private static class Sequence + { + public static readonly IEnumerable Empty = new T[0]; + } + + private sealed class Grouping : List, IGrouping + { + internal Grouping(K key) + { + Key = key; + } + + public K Key { get; private set; } + } + } + + internal partial class Enumerable + { + /// + /// Computes the sum of a sequence of nullable values. + /// + + public static int Sum( + this IEnumerable source) + { + CheckNotNull(source, "source"); + + int sum = 0; + foreach (var num in source) + sum = checked(sum + num); + + return sum; + } + + /// + /// Computes the sum of a sequence of nullable + /// values that are obtained by invoking a transform function on + /// each element of the input sequence. + /// + + public static int Sum( + this IEnumerable source, + Func selector) + { + return source.Select(selector).Sum(); + } + + /// + /// Computes the average of a sequence of nullable values. + /// + + public static double Average( + this IEnumerable source) + { + CheckNotNull(source, "source"); + + long sum = 0; + long count = 0; + + foreach (var num in source) + checked + { + sum += (int) num; + count++; + } + + if (count == 0) + throw new InvalidOperationException(); + + return (double) sum/count; + } + + /// + /// Computes the average of a sequence of nullable values + /// that are obtained by invoking a transform function on each + /// element of the input sequence. + /// + + public static double Average( + this IEnumerable source, + Func selector) + { + return source.Select(selector).Average(); + } + + + /// + /// Computes the sum of a sequence of values. + /// + + public static int? Sum( + this IEnumerable source) + { + CheckNotNull(source, "source"); + + int sum = 0; + foreach (var num in source) + sum = checked(sum + (num ?? 0)); + + return sum; + } + + /// + /// Computes the sum of a sequence of + /// values that are obtained by invoking a transform function on + /// each element of the input sequence. + /// + + public static int? Sum( + this IEnumerable source, + Func selector) + { + return source.Select(selector).Sum(); + } + + /// + /// Computes the average of a sequence of values. + /// + + public static double? Average( + this IEnumerable source) + { + CheckNotNull(source, "source"); + + long sum = 0; + long count = 0; + + foreach (var num in source.Where(n => n != null)) + checked + { + sum += (int) num; + count++; + } + + if (count == 0) + return null; + + return (double?) sum/count; + } + + /// + /// Computes the average of a sequence of values + /// that are obtained by invoking a transform function on each + /// element of the input sequence. + /// + + public static double? Average( + this IEnumerable source, + Func selector) + { + return source.Select(selector).Average(); + } + + /// + /// Returns the minimum value in a sequence of nullable + /// values. + /// + + public static int? Min( + this IEnumerable source) + { + CheckNotNull(source, "source"); + + return MinMaxImpl(source.Where(x => x != null), null, (min, x) => min < x); + } + + /// + /// Invokes a transform function on each element of a sequence and + /// returns the minimum nullable value. + /// + + public static int? Min( + this IEnumerable source, + Func selector) + { + return source.Select(selector).Min(); + } + + /// + /// Returns the maximum value in a sequence of nullable + /// values. + /// + + public static int? Max( + this IEnumerable source) + { + CheckNotNull(source, "source"); + + return MinMaxImpl(source.Where(x => x != null), + null, (max, x) => x == null || (max != null && x.Value < max.Value)); + } + + /// + /// Invokes a transform function on each element of a sequence and + /// returns the maximum nullable value. + /// + + public static int? Max( + this IEnumerable source, + Func selector) + { + return source.Select(selector).Max(); + } + + /// + /// Computes the sum of a sequence of nullable values. + /// + + public static long Sum( + this IEnumerable source) + { + CheckNotNull(source, "source"); + + long sum = 0; + foreach (var num in source) + sum = checked(sum + num); + + return sum; + } + + /// + /// Computes the sum of a sequence of nullable + /// values that are obtained by invoking a transform function on + /// each element of the input sequence. + /// + + public static long Sum( + this IEnumerable source, + Func selector) + { + return source.Select(selector).Sum(); + } + + /// + /// Computes the average of a sequence of nullable values. + /// + + public static double Average( + this IEnumerable source) + { + CheckNotNull(source, "source"); + + long sum = 0; + long count = 0; + + foreach (var num in source) + checked + { + sum += (long) num; + count++; + } + + if (count == 0) + throw new InvalidOperationException(); + + return (double) sum/count; + } + + /// + /// Computes the average of a sequence of nullable values + /// that are obtained by invoking a transform function on each + /// element of the input sequence. + /// + + public static double Average( + this IEnumerable source, + Func selector) + { + return source.Select(selector).Average(); + } + + + /// + /// Computes the sum of a sequence of values. + /// + + public static long? Sum( + this IEnumerable source) + { + CheckNotNull(source, "source"); + + long sum = 0; + foreach (var num in source) + sum = checked(sum + (num ?? 0)); + + return sum; + } + + /// + /// Computes the sum of a sequence of + /// values that are obtained by invoking a transform function on + /// each element of the input sequence. + /// + + public static long? Sum( + this IEnumerable source, + Func selector) + { + return source.Select(selector).Sum(); + } + + /// + /// Computes the average of a sequence of values. + /// + + public static double? Average( + this IEnumerable source) + { + CheckNotNull(source, "source"); + + long sum = 0; + long count = 0; + + foreach (var num in source.Where(n => n != null)) + checked + { + sum += (long) num; + count++; + } + + if (count == 0) + return null; + + return (double?) sum/count; + } + + /// + /// Computes the average of a sequence of values + /// that are obtained by invoking a transform function on each + /// element of the input sequence. + /// + + public static double? Average( + this IEnumerable source, + Func selector) + { + return source.Select(selector).Average(); + } + + /// + /// Returns the minimum value in a sequence of nullable + /// values. + /// + + public static long? Min( + this IEnumerable source) + { + CheckNotNull(source, "source"); + + return MinMaxImpl(source.Where(x => x != null), null, (min, x) => min < x); + } + + /// + /// Invokes a transform function on each element of a sequence and + /// returns the minimum nullable value. + /// + + public static long? Min( + this IEnumerable source, + Func selector) + { + return source.Select(selector).Min(); + } + + /// + /// Returns the maximum value in a sequence of nullable + /// values. + /// + + public static long? Max( + this IEnumerable source) + { + CheckNotNull(source, "source"); + + return MinMaxImpl(source.Where(x => x != null), + null, (max, x) => x == null || (max != null && x.Value < max.Value)); + } + + /// + /// Invokes a transform function on each element of a sequence and + /// returns the maximum nullable value. + /// + + public static long? Max( + this IEnumerable source, + Func selector) + { + return source.Select(selector).Max(); + } + + /// + /// Computes the sum of a sequence of nullable values. + /// + + public static float Sum( + this IEnumerable source) + { + CheckNotNull(source, "source"); + + float sum = 0; + foreach (var num in source) + sum = checked(sum + num); + + return sum; + } + + /// + /// Computes the sum of a sequence of nullable + /// values that are obtained by invoking a transform function on + /// each element of the input sequence. + /// + + public static float Sum( + this IEnumerable source, + Func selector) + { + return source.Select(selector).Sum(); + } + + /// + /// Computes the average of a sequence of nullable values. + /// + + public static float Average( + this IEnumerable source) + { + CheckNotNull(source, "source"); + + float sum = 0; + long count = 0; + + foreach (var num in source) + checked + { + sum += (float) num; + count++; + } + + if (count == 0) + throw new InvalidOperationException(); + + return (float) sum/count; + } + + /// + /// Computes the average of a sequence of nullable values + /// that are obtained by invoking a transform function on each + /// element of the input sequence. + /// + + public static float Average( + this IEnumerable source, + Func selector) + { + return source.Select(selector).Average(); + } + + + /// + /// Computes the sum of a sequence of values. + /// + + public static float? Sum( + this IEnumerable source) + { + CheckNotNull(source, "source"); + + float sum = 0; + foreach (var num in source) + sum = checked(sum + (num ?? 0)); + + return sum; + } + + /// + /// Computes the sum of a sequence of + /// values that are obtained by invoking a transform function on + /// each element of the input sequence. + /// + + public static float? Sum( + this IEnumerable source, + Func selector) + { + return source.Select(selector).Sum(); + } + + /// + /// Computes the average of a sequence of values. + /// + + public static float? Average( + this IEnumerable source) + { + CheckNotNull(source, "source"); + + float sum = 0; + long count = 0; + + foreach (var num in source.Where(n => n != null)) + checked + { + sum += (float) num; + count++; + } + + if (count == 0) + return null; + + return (float?) sum/count; + } + + /// + /// Computes the average of a sequence of values + /// that are obtained by invoking a transform function on each + /// element of the input sequence. + /// + + public static float? Average( + this IEnumerable source, + Func selector) + { + return source.Select(selector).Average(); + } + + /// + /// Returns the minimum value in a sequence of nullable + /// values. + /// + + public static float? Min( + this IEnumerable source) + { + CheckNotNull(source, "source"); + + return MinMaxImpl(source.Where(x => x != null), null, (min, x) => min < x); + } + + /// + /// Invokes a transform function on each element of a sequence and + /// returns the minimum nullable value. + /// + + public static float? Min( + this IEnumerable source, + Func selector) + { + return source.Select(selector).Min(); + } + + /// + /// Returns the maximum value in a sequence of nullable + /// values. + /// + + public static float? Max( + this IEnumerable source) + { + CheckNotNull(source, "source"); + + return MinMaxImpl(source.Where(x => x != null), + null, (max, x) => x == null || (max != null && x.Value < max.Value)); + } + + /// + /// Invokes a transform function on each element of a sequence and + /// returns the maximum nullable value. + /// + + public static float? Max( + this IEnumerable source, + Func selector) + { + return source.Select(selector).Max(); + } + + /// + /// Computes the sum of a sequence of nullable values. + /// + + public static double Sum( + this IEnumerable source) + { + CheckNotNull(source, "source"); + + double sum = 0; + foreach (var num in source) + sum = checked(sum + num); + + return sum; + } + + /// + /// Computes the sum of a sequence of nullable + /// values that are obtained by invoking a transform function on + /// each element of the input sequence. + /// + + public static double Sum( + this IEnumerable source, + Func selector) + { + return source.Select(selector).Sum(); + } + + /// + /// Computes the average of a sequence of nullable values. + /// + + public static double Average( + this IEnumerable source) + { + CheckNotNull(source, "source"); + + double sum = 0; + long count = 0; + + foreach (var num in source) + checked + { + sum += (double) num; + count++; + } + + if (count == 0) + throw new InvalidOperationException(); + + return (double) sum/count; + } + + /// + /// Computes the average of a sequence of nullable values + /// that are obtained by invoking a transform function on each + /// element of the input sequence. + /// + + public static double Average( + this IEnumerable source, + Func selector) + { + return source.Select(selector).Average(); + } + + + /// + /// Computes the sum of a sequence of values. + /// + + public static double? Sum( + this IEnumerable source) + { + CheckNotNull(source, "source"); + + double sum = 0; + foreach (var num in source) + sum = checked(sum + (num ?? 0)); + + return sum; + } + + /// + /// Computes the sum of a sequence of + /// values that are obtained by invoking a transform function on + /// each element of the input sequence. + /// + + public static double? Sum( + this IEnumerable source, + Func selector) + { + return source.Select(selector).Sum(); + } + + /// + /// Computes the average of a sequence of values. + /// + + public static double? Average( + this IEnumerable source) + { + CheckNotNull(source, "source"); + + double sum = 0; + long count = 0; + + foreach (var num in source.Where(n => n != null)) + checked + { + sum += (double) num; + count++; + } + + if (count == 0) + return null; + + return (double?) sum/count; + } + + /// + /// Computes the average of a sequence of values + /// that are obtained by invoking a transform function on each + /// element of the input sequence. + /// + + public static double? Average( + this IEnumerable source, + Func selector) + { + return source.Select(selector).Average(); + } + + /// + /// Returns the minimum value in a sequence of nullable + /// values. + /// + + public static double? Min( + this IEnumerable source) + { + CheckNotNull(source, "source"); + + return MinMaxImpl(source.Where(x => x != null), null, (min, x) => min < x); + } + + /// + /// Invokes a transform function on each element of a sequence and + /// returns the minimum nullable value. + /// + + public static double? Min( + this IEnumerable source, + Func selector) + { + return source.Select(selector).Min(); + } + + /// + /// Returns the maximum value in a sequence of nullable + /// values. + /// + + public static double? Max( + this IEnumerable source) + { + CheckNotNull(source, "source"); + + return MinMaxImpl(source.Where(x => x != null), + null, (max, x) => x == null || (max != null && x.Value < max.Value)); + } + + /// + /// Invokes a transform function on each element of a sequence and + /// returns the maximum nullable value. + /// + + public static double? Max( + this IEnumerable source, + Func selector) + { + return source.Select(selector).Max(); + } + + /// + /// Computes the sum of a sequence of nullable values. + /// + + public static decimal Sum( + this IEnumerable source) + { + CheckNotNull(source, "source"); + + decimal sum = 0; + foreach (var num in source) + sum = checked(sum + num); + + return sum; + } + + /// + /// Computes the sum of a sequence of nullable + /// values that are obtained by invoking a transform function on + /// each element of the input sequence. + /// + + public static decimal Sum( + this IEnumerable source, + Func selector) + { + return source.Select(selector).Sum(); + } + + /// + /// Computes the average of a sequence of nullable values. + /// + + public static decimal Average( + this IEnumerable source) + { + CheckNotNull(source, "source"); + + decimal sum = 0; + long count = 0; + + foreach (var num in source) + checked + { + sum += (decimal) num; + count++; + } + + if (count == 0) + throw new InvalidOperationException(); + + return (decimal) sum/count; + } + + /// + /// Computes the average of a sequence of nullable values + /// that are obtained by invoking a transform function on each + /// element of the input sequence. + /// + + public static decimal Average( + this IEnumerable source, + Func selector) + { + return source.Select(selector).Average(); + } + + + /// + /// Computes the sum of a sequence of values. + /// + + public static decimal? Sum( + this IEnumerable source) + { + CheckNotNull(source, "source"); + + decimal sum = 0; + foreach (var num in source) + sum = checked(sum + (num ?? 0)); + + return sum; + } + + /// + /// Computes the sum of a sequence of + /// values that are obtained by invoking a transform function on + /// each element of the input sequence. + /// + + public static decimal? Sum( + this IEnumerable source, + Func selector) + { + return source.Select(selector).Sum(); + } + + /// + /// Computes the average of a sequence of values. + /// + + public static decimal? Average( + this IEnumerable source) + { + CheckNotNull(source, "source"); + + decimal sum = 0; + long count = 0; + + foreach (var num in source.Where(n => n != null)) + checked + { + sum += (decimal) num; + count++; + } + + if (count == 0) + return null; + + return (decimal?) sum/count; + } + + /// + /// Computes the average of a sequence of values + /// that are obtained by invoking a transform function on each + /// element of the input sequence. + /// + + public static decimal? Average( + this IEnumerable source, + Func selector) + { + return source.Select(selector).Average(); + } + + /// + /// Returns the minimum value in a sequence of nullable + /// values. + /// + + public static decimal? Min( + this IEnumerable source) + { + CheckNotNull(source, "source"); + + return MinMaxImpl(source.Where(x => x != null), null, (min, x) => min < x); + } + + /// + /// Invokes a transform function on each element of a sequence and + /// returns the minimum nullable value. + /// + + public static decimal? Min( + this IEnumerable source, + Func selector) + { + return source.Select(selector).Min(); + } + + /// + /// Returns the maximum value in a sequence of nullable + /// values. + /// + + public static decimal? Max( + this IEnumerable source) + { + CheckNotNull(source, "source"); + + return MinMaxImpl(source.Where(x => x != null), + null, (max, x) => x == null || (max != null && x.Value < max.Value)); + } + + /// + /// Invokes a transform function on each element of a sequence and + /// returns the maximum nullable value. + /// + + public static decimal? Max( + this IEnumerable source, + Func selector) + { + return source.Select(selector).Max(); + } + } + + /// + /// Represents a collection of objects that have a common key. + /// + internal partial interface IGrouping : IEnumerable + { + /// + /// Gets the key of the . + /// + + TKey Key { get; } + } + + /// + /// Defines an indexer, size property, and Boolean search method for + /// data structures that map keys to + /// sequences of values. + /// + internal partial interface ILookup : IEnumerable> + { + bool Contains(TKey key); + int Count { get; } + IEnumerable this[TKey key] { get; } + } + + /// + /// Represents a sorted sequence. + /// + internal partial interface IOrderedEnumerable : IEnumerable + { + /// + /// Performs a subsequent ordering on the elements of an + /// according to a key. + /// + + IOrderedEnumerable CreateOrderedEnumerable( + Func keySelector, IComparer comparer, bool descending); + } + + /// + /// Represents a collection of keys each mapped to one or more values. + /// + internal sealed class Lookup : ILookup + { + private readonly Dictionary> _map; + + internal Lookup(IEqualityComparer comparer) + { + _map = new Dictionary>(comparer); + } + + internal void Add(IGrouping item) + { + _map.Add(item.Key, item); + } + + internal IEnumerable Find(TKey key) + { + IGrouping grouping; + return _map.TryGetValue(key, out grouping) ? grouping : null; + } + + /// + /// Gets the number of key/value collection pairs in the . + /// + + public int Count + { + get { return _map.Count; } + } + + /// + /// Gets the collection of values indexed by the specified key. + /// + + public IEnumerable this[TKey key] + { + get + { + IGrouping result; + return _map.TryGetValue(key, out result) ? result : Enumerable.Empty(); + } + } + + /// + /// Determines whether a specified key is in the . + /// + + public bool Contains(TKey key) + { + return _map.ContainsKey(key); + } + + /// + /// Applies a transform function to each key and its associated + /// values and returns the results. + /// + + public IEnumerable ApplyResultSelector( + Func, TResult> resultSelector) + { + if (resultSelector == null) + throw new ArgumentNullException("resultSelector"); + + foreach (var pair in _map) + yield return resultSelector(pair.Key, pair.Value); + } + + /// + /// Returns a generic enumerator that iterates through the . + /// + + public IEnumerator> GetEnumerator() + { + return _map.Values.GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + } + + internal sealed class OrderedEnumerable : IOrderedEnumerable + { + private readonly IEnumerable _source; + private readonly List> _comparisons; + + public OrderedEnumerable(IEnumerable source, + Func keySelector, IComparer comparer, bool descending) : + this(source, null, keySelector, comparer, descending) + { + } + + private OrderedEnumerable(IEnumerable source, List> comparisons, + Func keySelector, IComparer comparer, bool descending) + { + if (source == null) throw new ArgumentNullException("source"); + if (keySelector == null) throw new ArgumentNullException("keySelector"); + + _source = source; + + comparer = comparer ?? Comparer.Default; + + if (comparisons == null) + comparisons = new List>( /* capacity */ 4); + + comparisons.Add((x, y) + => (descending ? -1 : 1)*comparer.Compare(keySelector(x), keySelector(y))); + + _comparisons = comparisons; + } + + public IOrderedEnumerable CreateOrderedEnumerable( + Func keySelector, IComparer comparer, bool descending) + { + return new OrderedEnumerable(_source, _comparisons, keySelector, comparer, descending); + } + + public IEnumerator GetEnumerator() + { + // + // We sort using List.Sort, but docs say that it performs an + // unstable sort. LINQ, on the other hand, says OrderBy performs + // a stable sort. So convert the source sequence into a sequence + // of tuples where the second element tags the position of the + // element from the source sequence (First). The position is + // then used as a tie breaker when all keys compare equal, + // thus making the sort stable. + // + + var list = _source.Select(new Func>(TagPosition)).ToList(); + + list.Sort((x, y) => + { + // + // Compare keys from left to right. + // + + var comparisons = _comparisons; + for (var i = 0; i < comparisons.Count; i++) + { + var result = comparisons[i](x.First, y.First); + if (result != 0) + return result; + } + + // + // All keys compared equal so now break the tie by their + // position in the original sequence, making the sort stable. + // + + return x.Second.CompareTo(y.Second); + }); + + return list.Select(new Func, T>(GetFirst)).GetEnumerator(); + + } + + /// + /// See issue #11 + /// for why this method is needed and cannot be expressed as a + /// lambda at the call site. + /// + + private static Tuple TagPosition(T e, int i) + { + return new Tuple(e, i); + } + + /// + /// See issue #11 + /// for why this method is needed and cannot be expressed as a + /// lambda at the call site. + /// + + private static T GetFirst(Tuple pv) + { + return pv.First; + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + } + + [Serializable] + internal struct Tuple : IEquatable> + { + public TFirst First { get; private set; } + public TSecond Second { get; private set; } + + public Tuple(TFirst first, TSecond second) + : this() + { + First = first; + Second = second; + } + + public override bool Equals(object obj) + { + return obj != null + && obj is Tuple + && base.Equals((Tuple) obj); + } + + public bool Equals(Tuple other) + { + return EqualityComparer.Default.Equals(other.First, First) + && EqualityComparer.Default.Equals(other.Second, Second); + } + + public override int GetHashCode() + { + var num = 0x7a2f0b42; + num = (-1521134295*num) + EqualityComparer.Default.GetHashCode(First); + return (-1521134295*num) + EqualityComparer.Default.GetHashCode(Second); + } + + public override string ToString() + { + return string.Format(CultureInfo.InvariantCulture, @"{{ First = {0}, Second = {1} }}", First, Second); + } + } +} + +namespace Newtonsoft.Json.Serialization +{ +#pragma warning disable 1591 + public delegate TResult Func(); + + public delegate TResult Func(T a); + + public delegate TResult Func(T1 arg1, T2 arg2); + + public delegate TResult Func(T1 arg1, T2 arg2, T3 arg3); + + public delegate TResult Func(T1 arg1, T2 arg2, T3 arg3, T4 arg4); + + public delegate void Action(); + + public delegate void Action(T1 arg1, T2 arg2); + + public delegate void Action(T1 arg1, T2 arg2, T3 arg3); + + public delegate void Action(T1 arg1, T2 arg2, T3 arg3, T4 arg4); +#pragma warning restore 1591 +} + +namespace System.Runtime.CompilerServices +{ + /// + /// This attribute allows us to define extension methods without + /// requiring .NET Framework 3.5. For more information, see the section, + /// Extension Methods in .NET Framework 2.0 Apps, + /// of Basic Instincts: Extension Methods + /// column in MSDN Magazine, + /// issue Nov 2007. + /// + + [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Assembly)] + internal sealed class ExtensionAttribute : Attribute { } +} + +#endif \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Utilities/MathUtils.cs b/Common/00-1Json8.3/Json8.3/Utilities/MathUtils.cs new file mode 100644 index 0000000..2818483 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Utilities/MathUtils.cs @@ -0,0 +1,187 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Collections.Generic; +using System.Text; + +namespace Newtonsoft.Json.Utilities +{ + internal static class MathUtils + { + public static int IntLength(ulong i) + { + if (i < 10000000000) + { + if (i < 10) + { + return 1; + } + if (i < 100) + { + return 2; + } + if (i < 1000) + { + return 3; + } + if (i < 10000) + { + return 4; + } + if (i < 100000) + { + return 5; + } + if (i < 1000000) + { + return 6; + } + if (i < 10000000) + { + return 7; + } + if (i < 100000000) + { + return 8; + } + if (i < 1000000000) + { + return 9; + } + + return 10; + } + else + { + if (i < 100000000000) + { + return 11; + } + if (i < 1000000000000) + { + return 12; + } + if (i < 10000000000000) + { + return 13; + } + if (i < 100000000000000) + { + return 14; + } + if (i < 1000000000000000) + { + return 15; + } + if (i < 10000000000000000) + { + return 16; + } + if (i < 100000000000000000) + { + return 17; + } + if (i < 1000000000000000000) + { + return 18; + } + if (i < 10000000000000000000) + { + return 19; + } + + return 20; + } + } + + public static char IntToHex(int n) + { + if (n <= 9) + { + return (char)(n + 48); + } + + return (char)((n - 10) + 97); + } + + public static int? Min(int? val1, int? val2) + { + if (val1 == null) + { + return val2; + } + if (val2 == null) + { + return val1; + } + + return Math.Min(val1.GetValueOrDefault(), val2.GetValueOrDefault()); + } + + public static int? Max(int? val1, int? val2) + { + if (val1 == null) + { + return val2; + } + if (val2 == null) + { + return val1; + } + + return Math.Max(val1.GetValueOrDefault(), val2.GetValueOrDefault()); + } + + public static double? Max(double? val1, double? val2) + { + if (val1 == null) + { + return val2; + } + if (val2 == null) + { + return val1; + } + + return Math.Max(val1.GetValueOrDefault(), val2.GetValueOrDefault()); + } + + public static bool ApproxEquals(double d1, double d2) + { + const double epsilon = 2.2204460492503131E-16; + + if (d1 == d2) + { + return true; + } + + double tolerance = ((Math.Abs(d1) + Math.Abs(d2)) + 10.0) * epsilon; + double difference = d1 - d2; + + return (-tolerance < difference && tolerance > difference); + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Utilities/MethodCall.cs b/Common/00-1Json8.3/Json8.3/Utilities/MethodCall.cs new file mode 100644 index 0000000..8b16e28 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Utilities/MethodCall.cs @@ -0,0 +1,29 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +namespace Newtonsoft.Json.Utilities +{ + internal delegate TResult MethodCall(T target, params object[] args); +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Utilities/MiscellaneousUtils.cs b/Common/00-1Json8.3/Json8.3/Utilities/MiscellaneousUtils.cs new file mode 100644 index 0000000..85b8d38 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Utilities/MiscellaneousUtils.cs @@ -0,0 +1,162 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel; +using System.Reflection; +using System.Text; +using System.Globalization; + +namespace Newtonsoft.Json.Utilities +{ + internal delegate T Creator(); + + internal static class MiscellaneousUtils + { + public static bool ValueEquals(object objA, object objB) + { + if (objA == null && objB == null) + { + return true; + } + if (objA != null && objB == null) + { + return false; + } + if (objA == null && objB != null) + { + return false; + } + + // comparing an Int32 and Int64 both of the same value returns false + // make types the same then compare + if (objA.GetType() != objB.GetType()) + { + if (ConvertUtils.IsInteger(objA) && ConvertUtils.IsInteger(objB)) + { + return Convert.ToDecimal(objA, CultureInfo.CurrentCulture).Equals(Convert.ToDecimal(objB, CultureInfo.CurrentCulture)); + } + else if ((objA is double || objA is float || objA is decimal) && (objB is double || objB is float || objB is decimal)) + { + return MathUtils.ApproxEquals(Convert.ToDouble(objA, CultureInfo.CurrentCulture), Convert.ToDouble(objB, CultureInfo.CurrentCulture)); + } + else + { + return false; + } + } + + return objA.Equals(objB); + } + + public static ArgumentOutOfRangeException CreateArgumentOutOfRangeException(string paramName, object actualValue, string message) + { + string newMessage = message + Environment.NewLine + @"Actual value was {0}.".FormatWith(CultureInfo.InvariantCulture, actualValue); + + return new ArgumentOutOfRangeException(paramName, newMessage); + } + + public static string ToString(object value) + { + if (value == null) + { + return "{null}"; + } + + return (value is string) ? @"""" + value.ToString() + @"""" : value.ToString(); + } + + public static int ByteArrayCompare(byte[] a1, byte[] a2) + { + int lengthCompare = a1.Length.CompareTo(a2.Length); + if (lengthCompare != 0) + { + return lengthCompare; + } + + for (int i = 0; i < a1.Length; i++) + { + int valueCompare = a1[i].CompareTo(a2[i]); + if (valueCompare != 0) + { + return valueCompare; + } + } + + return 0; + } + + public static string GetPrefix(string qualifiedName) + { + string prefix; + string localName; + GetQualifiedNameParts(qualifiedName, out prefix, out localName); + + return prefix; + } + + public static string GetLocalName(string qualifiedName) + { + string prefix; + string localName; + GetQualifiedNameParts(qualifiedName, out prefix, out localName); + + return localName; + } + + public static void GetQualifiedNameParts(string qualifiedName, out string prefix, out string localName) + { + int colonPosition = qualifiedName.IndexOf(':'); + + if ((colonPosition == -1 || colonPosition == 0) || (qualifiedName.Length - 1) == colonPosition) + { + prefix = null; + localName = qualifiedName; + } + else + { + prefix = qualifiedName.Substring(0, colonPosition); + localName = qualifiedName.Substring(colonPosition + 1); + } + } + + internal static string FormatValueForPrint(object value) + { + if (value == null) + { + return "{null}"; + } + + if (value is string) + { + return @"""" + value + @""""; + } + + return value.ToString(); + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Utilities/PropertyNameTable.cs b/Common/00-1Json8.3/Json8.3/Utilities/PropertyNameTable.cs new file mode 100644 index 0000000..4f1d2fc --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Utilities/PropertyNameTable.cs @@ -0,0 +1,173 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; + +namespace Newtonsoft.Json.Utilities +{ + internal class PropertyNameTable + { + // used to defeat hashtable DoS attack where someone passes in lots of strings that hash to the same hash code + private static readonly int HashCodeRandomizer; + + private int _count; + private Entry[] _entries; + private int _mask = 31; + + static PropertyNameTable() + { + HashCodeRandomizer = Environment.TickCount; + } + + public PropertyNameTable() + { + _entries = new Entry[_mask + 1]; + } + + public string Get(char[] key, int start, int length) + { + if (length == 0) + { + return string.Empty; + } + + int hashCode = length + HashCodeRandomizer; + hashCode += (hashCode << 7) ^ key[start]; + int end = start + length; + for (int i = start + 1; i < end; i++) + { + hashCode += (hashCode << 7) ^ key[i]; + } + hashCode -= hashCode >> 17; + hashCode -= hashCode >> 11; + hashCode -= hashCode >> 5; + for (Entry entry = _entries[hashCode & _mask]; entry != null; entry = entry.Next) + { + if (entry.HashCode == hashCode && TextEquals(entry.Value, key, start, length)) + { + return entry.Value; + } + } + + return null; + } + + public string Add(string key) + { + if (key == null) + { + throw new ArgumentNullException(nameof(key)); + } + + int length = key.Length; + if (length == 0) + { + return string.Empty; + } + + int hashCode = length + HashCodeRandomizer; + for (int i = 0; i < key.Length; i++) + { + hashCode += (hashCode << 7) ^ key[i]; + } + hashCode -= hashCode >> 17; + hashCode -= hashCode >> 11; + hashCode -= hashCode >> 5; + for (Entry entry = _entries[hashCode & _mask]; entry != null; entry = entry.Next) + { + if (entry.HashCode == hashCode && entry.Value.Equals(key)) + { + return entry.Value; + } + } + + return AddEntry(key, hashCode); + } + + private string AddEntry(string str, int hashCode) + { + int index = hashCode & _mask; + Entry entry = new Entry(str, hashCode, _entries[index]); + _entries[index] = entry; + if (_count++ == _mask) + { + Grow(); + } + return entry.Value; + } + + private void Grow() + { + Entry[] entries = _entries; + int newMask = (_mask * 2) + 1; + Entry[] newEntries = new Entry[newMask + 1]; + + for (int i = 0; i < entries.Length; i++) + { + Entry next; + for (Entry entry = entries[i]; entry != null; entry = next) + { + int index = entry.HashCode & newMask; + next = entry.Next; + entry.Next = newEntries[index]; + newEntries[index] = entry; + } + } + _entries = newEntries; + _mask = newMask; + } + + private static bool TextEquals(string str1, char[] str2, int str2Start, int str2Length) + { + if (str1.Length != str2Length) + { + return false; + } + + for (int i = 0; i < str1.Length; i++) + { + if (str1[i] != str2[str2Start + i]) + { + return false; + } + } + return true; + } + + private class Entry + { + internal readonly string Value; + internal readonly int HashCode; + internal Entry Next; + + internal Entry(string value, int hashCode, Entry next) + { + Value = value; + HashCode = hashCode; + Next = next; + } + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Utilities/ReflectionDelegateFactory.cs b/Common/00-1Json8.3/Json8.3/Utilities/ReflectionDelegateFactory.cs new file mode 100644 index 0000000..4b1838c --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Utilities/ReflectionDelegateFactory.cs @@ -0,0 +1,81 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Globalization; +using System.Reflection; +using Newtonsoft.Json.Serialization; + +#if NET20 +using Newtonsoft.Json.Utilities.LinqBridge; +#endif + +namespace Newtonsoft.Json.Utilities +{ + internal abstract class ReflectionDelegateFactory + { + public Func CreateGet(MemberInfo memberInfo) + { + PropertyInfo propertyInfo = memberInfo as PropertyInfo; + if (propertyInfo != null) + { + return CreateGet(propertyInfo); + } + + FieldInfo fieldInfo = memberInfo as FieldInfo; + if (fieldInfo != null) + { + return CreateGet(fieldInfo); + } + + throw new Exception("Could not create getter for {0}.".FormatWith(CultureInfo.InvariantCulture, memberInfo)); + } + + public Action CreateSet(MemberInfo memberInfo) + { + PropertyInfo propertyInfo = memberInfo as PropertyInfo; + if (propertyInfo != null) + { + return CreateSet(propertyInfo); + } + + FieldInfo fieldInfo = memberInfo as FieldInfo; + if (fieldInfo != null) + { + return CreateSet(fieldInfo); + } + + throw new Exception("Could not create setter for {0}.".FormatWith(CultureInfo.InvariantCulture, memberInfo)); + } + + public abstract MethodCall CreateMethodCall(MethodBase method); + public abstract ObjectConstructor CreateParameterizedConstructor(MethodBase method); + public abstract Func CreateDefaultConstructor(Type type); + public abstract Func CreateGet(PropertyInfo propertyInfo); + public abstract Func CreateGet(FieldInfo fieldInfo); + public abstract Action CreateSet(FieldInfo fieldInfo); + public abstract Action CreateSet(PropertyInfo propertyInfo); + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Utilities/ReflectionObject.cs b/Common/00-1Json8.3/Json8.3/Utilities/ReflectionObject.cs new file mode 100644 index 0000000..7df9a01 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Utilities/ReflectionObject.cs @@ -0,0 +1,165 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using Newtonsoft.Json.Serialization; +using System; +using System.Collections.Generic; +using System.IO; +using System.Reflection; +using System.Globalization; +#if NET20 +using Newtonsoft.Json.Utilities.LinqBridge; +#else +using System.Linq; + +#endif + +namespace Newtonsoft.Json.Utilities +{ + internal class ReflectionMember + { + public Type MemberType { get; set; } + public Func Getter { get; set; } + public Action Setter { get; set; } + } + + internal class ReflectionObject + { + public ObjectConstructor Creator { get; private set; } + public IDictionary Members { get; private set; } + + public ReflectionObject() + { + Members = new Dictionary(); + } + + public object GetValue(object target, string member) + { + Func getter = Members[member].Getter; + return getter(target); + } + + public void SetValue(object target, string member, object value) + { + Action setter = Members[member].Setter; + setter(target, value); + } + + public Type GetType(string member) + { + return Members[member].MemberType; + } + + public static ReflectionObject Create(Type t, params string[] memberNames) + { + return Create(t, null, memberNames); + } + + public static ReflectionObject Create(Type t, MethodBase creator, params string[] memberNames) + { + ReflectionObject d = new ReflectionObject(); + + ReflectionDelegateFactory delegateFactory = JsonTypeReflector.ReflectionDelegateFactory; + + if (creator != null) + { + d.Creator = delegateFactory.CreateParameterizedConstructor(creator); + } + else + { + if (ReflectionUtils.HasDefaultConstructor(t, false)) + { + Func ctor = delegateFactory.CreateDefaultConstructor(t); + + d.Creator = args => ctor(); + } + } + + foreach (string memberName in memberNames) + { + MemberInfo[] members = t.GetMember(memberName, BindingFlags.Instance | BindingFlags.Public); + if (members.Length != 1) + { + throw new ArgumentException("Expected a single member with the name '{0}'.".FormatWith(CultureInfo.InvariantCulture, memberName)); + } + + MemberInfo member = members.Single(); + + ReflectionMember reflectionMember = new ReflectionMember(); + + switch (member.MemberType()) + { + case MemberTypes.Field: + case MemberTypes.Property: + if (ReflectionUtils.CanReadMemberValue(member, false)) + { + reflectionMember.Getter = delegateFactory.CreateGet(member); + } + + if (ReflectionUtils.CanSetMemberValue(member, false, false)) + { + reflectionMember.Setter = delegateFactory.CreateSet(member); + } + break; + case MemberTypes.Method: + MethodInfo method = (MethodInfo)member; + if (method.IsPublic) + { + ParameterInfo[] parameters = method.GetParameters(); + if (parameters.Length == 0 && method.ReturnType != typeof(void)) + { + MethodCall call = delegateFactory.CreateMethodCall(method); + reflectionMember.Getter = target => call(target); + } + else if (parameters.Length == 1 && method.ReturnType == typeof(void)) + { + MethodCall call = delegateFactory.CreateMethodCall(method); + reflectionMember.Setter = (target, arg) => call(target, arg); + } + } + break; + default: + throw new ArgumentException("Unexpected member type '{0}' for member '{1}'.".FormatWith(CultureInfo.InvariantCulture, member.MemberType(), member.Name)); + } + + if (ReflectionUtils.CanReadMemberValue(member, false)) + { + reflectionMember.Getter = delegateFactory.CreateGet(member); + } + + if (ReflectionUtils.CanSetMemberValue(member, false, false)) + { + reflectionMember.Setter = delegateFactory.CreateSet(member); + } + + reflectionMember.MemberType = ReflectionUtils.GetMemberUnderlyingType(member); + + d.Members[memberName] = reflectionMember; + } + + return d; + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Utilities/ReflectionUtils.cs b/Common/00-1Json8.3/Json8.3/Utilities/ReflectionUtils.cs new file mode 100644 index 0000000..ba79efc --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Utilities/ReflectionUtils.cs @@ -0,0 +1,1122 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Collections.Generic; +#if !(PORTABLE || PORTABLE40 || NET35 || NET20) +using System.Numerics; +#endif +using System.Reflection; +using System.Collections; +using System.Globalization; +using System.Runtime.Serialization; +using System.Runtime.Serialization.Formatters; +using System.Text; +#if NET20 +using Newtonsoft.Json.Utilities.LinqBridge; +#else +using System.Linq; +#endif +using Newtonsoft.Json.Serialization; + +namespace Newtonsoft.Json.Utilities +{ +#if (DOTNET || PORTABLE || PORTABLE40) + internal enum MemberTypes + { + Property = 0, + Field = 1, + Event = 2, + Method = 3, + Other = 4 + } +#endif + +#if PORTABLE + [Flags] + internal enum BindingFlags + { + Default = 0, + IgnoreCase = 1, + DeclaredOnly = 2, + Instance = 4, + Static = 8, + Public = 16, + NonPublic = 32, + FlattenHierarchy = 64, + InvokeMethod = 256, + CreateInstance = 512, + GetField = 1024, + SetField = 2048, + GetProperty = 4096, + SetProperty = 8192, + PutDispProperty = 16384, + ExactBinding = 65536, + PutRefDispProperty = 32768, + SuppressChangeType = 131072, + OptionalParamBinding = 262144, + IgnoreReturn = 16777216 + } +#endif + + internal static class ReflectionUtils + { + public static readonly Type[] EmptyTypes; + + static ReflectionUtils() + { +#if !(PORTABLE40 || PORTABLE) + EmptyTypes = Type.EmptyTypes; +#else + EmptyTypes = new Type[0]; +#endif + } + + public static bool IsVirtual(this PropertyInfo propertyInfo) + { + ValidationUtils.ArgumentNotNull(propertyInfo, nameof(propertyInfo)); + + MethodInfo m = propertyInfo.GetGetMethod(); + if (m != null && m.IsVirtual) + { + return true; + } + + m = propertyInfo.GetSetMethod(); + if (m != null && m.IsVirtual) + { + return true; + } + + return false; + } + + public static MethodInfo GetBaseDefinition(this PropertyInfo propertyInfo) + { + ValidationUtils.ArgumentNotNull(propertyInfo, nameof(propertyInfo)); + + MethodInfo m = propertyInfo.GetGetMethod(); + if (m != null) + { + return m.GetBaseDefinition(); + } + + m = propertyInfo.GetSetMethod(); + if (m != null) + { + return m.GetBaseDefinition(); + } + + return null; + } + + public static bool IsPublic(PropertyInfo property) + { + if (property.GetGetMethod() != null && property.GetGetMethod().IsPublic) + { + return true; + } + if (property.GetSetMethod() != null && property.GetSetMethod().IsPublic) + { + return true; + } + + return false; + } + + public static Type GetObjectType(object v) + { + return (v != null) ? v.GetType() : null; + } + + public static string GetTypeName(Type t, FormatterAssemblyStyle assemblyFormat, SerializationBinder binder) + { + string fullyQualifiedTypeName; +#if !(NET20 || NET35) + if (binder != null) + { + string assemblyName, typeName; + binder.BindToName(t, out assemblyName, out typeName); + fullyQualifiedTypeName = typeName + (assemblyName == null ? "" : ", " + assemblyName); + } + else + { + fullyQualifiedTypeName = t.AssemblyQualifiedName; + } +#else + fullyQualifiedTypeName = t.AssemblyQualifiedName; +#endif + + switch (assemblyFormat) + { + case FormatterAssemblyStyle.Simple: + return RemoveAssemblyDetails(fullyQualifiedTypeName); + case FormatterAssemblyStyle.Full: + return fullyQualifiedTypeName; + default: + throw new ArgumentOutOfRangeException(); + } + } + + private static string RemoveAssemblyDetails(string fullyQualifiedTypeName) + { + StringBuilder builder = new StringBuilder(); + + // loop through the type name and filter out qualified assembly details from nested type names + bool writingAssemblyName = false; + bool skippingAssemblyDetails = false; + for (int i = 0; i < fullyQualifiedTypeName.Length; i++) + { + char current = fullyQualifiedTypeName[i]; + switch (current) + { + case '[': + writingAssemblyName = false; + skippingAssemblyDetails = false; + builder.Append(current); + break; + case ']': + writingAssemblyName = false; + skippingAssemblyDetails = false; + builder.Append(current); + break; + case ',': + if (!writingAssemblyName) + { + writingAssemblyName = true; + builder.Append(current); + } + else + { + skippingAssemblyDetails = true; + } + break; + default: + if (!skippingAssemblyDetails) + { + builder.Append(current); + } + break; + } + } + + return builder.ToString(); + } + + public static bool HasDefaultConstructor(Type t, bool nonPublic) + { + ValidationUtils.ArgumentNotNull(t, nameof(t)); + + if (t.IsValueType()) + { + return true; + } + + return (GetDefaultConstructor(t, nonPublic) != null); + } + + public static ConstructorInfo GetDefaultConstructor(Type t) + { + return GetDefaultConstructor(t, false); + } + + public static ConstructorInfo GetDefaultConstructor(Type t, bool nonPublic) + { + BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public; + if (nonPublic) + { + bindingFlags = bindingFlags | BindingFlags.NonPublic; + } + + return t.GetConstructors(bindingFlags).SingleOrDefault(c => !c.GetParameters().Any()); + } + + public static bool IsNullable(Type t) + { + ValidationUtils.ArgumentNotNull(t, nameof(t)); + + if (t.IsValueType()) + { + return IsNullableType(t); + } + + return true; + } + + public static bool IsNullableType(Type t) + { + ValidationUtils.ArgumentNotNull(t, nameof(t)); + + return (t.IsGenericType() && t.GetGenericTypeDefinition() == typeof(Nullable<>)); + } + + public static Type EnsureNotNullableType(Type t) + { + return (IsNullableType(t)) + ? Nullable.GetUnderlyingType(t) + : t; + } + + public static bool IsGenericDefinition(Type type, Type genericInterfaceDefinition) + { + if (!type.IsGenericType()) + { + return false; + } + + Type t = type.GetGenericTypeDefinition(); + return (t == genericInterfaceDefinition); + } + + public static bool ImplementsGenericDefinition(Type type, Type genericInterfaceDefinition) + { + Type implementingType; + return ImplementsGenericDefinition(type, genericInterfaceDefinition, out implementingType); + } + + public static bool ImplementsGenericDefinition(Type type, Type genericInterfaceDefinition, out Type implementingType) + { + ValidationUtils.ArgumentNotNull(type, nameof(type)); + ValidationUtils.ArgumentNotNull(genericInterfaceDefinition, nameof(genericInterfaceDefinition)); + + if (!genericInterfaceDefinition.IsInterface() || !genericInterfaceDefinition.IsGenericTypeDefinition()) + { + throw new ArgumentNullException("'{0}' is not a generic interface definition.".FormatWith(CultureInfo.InvariantCulture, genericInterfaceDefinition)); + } + + if (type.IsInterface()) + { + if (type.IsGenericType()) + { + Type interfaceDefinition = type.GetGenericTypeDefinition(); + + if (genericInterfaceDefinition == interfaceDefinition) + { + implementingType = type; + return true; + } + } + } + + foreach (Type i in type.GetInterfaces()) + { + if (i.IsGenericType()) + { + Type interfaceDefinition = i.GetGenericTypeDefinition(); + + if (genericInterfaceDefinition == interfaceDefinition) + { + implementingType = i; + return true; + } + } + } + + implementingType = null; + return false; + } + + public static bool InheritsGenericDefinition(Type type, Type genericClassDefinition) + { + Type implementingType; + return InheritsGenericDefinition(type, genericClassDefinition, out implementingType); + } + + public static bool InheritsGenericDefinition(Type type, Type genericClassDefinition, out Type implementingType) + { + ValidationUtils.ArgumentNotNull(type, nameof(type)); + ValidationUtils.ArgumentNotNull(genericClassDefinition, nameof(genericClassDefinition)); + + if (!genericClassDefinition.IsClass() || !genericClassDefinition.IsGenericTypeDefinition()) + { + throw new ArgumentNullException("'{0}' is not a generic class definition.".FormatWith(CultureInfo.InvariantCulture, genericClassDefinition)); + } + + return InheritsGenericDefinitionInternal(type, genericClassDefinition, out implementingType); + } + + private static bool InheritsGenericDefinitionInternal(Type currentType, Type genericClassDefinition, out Type implementingType) + { + if (currentType.IsGenericType()) + { + Type currentGenericClassDefinition = currentType.GetGenericTypeDefinition(); + + if (genericClassDefinition == currentGenericClassDefinition) + { + implementingType = currentType; + return true; + } + } + + if (currentType.BaseType() == null) + { + implementingType = null; + return false; + } + + return InheritsGenericDefinitionInternal(currentType.BaseType(), genericClassDefinition, out implementingType); + } + + /// + /// Gets the type of the typed collection's items. + /// + /// The type. + /// The type of the typed collection's items. + public static Type GetCollectionItemType(Type type) + { + ValidationUtils.ArgumentNotNull(type, nameof(type)); + Type genericListType; + + if (type.IsArray) + { + return type.GetElementType(); + } + if (ImplementsGenericDefinition(type, typeof(IEnumerable<>), out genericListType)) + { + if (genericListType.IsGenericTypeDefinition()) + { + throw new Exception("Type {0} is not a collection.".FormatWith(CultureInfo.InvariantCulture, type)); + } + + return genericListType.GetGenericArguments()[0]; + } + if (typeof(IEnumerable).IsAssignableFrom(type)) + { + return null; + } + + throw new Exception("Type {0} is not a collection.".FormatWith(CultureInfo.InvariantCulture, type)); + } + + public static void GetDictionaryKeyValueTypes(Type dictionaryType, out Type keyType, out Type valueType) + { + ValidationUtils.ArgumentNotNull(dictionaryType, nameof(dictionaryType)); + + Type genericDictionaryType; + if (ImplementsGenericDefinition(dictionaryType, typeof(IDictionary<,>), out genericDictionaryType)) + { + if (genericDictionaryType.IsGenericTypeDefinition()) + { + throw new Exception("Type {0} is not a dictionary.".FormatWith(CultureInfo.InvariantCulture, dictionaryType)); + } + + Type[] dictionaryGenericArguments = genericDictionaryType.GetGenericArguments(); + + keyType = dictionaryGenericArguments[0]; + valueType = dictionaryGenericArguments[1]; + return; + } + if (typeof(IDictionary).IsAssignableFrom(dictionaryType)) + { + keyType = null; + valueType = null; + return; + } + + throw new Exception("Type {0} is not a dictionary.".FormatWith(CultureInfo.InvariantCulture, dictionaryType)); + } + + /// + /// Gets the member's underlying type. + /// + /// The member. + /// The underlying type of the member. + public static Type GetMemberUnderlyingType(MemberInfo member) + { + ValidationUtils.ArgumentNotNull(member, nameof(member)); + + switch (member.MemberType()) + { + case MemberTypes.Field: + return ((FieldInfo)member).FieldType; + case MemberTypes.Property: + return ((PropertyInfo)member).PropertyType; + case MemberTypes.Event: + return ((EventInfo)member).EventHandlerType; + case MemberTypes.Method: + return ((MethodInfo)member).ReturnType; + default: + throw new ArgumentException("MemberInfo must be of type FieldInfo, PropertyInfo, EventInfo or MethodInfo", nameof(member)); + } + } + + /// + /// Determines whether the member is an indexed property. + /// + /// The member. + /// + /// true if the member is an indexed property; otherwise, false. + /// + public static bool IsIndexedProperty(MemberInfo member) + { + ValidationUtils.ArgumentNotNull(member, nameof(member)); + + PropertyInfo propertyInfo = member as PropertyInfo; + + if (propertyInfo != null) + { + return IsIndexedProperty(propertyInfo); + } + else + { + return false; + } + } + + /// + /// Determines whether the property is an indexed property. + /// + /// The property. + /// + /// true if the property is an indexed property; otherwise, false. + /// + public static bool IsIndexedProperty(PropertyInfo property) + { + ValidationUtils.ArgumentNotNull(property, nameof(property)); + + return (property.GetIndexParameters().Length > 0); + } + + /// + /// Gets the member's value on the object. + /// + /// The member. + /// The target object. + /// The member's value on the object. + public static object GetMemberValue(MemberInfo member, object target) + { + ValidationUtils.ArgumentNotNull(member, nameof(member)); + ValidationUtils.ArgumentNotNull(target, nameof(target)); + + switch (member.MemberType()) + { + case MemberTypes.Field: + return ((FieldInfo)member).GetValue(target); + case MemberTypes.Property: + try + { + return ((PropertyInfo)member).GetValue(target, null); + } + catch (TargetParameterCountException e) + { + throw new ArgumentException("MemberInfo '{0}' has index parameters".FormatWith(CultureInfo.InvariantCulture, member.Name), e); + } + default: + throw new ArgumentException("MemberInfo '{0}' is not of type FieldInfo or PropertyInfo".FormatWith(CultureInfo.InvariantCulture, CultureInfo.InvariantCulture, member.Name), nameof(member)); + } + } + + /// + /// Sets the member's value on the target object. + /// + /// The member. + /// The target. + /// The value. + public static void SetMemberValue(MemberInfo member, object target, object value) + { + ValidationUtils.ArgumentNotNull(member, nameof(member)); + ValidationUtils.ArgumentNotNull(target, nameof(target)); + + switch (member.MemberType()) + { + case MemberTypes.Field: + ((FieldInfo)member).SetValue(target, value); + break; + case MemberTypes.Property: + ((PropertyInfo)member).SetValue(target, value, null); + break; + default: + throw new ArgumentException("MemberInfo '{0}' must be of type FieldInfo or PropertyInfo".FormatWith(CultureInfo.InvariantCulture, member.Name), nameof(member)); + } + } + + /// + /// Determines whether the specified MemberInfo can be read. + /// + /// The MemberInfo to determine whether can be read. + /// /// if set to true then allow the member to be gotten non-publicly. + /// + /// true if the specified MemberInfo can be read; otherwise, false. + /// + public static bool CanReadMemberValue(MemberInfo member, bool nonPublic) + { + switch (member.MemberType()) + { + case MemberTypes.Field: + FieldInfo fieldInfo = (FieldInfo)member; + + if (nonPublic) + { + return true; + } + else if (fieldInfo.IsPublic) + { + return true; + } + return false; + case MemberTypes.Property: + PropertyInfo propertyInfo = (PropertyInfo)member; + + if (!propertyInfo.CanRead) + { + return false; + } + if (nonPublic) + { + return true; + } + return (propertyInfo.GetGetMethod(nonPublic) != null); + default: + return false; + } + } + + /// + /// Determines whether the specified MemberInfo can be set. + /// + /// The MemberInfo to determine whether can be set. + /// if set to true then allow the member to be set non-publicly. + /// if set to true then allow the member to be set if read-only. + /// + /// true if the specified MemberInfo can be set; otherwise, false. + /// + public static bool CanSetMemberValue(MemberInfo member, bool nonPublic, bool canSetReadOnly) + { + switch (member.MemberType()) + { + case MemberTypes.Field: + FieldInfo fieldInfo = (FieldInfo)member; + + if (fieldInfo.IsLiteral) + { + return false; + } + if (fieldInfo.IsInitOnly && !canSetReadOnly) + { + return false; + } + if (nonPublic) + { + return true; + } + if (fieldInfo.IsPublic) + { + return true; + } + return false; + case MemberTypes.Property: + PropertyInfo propertyInfo = (PropertyInfo)member; + + if (!propertyInfo.CanWrite) + { + return false; + } + if (nonPublic) + { + return true; + } + return (propertyInfo.GetSetMethod(nonPublic) != null); + default: + return false; + } + } + + public static List GetFieldsAndProperties(Type type, BindingFlags bindingAttr) + { + List targetMembers = new List(); + + targetMembers.AddRange(GetFields(type, bindingAttr)); + targetMembers.AddRange(GetProperties(type, bindingAttr)); + + // for some reason .NET returns multiple members when overriding a generic member on a base class + // http://social.msdn.microsoft.com/Forums/en-US/b5abbfee-e292-4a64-8907-4e3f0fb90cd9/reflection-overriden-abstract-generic-properties?forum=netfxbcl + // filter members to only return the override on the topmost class + // update: I think this is fixed in .NET 3.5 SP1 - leave this in for now... + List distinctMembers = new List(targetMembers.Count); + + foreach (var groupedMember in targetMembers.GroupBy(m => m.Name)) + { + int count = groupedMember.Count(); + IList members = groupedMember.ToList(); + + if (count == 1) + { + distinctMembers.Add(members.First()); + } + else + { + IList resolvedMembers = new List(); + foreach (MemberInfo memberInfo in members) + { + // this is a bit hacky + // if the hiding property is hiding a base property and it is virtual + // then this ensures the derived property gets used + if (resolvedMembers.Count == 0) + { + resolvedMembers.Add(memberInfo); + } + else if (!IsOverridenGenericMember(memberInfo, bindingAttr) || memberInfo.Name == "Item") + { + resolvedMembers.Add(memberInfo); + } + } + + distinctMembers.AddRange(resolvedMembers); + } + } + + return distinctMembers; + } + + private static bool IsOverridenGenericMember(MemberInfo memberInfo, BindingFlags bindingAttr) + { + if (memberInfo.MemberType() != MemberTypes.Property) + { + return false; + } + + PropertyInfo propertyInfo = (PropertyInfo)memberInfo; + if (!IsVirtual(propertyInfo)) + { + return false; + } + + Type declaringType = propertyInfo.DeclaringType; + if (!declaringType.IsGenericType()) + { + return false; + } + Type genericTypeDefinition = declaringType.GetGenericTypeDefinition(); + if (genericTypeDefinition == null) + { + return false; + } + MemberInfo[] members = genericTypeDefinition.GetMember(propertyInfo.Name, bindingAttr); + if (members.Length == 0) + { + return false; + } + Type memberUnderlyingType = GetMemberUnderlyingType(members[0]); + if (!memberUnderlyingType.IsGenericParameter) + { + return false; + } + + return true; + } + + public static T GetAttribute(object attributeProvider) where T : Attribute + { + return GetAttribute(attributeProvider, true); + } + + public static T GetAttribute(object attributeProvider, bool inherit) where T : Attribute + { + T[] attributes = GetAttributes(attributeProvider, inherit); + + return (attributes != null) ? attributes.FirstOrDefault() : null; + } + +#if !(DOTNET || PORTABLE) + public static T[] GetAttributes(object attributeProvider, bool inherit) where T : Attribute + { + Attribute[] a = GetAttributes(attributeProvider, typeof(T), inherit); + + T[] attributes = a as T[]; + if (attributes != null) + { + return attributes; + } + + return a.Cast().ToArray(); + } + + public static Attribute[] GetAttributes(object attributeProvider, Type attributeType, bool inherit) + { + ValidationUtils.ArgumentNotNull(attributeProvider, nameof(attributeProvider)); + + object provider = attributeProvider; + + // http://hyperthink.net/blog/getcustomattributes-gotcha/ + // ICustomAttributeProvider doesn't do inheritance + + if (provider is Type) + { + Type t = (Type)provider; + object[] a = (attributeType != null) ? t.GetCustomAttributes(attributeType, inherit) : t.GetCustomAttributes(inherit); + Attribute[] attributes = a.Cast().ToArray(); + +#if (NET20 || NET35) + // ye olde .NET GetCustomAttributes doesn't respect the inherit argument + if (inherit && t.BaseType != null) + attributes = attributes.Union(GetAttributes(t.BaseType, attributeType, inherit)).ToArray(); +#endif + + return attributes; + } + + if (provider is Assembly) + { + Assembly a = (Assembly)provider; + return (attributeType != null) ? Attribute.GetCustomAttributes(a, attributeType) : Attribute.GetCustomAttributes(a); + } + + if (provider is MemberInfo) + { + MemberInfo m = (MemberInfo)provider; + return (attributeType != null) ? Attribute.GetCustomAttributes(m, attributeType, inherit) : Attribute.GetCustomAttributes(m, inherit); + } + +#if !PORTABLE40 + if (provider is Module) + { + Module m = (Module)provider; + return (attributeType != null) ? Attribute.GetCustomAttributes(m, attributeType, inherit) : Attribute.GetCustomAttributes(m, inherit); + } +#endif + + if (provider is ParameterInfo) + { + ParameterInfo p = (ParameterInfo)provider; + return (attributeType != null) ? Attribute.GetCustomAttributes(p, attributeType, inherit) : Attribute.GetCustomAttributes(p, inherit); + } + +#if !PORTABLE40 + ICustomAttributeProvider customAttributeProvider = (ICustomAttributeProvider)attributeProvider; + object[] result = (attributeType != null) ? customAttributeProvider.GetCustomAttributes(attributeType, inherit) : customAttributeProvider.GetCustomAttributes(inherit); + + return (Attribute[])result; +#else + throw new Exception("Cannot get attributes from '{0}'.".FormatWith(CultureInfo.InvariantCulture, provider)); +#endif + } +#else + public static T[] GetAttributes(object attributeProvider, bool inherit) where T : Attribute + { + return GetAttributes(attributeProvider, typeof(T), inherit).Cast().ToArray(); + } + + public static Attribute[] GetAttributes(object provider, Type attributeType, bool inherit) + { + if (provider is Type) + { + Type t = (Type)provider; + return (attributeType != null) + ? t.GetTypeInfo().GetCustomAttributes(attributeType, inherit).ToArray() + : t.GetTypeInfo().GetCustomAttributes(inherit).ToArray(); + } + + if (provider is Assembly) + { + Assembly a = (Assembly)provider; + return (attributeType != null) ? a.GetCustomAttributes(attributeType).ToArray() : a.GetCustomAttributes().ToArray(); + } + + if (provider is MemberInfo) + { + MemberInfo m = (MemberInfo)provider; + return (attributeType != null) ? m.GetCustomAttributes(attributeType, inherit).ToArray() : m.GetCustomAttributes(inherit).ToArray(); + } + + if (provider is Module) + { + Module m = (Module)provider; + return (attributeType != null) ? m.GetCustomAttributes(attributeType).ToArray() : m.GetCustomAttributes().ToArray(); + } + + if (provider is ParameterInfo) + { + ParameterInfo p = (ParameterInfo)provider; + return (attributeType != null) ? p.GetCustomAttributes(attributeType, inherit).ToArray() : p.GetCustomAttributes(inherit).ToArray(); + } + + throw new Exception("Cannot get attributes from '{0}'.".FormatWith(CultureInfo.InvariantCulture, provider)); + } +#endif + + public static void SplitFullyQualifiedTypeName(string fullyQualifiedTypeName, out string typeName, out string assemblyName) + { + int? assemblyDelimiterIndex = GetAssemblyDelimiterIndex(fullyQualifiedTypeName); + + if (assemblyDelimiterIndex != null) + { + typeName = fullyQualifiedTypeName.Substring(0, assemblyDelimiterIndex.GetValueOrDefault()).Trim(); + assemblyName = fullyQualifiedTypeName.Substring(assemblyDelimiterIndex.GetValueOrDefault() + 1, fullyQualifiedTypeName.Length - assemblyDelimiterIndex.GetValueOrDefault() - 1).Trim(); + } + else + { + typeName = fullyQualifiedTypeName; + assemblyName = null; + } + } + + private static int? GetAssemblyDelimiterIndex(string fullyQualifiedTypeName) + { + // we need to get the first comma following all surrounded in brackets because of generic types + // e.g. System.Collections.Generic.Dictionary`2[[System.String, mscorlib,Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + int scope = 0; + for (int i = 0; i < fullyQualifiedTypeName.Length; i++) + { + char current = fullyQualifiedTypeName[i]; + switch (current) + { + case '[': + scope++; + break; + case ']': + scope--; + break; + case ',': + if (scope == 0) + { + return i; + } + break; + } + } + + return null; + } + + public static MemberInfo GetMemberInfoFromType(Type targetType, MemberInfo memberInfo) + { + const BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic; + + switch (memberInfo.MemberType()) + { + case MemberTypes.Property: + PropertyInfo propertyInfo = (PropertyInfo)memberInfo; + + Type[] types = propertyInfo.GetIndexParameters().Select(p => p.ParameterType).ToArray(); + + return targetType.GetProperty(propertyInfo.Name, bindingAttr, null, propertyInfo.PropertyType, types, null); + default: + return targetType.GetMember(memberInfo.Name, memberInfo.MemberType(), bindingAttr).SingleOrDefault(); + } + } + + public static IEnumerable GetFields(Type targetType, BindingFlags bindingAttr) + { + ValidationUtils.ArgumentNotNull(targetType, nameof(targetType)); + + List fieldInfos = new List(targetType.GetFields(bindingAttr)); +#if !PORTABLE + // Type.GetFields doesn't return inherited private fields + // manually find private fields from base class + GetChildPrivateFields(fieldInfos, targetType, bindingAttr); +#endif + + return fieldInfos.Cast(); + } + +#if !PORTABLE + private static void GetChildPrivateFields(IList initialFields, Type targetType, BindingFlags bindingAttr) + { + // fix weirdness with private FieldInfos only being returned for the current Type + // find base type fields and add them to result + if ((bindingAttr & BindingFlags.NonPublic) != 0) + { + // modify flags to not search for public fields + BindingFlags nonPublicBindingAttr = bindingAttr.RemoveFlag(BindingFlags.Public); + + while ((targetType = targetType.BaseType()) != null) + { + // filter out protected fields + IEnumerable childPrivateFields = + targetType.GetFields(nonPublicBindingAttr).Where(f => f.IsPrivate).Cast(); + + initialFields.AddRange(childPrivateFields); + } + } + } +#endif + + public static IEnumerable GetProperties(Type targetType, BindingFlags bindingAttr) + { + ValidationUtils.ArgumentNotNull(targetType, nameof(targetType)); + + List propertyInfos = new List(targetType.GetProperties(bindingAttr)); + + // GetProperties on an interface doesn't return properties from its interfaces + if (targetType.IsInterface()) + { + foreach (Type i in targetType.GetInterfaces()) + { + propertyInfos.AddRange(i.GetProperties(bindingAttr)); + } + } + + GetChildPrivateProperties(propertyInfos, targetType, bindingAttr); + + // a base class private getter/setter will be inaccessable unless the property was gotten from the base class + for (int i = 0; i < propertyInfos.Count; i++) + { + PropertyInfo member = propertyInfos[i]; + if (member.DeclaringType != targetType) + { + PropertyInfo declaredMember = (PropertyInfo)GetMemberInfoFromType(member.DeclaringType, member); + propertyInfos[i] = declaredMember; + } + } + + return propertyInfos; + } + + public static BindingFlags RemoveFlag(this BindingFlags bindingAttr, BindingFlags flag) + { + return ((bindingAttr & flag) == flag) + ? bindingAttr ^ flag + : bindingAttr; + } + + private static void GetChildPrivateProperties(IList initialProperties, Type targetType, BindingFlags bindingAttr) + { + // fix weirdness with private PropertyInfos only being returned for the current Type + // find base type properties and add them to result + + // also find base properties that have been hidden by subtype properties with the same name + + while ((targetType = targetType.BaseType()) != null) + { + foreach (PropertyInfo propertyInfo in targetType.GetProperties(bindingAttr)) + { + PropertyInfo subTypeProperty = propertyInfo; + + if (!IsPublic(subTypeProperty)) + { + // have to test on name rather than reference because instances are different + // depending on the type that GetProperties was called on + int index = initialProperties.IndexOf(p => p.Name == subTypeProperty.Name); + if (index == -1) + { + initialProperties.Add(subTypeProperty); + } + else + { + PropertyInfo childProperty = initialProperties[index]; + // don't replace public child with private base + if (!IsPublic(childProperty)) + { + // replace nonpublic properties for a child, but gotten from + // the parent with the one from the child + // the property gotten from the child will have access to private getter/setter + initialProperties[index] = subTypeProperty; + } + } + } + else + { + if (!subTypeProperty.IsVirtual()) + { + int index = initialProperties.IndexOf(p => p.Name == subTypeProperty.Name + && p.DeclaringType == subTypeProperty.DeclaringType); + + if (index == -1) + { + initialProperties.Add(subTypeProperty); + } + } + else + { + int index = initialProperties.IndexOf(p => p.Name == subTypeProperty.Name + && p.IsVirtual() + && p.GetBaseDefinition() != null + && p.GetBaseDefinition().DeclaringType.IsAssignableFrom(subTypeProperty.GetBaseDefinition().DeclaringType)); + + if (index == -1) + { + initialProperties.Add(subTypeProperty); + } + } + } + } + } + } + + public static bool IsMethodOverridden(Type currentType, Type methodDeclaringType, string method) + { + bool isMethodOverriden = currentType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance) + .Any(info => + info.Name == method && + // check that the method overrides the original on DynamicObjectProxy + info.DeclaringType != methodDeclaringType + && info.GetBaseDefinition().DeclaringType == methodDeclaringType + ); + + return isMethodOverriden; + } + + public static object GetDefaultValue(Type type) + { + if (!type.IsValueType()) + { + return null; + } + + switch (ConvertUtils.GetTypeCode(type)) + { + case PrimitiveTypeCode.Boolean: + return false; + case PrimitiveTypeCode.Char: + case PrimitiveTypeCode.SByte: + case PrimitiveTypeCode.Byte: + case PrimitiveTypeCode.Int16: + case PrimitiveTypeCode.UInt16: + case PrimitiveTypeCode.Int32: + case PrimitiveTypeCode.UInt32: + return 0; + case PrimitiveTypeCode.Int64: + case PrimitiveTypeCode.UInt64: + return 0L; + case PrimitiveTypeCode.Single: + return 0f; + case PrimitiveTypeCode.Double: + return 0.0; + case PrimitiveTypeCode.Decimal: + return 0m; + case PrimitiveTypeCode.DateTime: + return new DateTime(); +#if !(PORTABLE || PORTABLE40 || NET35 || NET20) + case PrimitiveTypeCode.BigInteger: + return new BigInteger(); +#endif + case PrimitiveTypeCode.Guid: + return new Guid(); +#if !NET20 + case PrimitiveTypeCode.DateTimeOffset: + return new DateTimeOffset(); +#endif + } + + if (IsNullable(type)) + { + return null; + } + + // possibly use IL initobj for perf here? + return Activator.CreateInstance(type); + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Utilities/StringBuffer.cs b/Common/00-1Json8.3/Json8.3/Utilities/StringBuffer.cs new file mode 100644 index 0000000..ec6818e --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Utilities/StringBuffer.cs @@ -0,0 +1,122 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; + +namespace Newtonsoft.Json.Utilities +{ + /// + /// Builds a string. Unlike StringBuilder this class lets you reuse it's internal buffer. + /// + internal struct StringBuffer + { + private char[] _buffer; + private int _position; + + public int Position + { + get { return _position; } + set { _position = value; } + } + + public bool IsEmpty + { + get { return _buffer == null; } + } + + public StringBuffer(IArrayPool bufferPool, int initalSize) : this(BufferUtils.RentBuffer(bufferPool, initalSize)) + { + } + + private StringBuffer(char[] buffer) + { + _buffer = buffer; + _position = 0; + } + + public void Append(IArrayPool bufferPool, char value) + { + // test if the buffer array is large enough to take the value + if (_position == _buffer.Length) + { + EnsureSize(bufferPool, 1); + } + + // set value and increment poisition + _buffer[_position++] = value; + } + + public void Append(IArrayPool bufferPool, char[] buffer, int startIndex, int count) + { + if (_position + count >= _buffer.Length) + { + EnsureSize(bufferPool, count); + } + + Array.Copy(buffer, startIndex, _buffer, _position, count); + + _position += count; + } + + public void Clear(IArrayPool bufferPool) + { + if (_buffer != null) + { + BufferUtils.ReturnBuffer(bufferPool, _buffer); + _buffer = null; + } + _position = 0; + } + + private void EnsureSize(IArrayPool bufferPool, int appendLength) + { + char[] newBuffer = BufferUtils.RentBuffer(bufferPool, (_position + appendLength) * 2); + + if (_buffer != null) + { + Array.Copy(_buffer, newBuffer, _position); + BufferUtils.ReturnBuffer(bufferPool, _buffer); + } + + _buffer = newBuffer; + } + + public override string ToString() + { + return ToString(0, _position); + } + + public string ToString(int start, int length) + { + // TODO: validation + return new string(_buffer, start, length); + } + + public char[] InternalBuffer + { + get { return _buffer; } + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Utilities/StringReference.cs b/Common/00-1Json8.3/Json8.3/Utilities/StringReference.cs new file mode 100644 index 0000000..5028a41 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Utilities/StringReference.cs @@ -0,0 +1,123 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; + +namespace Newtonsoft.Json.Utilities +{ + internal struct StringReference + { + private readonly char[] _chars; + private readonly int _startIndex; + private readonly int _length; + + public char this[int i] + { + get { return _chars[i]; } + } + + public char[] Chars + { + get { return _chars; } + } + + public int StartIndex + { + get { return _startIndex; } + } + + public int Length + { + get { return _length; } + } + + public StringReference(char[] chars, int startIndex, int length) + { + _chars = chars; + _startIndex = startIndex; + _length = length; + } + + public override string ToString() + { + return new string(_chars, _startIndex, _length); + } + } + + internal static class StringReferenceExtensions + { + public static int IndexOf(this StringReference s, char c, int startIndex, int length) + { + int index = Array.IndexOf(s.Chars, c, s.StartIndex + startIndex, length); + if (index == -1) + { + return -1; + } + + return index - s.StartIndex; + } + + public static bool StartsWith(this StringReference s, string text) + { + if (text.Length > s.Length) + { + return false; + } + + char[] chars = s.Chars; + + for (int i = 0; i < text.Length; i++) + { + if (text[i] != chars[i + s.StartIndex]) + { + return false; + } + } + + return true; + } + + public static bool EndsWith(this StringReference s, string text) + { + if (text.Length > s.Length) + { + return false; + } + + char[] chars = s.Chars; + + int start = s.StartIndex + s.Length - text.Length; + for (int i = 0; i < text.Length; i++) + { + if (text[i] != chars[i + start]) + { + return false; + } + } + + return true; + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Utilities/StringUtils.cs b/Common/00-1Json8.3/Json8.3/Utilities/StringUtils.cs new file mode 100644 index 0000000..0913011 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Utilities/StringUtils.cs @@ -0,0 +1,231 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; +using System.Globalization; +#if NET20 +using Newtonsoft.Json.Utilities.LinqBridge; +#else +using System.Linq; +#endif +using Newtonsoft.Json.Serialization; + +namespace Newtonsoft.Json.Utilities +{ + internal static class StringUtils + { + public const string CarriageReturnLineFeed = "\r\n"; + public const string Empty = ""; + public const char CarriageReturn = '\r'; + public const char LineFeed = '\n'; + public const char Tab = '\t'; + + public static string FormatWith(this string format, IFormatProvider provider, object arg0) + { + return format.FormatWith(provider, new[] { arg0 }); + } + + public static string FormatWith(this string format, IFormatProvider provider, object arg0, object arg1) + { + return format.FormatWith(provider, new[] { arg0, arg1 }); + } + + public static string FormatWith(this string format, IFormatProvider provider, object arg0, object arg1, object arg2) + { + return format.FormatWith(provider, new[] { arg0, arg1, arg2 }); + } + + public static string FormatWith(this string format, IFormatProvider provider, object arg0, object arg1, object arg2, object arg3) + { + return format.FormatWith(provider, new[] { arg0, arg1, arg2, arg3 }); + } + + private static string FormatWith(this string format, IFormatProvider provider, params object[] args) + { + // leave this a private to force code to use an explicit overload + // avoids stack memory being reserved for the object array + ValidationUtils.ArgumentNotNull(format, nameof(format)); + + return string.Format(provider, format, args); + } + + /// + /// Determines whether the string is all white space. Empty string will return false. + /// + /// The string to test whether it is all white space. + /// + /// true if the string is all white space; otherwise, false. + /// + public static bool IsWhiteSpace(string s) + { + if (s == null) + { + throw new ArgumentNullException(nameof(s)); + } + + if (s.Length == 0) + { + return false; + } + + for (int i = 0; i < s.Length; i++) + { + if (!char.IsWhiteSpace(s[i])) + { + return false; + } + } + + return true; + } + + /// + /// Nulls an empty string. + /// + /// The string. + /// Null if the string was null, otherwise the string unchanged. + public static string NullEmptyString(string s) + { + return (string.IsNullOrEmpty(s)) ? null : s; + } + + public static StringWriter CreateStringWriter(int capacity) + { + StringBuilder sb = new StringBuilder(capacity); + StringWriter sw = new StringWriter(sb, CultureInfo.InvariantCulture); + + return sw; + } + + public static int? GetLength(string value) + { + if (value == null) + { + return null; + } + else + { + return value.Length; + } + } + + public static void ToCharAsUnicode(char c, char[] buffer) + { + buffer[0] = '\\'; + buffer[1] = 'u'; + buffer[2] = MathUtils.IntToHex((c >> 12) & '\x000f'); + buffer[3] = MathUtils.IntToHex((c >> 8) & '\x000f'); + buffer[4] = MathUtils.IntToHex((c >> 4) & '\x000f'); + buffer[5] = MathUtils.IntToHex(c & '\x000f'); + } + + public static TSource ForgivingCaseSensitiveFind(this IEnumerable source, Func valueSelector, string testValue) + { + if (source == null) + { + throw new ArgumentNullException(nameof(source)); + } + if (valueSelector == null) + { + throw new ArgumentNullException(nameof(valueSelector)); + } + + var caseInsensitiveResults = source.Where(s => string.Equals(valueSelector(s), testValue, StringComparison.OrdinalIgnoreCase)); + if (caseInsensitiveResults.Count() <= 1) + { + return caseInsensitiveResults.SingleOrDefault(); + } + else + { + // multiple results returned. now filter using case sensitivity + var caseSensitiveResults = source.Where(s => string.Equals(valueSelector(s), testValue, StringComparison.Ordinal)); + return caseSensitiveResults.SingleOrDefault(); + } + } + + public static string ToCamelCase(string s) + { + if (string.IsNullOrEmpty(s) || !char.IsUpper(s[0])) + { + return s; + } + + char[] chars = s.ToCharArray(); + + for (int i = 0; i < chars.Length; i++) + { + if (i == 1 && !char.IsUpper(chars[i])) + { + break; + } + + bool hasNext = (i + 1 < chars.Length); + if (i > 0 && hasNext && !char.IsUpper(chars[i + 1])) + { + break; + } + +#if !(DOTNET || PORTABLE) + chars[i] = char.ToLower(chars[i], CultureInfo.InvariantCulture); +#else + chars[i] = char.ToLowerInvariant(chars[i]); +#endif + } + + return new string(chars); + } + + public static bool IsHighSurrogate(char c) + { +#if !(PORTABLE40 || PORTABLE) + return char.IsHighSurrogate(c); +#else + return (c >= 55296 && c <= 56319); +#endif + } + + public static bool IsLowSurrogate(char c) + { +#if !(PORTABLE40 || PORTABLE) + return char.IsLowSurrogate(c); +#else + return (c >= 56320 && c <= 57343); +#endif + } + + public static bool StartsWith(this string source, char value) + { + return (source.Length > 0 && source[0] == value); + } + + public static bool EndsWith(this string source, char value) + { + return (source.Length > 0 && source[source.Length - 1] == value); + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Utilities/ThreadSafeStore.cs b/Common/00-1Json8.3/Json8.3/Utilities/ThreadSafeStore.cs new file mode 100644 index 0000000..1e56065 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Utilities/ThreadSafeStore.cs @@ -0,0 +1,97 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Collections.Generic; +#if NET20 +using Newtonsoft.Json.Utilities.LinqBridge; +#endif +using System.Threading; +using Newtonsoft.Json.Serialization; + +namespace Newtonsoft.Json.Utilities +{ + internal class ThreadSafeStore + { + private readonly object _lock = new object(); + private Dictionary _store; + private readonly Func _creator; + + public ThreadSafeStore(Func creator) + { + if (creator == null) + { + throw new ArgumentNullException(nameof(creator)); + } + + _creator = creator; + _store = new Dictionary(); + } + + public TValue Get(TKey key) + { + TValue value; + if (!_store.TryGetValue(key, out value)) + { + return AddValue(key); + } + + return value; + } + + private TValue AddValue(TKey key) + { + TValue value = _creator(key); + + lock (_lock) + { + if (_store == null) + { + _store = new Dictionary(); + _store[key] = value; + } + else + { + // double check locking + TValue checkValue; + if (_store.TryGetValue(key, out checkValue)) + { + return checkValue; + } + + Dictionary newStore = new Dictionary(_store); + newStore[key] = value; + +#if !(DOTNET || PORTABLE) + Thread.MemoryBarrier(); +#endif + _store = newStore; + } + + return value; + } + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Utilities/TypeExtensions.cs b/Common/00-1Json8.3/Json8.3/Utilities/TypeExtensions.cs new file mode 100644 index 0000000..ee7e092 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Utilities/TypeExtensions.cs @@ -0,0 +1,628 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; +using System.Collections.Generic; +using System.Reflection; +#if NET20 +using Newtonsoft.Json.Utilities.LinqBridge; +#else +using System.Linq; +#endif + +namespace Newtonsoft.Json.Utilities +{ + internal static class TypeExtensions + { +#if DOTNET || PORTABLE +#if !DOTNET + private static BindingFlags DefaultFlags = BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance; + + public static MethodInfo GetGetMethod(this PropertyInfo propertyInfo) + { + return propertyInfo.GetGetMethod(false); + } + + public static MethodInfo GetGetMethod(this PropertyInfo propertyInfo, bool nonPublic) + { + MethodInfo getMethod = propertyInfo.GetMethod; + if (getMethod != null && (getMethod.IsPublic || nonPublic)) + { + return getMethod; + } + + return null; + } + + public static MethodInfo GetSetMethod(this PropertyInfo propertyInfo) + { + return propertyInfo.GetSetMethod(false); + } + + public static MethodInfo GetSetMethod(this PropertyInfo propertyInfo, bool nonPublic) + { + MethodInfo setMethod = propertyInfo.SetMethod; + if (setMethod != null && (setMethod.IsPublic || nonPublic)) + { + return setMethod; + } + + return null; + } +#endif + + public static bool IsSubclassOf(this Type type, Type c) + { + return type.GetTypeInfo().IsSubclassOf(c); + } + +#if !DOTNET + public static bool IsAssignableFrom(this Type type, Type c) + { + return type.GetTypeInfo().IsAssignableFrom(c.GetTypeInfo()); + } +#endif + + public static bool IsInstanceOfType(this Type type, object o) + { + if (o == null) + { + return false; + } + + return type.IsAssignableFrom(o.GetType()); + } +#endif + + public static MethodInfo Method(this Delegate d) + { +#if !(DOTNET || PORTABLE) + return d.Method; +#else + return d.GetMethodInfo(); +#endif + } + + public static MemberTypes MemberType(this MemberInfo memberInfo) + { +#if !(DOTNET || PORTABLE || PORTABLE40) + return memberInfo.MemberType; +#else + if (memberInfo is PropertyInfo) + { + return MemberTypes.Property; + } + else if (memberInfo is FieldInfo) + { + return MemberTypes.Field; + } + else if (memberInfo is EventInfo) + { + return MemberTypes.Event; + } + else if (memberInfo is MethodInfo) + { + return MemberTypes.Method; + } + else + { + return MemberTypes.Other; + } +#endif + } + + public static bool ContainsGenericParameters(this Type type) + { +#if !(DOTNET || PORTABLE) + return type.ContainsGenericParameters; +#else + return type.GetTypeInfo().ContainsGenericParameters; +#endif + } + + public static bool IsInterface(this Type type) + { +#if !(DOTNET || PORTABLE) + return type.IsInterface; +#else + return type.GetTypeInfo().IsInterface; +#endif + } + + public static bool IsGenericType(this Type type) + { +#if !(DOTNET || PORTABLE) + return type.IsGenericType; +#else + return type.GetTypeInfo().IsGenericType; +#endif + } + + public static bool IsGenericTypeDefinition(this Type type) + { +#if !(DOTNET || PORTABLE) + return type.IsGenericTypeDefinition; +#else + return type.GetTypeInfo().IsGenericTypeDefinition; +#endif + } + + public static Type BaseType(this Type type) + { +#if !(DOTNET || PORTABLE) + return type.BaseType; +#else + return type.GetTypeInfo().BaseType; +#endif + } + + public static Assembly Assembly(this Type type) + { +#if !(DOTNET || PORTABLE) + return type.Assembly; +#else + return type.GetTypeInfo().Assembly; +#endif + } + + public static bool IsEnum(this Type type) + { +#if !(DOTNET || PORTABLE) + return type.IsEnum; +#else + return type.GetTypeInfo().IsEnum; +#endif + } + + public static bool IsClass(this Type type) + { +#if !(DOTNET || PORTABLE) + return type.IsClass; +#else + return type.GetTypeInfo().IsClass; +#endif + } + + public static bool IsSealed(this Type type) + { +#if !(DOTNET || PORTABLE) + return type.IsSealed; +#else + return type.GetTypeInfo().IsSealed; +#endif + } + +#if (PORTABLE40 || DOTNET || PORTABLE) + public static PropertyInfo GetProperty(this Type type, string name, BindingFlags bindingFlags, object placeholder1, Type propertyType, IList indexParameters, object placeholder2) + { + IEnumerable propertyInfos = type.GetProperties(bindingFlags); + + return propertyInfos.Where(p => + { + if (name != null && name != p.Name) + { + return false; + } + if (propertyType != null && propertyType != p.PropertyType) + { + return false; + } + if (indexParameters != null) + { + if (!p.GetIndexParameters().Select(ip => ip.ParameterType).SequenceEqual(indexParameters)) + { + return false; + } + } + + return true; + }).SingleOrDefault(); + } + + public static IEnumerable GetMember(this Type type, string name, MemberTypes memberType, BindingFlags bindingFlags) + { +#if PORTABLE + return type.GetMemberInternal(name, memberType, bindingFlags); +#else + return type.GetMember(name, bindingFlags).Where(m => + { + if (m.MemberType() != memberType) + { + return false; + } + + return true; + }); +#endif + } +#endif + +#if (DOTNET || PORTABLE) + public static MethodInfo GetBaseDefinition(this MethodInfo method) + { + return method.GetRuntimeBaseDefinition(); + } +#endif + +#if (DOTNET || PORTABLE) + public static bool IsDefined(this Type type, Type attributeType, bool inherit) + { + return type.GetTypeInfo().CustomAttributes.Any(a => a.AttributeType == attributeType); + } + +#if !DOTNET + public static MethodInfo GetMethod(this Type type, string name) + { + return type.GetMethod(name, DefaultFlags); + } + + public static MethodInfo GetMethod(this Type type, string name, BindingFlags bindingFlags) + { + return type.GetTypeInfo().GetDeclaredMethod(name); + } + + public static MethodInfo GetMethod(this Type type, IList parameterTypes) + { + return type.GetMethod(null, parameterTypes); + } + + public static MethodInfo GetMethod(this Type type, string name, IList parameterTypes) + { + return type.GetMethod(name, DefaultFlags, null, parameterTypes, null); + } + + public static MethodInfo GetMethod(this Type type, string name, BindingFlags bindingFlags, object placeHolder1, IList parameterTypes, object placeHolder2) + { + return type.GetTypeInfo().DeclaredMethods.Where( + m => + { + if (name != null && m.Name != name) + { + return false; + } + + if (!TestAccessibility(m, bindingFlags)) + { + return false; + } + + return m.GetParameters().Select(p => p.ParameterType).SequenceEqual(parameterTypes); + }).SingleOrDefault(); + } + + public static IEnumerable GetConstructors(this Type type) + { + return type.GetConstructors(DefaultFlags); + } + + public static IEnumerable GetConstructors(this Type type, BindingFlags bindingFlags) + { + return type.GetConstructors(bindingFlags, null); + } + + private static IEnumerable GetConstructors(this Type type, BindingFlags bindingFlags, IList parameterTypes) + { + return type.GetTypeInfo().DeclaredConstructors.Where( + c => + { + if (!TestAccessibility(c, bindingFlags)) + { + return false; + } + + if (parameterTypes != null && !c.GetParameters().Select(p => p.ParameterType).SequenceEqual(parameterTypes)) + { + return false; + } + + return true; + }); + } + + public static ConstructorInfo GetConstructor(this Type type, IList parameterTypes) + { + return type.GetConstructor(DefaultFlags, null, parameterTypes, null); + } + + public static ConstructorInfo GetConstructor(this Type type, BindingFlags bindingFlags, object placeholder1, IList parameterTypes, object placeholder2) + { + return type.GetConstructors(bindingFlags, parameterTypes).SingleOrDefault(); + } + + public static MemberInfo[] GetMember(this Type type, string member) + { + return type.GetMemberInternal(member, null, DefaultFlags); + } + + public static MemberInfo[] GetMember(this Type type, string member, BindingFlags bindingFlags) + { + return type.GetMemberInternal(member, null, bindingFlags); + } + + public static MemberInfo[] GetMemberInternal(this Type type, string member, MemberTypes? memberType, BindingFlags bindingFlags) + { + return type.GetTypeInfo().GetMembersRecursive().Where(m => + m.Name == member && + // test type before accessibility - accessibility doesn't support some types + (memberType == null || m.MemberType() == memberType) && + TestAccessibility(m, bindingFlags)).ToArray(); + } + + public static MemberInfo GetField(this Type type, string member) + { + return type.GetField(member, DefaultFlags); + } + + public static MemberInfo GetField(this Type type, string member, BindingFlags bindingFlags) + { + return type.GetTypeInfo().GetDeclaredField(member); + } + + public static IEnumerable GetProperties(this Type type, BindingFlags bindingFlags) + { + IList properties = (bindingFlags.HasFlag(BindingFlags.DeclaredOnly)) + ? type.GetTypeInfo().DeclaredProperties.ToList() + : type.GetTypeInfo().GetPropertiesRecursive(); + + return properties.Where(p => TestAccessibility(p, bindingFlags)); + } + + private static IList GetMembersRecursive(this TypeInfo type) + { + TypeInfo t = type; + IList members = new List(); + while (t != null) + { + foreach (MemberInfo member in t.DeclaredMembers) + { + if (!members.Any(p => p.Name == member.Name)) + { + members.Add(member); + } + } + t = (t.BaseType != null) ? t.BaseType.GetTypeInfo() : null; + } + + return members; + } + + private static IList GetPropertiesRecursive(this TypeInfo type) + { + TypeInfo t = type; + IList properties = new List(); + while (t != null) + { + foreach (PropertyInfo member in t.DeclaredProperties) + { + if (!properties.Any(p => p.Name == member.Name)) + { + properties.Add(member); + } + } + t = (t.BaseType != null) ? t.BaseType.GetTypeInfo() : null; + } + + return properties; + } + + private static IList GetFieldsRecursive(this TypeInfo type) + { + TypeInfo t = type; + IList fields = new List(); + while (t != null) + { + foreach (FieldInfo member in t.DeclaredFields) + { + if (!fields.Any(p => p.Name == member.Name)) + { + fields.Add(member); + } + } + t = (t.BaseType != null) ? t.BaseType.GetTypeInfo() : null; + } + + return fields; + } + + public static IEnumerable GetMethods(this Type type, BindingFlags bindingFlags) + { + return type.GetTypeInfo().DeclaredMethods; + } + + public static PropertyInfo GetProperty(this Type type, string name) + { + return type.GetProperty(name, DefaultFlags); + } + + public static PropertyInfo GetProperty(this Type type, string name, BindingFlags bindingFlags) + { + return type.GetTypeInfo().GetDeclaredProperty(name); + } + + public static IEnumerable GetFields(this Type type) + { + return type.GetFields(DefaultFlags); + } + + public static IEnumerable GetFields(this Type type, BindingFlags bindingFlags) + { + IList fields = (bindingFlags.HasFlag(BindingFlags.DeclaredOnly)) + ? type.GetTypeInfo().DeclaredFields.ToList() + : type.GetTypeInfo().GetFieldsRecursive(); + + return fields.Where(f => TestAccessibility(f, bindingFlags)).ToList(); + } + + private static bool TestAccessibility(PropertyInfo member, BindingFlags bindingFlags) + { + if (member.GetMethod != null && TestAccessibility(member.GetMethod, bindingFlags)) + { + return true; + } + + if (member.SetMethod != null && TestAccessibility(member.SetMethod, bindingFlags)) + { + return true; + } + + return false; + } + + private static bool TestAccessibility(MemberInfo member, BindingFlags bindingFlags) + { + if (member is FieldInfo) + { + return TestAccessibility((FieldInfo) member, bindingFlags); + } + else if (member is MethodBase) + { + return TestAccessibility((MethodBase) member, bindingFlags); + } + else if (member is PropertyInfo) + { + return TestAccessibility((PropertyInfo) member, bindingFlags); + } + + throw new Exception("Unexpected member type."); + } + + private static bool TestAccessibility(FieldInfo member, BindingFlags bindingFlags) + { + bool visibility = (member.IsPublic && bindingFlags.HasFlag(BindingFlags.Public)) || + (!member.IsPublic && bindingFlags.HasFlag(BindingFlags.NonPublic)); + + bool instance = (member.IsStatic && bindingFlags.HasFlag(BindingFlags.Static)) || + (!member.IsStatic && bindingFlags.HasFlag(BindingFlags.Instance)); + + return visibility && instance; + } + + private static bool TestAccessibility(MethodBase member, BindingFlags bindingFlags) + { + bool visibility = (member.IsPublic && bindingFlags.HasFlag(BindingFlags.Public)) || + (!member.IsPublic && bindingFlags.HasFlag(BindingFlags.NonPublic)); + + bool instance = (member.IsStatic && bindingFlags.HasFlag(BindingFlags.Static)) || + (!member.IsStatic && bindingFlags.HasFlag(BindingFlags.Instance)); + + return visibility && instance; + } + + public static Type[] GetGenericArguments(this Type type) + { + return type.GetTypeInfo().GenericTypeArguments; + } + + public static IEnumerable GetInterfaces(this Type type) + { + return type.GetTypeInfo().ImplementedInterfaces; + } + + public static IEnumerable GetMethods(this Type type) + { + return type.GetTypeInfo().DeclaredMethods; + } +#endif +#endif + + public static bool IsAbstract(this Type type) + { +#if !(DOTNET || PORTABLE) + return type.IsAbstract; +#else + return type.GetTypeInfo().IsAbstract; +#endif + } + + public static bool IsVisible(this Type type) + { +#if !(DOTNET || PORTABLE) + return type.IsVisible; +#else + return type.GetTypeInfo().IsVisible; +#endif + } + + public static bool IsValueType(this Type type) + { +#if !(DOTNET || PORTABLE) + return type.IsValueType; +#else + return type.GetTypeInfo().IsValueType; +#endif + } + + public static bool AssignableToTypeName(this Type type, string fullTypeName, out Type match) + { + Type current = type; + + while (current != null) + { + if (string.Equals(current.FullName, fullTypeName, StringComparison.Ordinal)) + { + match = current; + return true; + } + + current = current.BaseType(); + } + + foreach (Type i in type.GetInterfaces()) + { + if (string.Equals(i.Name, fullTypeName, StringComparison.Ordinal)) + { + match = type; + return true; + } + } + + match = null; + return false; + } + + public static bool AssignableToTypeName(this Type type, string fullTypeName) + { + Type match; + return type.AssignableToTypeName(fullTypeName, out match); + } + + public static bool ImplementInterface(this Type type, Type interfaceType) + { + for (Type currentType = type; currentType != null; currentType = currentType.BaseType()) + { + IEnumerable interfaces = currentType.GetInterfaces(); + foreach (Type i in interfaces) + { + if (i == interfaceType || (i != null && i.ImplementInterface(interfaceType))) + { + return true; + } + } + } + + return false; + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/Utilities/ValidationUtils.cs b/Common/00-1Json8.3/Json8.3/Utilities/ValidationUtils.cs new file mode 100644 index 0000000..845ba3e --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/Utilities/ValidationUtils.cs @@ -0,0 +1,40 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; + +namespace Newtonsoft.Json.Utilities +{ + internal static class ValidationUtils + { + public static void ArgumentNotNull(object value, string parameterName) + { + if (value == null) + { + throw new ArgumentNullException(parameterName); + } + } + } +} \ No newline at end of file diff --git a/Common/00-1Json8.3/Json8.3/WriteState.cs b/Common/00-1Json8.3/Json8.3/WriteState.cs new file mode 100644 index 0000000..b28b542 --- /dev/null +++ b/Common/00-1Json8.3/Json8.3/WriteState.cs @@ -0,0 +1,72 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// 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. +#endregion + +using System; + +namespace Newtonsoft.Json +{ + /// + /// Specifies the state of the . + /// + public enum WriteState + { + /// + /// An exception has been thrown, which has left the in an invalid state. + /// You may call the method to put the in the Closed state. + /// Any other method calls results in an being thrown. + /// + Error = 0, + + /// + /// The method has been called. + /// + Closed = 1, + + /// + /// An object is being written. + /// + Object = 2, + + /// + /// A array is being written. + /// + Array = 3, + + /// + /// A constructor is being written. + /// + Constructor = 4, + + /// + /// A property is being written. + /// + Property = 5, + + /// + /// A write method has not been called. + /// + Start = 6 + } +} \ No newline at end of file diff --git a/Common/00-2AppConfigSet/AppConfigSet.sln b/Common/00-2AppConfigSet/AppConfigSet.sln new file mode 100644 index 0000000..32d9819 --- /dev/null +++ b/Common/00-2AppConfigSet/AppConfigSet.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.32929.386 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AppConfigSet", "AppConfigSet\AppConfigSet.csproj", "{5FD5DE57-CC26-4FD0-B852-5362123BC4FF}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {5FD5DE57-CC26-4FD0-B852-5362123BC4FF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {5FD5DE57-CC26-4FD0-B852-5362123BC4FF}.Debug|Any CPU.Build.0 = Debug|Any CPU + {5FD5DE57-CC26-4FD0-B852-5362123BC4FF}.Release|Any CPU.ActiveCfg = Release|Any CPU + {5FD5DE57-CC26-4FD0-B852-5362123BC4FF}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {54390EDE-FC5D-4007-A0C4-5012CDDAF613} + EndGlobalSection +EndGlobal diff --git a/Common/00-2AppConfigSet/AppConfigSet/00-1AppConfigSetForm.csproj b/Common/00-2AppConfigSet/AppConfigSet/00-1AppConfigSetForm.csproj new file mode 100644 index 0000000..6cb61d1 --- /dev/null +++ b/Common/00-2AppConfigSet/AppConfigSet/00-1AppConfigSetForm.csproj @@ -0,0 +1,87 @@ + + + + + Debug + AnyCPU + {5FD5DE57-CC26-4FD0-B852-5362123BC4FF} + WinExe + AppConfigSet + AppConfigSet + v4.8 + 512 + true + true + + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + Form + + + AppConfigSetForm.cs + + + + + AppConfigSetForm.cs + Designer + + + ResXFileCodeGenerator + Resources.Designer.cs + Designer + + + True + Resources.resx + True + + + SettingsSingleFileGenerator + Settings.Designer.cs + + + True + Settings.settings + True + + + + + + + \ No newline at end of file diff --git a/Common/00-2AppConfigSet/AppConfigSet/App.config b/Common/00-2AppConfigSet/AppConfigSet/App.config new file mode 100644 index 0000000..4bfa005 --- /dev/null +++ b/Common/00-2AppConfigSet/AppConfigSet/App.config @@ -0,0 +1,6 @@ + + + + + + diff --git a/Common/00-2AppConfigSet/AppConfigSet/AppConfigSetForm.Designer.cs b/Common/00-2AppConfigSet/AppConfigSet/AppConfigSetForm.Designer.cs new file mode 100644 index 0000000..c0d66f0 --- /dev/null +++ b/Common/00-2AppConfigSet/AppConfigSet/AppConfigSetForm.Designer.cs @@ -0,0 +1,213 @@ + +namespace AppConfigSetting +{ + partial class AppConfigSetForm + { + /// + /// 必需的设计器变量。 + /// + 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() + { + System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(AppConfigSetForm)); + this.label1 = new System.Windows.Forms.Label(); + this.textBox_IsDemoMesServer = new System.Windows.Forms.TextBox(); + this.label2 = new System.Windows.Forms.Label(); + this.textBox_ConnectionString_MES = new System.Windows.Forms.TextBox(); + this.label3 = new System.Windows.Forms.Label(); + this.textBox_Url_WebApiDT = new System.Windows.Forms.TextBox(); + this.label4 = new System.Windows.Forms.Label(); + this.textBox_Url_WebApi = new System.Windows.Forms.TextBox(); + this.label5 = new System.Windows.Forms.Label(); + this.textBox_MqttUrl = new System.Windows.Forms.TextBox(); + this.label6 = new System.Windows.Forms.Label(); + this.textBox_MqttTargetTopicPLC = new System.Windows.Forms.TextBox(); + this.button_Read = new System.Windows.Forms.Button(); + this.button_Update = new System.Windows.Forms.Button(); + this.SuspendLayout(); + // + // label1 + // + this.label1.AutoSize = true; + this.label1.Location = new System.Drawing.Point(33, 28); + this.label1.Name = "label1"; + this.label1.Size = new System.Drawing.Size(95, 12); + this.label1.TabIndex = 0; + this.label1.Text = "IsDemoMesServer"; + // + // textBox_IsDemoMesServer + // + this.textBox_IsDemoMesServer.Location = new System.Drawing.Point(240, 25); + this.textBox_IsDemoMesServer.Name = "textBox_IsDemoMesServer"; + this.textBox_IsDemoMesServer.Size = new System.Drawing.Size(553, 21); + this.textBox_IsDemoMesServer.TabIndex = 1; + // + // label2 + // + this.label2.AutoSize = true; + this.label2.Location = new System.Drawing.Point(33, 66); + this.label2.Name = "label2"; + this.label2.Size = new System.Drawing.Size(125, 12); + this.label2.TabIndex = 0; + this.label2.Text = "ConnectionString_MES"; + // + // textBox_ConnectionString_MES + // + this.textBox_ConnectionString_MES.Location = new System.Drawing.Point(240, 63); + this.textBox_ConnectionString_MES.Name = "textBox_ConnectionString_MES"; + this.textBox_ConnectionString_MES.Size = new System.Drawing.Size(553, 21); + this.textBox_ConnectionString_MES.TabIndex = 1; + // + // label3 + // + this.label3.AutoSize = true; + this.label3.Location = new System.Drawing.Point(33, 105); + this.label3.Name = "label3"; + this.label3.Size = new System.Drawing.Size(77, 12); + this.label3.TabIndex = 0; + this.label3.Text = "Url_WebApiDT"; + // + // textBox_Url_WebApiDT + // + this.textBox_Url_WebApiDT.Location = new System.Drawing.Point(240, 102); + this.textBox_Url_WebApiDT.Name = "textBox_Url_WebApiDT"; + this.textBox_Url_WebApiDT.Size = new System.Drawing.Size(553, 21); + this.textBox_Url_WebApiDT.TabIndex = 1; + // + // label4 + // + this.label4.AutoSize = true; + this.label4.Location = new System.Drawing.Point(33, 147); + this.label4.Name = "label4"; + this.label4.Size = new System.Drawing.Size(65, 12); + this.label4.TabIndex = 0; + this.label4.Text = "Url_WebApi"; + // + // textBox_Url_WebApi + // + this.textBox_Url_WebApi.Location = new System.Drawing.Point(240, 144); + this.textBox_Url_WebApi.Name = "textBox_Url_WebApi"; + this.textBox_Url_WebApi.Size = new System.Drawing.Size(553, 21); + this.textBox_Url_WebApi.TabIndex = 1; + // + // label5 + // + this.label5.AutoSize = true; + this.label5.Location = new System.Drawing.Point(33, 184); + this.label5.Name = "label5"; + this.label5.Size = new System.Drawing.Size(47, 12); + this.label5.TabIndex = 0; + this.label5.Text = "MqttUrl"; + // + // textBox_MqttUrl + // + this.textBox_MqttUrl.Location = new System.Drawing.Point(240, 181); + this.textBox_MqttUrl.Name = "textBox_MqttUrl"; + this.textBox_MqttUrl.Size = new System.Drawing.Size(553, 21); + this.textBox_MqttUrl.TabIndex = 1; + // + // label6 + // + this.label6.AutoSize = true; + this.label6.Location = new System.Drawing.Point(33, 222); + this.label6.Name = "label6"; + this.label6.Size = new System.Drawing.Size(113, 12); + this.label6.TabIndex = 0; + this.label6.Text = "MqttTargetTopic"; + // + // textBox_MqttTargetTopicPLC + // + this.textBox_MqttTargetTopicPLC.Location = new System.Drawing.Point(240, 219); + this.textBox_MqttTargetTopicPLC.Name = "textBox_MqttTargetTopicPLC"; + this.textBox_MqttTargetTopicPLC.Size = new System.Drawing.Size(553, 21); + this.textBox_MqttTargetTopicPLC.TabIndex = 1; + // + // button_Read + // + this.button_Read.Location = new System.Drawing.Point(240, 259); + this.button_Read.Name = "button_Read"; + this.button_Read.Size = new System.Drawing.Size(102, 23); + this.button_Read.TabIndex = 2; + this.button_Read.Text = "读取配置文件"; + this.button_Read.UseVisualStyleBackColor = true; + this.button_Read.Click += new System.EventHandler(this.button_Read_Click); + // + // button_Update + // + this.button_Update.Location = new System.Drawing.Point(674, 259); + this.button_Update.Name = "button_Update"; + this.button_Update.Size = new System.Drawing.Size(102, 23); + this.button_Update.TabIndex = 2; + this.button_Update.Text = "更新配置文件"; + this.button_Update.UseVisualStyleBackColor = true; + this.button_Update.Click += new System.EventHandler(this.button_Update_Click); + // + // AppConfigSetForm + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(844, 301); + this.Controls.Add(this.button_Update); + this.Controls.Add(this.button_Read); + this.Controls.Add(this.textBox_MqttTargetTopicPLC); + this.Controls.Add(this.label6); + this.Controls.Add(this.textBox_MqttUrl); + this.Controls.Add(this.label5); + this.Controls.Add(this.textBox_Url_WebApi); + this.Controls.Add(this.label4); + this.Controls.Add(this.textBox_Url_WebApiDT); + this.Controls.Add(this.label3); + this.Controls.Add(this.textBox_ConnectionString_MES); + this.Controls.Add(this.label2); + this.Controls.Add(this.textBox_IsDemoMesServer); + this.Controls.Add(this.label1); + this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); + this.MaximumSize = new System.Drawing.Size(860, 340); + this.MinimumSize = new System.Drawing.Size(860, 340); + this.Name = "AppConfigSetForm"; + this.Text = "修改配置文件"; + this.TopMost = true; + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private System.Windows.Forms.Label label1; + private System.Windows.Forms.TextBox textBox_IsDemoMesServer; + private System.Windows.Forms.Label label2; + private System.Windows.Forms.TextBox textBox_ConnectionString_MES; + private System.Windows.Forms.Label label3; + private System.Windows.Forms.TextBox textBox_Url_WebApiDT; + private System.Windows.Forms.Label label4; + private System.Windows.Forms.TextBox textBox_Url_WebApi; + private System.Windows.Forms.Label label5; + private System.Windows.Forms.TextBox textBox_MqttUrl; + private System.Windows.Forms.Label label6; + private System.Windows.Forms.TextBox textBox_MqttTargetTopicPLC; + private System.Windows.Forms.Button button_Read; + private System.Windows.Forms.Button button_Update; + } +} + diff --git a/Common/00-2AppConfigSet/AppConfigSet/AppConfigSetForm.cs b/Common/00-2AppConfigSet/AppConfigSet/AppConfigSetForm.cs new file mode 100644 index 0000000..1299607 --- /dev/null +++ b/Common/00-2AppConfigSet/AppConfigSet/AppConfigSetForm.cs @@ -0,0 +1,81 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Configuration; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace AppConfigSetting +{ + public partial class AppConfigSetForm : Form + { + string key_IsDemoMesServer = "IsDemoMesServer"; + string key_ConnectionString_MES = "ConnectionString_MES"; + string key_Url_WebApiDT = "Url_WebApiDT"; + string key_Url_WebApi = "Url_WebApi"; + string key_MqttUrl = "MqttUrl"; + string key_MqttTargetTopicPLC = "MqttTargetTopic"; + + public AppConfigSetForm() + { + InitializeComponent(); + ReadConfig(); + } + + private void button_Read_Click(object sender, EventArgs e) + { + ReadConfig(); + } + private void ReadConfig() + { + textBox_IsDemoMesServer.Text = AppConfig.GetAppSettingsValue(key_IsDemoMesServer); + textBox_ConnectionString_MES.Text = AppConfig.GetAppSettingsValue(key_ConnectionString_MES); + textBox_Url_WebApiDT.Text = AppConfig.GetAppSettingsValue(key_Url_WebApiDT); + textBox_Url_WebApi.Text = AppConfig.GetAppSettingsValue(key_Url_WebApi); + textBox_MqttUrl.Text = AppConfig.GetAppSettingsValue(key_MqttUrl); + textBox_MqttTargetTopicPLC.Text = AppConfig.GetAppSettingsValue(key_MqttTargetTopicPLC); + } + private void UdateConfig() + { + AppConfig.UpdateAppSettings(key_IsDemoMesServer, textBox_IsDemoMesServer.Text); + AppConfig.UpdateAppSettings(key_ConnectionString_MES, textBox_ConnectionString_MES.Text); + AppConfig.UpdateAppSettings(key_Url_WebApiDT, textBox_Url_WebApiDT.Text); + AppConfig.UpdateAppSettings(key_Url_WebApi, textBox_Url_WebApi.Text); + AppConfig.UpdateAppSettings(key_MqttUrl, textBox_MqttUrl.Text); + AppConfig.UpdateAppSettings(key_MqttTargetTopicPLC, textBox_MqttTargetTopicPLC.Text); + } + + private void button_Update_Click(object sender, EventArgs e) + { + UdateConfig(); + } + } + + public class AppConfig + { + public static string GetAppSettingsValue(string key) + { + ConfigurationManager.RefreshSection("appSettings"); + return ConfigurationManager.AppSettings[key] ?? string.Empty; + } + public static bool UpdateAppSettings(string key, string value) + { + var _config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); + if (!_config.HasFile) + { + throw new ArgumentException("程序配置文件缺失!"); + } + KeyValueConfigurationElement _key = _config.AppSettings.Settings[key]; + if (_key == null) + _config.AppSettings.Settings.Add(key, value); + else + _config.AppSettings.Settings[key].Value = value; + _config.Save(ConfigurationSaveMode.Modified); + return true; + } + } +} diff --git a/Common/00-2AppConfigSet/AppConfigSet/AppConfigSetForm.resx b/Common/00-2AppConfigSet/AppConfigSet/AppConfigSetForm.resx new file mode 100644 index 0000000..39220d8 --- /dev/null +++ b/Common/00-2AppConfigSet/AppConfigSet/AppConfigSetForm.resx @@ -0,0 +1,200 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + + + AAABAAEAICAAAAEAIACoEAAAFgAAACgAAAAgAAAAQAAAAAEAIAAAAAAAABAAABMLAAATCwAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMgChADIAoQIyAKEgMgChczIA + occyAKHqMgChmTIAoTwyAKEJMgChAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMgChADIAoQQyAKEvMgChdzIA + odYyAKH7MgCh/zIAof8yAKH/MgCh6jIAoacyAKFJMgChEjIAoQAyAKEAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAyAKEAMgChADIAoQoyAKE+MgChkTIA + oeoyAKH+MgCh+TIAoe0yAKH+MgCh/zIAofwyAKH3MgCh/jIAofgyAKHBMgChZDIAoR4yAKEBMgChAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAyAKEAMgChATIAoRUyAKFcMgChujIA + ofEyAKH/MgCh9DIAobcyAKFPMgChfjIAof8yAKH/MgCh5TIAoVUyAKGLMgCh4jIAofwyAKH9MgCh2TIA + oYcyAKEoMgChBTIAoQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAyAKEAMgChAjIAoSYyAKF2MgCh0DIA + ofcyAKH+MgCh8zIAof8yAKGjMgChDTIAoQAyAKFpMgCh/zIAof8yAKHhMgChHjIAoQIyAKEiMgChbjIA + ocoyAKH3MgCh/jIAoeUyAKGfMgChQTIAoQsyAKEAAAAAAAAAAAAAAAAAMgChCDIAoUEyAKGXMgCh4jIA + of4yAKH/MgChzzIAoW0yAKFoMgCh+zIAoZcyAKEAMgChADIAoWkyAKH/MgCh/zIAoeEyAKEeMgChADIA + oQAyAKEBMgChETIAoVAyAKGiMgCh8DIAof8yAKH0MgChuTIAoW0yAKEVMgChADIAoQAyAKG2MgCh7TIA + of8yAKHvMgCh7jIAofgyAKFLMgChADIAoTcyAKH1MgChlzIAoQAyAKEAMgChaTIAof8yAKH/MgCh4TIA + oR4yAKEAAAAAAAAAAAAAAAAAMgChADIAoQcyAKE4MgChijIAod8yAKH9MgCh+zIAoc4yAKFdMgChADIA + of8yAKHlMgChlDIAoToyAKGgMgCh7jIAoSwyAKEAMgChFzIAodgyAKGZMgChADIAoQAyAKFpMgCh/zIA + of8yAKHxMgChfDIAoSkyAKEBMgChAAAAAAAAAAAAAAAAADIAoQAyAKECMgChITIAoW8yAKG/MgCh/zIA + oZYyAKEAMgCh/zIAoZoyAKEBMgChADIAoZkyAKHSMgChEjIAoQAyAKEGMgChujIAoZoyAKEAMgChADIA + oWkyAKH/MgCh/zIAof0yAKH+MgCh4TIAoZIyAKFEMgChDjIAoQAyAKEAAAAAAAAAAAAAAAAAMgChADIA + oUIyAKH7MgChlzIAoQAyAKH/MgChlzIAoQAyAKEAMgChmjIAobMyAKEEMgChADIAoQAyAKGcMgChmzIA + oQAyAKEAMgChaTIAof8yAKH/MgCh4zIAoZYyAKHRMgCh+zIAofQyAKHDMgChZDIAoSIyAKEBMgChAAAA + AAAyAKEAMgChPzIAofsyAKGXMgChADIAof8yAKGXMgChADIAoQAyAKGaMgChiDIAoQAAAAAAMgChADIA + oYgyAKGaMgChADIAoQAyAKFpMgCh/zIAof8yAKHhMgChIDIAoRIyAKFeMgChqzIAoe0yAKH+MgCh3jIA + oYYyAKEqMgChADIAoQAyAKE/MgCh+zIAoZcyAKEAMgCh/zIAoZcyAKEAMgChADIAoZgyAKFtMgChAAAA + AAAyAKEAMgChXDIAoZQyAKEAMgChADIAoWkyAKH/MgCh/zIAoeEyAKEeMgChADIAoQAyAKEGMgChMDIA + oX8yAKHTMgCh+jIAoWkyAKEAMgChADIAoT8yAKH7MgChlzIAoQAyAKH/MgChlzIAoQAyAKEAMgChlTIA + oWMyAKEAAAAAADIAoQAyAKE2MgChhTIAoQAyAKEAMgChaTIAof8yAKH/MgCh4TIAoR4yAKEAAAAAAAAA + AAAyAKEAMgChATIAoRUyAKFYMgChQDIAoQAyAKEAMgChPzIAofsyAKGXMgChADIAof8yAKGXMgChADIA + oQAyAKGLMgChQTIAoQAyAKEFMgChADIAoSMyAKF4MgChADIAoQAyAKFpMgCh/zIAof8yAKHhMgChHjIA + oQAAAAAAAAAAAAAAAAAAAAAAMgChADIAoQAyAKEBMgChADIAoQAyAKE/MgCh+zIAoZcyAKEAMgCh/zIA + oZcyAKEAMgChADIAoXcyAKEkMgChBzIAoUIyAKEBMgChFjIAoWUyAKEBMgChADIAoWkyAKH/MgCh/zIA + oeEyAKEeMgChADIAoQAyAKE5MgChSTIAoQ8yAKEBMgChAAAAAAAAAAAAMgChADIAoT8yAKH7MgChlzIA + oQAyAKH/MgChlzIAoQAyAKECMgChWzIAoQ8yAKEVMgChhTIAoQoyAKEHMgChMzIAoQEyAKEAMgChaTIA + of8yAKH/MgCh4TIAoR4yAKEAMgChADIAoWkyAKH1MgChyzIAoX8yAKE4MgChBTIAoQAyAKEAMgChPzIA + ofsyAKGXMgChADIAof8yAKGXMgChADIAoQMyAKFZMgChCzIAoS4yAKHDMgChGjIAoQAAAAAAAAAAADIA + oQAyAKFpMgCh/zIAof8yAKHhMgChHjIAoQAyAKEAMgChLDIAoaEyAKHkMgCh/DIAoe8yAKGrMgChUzIA + oREyAKFBMgCh+zIAoZcyAKEAMgCh/zIAoZcyAKEAMgChBzIAoVAyAKEEMgChQTIAodoyAKEjMgChAAAA + AAAAAAAAMgChADIAoWkyAKH/MgCh/zIAoeEyAKEeMgChAAAAAAAyAKEAMgChBjIAoSAyAKFyMgChwjIA + ofMyAKH4MgCh0zIAobMyAKH9MgChljIAoQAyAKH/MgChlzIAoQAyAKEBMgChBDIAoQAyAKFKMgCh7jIA + oT0yAKEAAAAAADIAoQAyAKEAMgChbDIAof8yAKH/MgCh4TIAoR8yAKEAAAAAAAAAAAAAAAAAMgChADIA + oQEyAKELMgChRzIAoZYyAKHeMgCh/TIAof8yAKGWMgChADIAof8yAKGXMgChAAAAAAAAAAAAMgChADIA + oW0yAKH/MgChZDIAoQAyAKEEMgChHDIAoWAyAKHPMgCh/zIAof8yAKH3MgChkTIAoS8yAKELMgChADIA + oQAAAAAAAAAAAAAAAAAyAKEAMgChATIAoSAyAKF2MgCh/zIAoZYyAKEAMgCh/zIAoZcyAKEAAAAAADIA + oQAyAKEAMgChljIAof8yAKGeMgChOTIAoZEyAKHcMgCh+TIAof8yAKH/MgCh/zIAof8yAKH+MgCh6jIA + obgyAKFXMgChITIAoQEyAKEAAAAAAAAAAAAAAAAAMgChADIAoT8yAKH7MgChlzIAoQAyAKH/MgChlzIA + oQAAAAAAMgChADIAoQwyAKG9MgCh/zIAofMyAKHyMgCh/jIAof8yAKH/MgCh/zIAofoyAKH3MgCh/jIA + of8yAKH/MgCh/zIAofsyAKHbMgChmzIAoUwyAKENMgChATIAoQAyAKEAMgChPzIAofsyAKGXMgChADIA + of8yAKGXMgChATIAoRkyAKFbMgChsTIAofAyAKH/MgCh/zIAof8yAKH/MgCh/DIAoeYyAKGxMgChVTIA + oUIyAKGFMgCh1TIAofUyAKH/MgCh/zIAof8yAKH/MgCh9DIAocUyAKGDMgChMDIAoQYyAKE/MgCh+zIA + oZcyAKEAMgCh/zIAocEyAKGOMgCh2TIAofcyAKH/MgCh/zIAof8yAKH/MgCh7jIAobMyAKFwMgChJjIA + oQoyAKEAMgChADIAoQEyAKEXMgChTTIAoZsyAKHYMgCh/TIAof8yAKH/MgCh/zIAof4yAKHqMgChszIA + oZgyAKH+MgChljIAoQAyAKH/MgCh/zIAof8yAKH/MgCh/zIAof8yAKH0MgChyTIAoYEyAKE/MgChBzIA + oQAAAAAAMgChADIAoSIyAKF2MgChQjIAoRIyAKEAMgChATIAoR4yAKFjMgChrjIAoecyAKH9MgCh/zIA + of8yAKH/MgCh/zIAof8yAKGWMgChADIAof8yAKH/MgCh/zIAofkyAKHWMgChmjIAoUIyAKERMgChATIA + oQAyAKEGMgChFTIAoQMyAKEAMgChKDIAoZUyAKHHMgChxjIAoXcyAKE3MgChBzIAoQAyAKEGMgChKTIA + oXYyAKHDMgCh7jIAof4yAKH/MgCh/zIAoZYyAKEAMgChrjIAoeYyAKH+MgCh0zIAoVcyAKELMgChADIA + oQAyAKEAMgChADIAoVUyAKHAMgChkjIAoVYyAKEUMgChATIAoRYyAKFhMgChqzIAodUyAKGmMgChZTIA + oR8yAKEDMgChBDIAoS0yAKGiMgCh9DIAofUyAKHGMgChWTIAoQAyAKEGMgChKjIAoWsyAKHBMgCh3DIA + ocEyAKFwMgChJTIAoQYyAKEAMgChDDIAoTgyAKF/MgChyjIAocMyAKGUMgChMzIAoQsyAKEEMgChJjIA + oWUyAKG/MgCh0TIAoaYyAKGoMgCh1TIAodYyAKGNMgChQTIAoRAyAKEAMgChAAAAAAAyAKEAMgChADIA + oQ8yAKE8MgChkDIAoc8yAKHfMgChpDIAoVIyAKEcMgChADIAoQEyAKETMgChRzIAoZ8yAKHGMgChvzIA + oWQyAKEtMgChMzIAoY8yAKHvMgCh5zIAoa8yAKFcMgChHDIAoQMyAKEAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAADIAoQAyAKECMgChFTIAoVcyAKGaMgCh3DIAodEyAKGaMgChSDIAoQsyAKEAMgChATIA + oSUyAKGGMgCh6TIAofEyAKHhMgChtzIAoXAyAKErMgChBTIAoQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMgChADIAoQIyAKElMgChXTIAobgyAKHbMgChxTIA + oYUyAKFbMgChqzIAodEyAKHLMgChhDIAoTsyAKELMgChAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAyAKEAMgChCzIA + oTcyAKGTMgCh0zIAofAyAKG2MgChWjIAoRcyAKEBMgChAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAA/+Af//+AB//8AAD/8AAAP8AIAA8AGDABARg+AQEYD4ERGAPxMZgAcTOY + ADEzmDAxM5g8MTKIPzEgCDDxIAgwMSB4MAEgeDgBJHg+ATxAD8E8AAHxOAAAMQAAAAEAAwABABwgAQBE + BAEBwAABAEAAA+AAAA/4AAB//wAD///gD/8= + + + \ No newline at end of file diff --git a/Common/00-2AppConfigSet/AppConfigSet/Program.cs b/Common/00-2AppConfigSet/AppConfigSet/Program.cs new file mode 100644 index 0000000..1925b68 --- /dev/null +++ b/Common/00-2AppConfigSet/AppConfigSet/Program.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace AppConfigSetting +{ + static class Program + { + /// + /// 应用程序的主入口点。 + /// + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + Application.Run(new AppConfigSetForm()); + } + } +} diff --git a/Common/00-2AppConfigSet/AppConfigSet/Properties/AssemblyInfo.cs b/Common/00-2AppConfigSet/AppConfigSet/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..2d2a19e --- /dev/null +++ b/Common/00-2AppConfigSet/AppConfigSet/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// 有关程序集的一般信息由以下 +// 控制。更改这些特性值可修改 +// 与程序集关联的信息。 +[assembly: AssemblyTitle("AppConfigSet")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("AppConfigSet")] +[assembly: AssemblyCopyright("Copyright © 2022")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// 将 ComVisible 设置为 false 会使此程序集中的类型 +//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型 +//请将此类型的 ComVisible 特性设置为 true。 +[assembly: ComVisible(false)] + +// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID +[assembly: Guid("5fd5de57-cc26-4fd0-b852-5362123bc4ff")] + +// 程序集的版本信息由下列四个值组成: +// +// 主版本 +// 次版本 +// 生成号 +// 修订号 +// +//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值 +//通过使用 "*",如下所示: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Common/00-2AppConfigSet/AppConfigSet/Properties/Resources.Designer.cs b/Common/00-2AppConfigSet/AppConfigSet/Properties/Resources.Designer.cs new file mode 100644 index 0000000..920e1e9 --- /dev/null +++ b/Common/00-2AppConfigSet/AppConfigSet/Properties/Resources.Designer.cs @@ -0,0 +1,63 @@ +//------------------------------------------------------------------------------ +// +// 此代码由工具生成。 +// 运行时版本:4.0.30319.42000 +// +// 对此文件的更改可能会导致不正确的行为,并且如果 +// 重新生成代码,这些更改将会丢失。 +// +//------------------------------------------------------------------------------ + +namespace AppConfigSet.Properties { + using System; + + + /// + /// 一个强类型的资源类,用于查找本地化的字符串等。 + /// + // 此类是由 StronglyTypedResourceBuilder + // 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。 + // 若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen + // (以 /str 作为命令选项),或重新生成 VS 项目。 + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.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 (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("AppConfigSet.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/Common/00-2AppConfigSet/AppConfigSet/Properties/Resources.resx b/Common/00-2AppConfigSet/AppConfigSet/Properties/Resources.resx new file mode 100644 index 0000000..af7dbeb --- /dev/null +++ b/Common/00-2AppConfigSet/AppConfigSet/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/Common/00-2AppConfigSet/AppConfigSet/Properties/Settings.Designer.cs b/Common/00-2AppConfigSet/AppConfigSet/Properties/Settings.Designer.cs new file mode 100644 index 0000000..2828d4f --- /dev/null +++ b/Common/00-2AppConfigSet/AppConfigSet/Properties/Settings.Designer.cs @@ -0,0 +1,26 @@ +//------------------------------------------------------------------------------ +// +// 此代码由工具生成。 +// 运行时版本:4.0.30319.42000 +// +// 对此文件的更改可能会导致不正确的行为,并且如果 +// 重新生成代码,这些更改将会丢失。 +// +//------------------------------------------------------------------------------ + +namespace AppConfigSet.Properties { + + + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "17.0.3.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/Common/00-2AppConfigSet/AppConfigSet/Properties/Settings.settings b/Common/00-2AppConfigSet/AppConfigSet/Properties/Settings.settings new file mode 100644 index 0000000..3964565 --- /dev/null +++ b/Common/00-2AppConfigSet/AppConfigSet/Properties/Settings.settings @@ -0,0 +1,7 @@ + + + + + + + diff --git a/Common/00MesWorkMqtt/Common/dll/MQTTnet.Extensions.ManagedClient.dll b/Common/00MesWorkMqtt/Common/dll/MQTTnet.Extensions.ManagedClient.dll new file mode 100644 index 0000000..99035f6 Binary files /dev/null and b/Common/00MesWorkMqtt/Common/dll/MQTTnet.Extensions.ManagedClient.dll differ diff --git a/Common/00MesWorkMqtt/Common/dll/MQTTnet.dll b/Common/00MesWorkMqtt/Common/dll/MQTTnet.dll new file mode 100644 index 0000000..2951433 Binary files /dev/null and b/Common/00MesWorkMqtt/Common/dll/MQTTnet.dll differ diff --git a/Common/00MesWorkMqtt/Common/dll/MesWorkMqtt.dll b/Common/00MesWorkMqtt/Common/dll/MesWorkMqtt.dll new file mode 100644 index 0000000..4834574 Binary files /dev/null and b/Common/00MesWorkMqtt/Common/dll/MesWorkMqtt.dll differ diff --git a/Common/00MesWorkMqtt/Common/dll/MesWorkMqtt.pdb b/Common/00MesWorkMqtt/Common/dll/MesWorkMqtt.pdb new file mode 100644 index 0000000..fb10624 Binary files /dev/null and b/Common/00MesWorkMqtt/Common/dll/MesWorkMqtt.pdb differ diff --git a/Common/00MesWorkMqtt/DataBaseAccess/04DataBaseAccess.csproj b/Common/00MesWorkMqtt/DataBaseAccess/04DataBaseAccess.csproj new file mode 100644 index 0000000..0a63414 --- /dev/null +++ b/Common/00MesWorkMqtt/DataBaseAccess/04DataBaseAccess.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {01CBA6DC-8B15-4D51-B073-004E2DB6F440} + Library + Properties + DataBaseAccess + DataBaseAccess + v4.6.1 + 512 + true + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Common/00MesWorkMqtt/DataBaseAccess/DataAccess.cs b/Common/00MesWorkMqtt/DataBaseAccess/DataAccess.cs new file mode 100644 index 0000000..a5b7b7b --- /dev/null +++ b/Common/00MesWorkMqtt/DataBaseAccess/DataAccess.cs @@ -0,0 +1,527 @@ +using System; +using System.Collections.Generic; +using System.Configuration; +using System.Data; +using System.Data.SqlClient; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace DataLinkMesWork +{ + public class DataAccess + { + public static string ConnectionString_MES = ConfigurationManager.AppSettings["ConnectionString_MES"]; + + + /// + /// 增 删 改 + /// + /// + /// + /// + public static bool ExecuteStoredProcedure(string procedureName, ref SqlParameter[] sqlParameters) + { + string connectionString = ConnectionString_MES; + string errorMessage; + bool result = false; + errorMessage = ""; + using (SqlConnection conn = new SqlConnection(connectionString)) + { + try + { + //if (!SqlServerConnectionStatus) return false; + conn.Open(); + using (SqlCommand cmd = new SqlCommand(procedureName, conn)) + { + cmd.CommandTimeout = 0; + cmd.CommandType = CommandType.StoredProcedure; + if (sqlParameters != null) + { + for (int i = 0; i < sqlParameters.Length; i++) + { + cmd.Parameters.Add(sqlParameters[i]); + } + } + cmd.ExecuteNonQuery(); + } + //SqlServerConnectionStatus = true; + result = true; + } + catch (Exception e) + { + errorMessage = e.ToString(); + //TestConnection(); + ////ApplicationLog.WriteLog(e, "\r\nExecuteStoredProcedure\r\n�洢���̣�\r\n" + procedureName + "\r\n�����ַ�����\r\n" + connectionString); + } + finally + { + if (conn.State == ConnectionState.Open) + conn.Close(); + } + } + return result; + } + public static bool ExecuteStoredProcedure(string procedureName, ref SqlParameter[] sqlParameters,out DataTable dt) + { + string connectionString = ConnectionString_MES; + string errorMessage; + bool result = false; + errorMessage = ""; + //ds = new DataSet(); + dt = new DataTable(); + using (SqlConnection conn = new SqlConnection(connectionString)) + { + try + { + //if (!SqlServerConnectionStatus) return false; + conn.Open(); + using (SqlDataAdapter dsCommand = new SqlDataAdapter()) + { + dsCommand.SelectCommand = new SqlCommand(procedureName, conn); + dsCommand.SelectCommand.CommandType = CommandType.StoredProcedure; + dsCommand.SelectCommand.CommandTimeout = 0; + if (sqlParameters != null) + { + for (int i = 0; i < sqlParameters.Length; i++) + { + dsCommand.SelectCommand.Parameters.Add(sqlParameters[i]); + } + } + + dsCommand.Fill(dt); + } + //SqlServerConnectionStatus = true; + result = true; + } + catch (Exception e) + { + errorMessage = e.ToString(); + //TestConnection(); + ////ApplicationLog.WriteLog(e, "\r\nExecuteStoredProcedure\r\n�洢���̣�\r\n" + procedureName + "\r\n�����ַ�����\r\n" + connectionString); + } + finally + { + if (conn.State == ConnectionState.Open) + conn.Close(); + } + } + return result; + } + public static bool ExecuteStoredProcedure(string procedureName, ref SqlParameter[] sqlParameters, out DataSet ds) + { + string connectionString = ConnectionString_MES; + string errorMessage; + bool result = false; + errorMessage = ""; + ds = new DataSet(); + using (SqlConnection conn = new SqlConnection(connectionString)) + { + try + { + //if (!SqlServerConnectionStatus) return false; + conn.Open(); + using (SqlDataAdapter dsCommand = new SqlDataAdapter()) + { + dsCommand.SelectCommand = new SqlCommand(procedureName, conn); + dsCommand.SelectCommand.CommandType = CommandType.StoredProcedure; + dsCommand.SelectCommand.CommandTimeout = 0; + if (sqlParameters != null) + { + for (int i = 0; i < sqlParameters.Length; i++) + { + dsCommand.SelectCommand.Parameters.Add(sqlParameters[i]); + } + } + + dsCommand.Fill(ds); + } + //SqlServerConnectionStatus = true; + result = true; + } + catch (Exception e) + { + errorMessage = e.ToString(); + //TestConnection(); + ////ApplicationLog.WriteLog(e, "\r\nExecuteStoredProcedure\r\n�洢���̣�\r\n" + procedureName + "\r\n�����ַ�����\r\n" + connectionString); + } + finally + { + if (conn.State == ConnectionState.Open) + conn.Close(); + } + } + return result; + } + public static bool ExecuteDataset(string sql, out DataSet ds) + { + string errorMessage; + string connectionString = ConnectionString_MES; + bool result = false; + errorMessage = ""; + ds = new DataSet(); + using (SqlConnection conn = new SqlConnection(connectionString)) + { + try + { + //if (!SqlServerConnectionStatus) return false; + conn.Open(); + using (SqlDataAdapter dsCommand = new SqlDataAdapter()) + { + dsCommand.SelectCommand = new SqlCommand(sql, conn); + dsCommand.Fill(ds); + } + //SqlServerConnectionStatus = true; + result = true; + } + catch (Exception e) + { + errorMessage = e.ToString(); + //TestConnection(); + ////ApplicationLog.WriteLog(e, "\r\nExecuteNonQuery\r\nSQL��䣺\r\n" + sql + "\r\n�����ַ�����\r\n" + connectionString); + } + finally + { + if (conn.State == ConnectionState.Open) + conn.Close(); + } + } + return result; + } + + public static bool ExecuteDataTable(string sql, out DataTable dt) + { + //public static bool ExecuteDataTable(string sql, string connectionString, out DataTable dt, out string errorMessage) + string errorMessage; + string connectionString = ConnectionString_MES; + bool result = false; + errorMessage = ""; + dt = new DataTable(); + using (SqlConnection conn = new SqlConnection(connectionString)) + { + try + { + //if (!SqlServerConnectionStatus) return false; + conn.Open(); + using (SqlDataAdapter dsCommand = new SqlDataAdapter()) + { + dsCommand.SelectCommand = new SqlCommand(sql, conn); + dsCommand.Fill(dt); + } + //SqlServerConnectionStatus = true; + result = true; + } + catch (Exception e) + { + errorMessage = e.ToString(); + //TestConnection(); + ////ApplicationLog.WriteLog(e, "\r\nExecuteNonQuery\r\nSQL��䣺\r\n" + sql + "\r\n�����ַ�����\r\n" + connectionString); + } + finally + { + if (conn.State == ConnectionState.Open) + conn.Close(); + } + } + return result; + } + + public static DataTable ExecuteSQL(string sql, ref SqlParameter[] sqlParameters) + { + string connectionString = ConnectionString_MES; + string err; + bool result = false; + err = ""; + DataTable dt = new DataTable(); + using (SqlConnection conn = new SqlConnection(connectionString)) + { + try + { + //if (!SqlServerConnectionStatus) return false; + conn.Open(); + using (SqlDataAdapter dsCommand = new SqlDataAdapter(sql, conn)) + { + if (sqlParameters != null) + { + for (int i = 0; i < sqlParameters.Length; i++) + { + dsCommand.SelectCommand.Parameters.Add(sqlParameters[i]); + } + } + dsCommand.Fill(dt); + } + result = true; + } + catch (Exception e) + { + err = e.ToString(); + ////ApplicationLog.WriteLog(e, "\r\nExecuteSelectMesWork\r\n" + sql + "\r\n" + connectionString); + } + finally + { + if (conn.State == ConnectionState.Open) + conn.Close(); + } + } + return dt; + } + + public static bool ExecuteSQL(string sql) + { + string connectionString = ConnectionString_MES; + string errorMessage; + bool result = false; + errorMessage = ""; + using (SqlConnection conn = new SqlConnection(connectionString)) + { + try + { + using (SqlCommand cmd = new SqlCommand(sql, conn)) + { + //if (!SqlServerConnectionStatus) return false; + conn.Open(); + cmd.ExecuteNonQuery(); + } + //SqlServerConnectionStatus = true; + result = true; + } + catch (Exception e) + { + errorMessage = e.ToString(); + //TestConnection(); + ////ApplicationLog.WriteLog(e, "\r\nExecuteNonQuery\r\nSQL��䣺\r\n" + sql + "\r\n�����ַ�����\r\n" + connectionString); + } + finally + { + if (conn.State == ConnectionState.Open) + conn.Close(); + } + } + return result; + } + + /// + /// 提供通用的调用存储过程的方法(增加数据的数据表的到数据库的调用) + /// + /// 存储过程名称 + /// 存储过程参数数组 + /// 增加数据的数据表 + /// + public static bool ExecuteStoredProcedure(string procedureName, ref SqlParameter[] sqlParameters, DataTable dt) + { + string connectionString = ConnectionString_MES; + string errorMessage; + bool result = false; + errorMessage = ""; + using (SqlConnection conn = new SqlConnection(connectionString)) + { + try + { + // if (!SqlServerConnectionStatus) return false; + conn.Open(); + using (SqlDataAdapter dsCommand = new SqlDataAdapter()) + { + dsCommand.InsertCommand = new SqlCommand(procedureName, conn); + dsCommand.InsertCommand.CommandType = CommandType.StoredProcedure; + for (int i = 0; i < sqlParameters.Length; i++) + { + dsCommand.InsertCommand.Parameters.Add(sqlParameters[i]); + } + if (dt == null) return false; + dt.AcceptChanges(); + for (int i = 0; i < dt.Rows.Count; i++) + { + dt.Rows[i].SetAdded(); + } + dsCommand.Update(dt); + } + //SqlServerConnectionStatus = true; + result = true; + } + catch (Exception e) + { + errorMessage = e.ToString(); + //TestConnection(); + ////ApplicationLog.WriteLog(e, "\r\nExecuteStoredProcedure\r\n�洢���̣�\r\n" + procedureName + "\r\n�����ַ�����\r\n" + connectionString); + } + finally + { + if (conn.State == ConnectionState.Open) + conn.Close(); + } + } + return result; + } + + /// + /// 提供通用的调用存储过程的方法(增加数据的数据表的到数据库的调用) + /// + /// + /// + /// + public static bool ExecuteStoredProcedure(string procedureName, out DataTable dt) + { + string connectionString = ConnectionString_MES; + string errorMessage; + bool result = false; + errorMessage = ""; + dt = new DataTable(); + using (SqlConnection conn = new SqlConnection(connectionString)) + { + try + { + + //if (!SqlServerConnectionStatus) return false; + conn.Open(); + using (SqlDataAdapter dsCommand = new SqlDataAdapter()) + { + dsCommand.SelectCommand = new SqlCommand(procedureName, conn); + dsCommand.SelectCommand.CommandType = CommandType.StoredProcedure; + + dsCommand.Fill(dt); + } + //SqlServerConnectionStatus = true; + result = true; + } + catch (Exception e) + { + errorMessage = e.ToString(); + //TestConnection(); + ////ApplicationLog.WriteLog(e, "\r\nExecuteStoredProcedure\r\n�洢���̣�\r\n" + procedureName + "\r\n�����ַ�����\r\n" + connectionString); + } + finally + { + if (conn.State == ConnectionState.Open) + conn.Close(); + } + } + return result; + } + + /// + /// + /// + /// + /// + /// + /// + public static bool ExecuteSQL(string sql, ref SqlParameter[] sqlParameters, DataTable dt) + { + string connectionString = ConnectionString_MES; + string errorMessage; + bool result = false; + errorMessage = ""; + using (SqlConnection conn = new SqlConnection(connectionString)) + { + + + try + { + // if (!SqlServerConnectionStatus) return false; + conn.Open(); + using (SqlDataAdapter dsCommand = new SqlDataAdapter()) + { + dsCommand.InsertCommand = new SqlCommand(sql, conn); + + for (int i = 0; i < sqlParameters.Length; i++) + { + sqlParameters[i].IsNullable = true; + dsCommand.InsertCommand.Parameters.Add(sqlParameters[i]); + } + if (dt == null) return false; + dt.AcceptChanges(); + for (int i = 0; i < dt.Rows.Count; i++) + { + dt.Rows[i].SetAdded(); + } + dsCommand.Update(dt); + } + //SqlServerConnectionStatus = true; + result = true; + } + catch (Exception e) + { + //ApplicationConfig.ConnectionStringPIS_NEW_Value = "0"; + //TestConnection(); + //errorMessage = e.ToString(); + ////ApplicationLog.WriteLog(e, "\r\nExecuteSQL\r\nSQL��䣺\r\n" + sql + "\r\n�����ַ�����\r\n" + connectionString); + } + finally + { + if (conn.State == ConnectionState.Open) + conn.Close(); + } + } + return result; + } + + public static bool ExecuteNonQuery_newID(string sql, out long newID) + { + sql += ";select @@identity"; + string connectionString; + connectionString = ConnectionString_MES; + using (SqlConnection conn = new SqlConnection(connectionString)) + { + try + { + using (SqlCommand cmd = new SqlCommand(sql, conn)) + { + conn.Open(); + newID = Convert.ToInt64(cmd.ExecuteScalar()); + } + return true; + } + catch (Exception e) + { + newID = 0; + //TestConnection(); + ////ApplicationLog.WriteLog(e, "\r\n ExecuteNonQuery_newID\r\n�洢���̣�\r\n" + sql + "\r\n�����ַ�����\r\n" + connectionString); + return false; + } + finally + { + if (conn.State == ConnectionState.Open) + conn.Close(); + } + } + } + + public static bool ExecuteOutNum(string sql, out int count) + { + string connectionString; + connectionString = ConnectionString_MES; + string errorMessage; + bool result = false; + errorMessage = ""; + using (SqlConnection conn = new SqlConnection(connectionString)) + { + count = 0; + try + { + using (SqlCommand cmd = new SqlCommand(sql, conn)) + { + //if (!SqlServerConnectionStatus) return false; + conn.Open(); + count = Convert.ToInt32(cmd.ExecuteScalar().ToString()); + } + //SqlServerConnectionStatus = true; + result = true; + } + catch (Exception e) + { + errorMessage = e.ToString(); + //TestConnection(); + ////ApplicationLog.WriteLog(e, "\r\nExecuteNonQuery\r\nSQL��䣺\r\n" + sql + "\r\n�����ַ�����\r\n" + connectionString); + } + finally + { + if (conn.State == ConnectionState.Open) + conn.Close(); + } + } + return result; + } + } + + +} diff --git a/Common/00MesWorkMqtt/DataBaseAccess/JsonHelper.cs b/Common/00MesWorkMqtt/DataBaseAccess/JsonHelper.cs new file mode 100644 index 0000000..1e07081 --- /dev/null +++ b/Common/00MesWorkMqtt/DataBaseAccess/JsonHelper.cs @@ -0,0 +1,334 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Data; +//using System.Runtime.Serialization.Json; +using System.Web.Script.Serialization; +using System.Runtime.Serialization.Json; + +public class JsonHelper +{ + #region 序列化和反序列化 + // 序列化 + public static string JsonSerializer(T t) + { + // 使用 DataContractJsonSerializer 将 T 对象序列化为内存流。 + DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(T)); + MemoryStream ms = new MemoryStream(); + // 使用 WriteObject 方法将 JSON 数据写入到流中。 + jsonSerializer.WriteObject(ms, t); + // 流转字符串 + string jsonString = Encoding.UTF8.GetString(ms.ToArray()); + ms.Close(); + //替换Json的Date字符串 + string p = @"\\/Date\((\d+)\+\d+\)\\/"; + MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertJsonDateToDateString); + Regex reg = new Regex(p); + jsonString = reg.Replace(jsonString, matchEvaluator); + return jsonString; + } + public static T JsonDeserialize(string jsonString) + { + //将"yyyy-MM-dd HH:mm:ss"格式的字符串转为"\/Date(1294499956278+0800)\/"格式 + string p = @"\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}"; + MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertDateStringToJsonDate); + Regex reg = new Regex(p); + jsonString = reg.Replace(jsonString, matchEvaluator); + DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(T)); + // 字符串转流 + MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)); + // 通过使用 DataContractJsonSerializer 的 ReadObject 方法,将 JSON 编码数据反序列化为T + T obj = (T)jsonSerializer.ReadObject(ms); + return obj; + } + public static string ConvertJsonDateToDateString(Match match) + { + string result = string.Empty; + DateTime dateTime = new DateTime(1970, 1, 1); + dateTime = dateTime.AddMilliseconds(long.Parse(match.Groups[1].Value)); + dateTime = dateTime.ToLocalTime(); + result = dateTime.ToString("yyyy-MM-dd HH:mm:ss"); + return result; + } + private static string ConvertDateStringToJsonDate(Match m) + { + string result = string.Empty; + DateTime dt = DateTime.Parse(m.Groups[0].Value); + dt = dt.ToUniversalTime(); + TimeSpan ts = dt - DateTime.Parse("1970-01-01"); + result = string.Format("\\/Date({0}+0800)\\/", ts.TotalMilliseconds); + return result; + } + #endregion + + // 对象转换为Json + public static string ObjectToJson(object obj) + { + JavaScriptSerializer js = new JavaScriptSerializer(); + js.MaxJsonLength = Int32.MaxValue; // 定义JavaScriptSerializer接受字符串的最大长度 hdk 20180524 + try + { + return js.Serialize(obj); + } + catch (Exception exception) + { + + throw new Exception(exception.Message); + } + } + // 数据表转化为集合 + public static List> DataTableToList(DataTable dt) + { + List> list = new List>(); + foreach (DataRow dataRow in dt.Rows) + { + Dictionary dic = new Dictionary(); + + + foreach (DataColumn dc in dt.Columns) + { + if (dataRow[dc.ColumnName].GetType() == typeof(DateTime)) + { + string str = Convert.ToDateTime(dataRow[dc.ColumnName]).ToString("yyyy-MM-dd HH:mm:ss"); + dic.Add(dc.ColumnName, str); + } + else if + (dataRow[dc.ColumnName].GetType() == typeof(byte[])) + { + string str = Convert.ToBase64String((byte[])dataRow[dc.ColumnName]); + dic.Add(dc.ColumnName, str); + } + else + { + dic.Add(dc.ColumnName, dataRow[dc.ColumnName]); + } + + //Type type1 = dt.Rows[0]["产品图片"].GetType(); + //Type type2 = typeof(byte[]); + + } + list.Add(dic); + } + return list; + } + /// + /// 表转换为Json + /// + /// + /// + public static string DataTableToJson(DataTable dt) + { + return ObjectToJson(DataTableToList(dt)); + } + /// + /// 将DataTable中的数据转换成JSON格式 + /// + /// 数据源DataTable + /// 是否输出数据总条数 + /// JSON中显示的数据总条数 + /// + public static string CreateJsonParameters(DataTable dt, bool displayCount, int totalcount) + { + StringBuilder JsonString = new StringBuilder(); + //Exception Handling + + if (dt != null) + { + JsonString.Append("{ "); + JsonString.Append("\"rows\":[ "); + for (int i = 0; i < dt.Rows.Count; i++) + { + JsonString.Append("{ "); + for (int j = 0; j < dt.Columns.Count; j++) + { + if (j < dt.Columns.Count - 1) + { + //if (dt.Rows[i][j] == DBNull.Value) continue; + if (dt.Columns[j].DataType == typeof(bool)) + { + JsonString.Append("\"" + dt.Columns[j].ColumnName.ToLower() + "\":" + + dt.Rows[i][j].ToString().ToLower() + ","); + } + else if (dt.Columns[j].DataType == typeof(string)) + { + JsonString.Append("\"" + dt.Columns[j].ColumnName.ToLower() + "\":" + + ObjectToJson(dt.Rows[i][j]).ToString() + ","); + //JsonString.Append("\"" + dt.Columns[j].ColumnName.ToLower() + "\":" + "\"" + + // dt.Rows[i][j].ToString().Replace("\"", "\\\"") + "\","); + } + else + { + JsonString.Append("\"" + dt.Columns[j].ColumnName.ToLower() + "\":" + "\"" + dt.Rows[i][j] + "\","); + } + } + else if (j == dt.Columns.Count - 1) + { + //if (dt.Rows[i][j] == DBNull.Value) continue; + if (dt.Columns[j].DataType == typeof(bool)) + { + JsonString.Append("\"" + dt.Columns[j].ColumnName.ToLower() + "\":" + + dt.Rows[i][j].ToString().ToLower()); + } + else if (dt.Columns[j].DataType == typeof(string)) + { + JsonString.Append("\"" + dt.Columns[j].ColumnName.ToLower() + "\":" + + ObjectToJson(dt.Rows[i][j]).ToString()); + //JsonString.Append("\"" + dt.Columns[j].ColumnName.ToLower() + "\":" + "\"" + + // dt.Rows[i][j].ToString().Replace("\"", "\\\"") + "\""); + } + else + { + JsonString.Append("\"" + dt.Columns[j].ColumnName.ToLower() + "\":" + "\"" + dt.Rows[i][j] + "\""); + } + } + } + /*end Of String*/ + if (i == dt.Rows.Count - 1) + { + JsonString.Append("} "); + } + else + { + JsonString.Append("}, "); + } + } + JsonString.Append("]"); + + if (displayCount) + { + JsonString.Append(","); + + JsonString.Append("\"total\":"); + JsonString.Append(totalcount); + } + + JsonString.Append("}"); + return JsonString.ToString().Replace("\n", ""); + } + else + { + return null; + } + } + public static string CreateJsonParameters(DataTable dt) + { + StringBuilder JsonString = new StringBuilder(); + //Exception Handling + + if (dt != null) + { + JsonString.Append("{ "); + JsonString.Append("\"rows\":[ "); + for (int i = 0; i < dt.Rows.Count; i++) + { + JsonString.Append("{ "); + for (int j = 0; j < dt.Columns.Count; j++) + { + if (j < dt.Columns.Count - 1) + { + //if (dt.Rows[i][j] == DBNull.Value) continue; + if (dt.Columns[j].DataType == typeof(bool)) + { + JsonString.Append("\"" + dt.Columns[j].ColumnName.ToLower() + "\":" + + dt.Rows[i][j].ToString().ToLower() + ","); + } + else if (dt.Columns[j].DataType == typeof(string)) + { + JsonString.Append("\"" + dt.Columns[j].ColumnName.ToLower() + "\":" + + ObjectToJson(dt.Rows[i][j]).ToString() + ","); + //JsonString.Append("\"" + dt.Columns[j].ColumnName.ToLower() + "\":" + "\"" + + // dt.Rows[i][j].ToString().Replace("\"", "\\\"") + "\","); + } + else + { + JsonString.Append("\"" + dt.Columns[j].ColumnName.ToLower() + "\":" + "\"" + dt.Rows[i][j] + "\","); + } + } + else if (j == dt.Columns.Count - 1) + { + //if (dt.Rows[i][j] == DBNull.Value) continue; + if (dt.Columns[j].DataType == typeof(bool)) + { + JsonString.Append("\"" + dt.Columns[j].ColumnName.ToLower() + "\":" + + dt.Rows[i][j].ToString().ToLower()); + } + else if (dt.Columns[j].DataType == typeof(string)) + { + JsonString.Append("\"" + dt.Columns[j].ColumnName.ToLower() + "\":" + + ObjectToJson(dt.Rows[i][j]).ToString()); + //JsonString.Append("\"" + dt.Columns[j].ColumnName.ToLower() + "\":" + "\"" + + // dt.Rows[i][j].ToString().Replace("\"", "\\\"") + "\""); + } + else + { + JsonString.Append("\"" + dt.Columns[j].ColumnName.ToLower() + "\":" + "\"" + dt.Rows[i][j] + "\""); + } + } + } + /*end Of String*/ + if (i == dt.Rows.Count - 1) + { + JsonString.Append("} "); + } + else + { + JsonString.Append("}, "); + } + } + JsonString.Append("]"); + + JsonString.Append("}"); + return JsonString.ToString().Replace("\n", ""); + } + else + { + return null; + } + } + StringBuilder result = new StringBuilder(); + StringBuilder sb = new StringBuilder(); + /// + /// 根据DataTable生成EasyUI Tree Json树结构 + /// + /// 数据源 + /// ID列 + /// Text列 + /// 节点Url + /// 关系字段 + /// 父ID + public string GetTreeJsonByTable(DataTable tabel, string idCol, string txtCol, string url, string rela, object pId) + { + result.Append(sb.ToString()); + sb.Clear(); + if (tabel.Rows.Count > 0) + { + sb.Append("["); + string filer = string.Format("{0}='{1}'", rela, pId); + DataRow[] rows = tabel.Select(filer); + if (rows.Length > 0) + { + foreach (DataRow row in rows) + { + sb.Append("{\"id\":\"" + row[idCol] + "\",\"text\":\"" + row[txtCol] + "\",\"attributes\":\"" + row[url] + "\",\"state\":\"open\""); + if (tabel.Select(string.Format("{0}='{1}'", rela, row[idCol])).Length > 0) + { + sb.Append(",\"children\":"); + GetTreeJsonByTable(tabel, idCol, txtCol, url, rela, row[idCol]); + result.Append(sb.ToString()); + sb.Clear(); + } + result.Append(sb.ToString()); + sb.Clear(); + sb.Append("},"); + } + sb = sb.Remove(sb.Length - 1, 1); + } + sb.Append("]"); + result.Append(sb.ToString()); + sb.Clear(); + } + return result.ToString(); + } +} \ No newline at end of file diff --git a/Common/00MesWorkMqtt/DataBaseAccess/Properties/AssemblyInfo.cs b/Common/00MesWorkMqtt/DataBaseAccess/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..e031332 --- /dev/null +++ b/Common/00MesWorkMqtt/DataBaseAccess/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// 有关程序集的一般信息由以下 +// 控制。更改这些特性值可修改 +// 与程序集关联的信息。 +[assembly: AssemblyTitle("DataBaseAccess")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("DataBaseAccess")] +[assembly: AssemblyCopyright("Copyright © 2022")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// 将 ComVisible 设置为 false 会使此程序集中的类型 +//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型 +//请将此类型的 ComVisible 特性设置为 true。 +[assembly: ComVisible(false)] + +// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID +[assembly: Guid("01cba6dc-8b15-4d51-b073-004e2db6f440")] + +// 程序集的版本信息由下列四个值组成: +// +// 主版本 +// 次版本 +// 生成号 +// 修订号 +// +//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值 +//通过使用 "*",如下所示: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Common/00MesWorkMqtt/MesWorkMqtt.sln b/Common/00MesWorkMqtt/MesWorkMqtt.sln new file mode 100644 index 0000000..7e4859b --- /dev/null +++ b/Common/00MesWorkMqtt/MesWorkMqtt.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.32901.82 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "00MesWorkMqtt", "MesWorkMqtt\00MesWorkMqtt.csproj", "{F55DA1A0-A982-4479-8C47-0D9A5AAF3E18}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {F55DA1A0-A982-4479-8C47-0D9A5AAF3E18}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F55DA1A0-A982-4479-8C47-0D9A5AAF3E18}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F55DA1A0-A982-4479-8C47-0D9A5AAF3E18}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F55DA1A0-A982-4479-8C47-0D9A5AAF3E18}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {C16A8637-B440-4EA0-99D9-A76AD9126EA9} + EndGlobalSection +EndGlobal diff --git a/Common/00MesWorkMqtt/MesWorkMqtt/00MesWorkMqtt.csproj b/Common/00MesWorkMqtt/MesWorkMqtt/00MesWorkMqtt.csproj new file mode 100644 index 0000000..5ea62aa --- /dev/null +++ b/Common/00MesWorkMqtt/MesWorkMqtt/00MesWorkMqtt.csproj @@ -0,0 +1,56 @@ + + + + + Debug + AnyCPU + {F55DA1A0-A982-4479-8C47-0D9A5AAF3E18} + Library + Properties + MesWorkMqtt + 00MesWorkMqtt + v4.8 + 512 + true + + + + true + full + false + ..\..\dll\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + ..\..\dll\MQTTnet.dll + + + ..\..\dll\MQTTnet.Extensions.ManagedClient.dll + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Common/00MesWorkMqtt/MesWorkMqtt/Mqtt.cs b/Common/00MesWorkMqtt/MesWorkMqtt/Mqtt.cs new file mode 100644 index 0000000..b0bca3a --- /dev/null +++ b/Common/00MesWorkMqtt/MesWorkMqtt/Mqtt.cs @@ -0,0 +1,281 @@ + +using MQTTnet; +using MQTTnet.Client; +using MQTTnet.Client.Connecting; +using MQTTnet.Client.Disconnecting; +using MQTTnet.Client.Options; +using MQTTnet.Client.Receiving; +using MQTTnet.Extensions.ManagedClient; +using MQTTnet.Formatter; + +using System; +using System.Collections.Generic; +using System.Configuration; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MesWorkMqtt +{ + public class Mqtt + { + /// + /// + /// + public static IManagedMqttClient mqttClient = null; + public static string MqttUrl = ConfigurationManager.AppSettings["MqttUrl"]; + /// + /// + /// + public static string topic = ""; + + + /// + /// + /// + /// + /// + public static async Task StartAsync() + { + string uri = MqttUrl; + //127.0.0.1:18083,123 + var array = uri.Split(new char[] { ':', ',' }); + string mqttUser = "MisDataFun"; + string mqttPassword = ""; + var options = new MqttClientOptions + { + ClientId = "MisDataFun-200170511", + ProtocolVersion = MqttProtocolVersion.V311, + ChannelOptions = new MqttClientTcpOptions { Server = array[0], Port = Convert.ToInt32(array[1]) }, + CleanSession = false, + SessionExpiryInterval = 300, + KeepAlivePeriod = TimeSpan.FromSeconds(20), + Credentials = new MqttClientCredentials + { + Username = mqttUser, + Password = Encoding.UTF8.GetBytes(mqttPassword) + } + }; + mqttClient = new MqttFactory().CreateManagedMqttClient(); + + //mqttClient.ConnectedHandler = new MqttClientConnectedHandlerDelegate(OnSubscriberConnected); + //mqttClient.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(OnSubscriberDisconnected); + //mqttClient.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(OnSubscriberMessageReceived); + await mqttClient.StartAsync(new ManagedMqttClientOptions { ClientOptions = options }); + topic = array[2]; + await mqttClient.SubscribeAsync(new MqttTopicFilter { Topic = topic }); + + } + + + /// + /// + /// + /// + /// + /// + public static async Task Publish(string publish_topic, string publish_msg) + { + if (mqttClient != null) + { + try + { + await mqttClient.PublishAsync(new MqttApplicationMessageBuilder().WithTopic(publish_topic).WithPayload(publish_msg).WithExactlyOnceQoS().Build()); + + } + catch (Exception err) + { + + } + } + } + /// + /// + /// + /// + /// + /// + public static async Task PublishQos0(string publish_topic, string publish_msg) + { + if (mqttClient != null) + { + await mqttClient.PublishAsync(new MqttApplicationMessageBuilder().WithTopic(publish_topic).WithPayload(publish_msg).WithAtLeastOnceQoS().Build()); + } + } + /// + /// + /// + /// + public static async Task StopAsync() + { + if (mqttClient != null) + { + await mqttClient.UnsubscribeAsync(new string[] { topic }); + await mqttClient.StopAsync(); + } + } + ///// + ///// + ///// + ///// + //private static void OnSubscriberConnected(MqttClientConnectedEventArgs x) + //{ + // var rec = x.AuthenticateResult.ResultCode.ToString(); + // // label_State.Text = rec; + //} + ///// + ///// + ///// + ///// + //private static void OnSubscriberDisconnected(MqttClientDisconnectedEventArgs x) + //{ + // //var rec = x.AuthenticateResult.ResultCode.ToString(); + // //label_State.Text = rec; + //} + ///// + ///// + ///// + ///// + //private static void OnSubscriberMessageReceived(MqttApplicationMessageReceivedEventArgs x) + //{ + // var rec = x.ApplicationMessage.ConvertPayloadToString(); + // // txt_Rec.Text = txt_Rec.Text + rec + System.Environment.NewLine; + + //} + + + + } + + public class Mqtt2 + { + /// + /// + /// + public IManagedMqttClient mqttClient = null; + public string MqttUrl; + /// + /// + /// + public string topic = ""; + + public Mqtt2() + { + mqttClient = new MqttFactory().CreateManagedMqttClient(); + } + /// + /// + /// + /// + /// + public async Task StartAsync() + { + string uri = MqttUrl; + //127.0.0.1:18083,123 + var array = uri.Split(new char[] { ':', ',' }); + string mqttUser = ""; + string mqttPassword = ""; + var options = new MqttClientOptions + { + ClientId = Guid.NewGuid().ToString(), + ProtocolVersion = MqttProtocolVersion.V311, + ChannelOptions = new MqttClientTcpOptions { Server = array[0], Port = Convert.ToInt32(array[1]) }, + CleanSession = true, + KeepAlivePeriod = TimeSpan.FromSeconds(100), + Credentials = new MqttClientCredentials + { + Username = mqttUser, + Password = Encoding.UTF8.GetBytes(mqttPassword) + } + }; + //mqttClient.ConnectedHandler = new MqttClientConnectedHandlerDelegate(OnSubscriberConnected); + //mqttClient.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(OnSubscriberDisconnected); + //mqttClient.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(OnSubscriberMessageReceived); + await mqttClient.StartAsync(new ManagedMqttClientOptions { ClientOptions = options }); + //topic = array[2]; + await mqttClient.SubscribeAsync(new MqttTopicFilter { Topic = topic }); + + } + + + /// + /// + /// + /// + /// + /// + public async Task Publish(string publish_topic, string publish_msg) + { + if (mqttClient != null) + { + try + { + await mqttClient.PublishAsync(new MqttApplicationMessageBuilder().WithTopic(publish_topic).WithPayload(publish_msg).WithExactlyOnceQoS().Build()); + + } + catch (Exception err) + { + + } + } + } + //static public async Task Publish(IManagedMqttClient mqttClient_1, string publish_topic, string publish_msg) + //{ + // if (mqttClient_1 != null) + // { + // try + // { + // await mqttClient_1.PublishAsync(new MqttApplicationMessageBuilder().WithTopic(publish_topic).WithPayload(publish_msg).WithExactlyOnceQoS().Build()); + + // } + // catch (Exception err) + // { + + // } + // } + //} + /// + /// + /// + /// + public async Task StopAsync() + { + if (mqttClient != null) + { + await mqttClient.UnsubscribeAsync(new string[] { topic }); + await mqttClient.StopAsync(); + } + } + ///// + ///// + ///// + ///// + //private static void OnSubscriberConnected(MqttClientConnectedEventArgs x) + //{ + // var rec = x.AuthenticateResult.ResultCode.ToString(); + // // label_State.Text = rec; + //} + ///// + ///// + ///// + ///// + //private static void OnSubscriberDisconnected(MqttClientDisconnectedEventArgs x) + //{ + // //var rec = x.AuthenticateResult.ResultCode.ToString(); + // //label_State.Text = rec; + //} + ///// + ///// + ///// + ///// + //private static void OnSubscriberMessageReceived(MqttApplicationMessageReceivedEventArgs x) + //{ + // var rec = x.ApplicationMessage.ConvertPayloadToString(); + // // txt_Rec.Text = txt_Rec.Text + rec + System.Environment.NewLine; + + //} + + + + } +} diff --git a/Common/00MesWorkMqtt/MesWorkMqtt/Properties/AssemblyInfo.cs b/Common/00MesWorkMqtt/MesWorkMqtt/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..b28e8c7 --- /dev/null +++ b/Common/00MesWorkMqtt/MesWorkMqtt/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// 有关程序集的一般信息由以下 +// 控制。更改这些特性值可修改 +// 与程序集关联的信息。 +[assembly: AssemblyTitle("MesWorkMqtt")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("MesWorkMqtt")] +[assembly: AssemblyCopyright("Copyright © 2022")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// 将 ComVisible 设置为 false 会使此程序集中的类型 +//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型 +//请将此类型的 ComVisible 特性设置为 true。 +[assembly: ComVisible(false)] + +// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID +[assembly: Guid("f55da1a0-a982-4479-8c47-0d9a5aaf3e18")] + +// 程序集的版本信息由下列四个值组成: +// +// 主版本 +// 次版本 +// 生成号 +// 修订号 +// +//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值 +//通过使用 "*",如下所示: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Common/01DoWhatPlc/01_01DoWhatPlc.csproj b/Common/01DoWhatPlc/01_01DoWhatPlc.csproj new file mode 100644 index 0000000..b93fbd9 --- /dev/null +++ b/Common/01DoWhatPlc/01_01DoWhatPlc.csproj @@ -0,0 +1,60 @@ + + + + + Debug + AnyCPU + {0D1AF432-439A-4920-8692-43AE139F5530} + Library + Properties + DoWhatPlc + DoWhatPlc + v4.8 + 512 + true + + + + true + full + false + ..\WebApiDll\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + False + ..\WebApiDll\Newtonsoft.Json.dll + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Common/01DoWhatPlc/01_01DoWhatPlc.sln b/Common/01DoWhatPlc/01_01DoWhatPlc.sln new file mode 100644 index 0000000..0ff0522 --- /dev/null +++ b/Common/01DoWhatPlc/01_01DoWhatPlc.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.32901.82 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "01_01DoWhatPlc", "01_01DoWhatPlc.csproj", "{0D1AF432-439A-4920-8692-43AE139F5530}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {0D1AF432-439A-4920-8692-43AE139F5530}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {0D1AF432-439A-4920-8692-43AE139F5530}.Debug|Any CPU.Build.0 = Debug|Any CPU + {0D1AF432-439A-4920-8692-43AE139F5530}.Release|Any CPU.ActiveCfg = Release|Any CPU + {0D1AF432-439A-4920-8692-43AE139F5530}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {7D43C0BB-C1DA-4B44-BB33-44E7909A8DE2} + EndGlobalSection +EndGlobal diff --git a/Common/01DoWhatPlc/DoWhat.cs b/Common/01DoWhatPlc/DoWhat.cs new file mode 100644 index 0000000..2c89006 --- /dev/null +++ b/Common/01DoWhatPlc/DoWhat.cs @@ -0,0 +1,1408 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.Specialized; +using System.Configuration; +using System.Data; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + + +namespace DoWhatPlc +{ + + public class MessageText + { + /// + /// Source|Cmd|OpName|TagValue + /// + /// + /// + public static List GetCmdStringList(string cmd) + { + List list = new List(); + string item; + int index; + try + { + index = cmd.IndexOf('|'); + item = cmd.Substring(0, index); + list.Add(item); + + cmd = cmd.Substring(index + 1); + index = cmd.IndexOf('|'); + item = cmd.Substring(0, index); + list.Add(item); + + cmd = cmd.Substring(index + 1); + index = cmd.IndexOf('|'); + item = cmd.Substring(0, index); + list.Add(item); + + item = cmd.Substring(index + 1); + + list.Add(item); + + } + catch { } + + + return list; + } + public string CmdType + { + get; + set; + } + public string Command + { + get; + set; + } + public string OpName + { + get; + set; + } + public string Value + { + get; + set; + } + } + public class ReturnResult + { + public bool success + { + get; + set; + } + public ReturnResult(bool success, string ResponseMessage) + { + this.success = success; + this.ResponseMessage = ResponseMessage; + } + public string ResponseMessage + { + get; + set; + } + } + public class EngineValue + { + public string OpName { set; get; } + public string EngineID { set; get; } + public string EngineType { set; get; } + public int EngineTypeID { set; get; } + public int PalletCode { set; get; } + public int ProcessCode { set; get; } + public int PartPalletCode { set; get; } + public string PalletInfo { set; get; } + /// + /// 显示返修标志 + /// + public int RepairPartStatusPLC { set; get; } + /// + /// 1 合格;2 不合格 + /// + public int QualityMask { set; get; } + + public string OrderForm { set; get; } + } + public class DoWhat + { + public const string ReadPLC_TagID = "ReadPLC_TagID"; + public const string WritePLC_TagID = "WritePLC_TagID"; + public const string ReadPLC_TagTypeCodeID = "ReadPLC_TagTypeCodeID"; + public const string WritePLC_TagTypeCodeID = "WritePLC_TagTypeCodeID"; + public const string ReadPLC_Cmd = "ReadPLC_Cmd"; + public const string WritePLC_Cmd = "WritePLC_Cmd"; + public const string ReadPLC_GroupData = "ReadPLC_GroupData"; + public const string ReadPLC_GroupMonitor = "ReadPLC_GroupMonitor"; + public const string ReadPLC_IpTag = "ReadPLC_IpTag"; + public const string ReadPLC_IpMonitorTag = "ReadPLC_IpMonitorTag"; + public const string ReadQualityDataList = "ReadQualityDataList"; + public const string ReadByteData_Op = "ReadByteData_Op"; + public const string ReadByteData_Ip = "ReadByteData_Ip"; + public const string WritePLC_Bytes_Op = "WritePLC_Bytes_Op"; + public const string WritePLC_Bytes_Ip = "WritePLC_Bytes_Ip"; + public const string IpAllTag = "IpAllTag"; + public const string IpMonitorTag = "IpMonitorTag"; + public const string RegionRead = "RegionRead"; + public const string ReadBytes = "ReadBytes"; + public const string WriteBytes = "WriteBytes"; + } + /// + /// object 类型数据转换成字符串变量表达 + /// + public class ReturnValueString + { + public string TagID { set; get; } + public string TagValue { set; get; } + public string ValueType { set; get; } + public string OpName { set; get; } + public string TimeStamp { set; get; } + public string TagTypeCodeID { set; get; } + public string TagTypeID { set; get; } + /// + /// 测量项目 TEXT1 报警的 工步内容 + /// + public string ItemName { set; get; } + /// + /// 测量位置 TEXT2 报警的 工步号 + /// + public string ShaftID { set; get; } + /// + /// 列位置 工步 工位工步分类 + /// + public string TagOrderBy { set; get; } + + + public string TagValueBefore { get; set; } + public string TimeStampBefore { get; set; } + public string TagName { get; set; } + + + /// + /// 变量变化的持续时间,单位 毫秒 + /// + public string TagKeepTime; + public string FunName; + public string FunCmd; + public string MesServerCode; + public string CmdPlcReadWrite; + public ReturnValueString() + { + + } + public ReturnValueString(string tagID, object tagValue, string opName = "", string tagTypeCodeID = "", string tagTypeID = "", string tagKeepTime = "", + string funName = "", string funCmd = "", string mesServerCode = "", string timeStamp = "", + string timeStampBefore = "", string tagValueBefore = "", string tagName = "",string itemName="", + string shaftID = "", string tagOrderBy = "") + { + TagTypeCodeID = tagTypeCodeID; + TagTypeID = tagTypeID; + TagValue = tagValue.ToString(); + ValueType = tagValue.GetType().Name; + TagID = tagID; + OpName = opName; + TagKeepTime = tagKeepTime; + FunName = funName; + FunCmd = funCmd; + MesServerCode = mesServerCode; + TimeStamp = timeStamp; + TimeStampBefore = timeStampBefore; + TagName = tagName; + TagValueBefore = tagValueBefore; + ItemName = itemName; + ShaftID = shaftID; + TagOrderBy = tagOrderBy; + } + public ReturnValueObject ReturnValueToObject() + { + ReturnValueObject ro = new ReturnValueObject(TagID, TagValue, OpName, TagTypeCodeID, ValueType, TimeStamp, TimeStampBefore, TagKeepTime, TagValueBefore, TagName, ItemName, ShaftID); + + return ro; + } + + + } + /// + /// 字符串变量转变成object类型变量 + /// + public class ReturnValueObject + { + public string TagID { set; get; } + public object TagValue { set; get; } + public string ValueType { set; get; } + public string OpName { set; get; } + public DateTime TimeStamp { set; get; } + public string TagTypeCodeID { set; get; } + /// + /// 变量变化的持续时间,单位 毫秒 + /// + public int TagKeepTime; + + public object TagValueBefore { get; set; } + public DateTime TimeStampBefore { get; set; } + /// + /// + /// + public string TagName { get; set; } + /// + /// 测量项目 TEXT2 报警的 工步内容 + /// + public string ItemName { set; get; } + /// + /// + /// + public string ShaftID { set; get; } + public string TagOrderBy { set; get; } + public ReturnValueObject(string tagID, string tagValue, string opName = "", string tagTypeCodeID = "", string valueType = "", + string timeStamp = "", string timeStampBefore = "", string tagKeepTime="", string tagValueBefore = "", + string tagName = "", string itemName = "", string shaftID = "", string tagOrderBy = "") + { + TagValue = GetTypeValue(valueType, tagValue); + if (tagValueBefore != null) + { + TagValueBefore = GetTypeValue(valueType, tagValueBefore); + } + ValueType = valueType; + TagID = tagID; + OpName = opName; + try + { + TimeStamp = Convert.ToDateTime(timeStamp); + } + catch + { + TimeStamp = DateTime.Now; + + } + try + { + TimeStampBefore = Convert.ToDateTime(timeStampBefore); + } + catch + { + TimeStampBefore = DateTime.Now; + + } + TagTypeCodeID = tagTypeCodeID; + TagName = tagName; + ItemName = itemName; + ShaftID = shaftID; + TagOrderBy = tagOrderBy; + TagKeepTime = Convert.ToInt32( tagKeepTime); + + } + + + public ReturnValueString ReturnValueToString() + { + ReturnValueString rs = new ReturnValueString(TagID, TagValue, OpName, TagTypeCodeID); + return rs; + } + public static object GetTypeValue(string type, string tagValue) + { + object tagV = "-1"; + if (type == null) + { + tagV = tagValue; + } + switch (type.ToLower()) + { + case "bool": + case "boolean": + tagV = false; + switch (tagValue.ToLower()) + { + case "1": + case "true": + tagV = true; + break; + case "0": + case "false": + tagV = false; + break; + } + return tagV; + //return Type.GetType(" System.Boolean ", true, true); + case "byte ": + return Convert.ToByte(tagValue); + case "sbyte": + return Convert.ToSByte(tagValue); + case "char": + return Convert.ToChar(tagValue); + case "decimal": + return Convert.ToDecimal(tagValue); + case "double": + return Convert.ToDouble(tagValue); + case "float": + return Convert.ToSingle(tagValue); + case "int": + return Convert.ToInt32(tagValue); + case "int16": + return Convert.ToInt32(tagValue); + case "uint": + return Convert.ToUInt32(tagValue); + case "long": + return Convert.ToInt64(tagValue); + case "ulong": + return Convert.ToUInt64(tagValue); + case "object": + return tagValue; + case "short": + return Convert.ToInt16(tagValue); + case "ushort": + return Convert.ToUInt16(tagValue); + case "string": + return tagValue; + case "date": + case "datetime": + return Convert.ToDateTime(tagValue); + case "guid": + return tagValue; + default: + return tagValue; + } + } + + + } + + public class TagIDTagFormat + { + public string TagID; + public TagFormat TF; + + public TagIDTagFormat(string tagID, TagFormat tF) + { + TagID = tagID; + TF = tF; + } + } + + + public class QualityDataSaveList + { + public Hashtable valuList; + public DataTable BasicDataTagValue; + public DataTable BasicDataTagValueUpDown; + public Hashtable hashtable_EngineTypeID; + public Hashtable hashtable_tagTable_OpName_SaveData; + } + + + + public struct ControlData + { + public int TagType; + public string opName; + public Control btn; public ControlData(Control Ctrl, string OpName) + { + string[] Array_NameSplit; + Array_NameSplit = Ctrl.Name.Split('_'); + TagType = Convert.ToInt32(Array_NameSplit[2]); + opName = OpName; + btn = Ctrl; + + } + } + + public struct ControlChangeByTagType + { + public ControlChangeByTagType(int tagType, string value) + { + TagType = tagType; + Value = value; + } + + public int TagType; + public string Value; + } + /// + /// tag格式化结构 + /// + public struct TagFormat + { + /// + /// TagID + /// + public string TagID; + /// + /// TagID + /// + public string TagName; + /// + /// 工位号 + /// + public string OpName; + /// + /// 数据来源 + /// + public string DataSources; + /// + /// IP + /// + public string IP; + /// + /// OPC的URL + /// + public string OpcIpPort; + /// + /// 组 + /// + public string Group; + /// + /// 监控时间间隔 + /// + public string MonitorInterval; + /// + /// DB号加起始地址,DB1001.30 + /// + public string TagDbAndStartAdr; + /// + /// DB号加起始地址,DB1001.30.1,为了bool写入专用 + /// + public string TagDbAndStartAdrWrite; + /// + /// OPC协议地址 + /// 例如:S7:[192.168.1.211|VFD1|S7ONLINE|01.00,192.168.1.211,02.02,1]DB1001,DINT154 + /// + public string TagOPCAdrStr; + /// + /// DB地址位置 + /// 变量起始地址,例如 0,1,2,56,80... + /// + public int Index; + /// + /// 变量字节长度 + /// 变量字节长度,l例如 1,2,4... + /// + public int Length; + /// + /// X 0,1,2,3,4,5,6,7 + /// 例如 X 0,1,2,3,4,5,6,7 + /// + public int BitIndex; + /// + /// 以连续Byte数组方式读取的DB地址实际位置 + /// 变量起始地址,例如 0,1,2,56,80... + /// + public int IndexBytes; + /// + /// 绝对地址差分,应用区域读取的拆分20200101_LLX + /// + public int AbsAddrDiff; + + + + /// + /// 点类型代码 + /// 比如bool是11,String是8 + /// + public int TagTypeID; + /// + /// 点类型 + /// 比如Bool,INT,STRING等 + /// + public string TagType; + /// + /// 变量类型代码 + /// 比如:允许保存是19 + /// + public int TagTypeCodeID; + /// + /// Value + /// + public object TagValue; + /// + /// 是否监控 + /// + public int IsMonitor; + + + + + + /// + /// 时间戳 + /// + public DateTime TimeStamp; + /// + /// 标签质量 192 , -1 + /// + public string TagQuality; + /// + /// 测量位置 + /// + public string ShaftID; + /// + /// 测量项目 + /// + public string ItemName; + /// + /// 测量单位 + /// + public string Unit; + /// + /// 上限值 + /// + public string TagValueUp; + /// + /// 下限值 + /// + public string TagValueDown; + /// + /// 理论值 + /// + public string TagValeNormal; + /// + /// 合格标志 + /// + public string IsGoodBad; + /// + /// 列位置 + /// + public string TagOrderBy; + /// + /// 变量排序 + /// + public string TagItemOrderBy; + /// + /// 是保存到数据库 + /// + public int IsSaveToSql; + /// + /// 是发送到WebSocket + /// + public int IsWebSocket; + /// + /// 是程序启动时候的值 + /// + public int IsFirstValue; + /// + /// 变量特点 + /// + public int TagProperty; + /// + /// 变量变化的持续时间,单位 毫秒 + /// + public int TagKeepTime; + /// + /// 变量变化前的值 + /// + public object TagValueBefore; + + } + + public class CustomeEvetnArgs : EventArgs + { + public int TagKeepTime { get; set; } + public object TagProperty { get; set; } + public object TagItemOrderBy { get; set; } + public object TagOrderBy { get; set; } + public object IsGoodBad { get; set; } + public object TagValeNormal { get; set; } + public object TagValueDown { get; set; } + public object TagValueUp { get; set; } + public object Unit { get; set; } + public object ItemName { get; set; } + public object ShaftID { get; set; } + public object IsMonitor { get; set; } + public object TagTypeActual { get; set; } + public object TagValueBefore { get; set; } + public object IsFirstValue { get; set; } + public object IsSaveToSql { get; set; } + public object DataDources { get; set; } + public object TagTypeID { get; set; } + public object TagTypeCodeID { get; set; } + public object TagID { get; set; } + public string TimeStamp { get; set; } + public object TagQuality { get; set; } + public object OpName { get; set; } + public object TagValue { get; set; } + public object TagValueType { get; set; } + public object TagType { get; set; } + public object TagName { get; set; } + public object TagKey { get; set; } + public object IsWebSocket { get; set; } + public string TimeStampBefore { get; set; } + } + + public class QualityDataType + { + public int tagValueType; + public int tagTypeID; + public string opName; + public string tagID; + public object tagValue; + public int tagQuality; + public int tagOrderBy; + public int tagItemOrderBy; + public int tagProperty; + public int isGoodBad; + } + + public class HashtableList + { + /// + /// MesServerCode + /// + static public Hashtable hashtable_MesServerCode_Temp; + /// + /// MesDll + /// + static public Hashtable hashtable_MesDll_Temp; + static public NameValueCollection hashtable_TagTypeDataType_Temp; + static public NameValueCollection hashtable_TagType_Temp; + static public Hashtable hashtable_TagTypeTagName_Temp; + + static public Hashtable hashtable_EngineGetOver_EngineTypeID_Temp; + static public Hashtable hashtable_EngineGetOver_EngineType_Temp; + static public Hashtable hashtable_EngineGetOver_EngineID_Temp; + static public Hashtable hashtable_EngineGetOver_OrderForm_Temp; + + static public Hashtable hashtable_OpNameRepair_Temp; + + static public Hashtable hashtable_WorkGroupIndex_Temp; + static public Hashtable hashtable_workStepProperty_Temp; + static public Hashtable hashtable_QualityMesRead_Temp; + static public Hashtable hashtable_IsAllowWork_Temp; + /// + /// 工位号与工位上下线类型 + /// (0普通工位)(1正常上线)(2正常下线)(3返修上线)(4返修下线) + /// 5 分线上线(总线) 6 分线上线(分线) + /// + static public Hashtable hashtableOpName_OpType_Temp; + + static public Hashtable hashtable_tagTable_OpName_SaveData_Temp; + + + public Hashtable hashtable_tagTable_OpName_SaveData; + + + /// + /// + /// 工位号与工位上下线类型 + /// (0普通工位)(1正常上线)(2正常下线)(3返修上线)(4返修下线) + /// 5 分线上线(总线) 6 分线上线(分线) + /// + public Hashtable hashtableOpName_OpType; + public Hashtable hashtable_IsAllowWork; + public Hashtable hashtable_QualityMesRead; + public Hashtable hashtable_workStepProperty; + public Hashtable hashtable_OpNameRepair; + /// + /// MesServerCode + /// + public Hashtable hashtable_MesServerCode; + public Hashtable hashtable_TagTypeTagName; + + /// + /// MesDll + /// + public Hashtable hashtable_MesDll; + public NameValueCollection hashtable_TagTypeDataType; + public NameValueCollection hashtable_TagType; + + + public Hashtable hashtable_EngineGetOver_EngineTypeID; + public Hashtable hashtable_EngineGetOver_EngineType; + public Hashtable hashtable_EngineGetOver_EngineID; + public Hashtable hashtable_EngineGetOver_OrderForm; + + public Hashtable hashtable_WorkGroupIndex; + + public DataTable BasicDataTagValue; + public DataTable BasicDataTagValueUpDown; + public Hashtable hashtable_EngineTypeID; + } + + public struct QualityDataQueryStruct + { + + public QualityDataQueryStruct(string opName, Control ctrl) + { + OpName = opName; + Ctrl = ctrl; + tagType = 0; + tagValue = ""; + tagID = ""; + tagTypeID = 0; + tempForm = null; + tagValue2 = null; + + } + + public QualityDataQueryStruct(string opName, int TagType) + { + + OpName = opName; + Ctrl = null; + tagType = TagType; + tagValue = ""; + tagID = ""; + tagTypeID = 0; + tempForm = null; + tagValue2 = null; + } + + public QualityDataQueryStruct(string opName, int TagType, Control ctrl) + { + + OpName = opName; + Ctrl = ctrl; + tagType = TagType; + tagValue = ""; + tagID = ""; + tagTypeID = 0; + tempForm = null; + tagValue2 = null; + } + public QualityDataQueryStruct(string opName, int TagType, object TagValue) + { + + OpName = opName; + Ctrl = null; + tagType = TagType; + tagValue = TagValue; + tagID = ""; + tagTypeID = 0; + tempForm = null; + tagValue2 = null; + } + public QualityDataQueryStruct(string TagID, int TagTypeID, object TagValue, object TagValue2, Form TempForm) + { + + OpName = ""; + Ctrl = null; + tagType = 0; + tagValue = TagValue; + tagID = TagID; + tagTypeID = TagTypeID; + tempForm = TempForm; + tagValue2 = TagValue2; + } + + + public string OpName; + public Control Ctrl; + public int tagType; + public object tagValue; + public object tagValue2; + public string tagID; + public int tagTypeID; + public Form tempForm; + + + } +} + + + +namespace DoWhatPlc1 +{ + public class EngineValue + { + public string OpName { set; get; } + public string EngineID { set; get; } + public string EngineType { set; get; } + public int EngineTypeID { set; get; } + public int PalletCode { set; get; } + public int ProcessCode { set; get; } + public int PartPalletCode { set; get; } + public string PalletInfo { set; get; } + /// + /// 显示返修标志 + /// + public int RepairPartStatusPLC { set; get; } + /// + /// 1 合格;2 不合格 + /// + public int QualityMask { set; get; } + + public string OrderForm { set; get; } + } + public class DoWhat + { + public const string ReadPLC_TagID = "ReadPLC_TagID"; + public const string WritePLC_TagID = "WritePLC_TagID"; + public const string ReadPLC_TagTypeCodeID = "ReadPLC_TagTypeCodeID"; + public const string WritePLC_TagTypeCodeID = "WritePLC_TagTypeCodeID"; + public const string ReadPLC_Cmd = "ReadPLC_Cmd"; + public const string WritePLC_Cmd = "WritePLC_Cmd"; + public const string ReadPLC_GroupData = "ReadPLC_GroupData"; + public const string ReadPLC_GroupMonitor = "ReadPLC_GroupMonitor"; + public const string ReadPLC_IpTag = "ReadPLC_IpTag"; + public const string ReadPLC_IpMonitorTag = "ReadPLC_IpMonitorTag"; + public const string ReadQualityDataList = "ReadQualityDataList"; + public const string ReadByteData_Op = "ReadByteData_Op"; + public const string ReadByteData_Ip = "ReadByteData_Ip"; + public const string WritePLC_Bytes_Op = "WritePLC_Bytes_Op"; + public const string WritePLC_Bytes_Ip = "WritePLC_Bytes_Ip"; + public const string IpAllTag = "IpAllTag"; + public const string IpMonitorTag = "IpMonitorTag"; + public const string RegionRead = "RegionRead"; + public const string ReadBytes = "ReadBytes"; + public const string WriteBytes = "WriteBytes"; + } + /// + /// object 类型数据转换成字符串变量表达 + /// + public class ReturnValueString + { + public string TagID { set; get; } + public string TagValue { set; get; } + public string ValueType { set; get; } + public string OpName { set; get; } + public string TimeStamp { set; get; } + public string TagTypeCodeID { set; get; } + public string TagTypeID { set; get; } + /// + /// 变量变化的持续时间,单位 毫秒 + /// + public string TagKeepTime; + public string FunName; + public string FunCmd; + public string MesServerCode; + public string CmdPlcReadWrite; + public ReturnValueString() + { + + } + public ReturnValueString(string tagID, object tagValue, string opName = "", string tagTypeCodeID = "", string tagTypeID = "", string tagKeepTime = "", string funName = "", string funCmd = "", string mesServerCode = "") + { + TagTypeCodeID = tagTypeCodeID; + TagTypeID = tagTypeID; + TagValue = tagValue.ToString(); + ValueType = tagValue.GetType().Name; + TagID = tagID; + OpName = opName; + TagKeepTime = tagKeepTime; + FunName = funName; + FunCmd = funCmd; + MesServerCode = mesServerCode; + TimeStamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff"); + } + + public ReturnValueObject ReturnValueToObject() + { + ReturnValueObject ro = new ReturnValueObject(TagID, TagValue, OpName, TagTypeCodeID, ValueType, TimeStamp); + + return ro; + } + + } + /// + /// 字符串变量转变成object类型变量 + /// + public class ReturnValueObject + { + public string TagID { set; get; } + public object TagValue { set; get; } + public string ValueType { set; get; } + public string OpName { set; get; } + public DateTime TimeStamp { set; get; } + public string TagTypeCodeID { set; get; } + /// + /// 变量变化的持续时间,单位 毫秒 + /// + public int TagKeepTime; + + public ReturnValueObject(string tagID, string tagValue, string opName = "", string tagTypeCodeID = "", string valueType = "", string timeStamp = "") + { + TagValue = GetTypeValue(valueType, tagValue); + ValueType = valueType; + TagID = tagID; + OpName = opName; + try + { + TimeStamp = Convert.ToDateTime(timeStamp); + } + catch + { + TimeStamp = DateTime.Now; + + } + TagTypeCodeID = tagTypeCodeID; + + } + + public ReturnValueString ReturnValueToString() + { + ReturnValueString rs = new ReturnValueString(TagID, TagValue, OpName, TagTypeCodeID); + return rs; + } + public static object GetTypeValue(string type, string tagValue) + { + object tagV = "-1"; + if (type == null) + { + tagV = tagValue; + } + switch (type.ToLower()) + { + case "bool": + case "boolean": + tagV = false; + switch (tagValue.ToLower()) + { + case "1": + case "true": + tagV = true; + break; + case "0": + case "false": + tagV = false; + break; + } + return tagV; + //return Type.GetType(" System.Boolean ", true, true); + case "byte ": + return Convert.ToByte(tagValue); + case "sbyte": + return Convert.ToSByte(tagValue); + case "char": + return Convert.ToChar(tagValue); + case "decimal": + return Convert.ToDecimal(tagValue); + case "double": + return Convert.ToDouble(tagValue); + case "float": + return Convert.ToSingle(tagValue); + case "int": + return Convert.ToInt32(tagValue); + case "int16": + return Convert.ToInt32(tagValue); + case "uint": + return Convert.ToUInt32(tagValue); + case "long": + return Convert.ToInt64(tagValue); + case "ulong": + return Convert.ToUInt64(tagValue); + case "object": + return tagValue; + case "short": + return Convert.ToInt16(tagValue); + case "ushort": + return Convert.ToUInt16(tagValue); + case "string": + return tagValue; + case "date": + case "datetime": + return Convert.ToDateTime(tagValue); + case "guid": + return tagValue; + default: + return tagValue; + } + } + + + } + + public class TagIDTagFormat + { + public string TagID; + public TagFormat TF; + + public TagIDTagFormat(string tagID, TagFormat tF) + { + TagID = tagID; + TF = tF; + } + } + + + public class QualityDataSaveList + { + public Hashtable valuList; + public DataTable BasicDataTagValue; + public DataTable BasicDataTagValueUpDown; + public Hashtable hashtable_EngineTypeID; + public Hashtable hashtable_tagTable_OpName_SaveData; + } + + + + public struct ControlData + { + public int TagType; + public string opName; + public Control btn; public ControlData(Control Ctrl, string OpName) + { + string[] Array_NameSplit; + Array_NameSplit = Ctrl.Name.Split('_'); + TagType = Convert.ToInt32(Array_NameSplit[2]); + opName = OpName; + btn = Ctrl; + + } + } + public struct ControlChangeByTagType + { + public ControlChangeByTagType(int tagType, string value) + { + TagType = tagType; + Value = value; + } + + public int TagType; + public string Value; + } + /// + /// tag格式化结构 + /// + public struct TagFormat + { + /// + /// TagID + /// + public string TagID; + /// + /// TagID + /// + public string TagName; + /// + /// 工位号 + /// + public string OpName; + /// + /// 数据来源 + /// + public string DataSources; + /// + /// IP + /// + public string IP; + /// + /// OPC的URL + /// + public string OpcIpPort; + /// + /// 组 + /// + public string Group; + /// + /// 监控时间间隔 + /// + public string MonitorInterval; + /// + /// DB号加起始地址,DB1001.30 + /// + public string TagDbAndStartAdr; + /// + /// DB号加起始地址,DB1001.30.1,为了bool写入专用 + /// + public string TagDbAndStartAdrWrite; + /// + /// OPC协议地址 + /// 例如:S7:[192.168.1.211|VFD1|S7ONLINE|01.00,192.168.1.211,02.02,1]DB1001,DINT154 + /// + public string TagOPCAdrStr; + /// + /// DB地址位置 + /// 变量起始地址,例如 0,1,2,56,80... + /// + public int Index; + /// + /// 变量字节长度 + /// 变量字节长度,l例如 1,2,4... + /// + public int Length; + /// + /// X 0,1,2,3,4,5,6,7 + /// 例如 X 0,1,2,3,4,5,6,7 + /// + public int BitIndex; + /// + /// 以连续Byte数组方式读取的DB地址实际位置 + /// 变量起始地址,例如 0,1,2,56,80... + /// + public int IndexBytes; + /// + /// 绝对地址差分,应用区域读取的拆分20200101_LLX + /// + public int AbsAddrDiff; + + + + /// + /// 点类型代码 + /// 比如bool是11,String是8 + /// + public int TagTypeID; + /// + /// 点类型 + /// 比如Bool,INT,STRING等 + /// + public string TagType; + /// + /// 变量类型代码 + /// 比如:允许保存是19 + /// + public int TagTypeCodeID; + /// + /// Value + /// + public object TagValue; + /// + /// 是否监控 + /// + public int IsMonitor; + + + + + + /// + /// 时间戳 + /// + public DateTime TimeStamp; + /// + /// 标签质量 192 , -1 + /// + public string TagQuality; + /// + /// 测量位置 + /// + public string ShaftID; + /// + /// 测量项目 + /// + public string ItemName; + /// + /// 测量单位 + /// + public string Unit; + /// + /// 上限值 + /// + public string TagValueUp; + /// + /// 下限值 + /// + public string TagValueDown; + /// + /// 理论值 + /// + public string TagValeNormal; + /// + /// 合格标志 + /// + public string IsGoodBad; + /// + /// 列位置 + /// + public string TagOrderBy; + /// + /// 变量排序 + /// + public string TagItemOrderBy; + /// + /// 是保存到数据库 + /// + public int IsSaveToSql; + /// + /// 是发送到WebSocket + /// + public int IsWebSocket; + /// + /// 是程序启动时候的值 + /// + public int IsFirstValue; + /// + /// 变量特点 + /// + public int TagProperty; + /// + /// 变量变化的持续时间,单位 毫秒 + /// + public int TagKeepTime; + /// + /// 变量变化前的值 + /// + public object TagValueBefore; + + } + + public class CustomeEvetnArgs : EventArgs + { + public int TagKeepTime { get; set; } + public object TagProperty { get; set; } + public object TagItemOrderBy { get; set; } + public object TagOrderBy { get; set; } + public object IsGoodBad { get; set; } + public object TagValeNormal { get; set; } + public object TagValueDown { get; set; } + public object TagValueUp { get; set; } + public object Unit { get; set; } + public object ItemName { get; set; } + public object ShaftID { get; set; } + public object IsMonitor { get; set; } + public object TagTypeActual { get; set; } + public object TagValueBefore { get; set; } + public object IsFirstValue { get; set; } + public object IsSaveToSql { get; set; } + public object DataDources { get; set; } + public object TagTypeID { get; set; } + public object TagTypeCodeID { get; set; } + public object TagID { get; set; } + public string TimeStamp { get; set; } + public object TagQuality { get; set; } + public object OpName { get; set; } + public object TagValue { get; set; } + public object TagValueType { get; set; } + public object TagType { get; set; } + public object TagName { get; set; } + public object TagKey { get; set; } + public object IsWebSocket { get; set; } + public string TimeStampBefore { get; set; } + } + + public class QualityDataType + { + public int tagValueType; + public int tagTypeID; + public string opName; + public string tagID; + public object tagValue; + public int tagQuality; + public int tagOrderBy; + public int tagItemOrderBy; + public int tagProperty; + public int isGoodBad; + } + + public class HashtableList + { + /// + /// MesServerCode + /// + static public Hashtable hashtable_MesServerCode_Temp; + /// + /// MesDll + /// + static public Hashtable hashtable_MesDll_Temp; + static public Hashtable hashtable_TagTypeDataType_Temp; + static public Hashtable hashtable_TagType_Temp; + + static public Hashtable hashtable_EngineGetOver_EngineTypeID_Temp; + static public Hashtable hashtable_EngineGetOver_EngineType_Temp; + static public Hashtable hashtable_EngineGetOver_EngineID_Temp; + static public Hashtable hashtable_EngineGetOver_OrderForm_Temp; + + static public Hashtable hashtable_OpNameRepair_Temp; + + static public Hashtable hashtable_WorkGroupIndex_Temp; + static public Hashtable hashtable_workStepProperty_Temp; + static public Hashtable hashtable_QualityMesRead_Temp; + static public Hashtable hashtable_IsAllowWork_Temp; + /// + /// 工位号与工位上下线类型 + /// (0普通工位)(1正常上线)(2正常下线)(3返修上线)(4返修下线) + /// 5 分线上线(总线) 6 分线上线(分线) + /// + static public Hashtable hashtableOpName_OpType_Temp; + + /// + /// + /// 工位号与工位上下线类型 + /// (0普通工位)(1正常上线)(2正常下线)(3返修上线)(4返修下线) + /// 5 分线上线(总线) 6 分线上线(分线) + /// + public Hashtable hashtableOpName_OpType; + public Hashtable hashtable_IsAllowWork; + public Hashtable hashtable_QualityMesRead; + public Hashtable hashtable_workStepProperty; + public Hashtable hashtable_OpNameRepair; + /// + /// MesServerCode + /// + public Hashtable hashtable_MesServerCode; + /// + /// MesDll + /// + public Hashtable hashtable_MesDll; + public Hashtable hashtable_TagTypeDataType; + public Hashtable hashtable_TagType; + + + public Hashtable hashtable_EngineGetOver_EngineTypeID; + public Hashtable hashtable_EngineGetOver_EngineType; + public Hashtable hashtable_EngineGetOver_EngineID; + public Hashtable hashtable_EngineGetOver_OrderForm; + + public Hashtable hashtable_WorkGroupIndex; + + + public DataTable BasicDataTagValue; + public DataTable BasicDataTagValueUpDown; + public Hashtable hashtable_EngineTypeID; + } + + public struct QualityDataQueryStruct + { + + public QualityDataQueryStruct(string opName, Control ctrl) + { + OpName = opName; + Ctrl = ctrl; + tagType = 0; + tagValue = ""; + tagID = ""; + tagTypeID = 0; + tempForm = null; + tagValue2 = null; + + } + + public QualityDataQueryStruct(string opName, int TagType) + { + + OpName = opName; + Ctrl = null; + tagType = TagType; + tagValue = ""; + tagID = ""; + tagTypeID = 0; + tempForm = null; + tagValue2 = null; + } + + public QualityDataQueryStruct(string opName, int TagType, Control ctrl) + { + + OpName = opName; + Ctrl = ctrl; + tagType = TagType; + tagValue = ""; + tagID = ""; + tagTypeID = 0; + tempForm = null; + tagValue2 = null; + } + public QualityDataQueryStruct(string opName, int TagType, object TagValue) + { + + OpName = opName; + Ctrl = null; + tagType = TagType; + tagValue = TagValue; + tagID = ""; + tagTypeID = 0; + tempForm = null; + tagValue2 = null; + } + public QualityDataQueryStruct(string TagID, int TagTypeID, object TagValue, object TagValue2, Form TempForm) + { + + OpName = ""; + Ctrl = null; + tagType = 0; + tagValue = TagValue; + tagID = TagID; + tagTypeID = TagTypeID; + tempForm = TempForm; + tagValue2 = TagValue2; + } + + + public string OpName; + public Control Ctrl; + public int tagType; + public object tagValue; + public object tagValue2; + public string tagID; + public int tagTypeID; + public Form tempForm; + + + } +} + + diff --git a/Common/01DoWhatPlc/Properties/AssemblyInfo.cs b/Common/01DoWhatPlc/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..d89ceef --- /dev/null +++ b/Common/01DoWhatPlc/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// 有关程序集的一般信息由以下 +// 控制。更改这些特性值可修改 +// 与程序集关联的信息。 +[assembly: AssemblyTitle("DoWhatPlc")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("DoWhatPlc")] +[assembly: AssemblyCopyright("Copyright © 2022")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// 将 ComVisible 设置为 false 会使此程序集中的类型 +//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型 +//请将此类型的 ComVisible 特性设置为 true。 +[assembly: ComVisible(false)] + +// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID +[assembly: Guid("0d1af432-439a-4920-8692-43ae139f5530")] + +// 程序集的版本信息由下列四个值组成: +// +// 主版本 +// 次版本 +// 生成号 +// 修订号 +// +//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值 +//通过使用 "*",如下所示: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Common/01DoWhatPlc/TagTypeCodeID.cs b/Common/01DoWhatPlc/TagTypeCodeID.cs new file mode 100644 index 0000000..2dd1a78 --- /dev/null +++ b/Common/01DoWhatPlc/TagTypeCodeID.cs @@ -0,0 +1,462 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +///1 X WorkStart 2 工件到位(PLC) 工件到位。托盘到达工位,并且托盘上有工件。 +///2 X RepairPartStatusPLC 3 RepairPartStatusPLC 备用 +///3 STRING RepairPathString 4 RepairPathString "工位返修字符串(121211112222111),前2位是西门子字符串格式,第一位是总长度,第二位是实际长度" +///4 X EngineTypeGetOverMES 5 传递机型(MES) MES传递总成信息给PLC(上线工位) +///5 X PartPalletGoOver 6 PartPalletGoOver 上线工位。0:正常工作;1:空托盘放行,PLC读取到此标志不走申请上线逻辑。 +///6 X MaterialVerifyOver 7 MaterialVerifyOver MES保存完质量数据,物料数据等与PLC信号交互完成后通知PLC,所以工步都完成,才可以放行工件,正常工作时工件放行的必要条件。 +///7 X FalseGo 8 FalseGo 按MES界面[不合格放行]按钮,MES发送此信号。操作者判断工件不合格,通知设备,按不合格方式放行工件,工件流转到返修下线工位后,返修下线。MES工作完成MES0.3=1,MES合格放行MES0.5=0,MES0.4=1 +///8 INT EngineTypeID 9 EngineTypeID MES发动机机型标志(必须PLC) +///9 STRING EngineID 10 EngineID MES发动机编号(必须PLC) +///10 STRING EngineType 11 机型(MES) MES发动机机型(必须PLC) +///11 X PartPalletStatus 13 PartPalletStatus MES激发变量托盘到位离开(必须PLC) +///12 X HeartBeatPLC 14 HeartBeatPLC 心跳处理:PLC收到MES心跳信号后,PLC延时5秒后,数值取反再写回PLC,写回PLC开始计时,如果5秒钟MES无反馈报通讯故障。 +///13 X HeartBeatMIS 15 HeartBeatMIS 间隔时间5S,心跳处理。收到PLC心跳信号后,MES按原值回写。PLC收到MES信号后延时5秒,取反写入,以此循环。 +///14 X TargetTimeRead 16 TargetTimeRead MES允许可读工位运行时间 +///15 Int MachineTargetTime 17 MachineTargetTime 目标运行时间 +///16 Int MachineActualTime 18 MachineActualTime 实际运行时间 +///17 X MesRead 19 允许保存(PLC) 质量数据可以读数据 +///18 X MesReadOver 20 保存完成(MES) MES保存完数据(必须MIS) +///19 INT QualityMask 21 合格标志(PLC) 质量数据工位合格标志0:没有工作;1:合格 ;2 :不合格(必须PLC) +///20 B PalletInfo 22 PalletInfo 0空托盘,1合格件,2不合格件 +///21 INT RepairStatusPLC 23 RepairStatusPLC 0正常件,1返修件 +///22 INT OrderNo 24 订单号(MES) 订单号(MES) +///23 X StorageNo 25 库位号(MES) 库位号(MES) +///24 X AllowPass 26 允许放行(MES) 允许放行 +///25 X PartLoadFinish 27 PartLoadFinish PartLoadFinish +///26 X Reserved_7 28 Reserved_7 备用 +///27 X Reserved_8 29 Reserved_8 备用 +///28 X Reserved_9 30 Reserved_9 备用 +///29 X Reserved_10 31 Reserved_10 备用 +///30 X Reserved_11 32 Reserved_11 备用 +///31 X Reserved_12 33 Reserved_12 备用 +///32 X Reserved_13 34 Reserved_13 备用 +///33 X Reserved_14 35 Reserved_14 备用 +///34 Int PLCSPareint1 36 PLCSPareint1 备用 +///35 Int PLCSPareint2 37 PLCSPareint2 备用 +///36 Int PLCSPareint3 38 PLCSPareint3 备用 +///37 STRING PLCSarestring1 39 PLCSarestring1 备用 +///38 STRING PLCSarestring2 40 PLCSarestring2 备用 +///39 STRING MarkID 42 MarkID 机体打标号(MES)前2位是西门子字符串格式,第一位是总长度,第二位是实际长度 +///40 X PartLoad 43 PartLoad 上线工位,PLC向MES申请总成编号。收到该信号后,MES将机型标志(DBB22 ~23)、总成号(DBB24 ~63)、总成机型DBB64 ~103写入PLC。之后MES通过信号“传递机型(DBX0.1)”通知PLC。 +///41 X EngineTypeGetOverPLC 44 传递机型(PLC) PLC将机型标志(DBB50…51)、工件编号(DBB52…101)、产品型号(DBB102…187)、托盘编号(DBB188…189)准备完毕后,通知MES。 +///42 X PartLoadOK 48 PartLoadOK 备用 +///43 X Reserved_18 49 Reserved_18 备用 +///44 X PalletDown 50 PalletDown 暂时保留,项目未使用 +///45 X ConfirmOkGo 51 ConfirmOkGo 按MES界面[合格放行]按钮,MES发送此信号。操作者判断工件合格,通知设备,工件按合格方式放行工件。MES工作完成MES0.3=1,MES合格放行MES0.5=1,MES0.4=0 +///46 X ResetDevice 52 ResetDevice 针对手动工位,无HMI,需要复位设备在MES页面操作。 +///47 X UnloadCompleted 53 UnloadCompleted 暂时保留,项目未使用 +///48 X MachineTime_ReadOver 54 MachineTime_ReadOver 备用 +///49 X Reserved_19 58 Reserved_19 备用 +///50 X FixOK 59 FixOK 手动拧紧工位,单工步螺栓拧紧完成,通知PC读取数据。 +///51 X Reserved_21 61 Reserved_21 备用 +///52 X Reserved_22 62 Reserved_22 备用 +///53 X Reserved_23 63 Reserved_23 备用 +///54 X Reserved_24 64 Reserved_24 备用 +///55 X Reserved_25 65 Reserved_25 备用 +///56 X FixAllow 66 FixAllow "设备工作的必须信号,对于有物料验证的工位,MES验证完成给出此信号,对于无物料验证工位,MES直接给出此信号。" +///57 X FixOver 67 FixOver 用于手动拧紧且有质量数据工位。通知设备当前工步拧紧螺钉工作结束。 +///58 X MatchingCompleted 68 MatchingCompleted 分线上总线,匹配成功是1;不成功是0。 +///59 X Match 69 Match 分线上总线,匹配成功是1;不成功是0。 +///60 X Reserved_2 70 Reserved_2 备用 +///61 X IsAutoGetEngineID 71 IsAutoGetEngineID 自动手动申请工件编号。0是自动方式;1:手动方式。暂时保留,生成流水号方式是在数据库中实现的 +///62 X RepairUplineMES 72 RepairUplineMES 上线清空MOBY(针对上线工位):通知PLC从新开始申请上线流程 +///63 INT EngineTypeID_MES 73 机型代码(MES) MES发动机机型标志(必须MES) +///64 STRING EngineID_MES 74 工件编号(MES) MES发动机编号(必须MES) +///65 STRING EngineType_MES 75 EngineType_MES MES发动机机型(必须MES) +///66 X Reserved_20 76 Reserved_20 备用 +///67 INT ProcessCode 77 ProcessCode 手动拧紧工位:由MES通知PLC拧紧序号 +///68 B OnLineState 79 OnLineState 通过线体工位PC实现下达工位工作状态:工位有三种状态:在线、离线、屏蔽。在线:0正常状态,实现正常功能。1离线:设备脱离MES工作,进入不交互模式。 +///69 INT PartPalletCode 80 托盘号(MES) 托盘编号(B5A) +///70 INT BoltCode 88 BoltCode 手动拧紧工位:指导PLC所用套筒 +///71 INT RepairStatus 93 RepairStatus "0正常件,1返修件。对于上线工位MES给出是正常上线还是返修上线,返修路径" +///72 DInt Reserved_15 110 Reserved_15 备用 +///73 DInt Reserved_16 111 Reserved_16 备用 +///74 B Reserved_17 112 Reserved_17 备用 +///75 INT SPareint1 113 SPareint1 备用int1 +///76 INT SPareint2 114 SPareint2 备用int2 +///77 INT SPareint3 115 SPareint3 备用int3 +///78 STRING Sparestring1 116 Sparestring1 备用字符串1 +///79 STRING Sparestring2 117 Sparestring2 备用字符串2 +///80 X MachineStatusPutOn 1000 机床上电(PLC) 机床上电(必须PLC) +///81 X MachineStatusWorkOn 1001 循环开始(PLC) 循环开始(必须PLC) +///82 X MachineStatusAlarm 1002 设备报警(PLC) 机床故障(必须PLC) +///83 X MachineStatusNoPart 1003 MachineStatusNoPart 上料无件(必须PLC) +///84 X MachineStatusBlock 1004 MachineStatusBlock 下料堵塞(必须PLC) + + +namespace MesWork +{ + /// + /// 这是变量类型代码的配置,几乎是不变的 + /// 请不要随意修改,为了保证变量版本同一,并且方便维护,请联系发行人修改! + /// 请注意,此修改为全局修改! + /// + public enum EnumTagTypeCodeID + { + /// + /// 工件到位(PLC) + /// 变量类型:Bool + /// 解释:托盘到达工位,并且托盘上有工件。 + /// + WorkStart = 2, + /// + /// + /// + RepairPartStatusPLC = 3, + /// + /// 工位返修字符串 + /// 变量类型:String + /// 解释:工位返修字符串 + /// + RepairPathString = 4, + /// + /// 传递机型(MES) + /// 变量类型:Bool + /// 解释:MES传递总成信息给PLC(上线工位) + /// + EngineTypeGetOverMES = 5, + /// + /// + /// + PartPalletGoOver = 6, + /// + /// + /// + MaterialVerifyOver = 7, + /// + /// + /// + FalseGo = 8, + /// + /// + /// + EngineTypeID = 9, + /// + /// + /// + EngineID = 10, + /// + /// 机型(MES) + /// 变量类型:String + /// + EngineType = 11, + /// + /// + /// + PartPalletStatus = 13, + /// + /// + /// + HeartBeatPLC = 14, + /// + /// + /// + HeartBeatMIS = 15, + /// + /// + /// + TargetTimeRead = 16, + /// + /// + /// + MachineTargetTime = 17, + /// + /// + /// + MachineActualTime = 18, + /// + /// 允许保存(PLC) + /// 变量类型:Bool + /// + MesRead = 19, + /// + /// 保存完成(MES) + /// 变量类型:Bool + /// + MesReadOver = 20, + /// + /// 合格标志(PLC) + /// 变量类型:Int + /// + QualityMask = 21, + /// + /// + /// + PalletInfo = 22, + /// + /// + /// + RepairStatusPLC = 23, + /// + /// 订单号(MES) + /// 变量类型:Int + /// + OrderNo = 24, + /// + /// 库位号(MES) + /// 变量类型:Bool + /// + StorageNo = 25, + /// + /// 允许放行(MES) + /// 变量类型:Bool + /// + AllowPass = 26, + /// + /// + /// + PartLoadFinish = 27, + /// + /// + /// + Reserved_7 = 28, + /// + /// + /// + Reserved_8 = 29, + /// + /// + /// + Reserved_9 = 30, + /// + /// + /// + Reserved_10 = 31, + /// + /// + /// + Reserved_11 = 32, + /// + /// + /// + Reserved_12 = 33, + /// + /// + /// + Reserved_13 = 34, + /// + /// + /// + Reserved_14 = 35, + /// + /// + /// + PLCSPareint1 = 36, + /// + /// + /// + PLCSPareint2 = 37, + /// + /// + /// + PLCSPareint3 = 38, + /// + /// 订单号(PLC) + /// + OrderFormPLC = 39, + /// + /// + /// + PLCSarestring2 = 40, + /// + /// + /// + MarkID = 42, + /// + /// + /// + PartLoad = 43, + /// + /// 传递机型(PLC) + /// 变量类型:Bool + /// + EngineTypeGetOverPLC = 44, + /// + /// + /// + PartLoadOK = 48, + /// + /// + /// + Reserved_18 = 49, + /// + /// + /// + PalletDown = 50, + /// + /// + /// + ConfirmOkGo = 51, + /// + /// + /// + ResetDevice = 52, + /// + /// + /// + UnloadCompleted = 53, + /// + /// + /// + MachineTime_ReadOver = 54, + /// + /// + /// + Reserved_19 = 58, + /// + /// + /// + FixOK = 59, + /// + /// + /// + Reserved_21 = 61, + /// + /// + /// + Reserved_22 = 62, + /// + /// + /// + Reserved_23 = 63, + /// + /// + /// + Reserved_24 = 64, + /// + /// + /// + Reserved_25 = 65, + /// + /// + /// + FixAllow = 66, + /// + /// + /// + FixOver = 67, + /// + /// + /// + MatchingCompleted = 68, + /// + /// + /// + Match = 69, + /// + /// + /// + Reserved_2 = 70, + /// + /// + /// + IsAutoGetEngineID = 71, + /// + /// + /// + RepairUplineMES = 72, + /// + /// 机型代码(MES) + /// 变量类型:Int + /// + EngineTypeID_MES = 73, + /// + /// 工件编号(MES) + /// 变量类型:String + /// + EngineID_MES = 74, + /// + /// + /// + EngineType_MES = 75, + /// + /// + /// + Reserved_20 = 76, + /// + /// + /// + ProcessCode = 77, + /// + /// + /// + OnLineState = 79, + /// + /// 托盘号(MES) + /// 变量类型:Int + /// + PartPalletCode = 80, + /// + /// + /// + BoltCode = 88, + /// + /// + /// + RepairStatus = 93, + /// + /// + /// + Reserved_15 = 110, + /// + /// + /// + Reserved_16 = 111, + /// + /// + /// + Reserved_17 = 112, + /// + /// + /// + SPareint1 = 113, + /// + /// + /// + SPareint2 = 114, + /// + /// + /// + /// + /// MES订单号 + /// + OrdeFormMES = 116, + /// + /// + /// + Sparestring2 = 117, + /// + /// 机床上电(PLC) + /// 变量类型:Bool + /// + MachineStatusPutOn = 1000, + /// + /// 循环开始(PLC) + /// 变量类型:Bool + /// + MachineStatusWorkOn = 1001, + /// + /// 设备报警(PLC) + /// 变量类型:Bool + /// + MachineStatusAlarm = 1002, + /// + /// 上料无件(PLC) + /// 变量类型:Bool + /// + MachineStatusNoPart = 1003, + /// + /// 下料堵塞(PLC) + /// 变量类型:Bool + /// + MachineStatusBlock = 1004, + + + } +} diff --git a/Common/01DoWhatPlc/TagTypeID.cs b/Common/01DoWhatPlc/TagTypeID.cs new file mode 100644 index 0000000..b8800ac --- /dev/null +++ b/Common/01DoWhatPlc/TagTypeID.cs @@ -0,0 +1,28 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MesWork +{ + /// + /// 这是信号点类型代码的配置 + /// 这里是不变的,请不要随意修改!!! + /// 请注意,此修改为全局修改! + /// + public enum EnumTagTypeID + { + Int16 = 2, + Int32 = 3, + Float = 4, + UInt64 = 7, + String = 8, + Bool = 11, + Byte = 17, + UInt16 = 18, + Double = 19, + Bytes = 21, + + } +} diff --git a/Common/01DoWhatPlc/Utils.cs b/Common/01DoWhatPlc/Utils.cs new file mode 100644 index 0000000..594de2a --- /dev/null +++ b/Common/01DoWhatPlc/Utils.cs @@ -0,0 +1,82 @@ +using System.Text; + +public static class Utils + { + public static string UrlEncode(this string str) + { + var encoding = UTF8Encoding.UTF8; + byte[] bytes = encoding.GetBytes(str); + int IsSafe = 0; + int NoSafe = 0; + for (int i = 0; i < bytes.Length; i++) + { + char ch = (char)bytes[i]; + if (ch == ' ') + { + IsSafe++; + } + else if (!IsSafeChar(ch)) + { + NoSafe ++; + } + } + if (IsSafe== 0 && NoSafe == 0) + { + return str; + } + byte[] buffer = new byte[bytes.Length + (NoSafe * 2)]; + int num1 = 0; + for (int j = 0; j < bytes.Length; j++) + { + byte num2 = bytes[j]; + char ch2 = (char)num2; + if (IsSafeChar(ch2)) + { + buffer[num1++] = num2; + } + else if (ch2 == ' ') + { + buffer[num1++] = 0x2B; + } + else + { + buffer[num1++] = 0x25; + buffer[num1++] = (byte)IntToHex((num2 >> 4) & 15); + buffer[num1++] = (byte)IntToHex(num2 & 15); + } + } + return encoding.GetString(buffer); + } + + private static bool IsSafeChar(char ch) + { + if ((((ch < 'a') || (ch > 'z')) && ((ch < 'A') || (ch > 'Z'))) && ((ch < '0') || (ch > '9'))) + { + + switch (ch) + { + case '-': + case '.': + break; //安全字符 + case '+': + case ',': + return false; //非安全字符 + default: //非安全字符 + if (ch != '_') + { + return false; + } + break; + } + } + return true; + } + private static char IntToHex(int n) + { + if (n <= 9) + { + return (char)(n + 0x30); + } + return (char)((n - 10) + 0x41); + } + } diff --git a/Common/01DoWhatPlc/packages.config b/Common/01DoWhatPlc/packages.config new file mode 100644 index 0000000..376abb5 --- /dev/null +++ b/Common/01DoWhatPlc/packages.config @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/Common/02WebApiCall/02_02WebApiCallPLC.csproj b/Common/02WebApiCall/02_02WebApiCallPLC.csproj new file mode 100644 index 0000000..3fa997b --- /dev/null +++ b/Common/02WebApiCall/02_02WebApiCallPLC.csproj @@ -0,0 +1,119 @@ + + + + + Debug + AnyCPU + {3E6D1DD5-01C9-435F-9941-61F906CE35BB} + Library + WebApiCall + 02WebApiCall + v4.8 + 512 + true + true + + + + AnyCPU + true + full + false + ..\dll\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + False + ..\..\dll_common\BasicData.dll + + + ..\..\dll_common\DataLinkMesWork.dll + + + + + + + + + + + + + + + + + Form + + + Form1.cs + + + + + + + + + + + + + Form1.cs + + + ResXFileCodeGenerator + Resources.Designer.cs + Designer + + + True + Resources.resx + True + + + + SettingsSingleFileGenerator + Settings.Designer.cs + + + True + Settings.settings + True + + + + + + + + {1a10fdb2-1a6a-44a8-ab4d-33387563247e} + 00-0Json8.3.1 + + + {0d1af432-439a-4920-8692-43ae139f5530} + 01_01DoWhatPlc + + + {1dc48c83-1842-4de8-acaf-26e1e7f7c58f} + 00_MyLog4Net + + + + \ No newline at end of file diff --git a/Common/02WebApiCall/02_02WebApiCallPLC.sln b/Common/02WebApiCall/02_02WebApiCallPLC.sln new file mode 100644 index 0000000..aa4443a --- /dev/null +++ b/Common/02WebApiCall/02_02WebApiCallPLC.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.32901.82 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "02_02WebApiCallPLC", "02_02WebApiCallPLC.csproj", "{3E6D1DD5-01C9-435F-9941-61F906CE35BB}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {3E6D1DD5-01C9-435F-9941-61F906CE35BB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {3E6D1DD5-01C9-435F-9941-61F906CE35BB}.Debug|Any CPU.Build.0 = Debug|Any CPU + {3E6D1DD5-01C9-435F-9941-61F906CE35BB}.Release|Any CPU.ActiveCfg = Release|Any CPU + {3E6D1DD5-01C9-435F-9941-61F906CE35BB}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {C034F50A-F3DF-47DC-ADB2-3724C1B74818} + EndGlobalSection +EndGlobal diff --git a/Common/02WebApiCall/App.config b/Common/02WebApiCall/App.config new file mode 100644 index 0000000..b740b86 --- /dev/null +++ b/Common/02WebApiCall/App.config @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/Common/02WebApiCall/Form1.Designer.cs b/Common/02WebApiCall/Form1.Designer.cs new file mode 100644 index 0000000..6cec970 --- /dev/null +++ b/Common/02WebApiCall/Form1.Designer.cs @@ -0,0 +1,48 @@ + +namespace WebApiCall +{ + partial class Form1 + { + /// + /// 必需的设计器变量。 + /// + 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.SuspendLayout(); + // + // Form1 + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(800, 525); + this.Name = "Form1"; + this.Text = "Form1"; + this.ResumeLayout(false); + + } + + #endregion + } +} + diff --git a/Common/02WebApiCall/Form1.cs b/Common/02WebApiCall/Form1.cs new file mode 100644 index 0000000..7118c17 --- /dev/null +++ b/Common/02WebApiCall/Form1.cs @@ -0,0 +1,20 @@ +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 WebApiCall +{ + public partial class Form1 : Form + { + public Form1() + { + InitializeComponent(); + } + } +} diff --git a/Common/02WebApiCall/Form1.resx b/Common/02WebApiCall/Form1.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/Common/02WebApiCall/Form1.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/Common/02WebApiCall/Program.cs b/Common/02WebApiCall/Program.cs new file mode 100644 index 0000000..c6cff80 --- /dev/null +++ b/Common/02WebApiCall/Program.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace WebApiCall +{ + static class Program + { + /// + /// 应用程序的主入口点。 + /// + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + Application.Run(new Form1()); + } + } +} diff --git a/Common/02WebApiCall/Properties/AssemblyInfo.cs b/Common/02WebApiCall/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..7ca56e7 --- /dev/null +++ b/Common/02WebApiCall/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// 有关程序集的一般信息由以下 +// 控制。更改这些特性值可修改 +// 与程序集关联的信息。 +[assembly: AssemblyTitle("WebApiCall")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("WebApiCall")] +[assembly: AssemblyCopyright("Copyright © 2022")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// 将 ComVisible 设置为 false 会使此程序集中的类型 +//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型 +//请将此类型的 ComVisible 特性设置为 true。 +[assembly: ComVisible(false)] + +// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID +[assembly: Guid("3e6d1dd5-01c9-435f-9941-61f906ce35bb")] + +// 程序集的版本信息由下列四个值组成: +// +// 主版本 +// 次版本 +// 生成号 +// 修订号 +// +//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值 +//通过使用 "*",如下所示: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Common/02WebApiCall/Properties/Resources.Designer.cs b/Common/02WebApiCall/Properties/Resources.Designer.cs new file mode 100644 index 0000000..ab59e5c --- /dev/null +++ b/Common/02WebApiCall/Properties/Resources.Designer.cs @@ -0,0 +1,63 @@ +//------------------------------------------------------------------------------ +// +// 此代码由工具生成。 +// 运行时版本:4.0.30319.42000 +// +// 对此文件的更改可能会导致不正确的行为,并且如果 +// 重新生成代码,这些更改将会丢失。 +// +//------------------------------------------------------------------------------ + +namespace WebApiCall.Properties { + using System; + + + /// + /// 一个强类型的资源类,用于查找本地化的字符串等。 + /// + // 此类是由 StronglyTypedResourceBuilder + // 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。 + // 若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen + // (以 /str 作为命令选项),或重新生成 VS 项目。 + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.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 (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("WebApiCall.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/Common/02WebApiCall/Properties/Resources.resx b/Common/02WebApiCall/Properties/Resources.resx new file mode 100644 index 0000000..af7dbeb --- /dev/null +++ b/Common/02WebApiCall/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/Common/02WebApiCall/Properties/Settings.Designer.cs b/Common/02WebApiCall/Properties/Settings.Designer.cs new file mode 100644 index 0000000..3cb3577 --- /dev/null +++ b/Common/02WebApiCall/Properties/Settings.Designer.cs @@ -0,0 +1,26 @@ +//------------------------------------------------------------------------------ +// +// 此代码由工具生成。 +// 运行时版本:4.0.30319.42000 +// +// 对此文件的更改可能会导致不正确的行为,并且如果 +// 重新生成代码,这些更改将会丢失。 +// +//------------------------------------------------------------------------------ + +namespace WebApiCall.Properties { + + + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "17.0.3.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/Common/02WebApiCall/Properties/Settings.settings b/Common/02WebApiCall/Properties/Settings.settings new file mode 100644 index 0000000..3964565 --- /dev/null +++ b/Common/02WebApiCall/Properties/Settings.settings @@ -0,0 +1,7 @@ + + + + + + + diff --git a/Common/02WebApiCall/WebApi/AGVWebApiCall.cs b/Common/02WebApiCall/WebApi/AGVWebApiCall.cs new file mode 100644 index 0000000..f490a62 --- /dev/null +++ b/Common/02WebApiCall/WebApi/AGVWebApiCall.cs @@ -0,0 +1,211 @@ +using Newtonsoft.Json; +using System; +using System.Configuration; +using System.Net; +using System.Net.Http; +using System.Reflection; +using System.Text; +using System.Threading.Tasks; +using WebApi.Helpers; +using WebApi.Models; + + +namespace WebApiCall +{ + /// + /// WMS WebApi调用类 + /// + public class AGVWebApiCall + { + private static readonly HttpClient httpClient; + + static AGVWebApiCall() + { + httpClient = new HttpClient(); + httpClient.Timeout = TimeSpan.FromSeconds(20); // 设置超时时间为20秒 + } + + /// + /// MES叫料接口 - 同步版本,返回bool结果 + /// + /// 叫料位置(库位号) + /// 物料号(型号) + /// 是否成功 + public static bool MES_To_AGV_CallGoods(string storageCode, string goodsCode) + { + try + { + var task = MES_To_AGV_CallGoods_Async(storageCode, goodsCode); + task.Wait(); // 同步等待异步任务完成 + return task.Result; + } + catch (Exception err) + { + string errorMsg = $"叫料同步调用异常 - 库位: {storageCode}, 物料号: {goodsCode}, 异常: {err.Message}"; + LogHelper.ShowMsg(errorMsg); + Console.WriteLine($"错误: {MethodBase.GetCurrentMethod().Name} - {errorMsg}"); + return false; + } + } + + /// + /// MES叫料接口 - 内部异步实现 + /// + private static async Task MES_To_AGV_CallGoods_Async(string storageCode, string goodsCode) + { + int AID = -1; + try + { + string WMSIPPort = ConfigurationManager.AppSettings["AGVIPPort"]; + string url = $"http://{WMSIPPort}/wms/apiForThirdPartySys/callGoods"; + + var requestData = new MES_To_AGV_CallGoods_Req + { + storageCode = storageCode, + goodsCode = goodsCode + }; + + string json = JsonConvert.SerializeObject(requestData); + LogHelper.ShowMsg($"发起叫料请求 - 库位: {storageCode}, 物料号: {goodsCode} -> Send【{url}】{json}"); + AID = LogHelper.SaveWebApiReqLogo(url, json); + + var content = new StringContent(json, Encoding.UTF8, "application/json"); + var response = await httpClient.PostAsync(url, content); + var responseContent = await response.Content.ReadAsStringAsync(); + + LogHelper.ShowMsg($"叫料响应 - 库位: {storageCode}, 物料号: {goodsCode} -> Response【{url}】{responseContent}"); + + if (response.IsSuccessStatusCode) + { + // 解析WMS响应 + var wmsResponse = JsonConvert.DeserializeObject(responseContent); + + if (wmsResponse != null && wmsResponse.code == 200) + { + LogHelper.ShowMsg($"叫料成功 - 库位: {storageCode}, 物料号: {goodsCode}, 响应消息: {wmsResponse.msg}"); + LogHelper.SaveWebApiResLogo(AID, JsonConvert.SerializeObject(wmsResponse)); + return true; + } + else + { + LogHelper.ShowMsg($"叫料失败 - 库位: {storageCode}, 物料号: {goodsCode}, 错误信息: {wmsResponse?.msg ?? "未知错误"}"); + LogHelper.SaveWebApiResLogo(AID, JsonConvert.SerializeObject(wmsResponse)); + return false; + } + } + else + { + string msg = $"叫料HTTP请求失败 - 库位: {storageCode}, 物料号: {goodsCode}, 状态码: {response.StatusCode}, 响应: {responseContent}"; + LogHelper.ShowMsg(msg); + LogHelper.SaveWebApiResLogo(AID, msg); + return false; + } + } + catch (Exception err) + { + string errorMsg = $"叫料异常 - 库位: {storageCode}, 物料号: {goodsCode}, 异常详情: {err.Message}"; + LogHelper.ShowMsg(errorMsg); + Console.WriteLine($"错误: {MethodBase.GetCurrentMethod().Name} - {errorMsg}"); + if (AID > 0) + { + LogHelper.SaveWebApiResLogo(AID, errorMsg); + } + return false; + } + } + + /// + /// MES退料接口 - 同步版本,返回bool结果 + /// + /// 退料位置(库位号) + /// 物料号(型号) + /// 是否为空 0.空托 1.余料 + /// 是否成功 + public static bool MES_To_AGV_ReturnGoods(string storageCode, string goodsCode, int isEmpty) + { + try + { + var task = MES_To_AGV_ReturnGoods_Async(storageCode, goodsCode, isEmpty); + task.Wait(); // 同步等待异步任务完成 + return task.Result; + } + catch (Exception err) + { + string emptyTypeDesc = isEmpty == 0 ? "空托" : "余料"; + string errorMsg = $"退料同步调用异常 - 库位: {storageCode}, 物料号: {goodsCode}, 类型: {emptyTypeDesc}({isEmpty}), 异常: {err.Message}"; + LogHelper.ShowMsg(errorMsg); + Console.WriteLine($"错误: {MethodBase.GetCurrentMethod().Name} - {errorMsg}"); + return false; + } + } + + /// + /// MES退料接口 - 内部异步实现 + /// + private static async Task MES_To_AGV_ReturnGoods_Async(string storageCode, string goodsCode, int isEmpty) + { + int AID = -1; + try + { + string emptyTypeDesc = isEmpty == 0 ? "空托" : "余料"; + string WMSIPPort = ConfigurationManager.AppSettings["AGVIPPort"]; + string url = $"http://{WMSIPPort}/wms/apiForThirdPartySys/returnGoods"; + + var requestData = new MES_To_AGV_ReturnGoods_Req + { + storageCode = storageCode, + goodsCode = goodsCode, + isEmpty = isEmpty + }; + + string json = JsonConvert.SerializeObject(requestData); + LogHelper.ShowMsg($"发起退料请求 - 库位: {storageCode}, 物料号: {goodsCode}, 类型: {emptyTypeDesc}({isEmpty}) -> Send【{url}】{json}"); + AID = LogHelper.SaveWebApiReqLogo(url, json); + + var content = new StringContent(json, Encoding.UTF8, "application/json"); + var response = await httpClient.PostAsync(url, content); + var responseContent = await response.Content.ReadAsStringAsync(); + + LogHelper.ShowMsg($"退料响应 - 库位: {storageCode}, 物料号: {goodsCode}, 类型: {emptyTypeDesc}({isEmpty}) -> Response【{url}】{responseContent}"); + + if (response.IsSuccessStatusCode) + { + // 解析WMS响应 + var wmsResponse = JsonConvert.DeserializeObject(responseContent); + + if (wmsResponse != null && wmsResponse.code == 200) + { + LogHelper.ShowMsg($"退料成功 - 库位: {storageCode}, 物料号: {goodsCode}, 类型: {emptyTypeDesc}({isEmpty}), 响应消息: {wmsResponse.msg}"); + LogHelper.SaveWebApiResLogo(AID, JsonConvert.SerializeObject(wmsResponse)); + return true; + } + else + { + LogHelper.ShowMsg($"退料失败 - 库位: {storageCode}, 物料号: {goodsCode}, 类型: {emptyTypeDesc}({isEmpty}), 错误信息: {wmsResponse?.msg ?? "未知错误"}"); + LogHelper.SaveWebApiResLogo(AID, JsonConvert.SerializeObject(wmsResponse)); + return false; + } + } + else + { + string msg = $"退料HTTP请求失败 - 库位: {storageCode}, 物料号: {goodsCode}, 类型: {emptyTypeDesc}({isEmpty}), 状态码: {response.StatusCode}, 响应: {responseContent}"; + LogHelper.ShowMsg(msg); + LogHelper.SaveWebApiResLogo(AID, msg); + return false; + } + } + catch (Exception err) + { + string emptyTypeDesc = isEmpty == 0 ? "空托" : "余料"; + string errorMsg = $"退料异常 - 库位: {storageCode}, 物料号: {goodsCode}, 类型: {emptyTypeDesc}({isEmpty}), 异常详情: {err.Message}"; + LogHelper.ShowMsg(errorMsg); + Console.WriteLine($"错误: {MethodBase.GetCurrentMethod().Name} - {errorMsg}"); + if (AID > 0) + { + LogHelper.SaveWebApiResLogo(AID, errorMsg); + } + return false; + } + } + } +} \ No newline at end of file diff --git a/Common/02WebApiCall/WebApi/Helpers/LogHelper.cs b/Common/02WebApiCall/WebApi/Helpers/LogHelper.cs new file mode 100644 index 0000000..da517e3 --- /dev/null +++ b/Common/02WebApiCall/WebApi/Helpers/LogHelper.cs @@ -0,0 +1,76 @@ +using System; +using System.Collections.Generic; +using System.Data.SqlClient; +using System.Data; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using DataLinkMesWork; + + +namespace WebApi.Helpers +{ + public class LogHelper + { + /// + /// UUID生成 + /// + /// + public static string UuidUtil() + { + string result = Guid.NewGuid().ToString(); + return result; + } + + public static void ShowMsg(string msg) + { + MyLog4Net.MyLogHelper.Error("WebApi", msg); + } + + public static int SaveWebApiReqLogo(string url, string JSON) + { + int AID = -1; + try + { + //存储日志 + var CreateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"); + + string procedureName = "接口_IOT接口交互日志_请求记录"; + SqlParameter[] thisParms = new SqlParameter[4]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@接口地址", url); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@接口类型", 2); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@请求内容", JSON); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@请求时间", CreateTime); + SQLCommon.ExecuteStoredProcedure(procedureName, ApplicationConfig.ConnectionString_MES, out DataTable dt, out string errorMessage); + // DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out DataTable dt); + if (dt.Rows.Count > 0) + { + AID = Convert.ToInt32(dt.Rows[0]["AID"]); + } + } + catch (Exception ex) + { + + } + return AID; + } + + public static void SaveWebApiResLogo(int AID, string JSON) + { + try + { + //存储日志 + var CreateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"); + string procedureName = "接口_IOT接口交互日志_响应记录"; + SqlParameter[] thisParms = new SqlParameter[3]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@AID", AID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@响应时间", CreateTime); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@响应内容", JSON); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out DataTable dt); + } + catch (Exception ex) + { + } + } + } +} diff --git a/Common/02WebApiCall/WebApi/Helpers/ValidationHelper.cs b/Common/02WebApiCall/WebApi/Helpers/ValidationHelper.cs new file mode 100644 index 0000000..43e3a32 --- /dev/null +++ b/Common/02WebApiCall/WebApi/Helpers/ValidationHelper.cs @@ -0,0 +1,98 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; + +namespace WebApi.Helpers +{ + public class ValidationHelper + { + /// + /// 验证对象的必填字段 + /// + /// 要验证的对象类型 + /// 要验证的对象 + /// 错误信息 + /// 验证是否通过 + public static bool ValidateRequired(T obj, out string errorMessage) + { + errorMessage = string.Empty; + if (obj == null) + { + errorMessage = "对象不能为空"; + return false; + } + + var properties = typeof(T).GetProperties(); + foreach (var prop in properties) + { + var value = prop.GetValue(obj); + if (value == null) + { + errorMessage = $"【{prop.Name}不能为空】"; + return false; + } + //else if (prop.PropertyType == typeof(int) && (int)value == 0) + //{ + // errorMessage = $"【{prop.Name}不能为0】"; + // return false; + //} + else if (prop.PropertyType == typeof(string) && string.IsNullOrEmpty((string)value)) + { + errorMessage = $"【{prop.Name}不能为空】"; + return false; + } + else if (prop.PropertyType == typeof(object) && (object)value == null) + { + errorMessage = $"【{prop.Name}不能为空】"; + return false; + } + } + + return true; + } + + /// + /// 验证对象的指定字段 + /// + /// 要验证的对象类型 + /// 要验证的对象 + /// 要验证的属性名列表 + /// 错误信息 + /// 验证是否通过 + public static bool ValidateProperties(T obj, string[] propertyNames, out string errorMessage) + { + errorMessage = string.Empty; + if (obj == null) + { + errorMessage = "对象不能为空"; + return false; + } + + foreach (var propName in propertyNames) + { + var prop = typeof(T).GetProperty(propName); + if (prop == null) continue; + + var value = prop.GetValue(obj); + if (value == null) + { + errorMessage = $"【{propName}不能为空】"; + return false; + } + //else if (prop.PropertyType == typeof(int) && (int)value == 0) + //{ + // errorMessage = $"【{propName}不能为0】"; + // return false; + //} + else if (prop.PropertyType == typeof(string) && string.IsNullOrEmpty((string)value)) + { + errorMessage = $"【{propName}不能为空】"; + return false; + } + } + + return true; + } + } +} \ No newline at end of file diff --git a/Common/02WebApiCall/WebApi/Models/AGV_To_MES_AgvPass_Req.cs b/Common/02WebApiCall/WebApi/Models/AGV_To_MES_AgvPass_Req.cs new file mode 100644 index 0000000..429a67e --- /dev/null +++ b/Common/02WebApiCall/WebApi/Models/AGV_To_MES_AgvPass_Req.cs @@ -0,0 +1,12 @@ +using System; + +namespace WebApi.Models +{ + public class AGV_To_MES_AgvPass_Req + { + /// + /// 进入或离开 + /// + public string agvStatus { get; set; } + } +} \ No newline at end of file diff --git a/Common/02WebApiCall/WebApi/Models/MES_To_AGV_CallGoods_Req.cs b/Common/02WebApiCall/WebApi/Models/MES_To_AGV_CallGoods_Req.cs new file mode 100644 index 0000000..f4e39ea --- /dev/null +++ b/Common/02WebApiCall/WebApi/Models/MES_To_AGV_CallGoods_Req.cs @@ -0,0 +1,18 @@ +namespace WebApi.Models +{ + /// + /// MES叫料请求 + /// + public class MES_To_AGV_CallGoods_Req + { + /// + /// 叫料位置(库位号) + /// + public string storageCode { get; set; } + + /// + /// 物料号(型号) + /// + public string goodsCode { get; set; } + } +} diff --git a/Common/02WebApiCall/WebApi/Models/MES_To_AGV_ReturnGoods_Req.cs b/Common/02WebApiCall/WebApi/Models/MES_To_AGV_ReturnGoods_Req.cs new file mode 100644 index 0000000..21525cf --- /dev/null +++ b/Common/02WebApiCall/WebApi/Models/MES_To_AGV_ReturnGoods_Req.cs @@ -0,0 +1,23 @@ +namespace WebApi.Models +{ + /// + /// MES退料请求 + /// + public class MES_To_AGV_ReturnGoods_Req + { + /// + /// 退料位置(库位号) + /// + public string storageCode { get; set; } + + /// + /// 物料号(型号) + /// + public string goodsCode { get; set; } + + /// + /// 是否为空 0.空托 1.余料 + /// + public int isEmpty { get; set; } + } +} diff --git a/Common/02WebApiCall/WebApi/Models/WmsApiResponse.cs b/Common/02WebApiCall/WebApi/Models/WmsApiResponse.cs new file mode 100644 index 0000000..f6616a6 --- /dev/null +++ b/Common/02WebApiCall/WebApi/Models/WmsApiResponse.cs @@ -0,0 +1,23 @@ +namespace WebApi.Models +{ + /// + /// WMS接口响应 + /// + public class WmsApiResponse + { + /// + /// 状态码 200:成功 500:失败 + /// + public int code { get; set; } + + /// + /// 消息 + /// + public string msg { get; set; } + + /// + /// 返回数据 + /// + public object data { get; set; } + } +} \ No newline at end of file diff --git a/Common/02WebApiCall/WebApi/Models/msgResHeader.cs b/Common/02WebApiCall/WebApi/Models/msgResHeader.cs new file mode 100644 index 0000000..09b810b --- /dev/null +++ b/Common/02WebApiCall/WebApi/Models/msgResHeader.cs @@ -0,0 +1,23 @@ + +namespace WebApi.Models +{ + public class msgResHeader + { + /// + /// 成功时反馈“200”;失败时反馈“500” + /// + public string code + { + get; + set; + } + /// + /// 返回消息 + /// + public string message + { + get; + set; + } + } +} diff --git a/Common/02WebApiCall/packages.config b/Common/02WebApiCall/packages.config new file mode 100644 index 0000000..ce3dc38 --- /dev/null +++ b/Common/02WebApiCall/packages.config @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/Common/04DataBaseAccess/Common/dll/DataBaseAccess.dll b/Common/04DataBaseAccess/Common/dll/DataBaseAccess.dll new file mode 100644 index 0000000..137dc82 Binary files /dev/null and b/Common/04DataBaseAccess/Common/dll/DataBaseAccess.dll differ diff --git a/Common/04DataBaseAccess/Common/dll/DataBaseAccess.pdb b/Common/04DataBaseAccess/Common/dll/DataBaseAccess.pdb new file mode 100644 index 0000000..e9bf580 Binary files /dev/null and b/Common/04DataBaseAccess/Common/dll/DataBaseAccess.pdb differ diff --git a/Common/04DataBaseAccess/Common/dll/DoWhatPlc.dll b/Common/04DataBaseAccess/Common/dll/DoWhatPlc.dll new file mode 100644 index 0000000..34ab0bb Binary files /dev/null and b/Common/04DataBaseAccess/Common/dll/DoWhatPlc.dll differ diff --git a/Common/04DataBaseAccess/Common/dll/DoWhatPlc.pdb b/Common/04DataBaseAccess/Common/dll/DoWhatPlc.pdb new file mode 100644 index 0000000..e75a71b Binary files /dev/null and b/Common/04DataBaseAccess/Common/dll/DoWhatPlc.pdb differ diff --git a/Common/04DataBaseAccess/Common/dll/MQTTnet.Extensions.ManagedClient.dll b/Common/04DataBaseAccess/Common/dll/MQTTnet.Extensions.ManagedClient.dll new file mode 100644 index 0000000..99035f6 Binary files /dev/null and b/Common/04DataBaseAccess/Common/dll/MQTTnet.Extensions.ManagedClient.dll differ diff --git a/Common/04DataBaseAccess/Common/dll/MQTTnet.dll b/Common/04DataBaseAccess/Common/dll/MQTTnet.dll new file mode 100644 index 0000000..2951433 Binary files /dev/null and b/Common/04DataBaseAccess/Common/dll/MQTTnet.dll differ diff --git a/Common/04DataBaseAccess/Common/dll/MesWorkMqtt.dll b/Common/04DataBaseAccess/Common/dll/MesWorkMqtt.dll new file mode 100644 index 0000000..4834574 Binary files /dev/null and b/Common/04DataBaseAccess/Common/dll/MesWorkMqtt.dll differ diff --git a/Common/04DataBaseAccess/Common/dll/MesWorkMqtt.pdb b/Common/04DataBaseAccess/Common/dll/MesWorkMqtt.pdb new file mode 100644 index 0000000..fb10624 Binary files /dev/null and b/Common/04DataBaseAccess/Common/dll/MesWorkMqtt.pdb differ diff --git a/Common/04DataBaseAccess/Common/dll/Newtonsoft.Json.dll b/Common/04DataBaseAccess/Common/dll/Newtonsoft.Json.dll new file mode 100644 index 0000000..597a1ce Binary files /dev/null and b/Common/04DataBaseAccess/Common/dll/Newtonsoft.Json.dll differ diff --git a/Common/04DataBaseAccess/Common/dll/WebApiCall.dll b/Common/04DataBaseAccess/Common/dll/WebApiCall.dll new file mode 100644 index 0000000..a519e2a Binary files /dev/null and b/Common/04DataBaseAccess/Common/dll/WebApiCall.dll differ diff --git a/Common/04DataBaseAccess/Common/dll/WebApiCall.dll.config b/Common/04DataBaseAccess/Common/dll/WebApiCall.dll.config new file mode 100644 index 0000000..6035ea8 --- /dev/null +++ b/Common/04DataBaseAccess/Common/dll/WebApiCall.dll.config @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/Common/04DataBaseAccess/Common/dll/WebApiCall.pdb b/Common/04DataBaseAccess/Common/dll/WebApiCall.pdb new file mode 100644 index 0000000..16b7902 Binary files /dev/null and b/Common/04DataBaseAccess/Common/dll/WebApiCall.pdb differ diff --git a/Common/04DataBaseAccess/DataBaseAccess.sln b/Common/04DataBaseAccess/DataBaseAccess.sln new file mode 100644 index 0000000..87a94f3 --- /dev/null +++ b/Common/04DataBaseAccess/DataBaseAccess.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.32901.82 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "04-DataBaseAccess", "DataBaseAccess\04-DataBaseAccess.csproj", "{F434E066-4C59-47C8-AA82-6F48CC84501A}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {F434E066-4C59-47C8-AA82-6F48CC84501A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F434E066-4C59-47C8-AA82-6F48CC84501A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F434E066-4C59-47C8-AA82-6F48CC84501A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F434E066-4C59-47C8-AA82-6F48CC84501A}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {CB4AAB51-C433-4A0B-B835-FF7E3CB86238} + EndGlobalSection +EndGlobal diff --git a/Common/04DataBaseAccess/DataBaseAccess/04-DataBaseAccess.csproj b/Common/04DataBaseAccess/DataBaseAccess/04-DataBaseAccess.csproj new file mode 100644 index 0000000..6218853 --- /dev/null +++ b/Common/04DataBaseAccess/DataBaseAccess/04-DataBaseAccess.csproj @@ -0,0 +1,54 @@ + + + + + Debug + AnyCPU + {F434E066-4C59-47C8-AA82-6F48CC84501A} + Library + Properties + DataBaseAccess + 04DataBaseAccess + v4.8 + 512 + true + + + + true + full + false + ..\..\dll\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Common/04DataBaseAccess/DataBaseAccess/DataAccess.cs b/Common/04DataBaseAccess/DataBaseAccess/DataAccess.cs new file mode 100644 index 0000000..b04d9cf --- /dev/null +++ b/Common/04DataBaseAccess/DataBaseAccess/DataAccess.cs @@ -0,0 +1,611 @@ +using System; +using System.Collections.Generic; +using System.Collections.Specialized; +using System.Configuration; +using System.Data; +using System.Data.SqlClient; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace DataLinkMesWork +{ + public class DataAccess + { + public static string ConnectionString_MES = ConfigurationManager.AppSettings["ConnectionString_MES"]; + public static bool ExecuteNonQuery(string sql, string connectionString, out string errorMessage) + { + bool result = false; + errorMessage = ""; + using (SqlConnection conn = new SqlConnection(connectionString)) + { + try + { + using (SqlCommand cmd = new SqlCommand(sql, conn)) + { + //if (!SqlServerConnectionStatus) return false; + conn.Open(); + cmd.ExecuteNonQuery(); + } + //SqlServerConnectionStatus = true; + result = true; + } + catch (Exception e) + { + errorMessage = e.ToString(); + //TestConnection(); + //ApplicationLog.WriteLog(e, "\r\nExecuteNonQuery\r\nSQL��䣺\r\n" + sql + "\r\n�����ַ�����\r\n" + connectionString); + } + finally + { + if (conn.State == ConnectionState.Open) + conn.Close(); + } + } + return result; + + } + public static bool ExecuteDataset(string sql, string connectionString, out DataSet ds, out string errorMessage) + { + errorMessage = ""; + bool result = true; + errorMessage = ""; + ds = new DataSet(); + + /// SQLSERVER + /// SQLiteDB + try + { + //bool result = false; + errorMessage = ""; + ds = new DataSet(); + using (SqlConnection conn = new SqlConnection(connectionString)) + { + try + { + //if (!SqlServerConnectionStatus) return false; + conn.Open(); + using (SqlDataAdapter dsCommand = new SqlDataAdapter()) + { + dsCommand.SelectCommand = new SqlCommand(sql, conn); + dsCommand.Fill(ds); + } + //SqlServerConnectionStatus = true; + result = true; + } + catch (Exception e) + { + errorMessage = e.ToString(); + //TestConnection(); + //ApplicationLog.WriteLog(e, "\r\nExecuteNonQuery\r\nSQL��䣺\r\n" + sql + "\r\n�����ַ�����\r\n" + connectionString); + } + finally + { + if (conn.State == ConnectionState.Open) + conn.Close(); + } + } + return result; + } + catch (Exception err) + { + + } + + return result; + + + } + /// + /// 增 删 改 + /// + /// + /// + /// + public static bool ExecuteStoredProcedure(string procedureName, ref SqlParameter[] sqlParameters) + { + string connectionString = ConnectionString_MES; + string errorMessage; + bool result = false; + errorMessage = ""; + using (SqlConnection conn = new SqlConnection(connectionString)) + { + try + { + //if (!SqlServerConnectionStatus) return false; + conn.Open(); + using (SqlCommand cmd = new SqlCommand(procedureName, conn)) + { + cmd.CommandTimeout = 0; + cmd.CommandType = CommandType.StoredProcedure; + if (sqlParameters != null) + { + for (int i = 0; i < sqlParameters.Length; i++) + { + cmd.Parameters.Add(sqlParameters[i]); + } + } + cmd.ExecuteNonQuery(); + } + //SqlServerConnectionStatus = true; + result = true; + } + catch (Exception e) + { + errorMessage = e.ToString(); + if (conn.State == ConnectionState.Open) + conn.Close(); + //TestConnection(); + ////ApplicationLog.WriteLog(e, "\r\nExecuteStoredProcedure\r\n�洢���̣�\r\n" + procedureName + "\r\n�����ַ�����\r\n" + connectionString); + } + finally + { + if (conn.State == ConnectionState.Open) + conn.Close(); + } + } + return result; + } + public static bool ExecuteStoredProcedure(string procedureName, ref SqlParameter[] sqlParameters,out DataTable dt) + { + string connectionString = ConnectionString_MES; + string errorMessage; + bool result = false; + errorMessage = ""; + //ds = new DataSet(); + dt = new DataTable(); + using (SqlConnection conn = new SqlConnection(connectionString)) + { + try + { + //if (!SqlServerConnectionStatus) return false; + conn.Open(); + using (SqlDataAdapter dsCommand = new SqlDataAdapter()) + { + dsCommand.SelectCommand = new SqlCommand(procedureName, conn); + dsCommand.SelectCommand.CommandType = CommandType.StoredProcedure; + dsCommand.SelectCommand.CommandTimeout = 0; + if (sqlParameters != null) + { + for (int i = 0; i < sqlParameters.Length; i++) + { + dsCommand.SelectCommand.Parameters.Add(sqlParameters[i]); + } + } + + dsCommand.Fill(dt); + } + //SqlServerConnectionStatus = true; + result = true; + } + catch (Exception e) + { + errorMessage = e.ToString(); + //TestConnection(); + ////ApplicationLog.WriteLog(e, "\r\nExecuteStoredProcedure\r\n�洢���̣�\r\n" + procedureName + "\r\n�����ַ�����\r\n" + connectionString); + } + finally + { + if (conn.State == ConnectionState.Open) + conn.Close(); + } + } + return result; + } + public static bool ExecuteStoredProcedure(string procedureName, ref SqlParameter[] sqlParameters, out DataSet ds) + { + string connectionString = ConnectionString_MES; + string errorMessage; + bool result = false; + errorMessage = ""; + ds = new DataSet(); + using (SqlConnection conn = new SqlConnection(connectionString)) + { + try + { + //if (!SqlServerConnectionStatus) return false; + conn.Open(); + using (SqlDataAdapter dsCommand = new SqlDataAdapter()) + { + dsCommand.SelectCommand = new SqlCommand(procedureName, conn); + dsCommand.SelectCommand.CommandType = CommandType.StoredProcedure; + dsCommand.SelectCommand.CommandTimeout = 0; + if (sqlParameters != null) + { + for (int i = 0; i < sqlParameters.Length; i++) + { + dsCommand.SelectCommand.Parameters.Add(sqlParameters[i]); + } + } + + dsCommand.Fill(ds); + } + //SqlServerConnectionStatus = true; + result = true; + } + catch (Exception e) + { + errorMessage = e.ToString(); + //TestConnection(); + ////ApplicationLog.WriteLog(e, "\r\nExecuteStoredProcedure\r\n�洢���̣�\r\n" + procedureName + "\r\n�����ַ�����\r\n" + connectionString); + } + finally + { + if (conn.State == ConnectionState.Open) + conn.Close(); + } + } + return result; + } + public static bool ExecuteDataset(string sql, out DataSet ds) + { + string errorMessage; + string connectionString = ConnectionString_MES; + bool result = false; + errorMessage = ""; + ds = new DataSet(); + using (SqlConnection conn = new SqlConnection(connectionString)) + { + try + { + //if (!SqlServerConnectionStatus) return false; + conn.Open(); + using (SqlDataAdapter dsCommand = new SqlDataAdapter()) + { + dsCommand.SelectCommand = new SqlCommand(sql, conn); + dsCommand.Fill(ds); + } + //SqlServerConnectionStatus = true; + result = true; + } + catch (Exception e) + { + errorMessage = e.ToString(); + //TestConnection(); + ////ApplicationLog.WriteLog(e, "\r\nExecuteNonQuery\r\nSQL��䣺\r\n" + sql + "\r\n�����ַ�����\r\n" + connectionString); + } + finally + { + if (conn.State == ConnectionState.Open) + conn.Close(); + } + } + return result; + } + + public static bool ExecuteDataTable(string sql, out DataTable dt) + { + //public static bool ExecuteDataTable(string sql, string connectionString, out DataTable dt, out string errorMessage) + string errorMessage; + string connectionString = ConnectionString_MES; + bool result = false; + errorMessage = ""; + dt = new DataTable(); + using (SqlConnection conn = new SqlConnection(connectionString)) + { + try + { + //if (!SqlServerConnectionStatus) return false; + conn.Open(); + using (SqlDataAdapter dsCommand = new SqlDataAdapter()) + { + dsCommand.SelectCommand = new SqlCommand(sql, conn); + dsCommand.Fill(dt); + } + //SqlServerConnectionStatus = true; + result = true; + } + catch (Exception e) + { + errorMessage = e.ToString(); + //TestConnection(); + ////ApplicationLog.WriteLog(e, "\r\nExecuteNonQuery\r\nSQL��䣺\r\n" + sql + "\r\n�����ַ�����\r\n" + connectionString); + } + finally + { + if (conn.State == ConnectionState.Open) + conn.Close(); + } + } + return result; + } + + public static DataTable ExecuteSQL(string sql, ref SqlParameter[] sqlParameters) + { + string connectionString = ConnectionString_MES; + string err; + bool result = false; + err = ""; + DataTable dt = new DataTable(); + using (SqlConnection conn = new SqlConnection(connectionString)) + { + try + { + //if (!SqlServerConnectionStatus) return false; + conn.Open(); + using (SqlDataAdapter dsCommand = new SqlDataAdapter(sql, conn)) + { + if (sqlParameters != null) + { + for (int i = 0; i < sqlParameters.Length; i++) + { + dsCommand.SelectCommand.Parameters.Add(sqlParameters[i]); + } + } + dsCommand.Fill(dt); + } + result = true; + } + catch (Exception e) + { + err = e.ToString(); + ////ApplicationLog.WriteLog(e, "\r\nExecuteSelectMesWork\r\n" + sql + "\r\n" + connectionString); + } + finally + { + if (conn.State == ConnectionState.Open) + conn.Close(); + } + } + return dt; + } + + public static bool ExecuteSQL(string sql) + { + string connectionString = ConnectionString_MES; + string errorMessage; + bool result = false; + errorMessage = ""; + using (SqlConnection conn = new SqlConnection(connectionString)) + { + try + { + using (SqlCommand cmd = new SqlCommand(sql, conn)) + { + //if (!SqlServerConnectionStatus) return false; + conn.Open(); + cmd.ExecuteNonQuery(); + } + //SqlServerConnectionStatus = true; + result = true; + } + catch (Exception e) + { + errorMessage = e.ToString(); + //TestConnection(); + ////ApplicationLog.WriteLog(e, "\r\nExecuteNonQuery\r\nSQL��䣺\r\n" + sql + "\r\n�����ַ�����\r\n" + connectionString); + } + finally + { + if (conn.State == ConnectionState.Open) + conn.Close(); + } + } + return result; + } + + /// + /// 提供通用的调用存储过程的方法(增加数据的数据表的到数据库的调用) + /// + /// 存储过程名称 + /// 存储过程参数数组 + /// 增加数据的数据表 + /// + public static bool ExecuteStoredProcedure(string procedureName, ref SqlParameter[] sqlParameters, DataTable dt) + { + string connectionString = ConnectionString_MES; + string errorMessage; + bool result = false; + errorMessage = ""; + using (SqlConnection conn = new SqlConnection(connectionString)) + { + try + { + // if (!SqlServerConnectionStatus) return false; + conn.Open(); + using (SqlDataAdapter dsCommand = new SqlDataAdapter()) + { + dsCommand.InsertCommand = new SqlCommand(procedureName, conn); + dsCommand.InsertCommand.CommandType = CommandType.StoredProcedure; + for (int i = 0; i < sqlParameters.Length; i++) + { + dsCommand.InsertCommand.Parameters.Add(sqlParameters[i]); + } + if (dt == null) return false; + dt.AcceptChanges(); + for (int i = 0; i < dt.Rows.Count; i++) + { + dt.Rows[i].SetAdded(); + } + dsCommand.Update(dt); + } + //SqlServerConnectionStatus = true; + result = true; + } + catch (Exception e) + { + errorMessage = e.ToString(); + //TestConnection(); + ////ApplicationLog.WriteLog(e, "\r\nExecuteStoredProcedure\r\n�洢���̣�\r\n" + procedureName + "\r\n�����ַ�����\r\n" + connectionString); + } + finally + { + if (conn.State == ConnectionState.Open) + conn.Close(); + } + } + return result; + } + + /// + /// 提供通用的调用存储过程的方法(增加数据的数据表的到数据库的调用) + /// + /// + /// + /// + public static bool ExecuteStoredProcedure(string procedureName, out DataTable dt) + { + string connectionString = ConnectionString_MES; + string errorMessage; + bool result = false; + errorMessage = ""; + dt = new DataTable(); + using (SqlConnection conn = new SqlConnection(connectionString)) + { + try + { + + //if (!SqlServerConnectionStatus) return false; + conn.Open(); + using (SqlDataAdapter dsCommand = new SqlDataAdapter()) + { + dsCommand.SelectCommand = new SqlCommand(procedureName, conn); + dsCommand.SelectCommand.CommandType = CommandType.StoredProcedure; + + dsCommand.Fill(dt); + } + //SqlServerConnectionStatus = true; + result = true; + } + catch (Exception e) + { + errorMessage = e.ToString(); + //TestConnection(); + ////ApplicationLog.WriteLog(e, "\r\nExecuteStoredProcedure\r\n�洢���̣�\r\n" + procedureName + "\r\n�����ַ�����\r\n" + connectionString); + } + finally + { + if (conn.State == ConnectionState.Open) + conn.Close(); + } + } + return result; + } + + /// + /// + /// + /// + /// + /// + /// + public static bool ExecuteSQL(string sql, ref SqlParameter[] sqlParameters, DataTable dt) + { + string connectionString = ConnectionString_MES; + string errorMessage; + bool result = false; + errorMessage = ""; + using (SqlConnection conn = new SqlConnection(connectionString)) + { + + + try + { + // if (!SqlServerConnectionStatus) return false; + conn.Open(); + using (SqlDataAdapter dsCommand = new SqlDataAdapter()) + { + dsCommand.InsertCommand = new SqlCommand(sql, conn); + + for (int i = 0; i < sqlParameters.Length; i++) + { + sqlParameters[i].IsNullable = true; + dsCommand.InsertCommand.Parameters.Add(sqlParameters[i]); + } + if (dt == null) return false; + dt.AcceptChanges(); + for (int i = 0; i < dt.Rows.Count; i++) + { + dt.Rows[i].SetAdded(); + } + dsCommand.Update(dt); + } + //SqlServerConnectionStatus = true; + result = true; + } + catch (Exception e) + { + //ApplicationConfig.ConnectionStringPIS_NEW_Value = "0"; + //TestConnection(); + //errorMessage = e.ToString(); + ////ApplicationLog.WriteLog(e, "\r\nExecuteSQL\r\nSQL��䣺\r\n" + sql + "\r\n�����ַ�����\r\n" + connectionString); + } + finally + { + if (conn.State == ConnectionState.Open) + conn.Close(); + } + } + return result; + } + + public static bool ExecuteNonQuery_newID(string sql, out long newID) + { + sql += ";select @@identity"; + string connectionString; + connectionString = ConnectionString_MES; + using (SqlConnection conn = new SqlConnection(connectionString)) + { + try + { + using (SqlCommand cmd = new SqlCommand(sql, conn)) + { + conn.Open(); + newID = Convert.ToInt64(cmd.ExecuteScalar()); + } + return true; + } + catch (Exception e) + { + newID = 0; + //TestConnection(); + ////ApplicationLog.WriteLog(e, "\r\n ExecuteNonQuery_newID\r\n�洢���̣�\r\n" + sql + "\r\n�����ַ�����\r\n" + connectionString); + return false; + } + finally + { + if (conn.State == ConnectionState.Open) + conn.Close(); + } + } + } + + public static bool ExecuteOutNum(string sql, out int count) + { + string connectionString; + connectionString = ConnectionString_MES; + string errorMessage; + bool result = false; + errorMessage = ""; + using (SqlConnection conn = new SqlConnection(connectionString)) + { + count = 0; + try + { + using (SqlCommand cmd = new SqlCommand(sql, conn)) + { + //if (!SqlServerConnectionStatus) return false; + conn.Open(); + count = Convert.ToInt32(cmd.ExecuteScalar().ToString()); + } + //SqlServerConnectionStatus = true; + result = true; + } + catch (Exception e) + { + errorMessage = e.ToString(); + //TestConnection(); + ////ApplicationLog.WriteLog(e, "\r\nExecuteNonQuery\r\nSQL��䣺\r\n" + sql + "\r\n�����ַ�����\r\n" + connectionString); + } + finally + { + if (conn.State == ConnectionState.Open) + conn.Close(); + } + } + return result; + } + } + + +} diff --git a/Common/04DataBaseAccess/DataBaseAccess/JsonHelper.cs b/Common/04DataBaseAccess/DataBaseAccess/JsonHelper.cs new file mode 100644 index 0000000..5ec9f9c --- /dev/null +++ b/Common/04DataBaseAccess/DataBaseAccess/JsonHelper.cs @@ -0,0 +1,336 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Data; +using System.Runtime.Serialization.Json; +using System.Web.Script.Serialization; +//using System.Runtime.Serialization.Json; + +//using System.Runtime.Serialization.Json; + +public class JsonHelper +{ + #region 序列化和反序列化 + // 序列化 + public static string JsonSerializer(T t) + { + // 使用 DataContractJsonSerializer 将 T 对象序列化为内存流。 + DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(T)); + MemoryStream ms = new MemoryStream(); + // 使用 WriteObject 方法将 JSON 数据写入到流中。 + jsonSerializer.WriteObject(ms, t); + // 流转字符串 + string jsonString = Encoding.UTF8.GetString(ms.ToArray()); + ms.Close(); + //替换Json的Date字符串 + string p = @"\\/Date\((\d+)\+\d+\)\\/"; + MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertJsonDateToDateString); + Regex reg = new Regex(p); + jsonString = reg.Replace(jsonString, matchEvaluator); + return jsonString; + } + public static T JsonDeserialize(string jsonString) + { + //将"yyyy-MM-dd HH:mm:ss"格式的字符串转为"\/Date(1294499956278+0800)\/"格式 + string p = @"\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}"; + MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertDateStringToJsonDate); + Regex reg = new Regex(p); + jsonString = reg.Replace(jsonString, matchEvaluator); + DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(T)); + // 字符串转流 + MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)); + // 通过使用 DataContractJsonSerializer 的 ReadObject 方法,将 JSON 编码数据反序列化为T + T obj = (T)jsonSerializer.ReadObject(ms); + return obj; + } + public static string ConvertJsonDateToDateString(Match match) + { + string result = string.Empty; + DateTime dateTime = new DateTime(1970, 1, 1); + dateTime = dateTime.AddMilliseconds(long.Parse(match.Groups[1].Value)); + dateTime = dateTime.ToLocalTime(); + result = dateTime.ToString("yyyy-MM-dd HH:mm:ss"); + return result; + } + private static string ConvertDateStringToJsonDate(Match m) + { + string result = string.Empty; + DateTime dt = DateTime.Parse(m.Groups[0].Value); + dt = dt.ToUniversalTime(); + TimeSpan ts = dt - DateTime.Parse("1970-01-01"); + result = string.Format("\\/Date({0}+0800)\\/", ts.TotalMilliseconds); + return result; + } + #endregion + + // 对象转换为Json + public static string ObjectToJson(object obj) + { + JavaScriptSerializer js = new JavaScriptSerializer(); + js.MaxJsonLength = Int32.MaxValue; // 定义JavaScriptSerializer接受字符串的最大长度 hdk 20180524 + try + { + return js.Serialize(obj); + } + catch (Exception exception) + { + + throw new Exception(exception.Message); + } + } + // 数据表转化为集合 + public static List> DataTableToList(DataTable dt) + { + List> list = new List>(); + foreach (DataRow dataRow in dt.Rows) + { + Dictionary dic = new Dictionary(); + + + foreach (DataColumn dc in dt.Columns) + { + if (dataRow[dc.ColumnName].GetType() == typeof(DateTime)) + { + string str = Convert.ToDateTime(dataRow[dc.ColumnName]).ToString("yyyy-MM-dd HH:mm:ss"); + dic.Add(dc.ColumnName, str); + } + else if + (dataRow[dc.ColumnName].GetType() == typeof(byte[])) + { + string str = Convert.ToBase64String((byte[])dataRow[dc.ColumnName]); + dic.Add(dc.ColumnName, str); + } + else + { + dic.Add(dc.ColumnName, dataRow[dc.ColumnName]); + } + + //Type type1 = dt.Rows[0]["产品图片"].GetType(); + //Type type2 = typeof(byte[]); + + } + list.Add(dic); + } + return list; + } + /// + /// 表转换为Json + /// + /// + /// + public static string DataTableToJson(DataTable dt) + { + return ObjectToJson(DataTableToList(dt)); + } + /// + /// 将DataTable中的数据转换成JSON格式 + /// + /// 数据源DataTable + /// 是否输出数据总条数 + /// JSON中显示的数据总条数 + /// + public static string CreateJsonParameters(DataTable dt, bool displayCount, int totalcount) + { + StringBuilder JsonString = new StringBuilder(); + //Exception Handling + + if (dt != null) + { + JsonString.Append("{ "); + JsonString.Append("\"rows\":[ "); + for (int i = 0; i < dt.Rows.Count; i++) + { + JsonString.Append("{ "); + for (int j = 0; j < dt.Columns.Count; j++) + { + if (j < dt.Columns.Count - 1) + { + //if (dt.Rows[i][j] == DBNull.Value) continue; + if (dt.Columns[j].DataType == typeof(bool)) + { + JsonString.Append("\"" + dt.Columns[j].ColumnName.ToLower() + "\":" + + dt.Rows[i][j].ToString().ToLower() + ","); + } + else if (dt.Columns[j].DataType == typeof(string)) + { + JsonString.Append("\"" + dt.Columns[j].ColumnName.ToLower() + "\":" + + ObjectToJson(dt.Rows[i][j]).ToString() + ","); + //JsonString.Append("\"" + dt.Columns[j].ColumnName.ToLower() + "\":" + "\"" + + // dt.Rows[i][j].ToString().Replace("\"", "\\\"") + "\","); + } + else + { + JsonString.Append("\"" + dt.Columns[j].ColumnName.ToLower() + "\":" + "\"" + dt.Rows[i][j] + "\","); + } + } + else if (j == dt.Columns.Count - 1) + { + //if (dt.Rows[i][j] == DBNull.Value) continue; + if (dt.Columns[j].DataType == typeof(bool)) + { + JsonString.Append("\"" + dt.Columns[j].ColumnName.ToLower() + "\":" + + dt.Rows[i][j].ToString().ToLower()); + } + else if (dt.Columns[j].DataType == typeof(string)) + { + JsonString.Append("\"" + dt.Columns[j].ColumnName.ToLower() + "\":" + + ObjectToJson(dt.Rows[i][j]).ToString()); + //JsonString.Append("\"" + dt.Columns[j].ColumnName.ToLower() + "\":" + "\"" + + // dt.Rows[i][j].ToString().Replace("\"", "\\\"") + "\""); + } + else + { + JsonString.Append("\"" + dt.Columns[j].ColumnName.ToLower() + "\":" + "\"" + dt.Rows[i][j] + "\""); + } + } + } + /*end Of String*/ + if (i == dt.Rows.Count - 1) + { + JsonString.Append("} "); + } + else + { + JsonString.Append("}, "); + } + } + JsonString.Append("]"); + + if (displayCount) + { + JsonString.Append(","); + + JsonString.Append("\"total\":"); + JsonString.Append(totalcount); + } + + JsonString.Append("}"); + return JsonString.ToString().Replace("\n", ""); + } + else + { + return null; + } + } + public static string CreateJsonParameters(DataTable dt) + { + StringBuilder JsonString = new StringBuilder(); + //Exception Handling + + if (dt != null) + { + JsonString.Append("{ "); + JsonString.Append("\"rows\":[ "); + for (int i = 0; i < dt.Rows.Count; i++) + { + JsonString.Append("{ "); + for (int j = 0; j < dt.Columns.Count; j++) + { + if (j < dt.Columns.Count - 1) + { + //if (dt.Rows[i][j] == DBNull.Value) continue; + if (dt.Columns[j].DataType == typeof(bool)) + { + JsonString.Append("\"" + dt.Columns[j].ColumnName.ToLower() + "\":" + + dt.Rows[i][j].ToString().ToLower() + ","); + } + else if (dt.Columns[j].DataType == typeof(string)) + { + JsonString.Append("\"" + dt.Columns[j].ColumnName.ToLower() + "\":" + + ObjectToJson(dt.Rows[i][j]).ToString() + ","); + //JsonString.Append("\"" + dt.Columns[j].ColumnName.ToLower() + "\":" + "\"" + + // dt.Rows[i][j].ToString().Replace("\"", "\\\"") + "\","); + } + else + { + JsonString.Append("\"" + dt.Columns[j].ColumnName.ToLower() + "\":" + "\"" + dt.Rows[i][j] + "\","); + } + } + else if (j == dt.Columns.Count - 1) + { + //if (dt.Rows[i][j] == DBNull.Value) continue; + if (dt.Columns[j].DataType == typeof(bool)) + { + JsonString.Append("\"" + dt.Columns[j].ColumnName.ToLower() + "\":" + + dt.Rows[i][j].ToString().ToLower()); + } + else if (dt.Columns[j].DataType == typeof(string)) + { + JsonString.Append("\"" + dt.Columns[j].ColumnName.ToLower() + "\":" + + ObjectToJson(dt.Rows[i][j]).ToString()); + //JsonString.Append("\"" + dt.Columns[j].ColumnName.ToLower() + "\":" + "\"" + + // dt.Rows[i][j].ToString().Replace("\"", "\\\"") + "\""); + } + else + { + JsonString.Append("\"" + dt.Columns[j].ColumnName.ToLower() + "\":" + "\"" + dt.Rows[i][j] + "\""); + } + } + } + /*end Of String*/ + if (i == dt.Rows.Count - 1) + { + JsonString.Append("} "); + } + else + { + JsonString.Append("}, "); + } + } + JsonString.Append("]"); + + JsonString.Append("}"); + return JsonString.ToString().Replace("\n", ""); + } + else + { + return null; + } + } + StringBuilder result = new StringBuilder(); + StringBuilder sb = new StringBuilder(); + /// + /// 根据DataTable生成EasyUI Tree Json树结构 + /// + /// 数据源 + /// ID列 + /// Text列 + /// 节点Url + /// 关系字段 + /// 父ID + public string GetTreeJsonByTable(DataTable tabel, string idCol, string txtCol, string url, string rela, object pId) + { + result.Append(sb.ToString()); + sb.Clear(); + if (tabel.Rows.Count > 0) + { + sb.Append("["); + string filer = string.Format("{0}='{1}'", rela, pId); + DataRow[] rows = tabel.Select(filer); + if (rows.Length > 0) + { + foreach (DataRow row in rows) + { + sb.Append("{\"id\":\"" + row[idCol] + "\",\"text\":\"" + row[txtCol] + "\",\"attributes\":\"" + row[url] + "\",\"state\":\"open\""); + if (tabel.Select(string.Format("{0}='{1}'", rela, row[idCol])).Length > 0) + { + sb.Append(",\"children\":"); + GetTreeJsonByTable(tabel, idCol, txtCol, url, rela, row[idCol]); + result.Append(sb.ToString()); + sb.Clear(); + } + result.Append(sb.ToString()); + sb.Clear(); + sb.Append("},"); + } + sb = sb.Remove(sb.Length - 1, 1); + } + sb.Append("]"); + result.Append(sb.ToString()); + sb.Clear(); + } + return result.ToString(); + } +} \ No newline at end of file diff --git a/Common/04DataBaseAccess/DataBaseAccess/Properties/AssemblyInfo.cs b/Common/04DataBaseAccess/DataBaseAccess/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..34eb61c --- /dev/null +++ b/Common/04DataBaseAccess/DataBaseAccess/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// 有关程序集的一般信息由以下 +// 控制。更改这些特性值可修改 +// 与程序集关联的信息。 +[assembly: AssemblyTitle("DataBaseAccess")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("DataBaseAccess")] +[assembly: AssemblyCopyright("Copyright © 2022")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// 将 ComVisible 设置为 false 会使此程序集中的类型 +//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型 +//请将此类型的 ComVisible 特性设置为 true。 +[assembly: ComVisible(false)] + +// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID +[assembly: Guid("f434e066-4c59-47c8-aa82-6f48cc84501a")] + +// 程序集的版本信息由下列四个值组成: +// +// 主版本 +// 次版本 +// 生成号 +// 修订号 +// +//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值 +//通过使用 "*",如下所示: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Common/07WebBusinessFacade/BusinessFacade.sln b/Common/07WebBusinessFacade/BusinessFacade.sln new file mode 100644 index 0000000..dd3b15d --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.32901.82 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "07BusinessFacade", "BusinessFacade\07BusinessFacade.csproj", "{F0A0C525-03FD-428A-9B17-7F54AA0E4475}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {F0A0C525-03FD-428A-9B17-7F54AA0E4475}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F0A0C525-03FD-428A-9B17-7F54AA0E4475}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F0A0C525-03FD-428A-9B17-7F54AA0E4475}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F0A0C525-03FD-428A-9B17-7F54AA0E4475}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {855F5203-2363-4447-B96A-9A6FE08E1E46} + EndGlobalSection +EndGlobal diff --git a/Common/07WebBusinessFacade/BusinessFacade/05Biz/MES/EngineIDCode.cs b/Common/07WebBusinessFacade/BusinessFacade/05Biz/MES/EngineIDCode.cs new file mode 100644 index 0000000..0a7e003 --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/05Biz/MES/EngineIDCode.cs @@ -0,0 +1,105 @@ +using System; +using System.Data; +using System.Data.SqlClient; + +using System.Collections; +using System.Collections.Specialized; +//using SystemFramework; +using DataLinkMesWork; +namespace SystemFramework +{ + +} +namespace bizFacade +{ + /// + /// 电子看板信息系统 + /// select 重量1,重量2,重量差,允许重量差,合格标志 + /// + public partial class BaseDataSystemMES + { + + /// + /// 电子看板_发动机号_分线组件装配关系_增加 + /// + /// + /// + /// + /// + static public void MailLineAndSubLineData_Insert(string engineID, int engineTypeID, string engineType, string engineID_SubLine) + { + string procedureName; + procedureName = "电子看板_发动机号_分线组件装配关系_增加"; + SqlParameter[] thisParms = new SqlParameter[4]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@发动机号_分线", engineID_SubLine); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@发动机号", engineID); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@机型代码", engineTypeID); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@发动机型号", engineType); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } + /// + /// 电子看板_发动机号_线首工位_查询_根据发动机号 + /// select 工位号,订单号,发动机号,基本机型,机型代码,发动机型号,托盘号, + /// 条码类型,零件流水号,零件流水号带空格,壳体编号型号,壳体编号型号带空格,QR码 + /// from dbo.电子看板_发动机号_线首工位 + /// where 发动机号=@发动机号 and 是否禁用=0 + /// + /// + /// + /// + static public void GetEngineID_Select(string opName,string engineID, out DataTable dt) + { + string procedureName; + procedureName = "电子看板_发动机号_线首工位_查询_根据发动机号"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@发动机号", engineID); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out dt); + } + + /// + /// 测量数据工位_监控系统_操作者工号_是否登录 + /// + /// + /// + /// + static public void CheckUser_IsLogin(string opName, out DataTable dt) + { + string procedureName; + procedureName = "测量数据工位_监控系统_操作者工号_是否登录"; + SqlParameter[] thisParms = new SqlParameter[1]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out dt); + } + + static public void SubLineLoadPartCountMatch_Update( string opName, int SubLineLoadPartCountMatch) + { + string procedureName; + procedureName = "MES_计划BOM_工位与名称_工步属性修改"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@工步属性", SubLineLoadPartCountMatch); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } + + + static public void SubLineLoadPartCountMatch_Select(string opName, out int SubLineLoadPartCountMatch) + { + string procedureName; + DataTable dt; + procedureName = "MES_计划BOM_工位与名称_工步属性查询"; + SqlParameter[] thisParms = new SqlParameter[1]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out dt); + if(dt.Rows.Count>0) + { + SubLineLoadPartCountMatch = Convert.ToInt32(dt.Rows[0][0]); + } + else + { + SubLineLoadPartCountMatch = 0; + } + } + + } +} diff --git a/Common/07WebBusinessFacade/BusinessFacade/05Biz/MES/Materials.cs b/Common/07WebBusinessFacade/BusinessFacade/05Biz/MES/Materials.cs new file mode 100644 index 0000000..371a141 --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/05Biz/MES/Materials.cs @@ -0,0 +1,204 @@ +using DataLinkMesWork; +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.SqlClient; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace bizFacade +{ + public partial class BaseDataSystemMES + { + /// + /// 测量数据工位_监控系统_自动手动_查询 + /// + /// + /// + public static DataTable OpName_MIS_AutoOrMaunal_Select(string opName) + { + DataTable dt = null; + string sql; + sql = "SELECT top 1 自动手动 from 测量数据工位_监控系统_自动手动 where 工位号='" + opName + "' "; + DataAccess.ExecuteDataTable(sql, out dt); + return dt; + } + /// + /// 订单下达到线首工位 + /// 北汽福田工位状态监控MOBY_增加_线首工位订单下达 + /// + /// + /// + public static void OrderWorkStartToOpName(string opName,string orderForm) + { + string procedureName = "北汽福田工位状态监控MOBY_增加_线首工位订单下达"; + SqlParameter[] thisParms = new SqlParameter[3]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@订单号", orderForm); + + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } + + /// + /// 电子看板_发动机号_线首工位_流水号_修改 + /// + /// + /// + /// + static public bool FirstOpName_Code_Update(string opName, string engineID, string partcode) + { + string procedureName = "电子看板_发动机号_线首工位_流水号_修改"; + SqlParameter[] thisParms = new SqlParameter[3]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@发动机号", engineID); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@托盘号", partcode); + if (DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms)) + { + return true; + } + else + { + return false; + } + } + + /// + /// 测量数据工位_监控系统_自动手动_增加 + /// + /// + /// + /// + public static bool OpName_MIS_AutoOrMaunal_Insert(string opName, int isAutoOrManul) + { + string produceName = "测量数据工位_监控系统_自动手动_增加"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@自动手动", isAutoOrManul); + return DataAccess.ExecuteStoredProcedure(produceName, ref thisParms); + } + + /// + /// MES_装配数据_零部件追溯_增加_不合格 + /// + /// + /// + /// + public static bool Material_Insert_NG(string opName, int m_ConfirmOkGo) + { + string produceName = "MES_装配数据_零部件追溯_增加_不合格"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@放行方式", m_ConfirmOkGo); + return DataAccess.ExecuteStoredProcedure(produceName, ref thisParms); + } + + /// + /// 测量数据工位_监控系统_手动打印_查询 + /// + /// + /// + /// + public static bool OpName_MIS_MaualPrint_Select(string opName, out DataTable dt) + { + string sql; + sql = "SELECT top 1 * FROM [测量数据工位_监控系统_手动打印] " + + "where 工位号='" + opName + "'"; + return DataAccess.ExecuteDataTable(sql, out dt); + } + /// + /// 测量数据工位_监控系统_MOBY_查询 + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + public static bool OpName_MIS_CreateMoby_Select(string opName, + out string orderForm, out int engineTypeID, out string engineType, + out string engineID, out string palletCode, out int isRepair, out string repairCode) + { + orderForm = ""; + engineTypeID = 0; + engineType = ""; + engineID = ""; + palletCode = ""; + isRepair = 0; + repairCode = ""; + + string produceName = "测量数据工位_监控系统_创建发动机号_扫描方式"; + SqlParameter[] thisParms = new SqlParameter[8]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@订单号", SqlDbType.NVarChar, 50); + thisParms[1].Direction = ParameterDirection.Output; + thisParms[2] = new System.Data.SqlClient.SqlParameter("@产品型号代码", SqlDbType.Int, 4); + thisParms[2].Direction = ParameterDirection.Output; + thisParms[3] = new System.Data.SqlClient.SqlParameter("@发动机型号", SqlDbType.NVarChar, 50); + thisParms[3].Direction = ParameterDirection.Output; + thisParms[4] = new System.Data.SqlClient.SqlParameter("@发动机号", SqlDbType.NVarChar, 50); + thisParms[4].Direction = ParameterDirection.Output; + thisParms[5] = new System.Data.SqlClient.SqlParameter("@托盘号", SqlDbType.NVarChar, 50); + thisParms[5].Direction = ParameterDirection.Output; + thisParms[6] = new System.Data.SqlClient.SqlParameter("@拆解标志", SqlDbType.Int, 4); + thisParms[6].Direction = ParameterDirection.Output; + thisParms[7] = new System.Data.SqlClient.SqlParameter("@拆解返修条码", SqlDbType.NVarChar, 50); + thisParms[7].Direction = ParameterDirection.Output; + if (DataAccess.ExecuteStoredProcedure(produceName, ref thisParms)) + { + orderForm = thisParms[1].Value.ToString(); + engineTypeID = Convert.ToInt32(thisParms[2].Value); + engineType = thisParms[3].Value.ToString(); + engineID = thisParms[4].Value.ToString(); + palletCode = thisParms[5].Value.ToString(); + isRepair = Convert.ToInt32(thisParms[6].Value); + repairCode = thisParms[7].Value.ToString(); + return true; + } + return false; + } + + /// + /// 电子看板_工位机型_质量数据测量位置_临时表_查询_完成情况 + /// + /// 工位号 + /// 拧紧序号 + /// 套筒号 + /// 工步属性 + /// 是否全部完成 + /// + public static bool MesServer_ShaftPosition_Select_FinishResult(string opName, out int ProcessCode, out int BoltCode, out int workStepProperty, out bool sn_WorkingStepIsOver) + { + BoltCode = 0; + ProcessCode = 512; + workStepProperty = 0; + sn_WorkingStepIsOver = true; + + string produceName = "电子看板_工位机型_质量数据测量位置_临时表_查询_完成情况"; + SqlParameter[] thisParms = new SqlParameter[5]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@拧紧序号", SqlDbType.Int, 4); + thisParms[1].Direction = ParameterDirection.Output; + thisParms[2] = new System.Data.SqlClient.SqlParameter("@套筒号", SqlDbType.Int, 4); + thisParms[2].Direction = ParameterDirection.Output; + thisParms[3] = new System.Data.SqlClient.SqlParameter("@工步属性", SqlDbType.Int, 4); + thisParms[3].Direction = ParameterDirection.Output; + thisParms[4] = new System.Data.SqlClient.SqlParameter("@是否全部完成", SqlDbType.Int, 4); + thisParms[4].Direction = ParameterDirection.Output; + if (DataAccess.ExecuteStoredProcedure(produceName, ref thisParms)) + { + ProcessCode = Convert.ToInt32(thisParms[1].Value); + BoltCode = Convert.ToInt32(thisParms[2].Value); + workStepProperty = Convert.ToInt32(thisParms[3].Value); + sn_WorkingStepIsOver = Convert.ToBoolean(thisParms[4].Value); + return true; + } + return false; + } + + + } +} diff --git a/Common/07WebBusinessFacade/BusinessFacade/05Biz/MES/OpName.MainForm.Launch.cs b/Common/07WebBusinessFacade/BusinessFacade/05Biz/MES/OpName.MainForm.Launch.cs new file mode 100644 index 0000000..2967908 --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/05Biz/MES/OpName.MainForm.Launch.cs @@ -0,0 +1,447 @@ +using System; +using System.Data; +using System.Data.SqlClient; +using DataLinkMesWork; +using System.Collections; +using System.Collections.Specialized; +using SystemFramework; + +namespace bizFacade +{ + /// + /// 电子看板信息系统 + /// + public partial class BaseDataSystemMES + { + ///// + ///// 电子看板_发动机号_线首工位_创建线首发动机号_根据输入机型代码_手动方式 + ///// + ///// 工位号 + ///// 发动机型号 + ///// 年份 + ///// 月份 + ///// 日期 + ///// 流水号 + ///// @是否分线 bit=0 @是否分线 = 0 总线线首(OP2010);=1分线线首(OP1010,OP2100) + ///// + //static public void GetEngineID_Manual(string opName, string engineType, string engineYear, string engineMoon, string engineDay, int engineNumber, bool isSubLine, out DataTable dt) + //{ + // string procedureName; + // procedureName = "电子看板_发动机号_线首工位_创建线首发动机号_根据输入机型代码_手动方式"; + // SqlParameter[] thisParms = new SqlParameter[7]; + // thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + // thisParms[1] = new System.Data.SqlClient.SqlParameter("@发动机型号", engineType); + // thisParms[2] = new System.Data.SqlClient.SqlParameter("@年份", engineYear); + // thisParms[3] = new System.Data.SqlClient.SqlParameter("@月份", engineMoon); + // thisParms[4] = new System.Data.SqlClient.SqlParameter("@日期", engineDay); + // thisParms[5] = new System.Data.SqlClient.SqlParameter("@流水号", engineNumber); + // thisParms[6] = new System.Data.SqlClient.SqlParameter("@是否分线", isSubLine); + // DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out dt); + //} + + /// + /// 电子看板_发动机号_线首工位_创建线首发动机号_根据输入机型代码 + /// 工件机型,机型代码,工件编号,壳体编号型号,工件流水号,QR码,基本流水号 + /// + /// 工位号 + /// 发动机型号 + /// 托盘号 = 0 总线线首(OP2010);=1分线线首(OP1010,OP2100) + /// 工件机型,机型代码,工件编号,壳体编号型号,工件流水号,QR码,基本流水号 + static public void GetEngineID_Auto(string opName, string engineType, string palletCode, out DataTable dt) + { + try + { + string procedureName; + procedureName = "电子看板_发动机号_线首工位_创建线首发动机号_根据输入机型代码"; + SqlParameter[] thisParms = new SqlParameter[3]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@发动机型号", engineType); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@托盘号", palletCode); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out dt); + } + catch (Exception err) + { + dt = null; + } + } + + /// + /// 分线线首号生成 + /// + /// + /// + /// + /// + static public void GetEngineID_Auto_branch(string opName, string engineType, string partcode, out DataTable dt) + { + string procedureName; + procedureName = "电子看板_发动机号_线首工位_创建线首发动机号_根据输入机型代码_分线"; + SqlParameter[] thisParms = new SqlParameter[3]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@发动机型号", engineType); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@托盘号", partcode); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out dt); + } + /// + /// 电子看板_发动机号_线首工位_创建线首发动机号_根据输入机型代码_分线_手动方式 + /// + /// + /// + /// + /// + /// + /// + /// + /// + static public void GetEngineID_Manual_branch(string opName, string engineType, string engineYear, string engineMoon, string engineDay, int engineNumber, bool isSubLine, out DataTable dt) + { + string procedureName; + procedureName = "电子看板_发动机号_线首工位_创建线首发动机号_根据输入机型代码_分线_手动方式"; + SqlParameter[] thisParms = new SqlParameter[7]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@发动机型号", engineType); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@年份", engineYear); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@月份", engineMoon); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@日期", engineDay); + thisParms[5] = new System.Data.SqlClient.SqlParameter("@流水号", engineNumber); + thisParms[6] = new System.Data.SqlClient.SqlParameter("@是否分线", isSubLine); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out dt); + } + + ///// + ///// [电子看板_发动机号_线首工位_手动方式_增加] + ///// + ///// 工位号 + ///// 订单号 + ///// 托盘号 + ///// 工件机型 + ///// 工件机型,机型代码,工件编号, 壳体编号型号,工件流水号,QR码,基本流水号 + //static public bool GetEngineID_ManulEngine_Save(string opName, string orderForm, string PartPalletCode, string engineType, string EngineID_DateTime, DataTable dt) + //{ + // string engineID; + // int engineTypeID; + // string partCode_Space; + // string partCode; + // string shellCode; + // string shellCode_Space; + // string QR_Code; + // int engineCount; + // int barCodeType; + // string engineTypeBase; + // string partCode_Text; + // string partCode_BarCode; + // string engineType_Text; + // string engineType_BarCode; + + // try + // { + // GetEngineIDFromFirstOpName(out engineID, out engineTypeID, out partCode_Space, + // out partCode, out shellCode, out shellCode_Space, out QR_Code, + // out engineCount, out barCodeType, out engineTypeBase, + // out partCode_Text, out partCode_BarCode, out engineType_Text, out engineType_BarCode, dt); + + + // string procedureName; + // procedureName = "电子看板_发动机号_线首工位_手动方式_增加"; + // SqlParameter[] thisParms = new SqlParameter[19]; + // thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + // thisParms[1] = new System.Data.SqlClient.SqlParameter("@订单号", orderForm); + // thisParms[2] = new System.Data.SqlClient.SqlParameter("@发动机号", engineID); + // thisParms[3] = new System.Data.SqlClient.SqlParameter("@发动机型号", engineType); + // thisParms[4] = new System.Data.SqlClient.SqlParameter("@基本机型", engineTypeBase); + // thisParms[5] = new System.Data.SqlClient.SqlParameter("@机型代码", engineTypeID); + // thisParms[6] = new System.Data.SqlClient.SqlParameter("@托盘号", PartPalletCode); + // thisParms[7] = new System.Data.SqlClient.SqlParameter("@条码类型", barCodeType); + // thisParms[8] = new System.Data.SqlClient.SqlParameter("@零件流水号", partCode); + // thisParms[9] = new System.Data.SqlClient.SqlParameter("@零件流水号带空格", partCode_Space); + // thisParms[10] = new System.Data.SqlClient.SqlParameter("@壳体编号型号", shellCode); + // thisParms[11] = new System.Data.SqlClient.SqlParameter("@壳体编号型号带空格", shellCode_Space); + // thisParms[12] = new System.Data.SqlClient.SqlParameter("@QR码", QR_Code); + // thisParms[13] = new System.Data.SqlClient.SqlParameter("@基本流水号", engineCount); + // thisParms[14] = new System.Data.SqlClient.SqlParameter("@流水号文本", partCode_Text); + // thisParms[15] = new System.Data.SqlClient.SqlParameter("@流水号条码", partCode_BarCode); + // thisParms[16] = new System.Data.SqlClient.SqlParameter("@型号文本", engineType_Text); + // thisParms[17] = new System.Data.SqlClient.SqlParameter("@型号条码", engineType_BarCode); + // thisParms[18] = new System.Data.SqlClient.SqlParameter("@工件编号时间", EngineID_DateTime); + + // return DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + // // return DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out dt); + // } + + // catch (Exception err) + // { + // ////ApplicationLog.WriteLog(err, err.Message); + // return false; + + // } + //} + + + ///// + ///// 电子看板_发动机号_线首工位_增加 + ///// + ///// 工位号 + ///// 订单号 + ///// 托盘号 + ///// 工件机型 + ///// 工件机型,机型代码,工件编号, 壳体编号型号,工件流水号,QR码,基本流水号 + //static public bool GetEngineID_Save(string opName, string orderForm, string PartPalletCode, string engineType, DataTable dt) + //{ + // string engineID; + // int engineTypeID; + // string partCode_Space; + // string partCode; + // string shellCode; + // string shellCode_Space; + // string QR_Code; + // int engineCount; + // int barCodeType; + // string engineTypeBase; + // string partCode_Text; + // string partCode_BarCode; + // string engineType_Text; + // string engineType_BarCode; + // string codeCreatetime; + // string a_code; + // string b_code; + // string c_code; + // string d_code; + + // try + // { + // GetEngineIDFromFirstOpName_Auto(out engineID, out engineTypeID, out partCode_Space, + // out partCode, out shellCode, out shellCode_Space, out QR_Code, + // out engineCount, out barCodeType, out engineTypeBase, + // out partCode_Text, out partCode_BarCode, out engineType_Text, out engineType_BarCode, out codeCreatetime, + // out a_code, out b_code, out c_code, out d_code, + // dt); + + + // string procedureName; + // procedureName = "电子看板_发动机号_线首工位_增加"; + // SqlParameter[] thisParms = new SqlParameter[23]; + // thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + // thisParms[1] = new System.Data.SqlClient.SqlParameter("@订单号", orderForm); + // thisParms[2] = new System.Data.SqlClient.SqlParameter("@发动机号", engineID); + // thisParms[3] = new System.Data.SqlClient.SqlParameter("@发动机型号", engineType); + // thisParms[4] = new System.Data.SqlClient.SqlParameter("@基本机型", engineTypeBase); + // thisParms[5] = new System.Data.SqlClient.SqlParameter("@机型代码", engineTypeID); + // thisParms[6] = new System.Data.SqlClient.SqlParameter("@托盘号", PartPalletCode); + // thisParms[7] = new System.Data.SqlClient.SqlParameter("@条码类型", barCodeType); + // thisParms[8] = new System.Data.SqlClient.SqlParameter("@零件流水号", partCode); + // thisParms[9] = new System.Data.SqlClient.SqlParameter("@零件流水号带空格", partCode_Space); + // thisParms[10] = new System.Data.SqlClient.SqlParameter("@壳体编号型号", shellCode); + // thisParms[11] = new System.Data.SqlClient.SqlParameter("@壳体编号型号带空格", shellCode_Space); + // thisParms[12] = new System.Data.SqlClient.SqlParameter("@QR码", QR_Code); + // thisParms[13] = new System.Data.SqlClient.SqlParameter("@基本流水号", engineCount); + // thisParms[14] = new System.Data.SqlClient.SqlParameter("@流水号文本", partCode_Text); + // thisParms[15] = new System.Data.SqlClient.SqlParameter("@流水号条码", partCode_BarCode); + // thisParms[16] = new System.Data.SqlClient.SqlParameter("@型号文本", engineType_Text); + // thisParms[17] = new System.Data.SqlClient.SqlParameter("@型号条码", engineType_BarCode); + // thisParms[18] = new System.Data.SqlClient.SqlParameter("@条码创建时间", codeCreatetime); + // thisParms[19] = new System.Data.SqlClient.SqlParameter("@总成代码", a_code); + // thisParms[20] = new System.Data.SqlClient.SqlParameter("@零件图号", b_code); + // thisParms[21] = new System.Data.SqlClient.SqlParameter("@邓氏码", c_code); + // thisParms[22] = new System.Data.SqlClient.SqlParameter("@VPPS码", d_code); + + + // return DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + // // return DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out dt); + // } + + // catch (Exception err) + // { + // ////ApplicationLog.WriteLog(err, err.Message); + // return false; + + // } + //} + + /// + /// 电子看板_发动机号_线首工位_增加 + /// + /// 工位号 + /// 订单号 + /// 托盘号 + /// 工件机型 + /// 工件机型,机型代码,工件编号, 壳体编号型号,工件流水号,QR码,基本流水号 + static public bool GetEngineID_Save_Outline(string opName, string orderForm, string PartPalletCode, string engineType, int engineTypeID, string engineID, string barCodeType) + { + + try + { + string procedureName; + procedureName = "电子看板_发动机号_线首工位_增加"; + SqlParameter[] thisParms = new SqlParameter[19]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@订单号", orderForm); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@发动机号", engineID); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@发动机型号", engineType); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@基本机型", engineType); + thisParms[5] = new System.Data.SqlClient.SqlParameter("@机型代码", engineTypeID); + thisParms[6] = new System.Data.SqlClient.SqlParameter("@托盘号", PartPalletCode); + thisParms[7] = new System.Data.SqlClient.SqlParameter("@条码类型", barCodeType); + thisParms[8] = new System.Data.SqlClient.SqlParameter("@零件流水号", engineID); + thisParms[9] = new System.Data.SqlClient.SqlParameter("@零件流水号带空格", engineID); + thisParms[10] = new System.Data.SqlClient.SqlParameter("@壳体编号型号", engineType); + thisParms[11] = new System.Data.SqlClient.SqlParameter("@壳体编号型号带空格", engineType); + thisParms[12] = new System.Data.SqlClient.SqlParameter("@QR码", engineID); + thisParms[13] = new System.Data.SqlClient.SqlParameter("@基本流水号", 1); + thisParms[14] = new System.Data.SqlClient.SqlParameter("@流水号文本", engineID); + thisParms[15] = new System.Data.SqlClient.SqlParameter("@流水号条码", engineID); + thisParms[16] = new System.Data.SqlClient.SqlParameter("@型号文本", engineType); + thisParms[17] = new System.Data.SqlClient.SqlParameter("@型号条码", engineType); + thisParms[18] = new System.Data.SqlClient.SqlParameter("@条码创建时间", DateTime.Now.ToShortDateString()); + return DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } + + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, err.Message); + return false; + + } + } + /// + /// 电子看板_装配零件_盆子类型_查询 + /// + static public DataTable WorkPlatePartSelect(string opName, string engineID) + { + try + { + DataTable dt = new DataTable(); + string procedureName; + procedureName = "电子看板_装配零件_盆子类型_查询"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@发动机型号", engineID); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out dt); + return dt; + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, err.Message); + return null; + } + } + /// + /// [电子看板_发动机号_线首工位]信息手动用 + /// + /// 发动机号 + /// 机型代码 + /// 零件流水号带空格 + /// 零件流水号 + /// 壳体编号型号 + /// 壳体编号型号带空格 + /// QR码 + /// 基本流水号 + /// 条码类型 + /// 基本机型 + /// 流水号文本 + /// 流水号条码 + /// 型号文本 + /// 型号条码 + /// + //static public void GetEngineIDFromFirstOpName(out string engineID, out int engineTypeID, out string partCode_Space, + // out string partCode, out string shellCode, out string shellCode_Space, out string QR_Code, + // out int engineCount, out int barCodeType, out string engineTypeBase, + // out string partCode_Text, out string partCode_BarCode, + // out string engineType_Text, out string engineType_BarCode, + // DataTable dt) + //{ + // engineID = ""; + // engineTypeID = 0; + // partCode_Space = ""; + // partCode = ""; + // shellCode = ""; + // shellCode_Space = ""; + // QR_Code = ""; + // engineCount = 0; + // barCodeType = 0; + // engineTypeBase = ""; + // partCode_Text = ""; + // partCode_BarCode = ""; + // engineType_Text = ""; + // engineType_BarCode = ""; + + // engineID = dt.Rows[0]["发动机号"].ToString(); + // engineTypeID = Convert.ToInt32(dt.Rows[0]["机型代码"]); + // shellCode = dt.Rows[0]["壳体编号型号"].ToString(); + // shellCode_Space = dt.Rows[0]["壳体编号型号带空格"].ToString(); + // partCode = dt.Rows[0]["零件流水号"].ToString(); + // partCode_Space = dt.Rows[0]["零件流水号带空格"].ToString(); + // QR_Code = dt.Rows[0]["QR码"].ToString(); + // engineCount = Convert.ToInt32(dt.Rows[0]["基本流水号"]); + // engineTypeBase = dt.Rows[0]["基本机型"].ToString(); + // barCodeType = Convert.ToInt32(dt.Rows[0]["条码类型"]); + // partCode_Text = dt.Rows[0]["流水号文本"].ToString(); + // partCode_BarCode = dt.Rows[0]["流水号条码"].ToString(); + // engineType_Text = dt.Rows[0]["型号文本"].ToString(); + // engineType_BarCode = dt.Rows[0]["型号条码"].ToString(); + + //} + + /// + /// [电子看板_发动机号_线首工位]信息自动用 + /// + /// 发动机号 + /// 机型代码 + /// 零件流水号带空格 + /// 零件流水号 + /// 壳体编号型号 + /// 壳体编号型号带空格 + /// QR码 + /// 基本流水号 + /// 条码类型 + /// 基本机型 + /// 流水号文本 + /// 流水号条码 + /// 型号文本 + /// 型号条码 + /// + static public void GetEngineIDFromFirstOpName_Auto(out string engineID, out int engineTypeID, out string partCode_Space, + out string partCode, out string shellCode, out string shellCode_Space, out string QR_Code, + out int engineCount, out int barCodeType, out string engineTypeBase, + out string partCode_Text, out string partCode_BarCode, + out string engineType_Text, out string engineType_BarCode, out string CodeCreatetime, + out string a_code, out string b_code, out string c_code, out string d_code, + DataTable dt) + { + engineID = ""; + engineTypeID = 0; + partCode_Space = ""; + partCode = ""; + shellCode = ""; + shellCode_Space = ""; + QR_Code = ""; + engineCount = 0; + barCodeType = 0; + engineTypeBase = ""; + partCode_Text = ""; + partCode_BarCode = ""; + engineType_Text = ""; + engineType_BarCode = ""; + + engineID = dt.Rows[0]["发动机号"].ToString(); + engineTypeID = Convert.ToInt32(dt.Rows[0]["机型代码"]); + shellCode = dt.Rows[0]["壳体编号型号"].ToString(); + shellCode_Space = dt.Rows[0]["壳体编号型号带空格"].ToString(); + partCode = dt.Rows[0]["零件流水号"].ToString(); + partCode_Space = dt.Rows[0]["零件流水号带空格"].ToString(); + QR_Code = dt.Rows[0]["QR码"].ToString(); + engineCount = Convert.ToInt32(dt.Rows[0]["基本流水号"]); + engineTypeBase = dt.Rows[0]["基本机型"].ToString(); + barCodeType = Convert.ToInt32(dt.Rows[0]["条码类型"]); + partCode_Text = dt.Rows[0]["流水号文本"].ToString(); + partCode_BarCode = dt.Rows[0]["流水号条码"].ToString(); + engineType_Text = dt.Rows[0]["型号文本"].ToString(); + engineType_BarCode = dt.Rows[0]["型号条码"].ToString(); + CodeCreatetime = dt.Rows[0]["条码创建时间"].ToString(); + a_code = dt.Rows[0]["总成代码"].ToString(); + b_code = dt.Rows[0]["零件图号"].ToString(); + c_code = dt.Rows[0]["邓氏码"].ToString(); + d_code = dt.Rows[0]["VPPS码"].ToString(); + } + + } +} diff --git a/Common/07WebBusinessFacade/BusinessFacade/05Biz/MES/RepairWorkStation.cs b/Common/07WebBusinessFacade/BusinessFacade/05Biz/MES/RepairWorkStation.cs new file mode 100644 index 0000000..d855a37 --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/05Biz/MES/RepairWorkStation.cs @@ -0,0 +1,52 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace bizFacade +{ + public class RepairWorkStation + { + /// + /// 保存复合工位工作状态 + /// + /// + /// + public static void StationStatusChanges(string OpName,int Status) + { + if (NormalOrRepairRecord_Hash.ContainsKey (OpName)) + { + NormalOrRepairRecord_Hash[OpName] = Status; + + } + else + { + NormalOrRepairRecord_Hash.Add(OpName,Status ); + } + + } + + /// + /// 查询工位工作状态 1为正常,其他为返修 + /// + /// + /// + public static int StationStatusSearch(string OpName) + { + if (NormalOrRepairRecord_Hash.ContainsKey(OpName)) + { + return Convert.ToInt32(NormalOrRepairRecord_Hash[OpName]); + + } + else + { + return 1; + } + } + + + + public static Hashtable NormalOrRepairRecord_Hash = new Hashtable(); + } +} diff --git a/Common/07WebBusinessFacade/BusinessFacade/05Biz/MES/ShowLED.cs b/Common/07WebBusinessFacade/BusinessFacade/05Biz/MES/ShowLED.cs new file mode 100644 index 0000000..732ff13 --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/05Biz/MES/ShowLED.cs @@ -0,0 +1,91 @@ +using System; +using System.Data; +using System.Data.SqlClient; +using DataLinkMesWork; +using System.Collections; +using System.Collections.Specialized; +using SystemFramework; + +namespace bizFacade +{ + /// + /// 电子看板信息系统 + /// + public partial class BaseDataSystemMES + { + /// + /// 基本数据_工作日历_班次产量查询_New + /// + /// + /// 在线产量 + /// 在线节拍 + static public void OpNameCount_BQ(string opName, out int opNameCount, out int opNameCountTime) + { + opNameCount = 0; + opNameCountTime = 0; + string procedureName; + procedureName = "基本数据_工作日历_班次产量查询_北汽"; + SqlParameter[] thisParms = new SqlParameter[3]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@在线产量", 0); + thisParms[1].Direction = ParameterDirection.Output; + thisParms[2] = new System.Data.SqlClient.SqlParameter("@在线节拍", 0); + thisParms[2].Direction = ParameterDirection.Output; + if (DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms)) + { + opNameCount = Convert.ToInt32(thisParms[1].Value); + opNameCountTime = Convert.ToInt32(thisParms[2].Value); + } + } + + /// + /// 基本数据_工作日历_班次产量查询_New + /// + /// + /// 在线产量 + /// 在线节拍 + static public void OpNameCount_New(string opName, out int opNameCount, out int opNameCountTime) + { + opNameCount = 0; + opNameCountTime = 0; + string procedureName; + procedureName = "基本数据_工作日历_班次产量查询_New"; + SqlParameter[] thisParms = new SqlParameter[3]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@在线产量", 0); + thisParms[1].Direction = ParameterDirection.Output; + thisParms[2] = new System.Data.SqlClient.SqlParameter("@在线节拍", 0); + thisParms[2].Direction = ParameterDirection.Output; + if (DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms)) + { + opNameCount = Convert.ToInt32(thisParms[1].Value); + opNameCountTime = Convert.ToInt32(thisParms[2].Value); + } + } + + /// + /// MES界面显示_消息滚动_增加 + /// + /// + /// + /// + public static bool Rolling_news_Add(string opName, string content) + { + + string procedureName = "MES界面显示_消息滚动_增加"; + bool isOK; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@ScollNotice", content); + isOK = DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + if (isOK) + { + return true; + } + else + { + return false; + } + } + } +} diff --git a/Common/07WebBusinessFacade/BusinessFacade/05Biz/MES/vssver2.scc b/Common/07WebBusinessFacade/BusinessFacade/05Biz/MES/vssver2.scc new file mode 100644 index 0000000..f6a0360 Binary files /dev/null and b/Common/07WebBusinessFacade/BusinessFacade/05Biz/MES/vssver2.scc differ diff --git a/Common/07WebBusinessFacade/BusinessFacade/05Biz/OPC/BaseDataSystemMES.OPC.Alarm.cs b/Common/07WebBusinessFacade/BusinessFacade/05Biz/OPC/BaseDataSystemMES.OPC.Alarm.cs new file mode 100644 index 0000000..6f56a9a --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/05Biz/OPC/BaseDataSystemMES.OPC.Alarm.cs @@ -0,0 +1,162 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Data; +using System.Data.SqlClient; +using DataLinkMesWork; + +using SystemFramework; +namespace bizFacade +{ + partial class BaseDataSystemMES + { + /// + /// 机床报警变量 + /// 103 + /// + /// + public static DataTable BaseData_tagTable_Alarm() + { + //string errorMessage; + DataTable dt; + string sql; + sql = "SELECT TagID,0 as TagValue,TagName,工位号,数据来源,TagTypeID,TagLong,列位置,测量位置,变量类型代码,测量项目,TagAdr,TagAdrDemo FROM [MES_基本变量_原始数据] where 变量类型代码 = 103 and 是否启用 = 1" + + " and (监控属性代码 = '" + 1 + "')"; + DataAccess.ExecuteDataTable(sql, out dt); + return dt; + } + /// + /// 测量数据发动机在线状态_增加数据_自动工位 + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + static public void WorkStartInsert_AutoWorkStation(string opName, string EngineID, int Pallet, DateTime arrivedTime, DateTime leavedTime, int TimeDiff, int Target, string lineType, string isPass, int OpNameUpDownType) + { + string procedureName; + procedureName = "测量数据发动机在线状态_增加数据_自动工位"; + SqlParameter[] thisParms = new SqlParameter[10]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@发动机号", EngineID); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@托盘编号", Pallet); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@到达时间", arrivedTime); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@离开时间", leavedTime); + thisParms[5] = new System.Data.SqlClient.SqlParameter("@在线时间", TimeDiff); + thisParms[6] = new System.Data.SqlClient.SqlParameter("@目标时间", Target); + thisParms[7] = new System.Data.SqlClient.SqlParameter("@线体类型", lineType); + thisParms[8] = new System.Data.SqlClient.SqlParameter("@是否合格", isPass); + thisParms[9] = new System.Data.SqlClient.SqlParameter("@工位上下线类型", OpNameUpDownType); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } + static public void WorkStartInsert(string opName, int isOK) + { + string procedureName; + procedureName = "测量数据发动机在线状态_增加数据"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@是否合格", isOK.ToString()); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } + + static public void OPA90CheckErrorData(string EngineID) + { + string procedureName; + procedureName = "合力_轮毂桥壳缓存数据_异常记录标记"; + SqlParameter[] thisParms = new SqlParameter[1]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@轮毂总成号", EngineID); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } + + static public void OPA90CheckQiaoKeErrorData(string EngineID) + { + string procedureName; + procedureName = "合力_轮毂桥壳缓存数据_异常记录标记_桥壳"; + SqlParameter[] thisParms = new SqlParameter[1]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@桥壳总成号", EngineID); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } + + static public void Set_EngineWorkOpName(string EngineID, string targetOpName) + { + string procedureName; + procedureName = "合力_转线设置工件状态"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@总成号", EngineID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@目标工位号", targetOpName); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } + + static public void SLResult_Add(string SLResult, string EngineID, string EngineType, int EngineTypeID, int TurnLineWork) + { + string procedureName; + procedureName = "试漏结果_增加"; + SqlParameter[] thisParms = new SqlParameter[5]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@测量结果", SLResult); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@总成码", EngineID); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@机型号", EngineType); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@机型代码", EngineTypeID); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@转线工件", TurnLineWork); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } + + + // ALTER PROCEDURE[dbo].[测量数据报警全部_增加数据] + // @TagID nvarchar(50), + //@OpName nvarchar(50), + //@TagValue int, + //@State int, + //@alarmStartTime datetime, + //@alarmEndTime datetime, + //@TimeDiff int, + //@Text1 nvarchar(255), + //@Text2 nvarchar(255) + + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// 报警级别 + /// 报文 + /// + /// + public static bool Alarm_Insert(string TagID, string tagTypeID, string opName, int TagValue, + DateTime alarmStartTime, DateTime alarmEndTime, int TimeDiff, + string Text1, string Text2, string TagOrderBy) + { + + + string produceName = "测量数据工位报警全部_增加数据"; + SqlParameter[] thisParms = new SqlParameter[10]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@TagID", TagID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@TagTypeID", tagTypeID); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@opName", opName); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@TagValue", TagValue); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@alarmStartTime", alarmStartTime); + thisParms[5] = new System.Data.SqlClient.SqlParameter("@alarmEndTime", alarmEndTime); + thisParms[6] = new System.Data.SqlClient.SqlParameter("@TimeDiff", TimeDiff); + thisParms[7] = new System.Data.SqlClient.SqlParameter("@Text1", Text1); + thisParms[8] = new System.Data.SqlClient.SqlParameter("@Text2", Text2); + thisParms[9] = new System.Data.SqlClient.SqlParameter("@TagOrderBy", TagOrderBy); + if (DataAccess.ExecuteStoredProcedure(produceName, ref thisParms)) + { + + return true; + } + return false; + } + + } +} diff --git a/Common/07WebBusinessFacade/BusinessFacade/05Biz/OPC/BaseDataSystemMES.OPC.QualityData.GoodBad.cs b/Common/07WebBusinessFacade/BusinessFacade/05Biz/OPC/BaseDataSystemMES.OPC.QualityData.GoodBad.cs new file mode 100644 index 0000000..d56b31f --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/05Biz/OPC/BaseDataSystemMES.OPC.QualityData.GoodBad.cs @@ -0,0 +1,84 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Data; +using System.Data.SqlClient; +using DataLinkMesWork; + +using SystemFramework; + +namespace bizFacade +{ + public partial class BaseDataSystemMES + { + /// + /// 发动机类型转换表 + /// SELECT ID,发动机机型代码 FROM MES_计划BOM_发动机型号代码 + /// + /// + public static DataTable BaseData_tagTable_QualityData_EngineTypeID() + { + DataTable dt; + string sql; + sql = "SELECT ID,发动机机型代码 FROM MES_计划BOM_发动机型号代码 "; + DataAccess.ExecuteDataTable(sql, out dt); + return dt; + } + + + /// + /// 测量合格标志 + /// 全部测量数据的测量工位 + /// + /// + public static DataTable BaseData_tagTable_QualityData_GoodBad_MIS_OpName_B5A() + { + DataTable dt; + string sql; + sql = "SELECT distinct 工位号 " + + " FROM MES_基本变量_原始数据 " + + " where 变量特点 = 8 and 是否启用 = 1 " + + " and (监控属性代码 = '" + 1 + "')"; + DataAccess.ExecuteDataTable(sql, out dt); + return dt; + } + + /// + /// 测量合格标志 + /// 全部测量数据的测量工位的数据来源 + /// + /// + public static DataTable BaseData_tagTable_QualityData_GoodBad_MIS_OpName(string opName) + { + DataTable dt; + string sql; + sql = "SELECT TagID,工位号,数据来源 " + + " FROM MES_基本变量_原始数据 " + + " where OpcServer_OPNAME = '1' and 是否启用 = 1 " + + " and 工位号='" + opName+"'" + + " and (监控属性代码 = '" + 1 + "')"; + DataAccess.ExecuteDataTable(sql, out dt); + return dt; + } + + /// + /// 测量合格标志 + /// 全部测量数据的测量工位的数据来源的测量变量 + /// + /// + public static DataTable BaseData_tagTable_QualityData_GoodBad_MIS_OpName(string opName,string opNameFrom) + { + DataTable dt; + string sql; + sql = "SELECT TagID " + + " FROM MES_基本变量_原始数据 " + + " where OpcServer_OPNAME = '2' and 是否启用 = 1 " + + " and 工位号='" + opName + "'" + + " and 数据来源='" + opNameFrom + "'" + + " and (监控属性代码 = '" + 1 + "')"; + DataAccess.ExecuteDataTable(sql, out dt); + return dt; + } + + } +} diff --git a/Common/07WebBusinessFacade/BusinessFacade/05Biz/OPC/BaseDataSystemMES.OPC.QualityData.cs b/Common/07WebBusinessFacade/BusinessFacade/05Biz/OPC/BaseDataSystemMES.OPC.QualityData.cs new file mode 100644 index 0000000..0b83b7f --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/05Biz/OPC/BaseDataSystemMES.OPC.QualityData.cs @@ -0,0 +1,54 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Data; +using System.Data.SqlClient; +using DataLinkMesWork; + +using SystemFramework; + +namespace bizFacade +{ + public partial class BaseDataSystemMES + { + + + /// + /// 测量工位号和工位名称 + /// + /// + public static DataTable BaseData_tagTable_QualityData_OpName_Name() + { + DataTable dt; + string sql = "SELECT distinct [工位号],[工位名称] FROM [MES_计划BOM_工位与名称] " + + " where (监控属性代码 = '" + 1+ "')" + + " ORDER BY 工位号 "; + //来源于SQL Server + DataAccess.ExecuteDataTable(sql, out dt); + return dt; + } + /// + /// MES_计划BOM_工位与名称 + /// + /// + public static DataTable BaseData_tagTable_OpName() + { + //DataTable dt; + //string sql = "SELECT * FROM [MES_计划BOM_工位与名称] " + // + " where (监控属性代码 = '" + ApplicationConfig.MES_Code.ToString() + "')" + // + " ORDER BY 工位号 "; + //DataAccess.ExecuteDataTable(sql, out dt); + //return dt; + + //2022.07.27.LLX 处理了一下子 + DataTable dt; + string sql = "SELECT * FROM [MES_计划BOM_工位与名称] " + + " where (监控属性代码 = '" + 1 + "') and [是否通过监控系统保存数据] is not null" + + " ORDER BY 工位号 "; + DataAccess.ExecuteDataTable(sql, out dt); + return dt; + } + + + } +} diff --git a/Common/07WebBusinessFacade/BusinessFacade/05Biz/OPC/BaseDataSystemMES.OPC.cs b/Common/07WebBusinessFacade/BusinessFacade/05Biz/OPC/BaseDataSystemMES.OPC.cs new file mode 100644 index 0000000..ac285f5 --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/05Biz/OPC/BaseDataSystemMES.OPC.cs @@ -0,0 +1,98 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Data; +using System.Data.SqlClient; +using DataLinkMesWork; + +using SystemFramework; + +namespace bizFacade +{ + public partial class BaseDataSystemMES + { + + /// + /// MES_基本变量_DB数据结构_根据工位代码_获得普通变量 + /// + /// + public static DataTable BaseData_tagTable_OpcServerMES(int mesCode, string opName) + { + DataTable dt; + string sql; + sql = "SELECT TagID,0 as TagValue,TagName,工位号,数据来源,TagTypeID,TagLong,列位置,测量位置,变量类型代码,测量项目,TagAdr,TagAdrDemo,变量特点,变量排序 " + + " FROM MES_基本变量_原始数据 " + + " where 变量类型代码 = "+mesCode.ToString()+" and 是否启用 = 1" + + " and 工位号='" + opName + "'" + + " and (监控属性代码 = '" + 1+ "')"; + DataAccess.ExecuteDataTable(sql, out dt); + return dt; + } + /// + /// MES_基本变量_DB数据结构_根据工位代码_获得普通变量 + /// + /// + public static DataTable BaseData_tagTable_OpcServerMES(int mesCode) + { + DataTable dt; + string sql; + sql = "SELECT TagID,0 as TagValue,TagName,工位号,数据来源,TagTypeID,TagLong,列位置,测量位置,变量类型代码,测量项目,TagAdr,TagAdrDemo,变量特点,变量排序 " + + " FROM MES_基本变量_原始数据 " + + " where 变量类型代码 = " + mesCode.ToString() + " and 是否启用 = 1" + + " and (监控属性代码 = '" + 1 + "')"; + DataAccess.ExecuteDataTable(sql, out dt); + return dt; + } + + /// + /// MES_基本变量_DB数据结构_获得激发变量 + /// + /// + public static DataTable BaseData_tagTable_All() + { + //string errorMessage; + DataTable dt = null; + string sql; + sql = "SELECT TagID,0 as TagValue,TagName,工位号,数据来源,TagTypeID,TagLong,列位置,测量位置,变量类型代码,测量项目,TagAdr,TagAdrDemo,变量特点,变量排序 FROM [MES_基本变量_原始数据] " + + " where ((变量类型代码 >= 19 and 变量类型代码 <= 27) or (变量类型代码 = 101) or (变量类型代码 = 102) or (变量类型代码 = 105) or (变量类型代码 = 1000) or (变量类型代码 = 1001) or (变量类型代码 = 1002) or (变量类型代码 = 1003) or (变量类型代码 = 1004)) and (是否启用 = 1) " + + " and (监控属性代码 = '" + 1 + "')" + + " ORDER BY TagID "; + DataAccess.ExecuteDataTable(sql, out dt); + return dt; + } + /// + /// MES_基本变量_DB数据结构_获得激发变量 + /// + /// + public static DataTable BaseData_tagTable_All_B5A() + { + //string errorMessage; + DataTable dt = null; + string sql; + sql = "SELECT TagID,0 as TagValue,TagName,工位号,数据来源,TagTypeID,TagLong,列位置,测量位置,变量类型代码,测量项目,TagAdr,TagAdrDemo,变量特点,变量排序 FROM [MES_基本变量_原始数据] " + + " where ((变量类型代码 = 101) or (变量类型代码 = 102) ) and (是否启用 = 1) " + + " and (监控属性代码 = '" + 1 + "')" + + " ORDER BY TagID "; + DataAccess.ExecuteDataTable(sql, out dt); + return dt; + } + + /// + /// 20170310 新加 + /// MES_基本变量_DB数据结构_获得所有普通变量(除101.102.103.104.105) + /// + /// + public static DataTable BaseData_tagTable_OpcServerMES_ALL_CF() + { + DataTable dt; + string sql; + sql = "SELECT TagID,0 as TagValue,TagName,工位号,数据来源,TagTypeID,TagLong,列位置,测量位置,变量类型代码,测量项目,TagAdr,TagAdrDemo,变量特点,变量排序 " + + " FROM MES_基本变量_原始数据 " + + " where 变量类型代码 <> 101 and 变量类型代码 <> 102 and 变量类型代码 <> 103 and 变量类型代码 <> 104 and 变量类型代码 <> 105 and 是否启用 = 1" + + " and (监控属性代码 = '" + 1 + "')"; + DataAccess.ExecuteDataTable(sql, out dt); + return dt; + } + + } +} diff --git a/Common/07WebBusinessFacade/BusinessFacade/05Biz/OPC/vssver2.scc b/Common/07WebBusinessFacade/BusinessFacade/05Biz/OPC/vssver2.scc new file mode 100644 index 0000000..37c4fff Binary files /dev/null and b/Common/07WebBusinessFacade/BusinessFacade/05Biz/OPC/vssver2.scc differ diff --git a/Common/07WebBusinessFacade/BusinessFacade/05Biz/QualityData/DataVerify.cs b/Common/07WebBusinessFacade/BusinessFacade/05Biz/QualityData/DataVerify.cs new file mode 100644 index 0000000..b079de3 --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/05Biz/QualityData/DataVerify.cs @@ -0,0 +1,129 @@ +using DataLinkMesWork; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Data; +using System.Data.SqlClient; +using System.Linq; +using System.Text; + +namespace bizFacade +{ + /// + /// 通用BizFaced类 + /// + public partial class BaseDataSystemMES + { + /// + /// 验证质量数据状态哈希表 + /// + public static Hashtable QualityVerifyStatus_Hash = new Hashtable(); + + /// + /// 读取工位质量数据验证状态 + /// + /// + /// + public static bool QualityVerifyStatus_Hash_Read(string OpName) + { + if (QualityVerifyStatus_Hash.Contains(OpName)) + { + return Convert.ToBoolean(QualityVerifyStatus_Hash[OpName]); + + } + return false; + + } + + + /// + /// 写入工位质量数据验证状态 + /// + /// + /// + public static void QualityVerifyStatus_Hash_Write(string OpName, bool Result) + { + if (QualityVerifyStatus_Hash.Contains(OpName)) + { + QualityVerifyStatus_Hash[OpName] = Result; + + } + else + { + QualityVerifyStatus_Hash.Add(OpName, Result); + + } + } + + + + + /// + /// 部装工位质量数据验证 + /// + /// + public static bool QulityDataVerify(string OpName, string EngineID_Subline, out string AlarmStr) + { + int IsAlarm = 0; + AlarmStr = ""; + string procedureName; + procedureName = "测量数据工位_监控系统_部装质量数据验证"; + SqlParameter[] thisParms = new SqlParameter[4]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", OpName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@部装总成号", EngineID_Subline); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@是否报警", IsAlarm); + thisParms[2].Direction = ParameterDirection.Output; + thisParms[3] = new System.Data.SqlClient.SqlParameter("@报警工位号", AlarmStr); + thisParms[3].Direction = ParameterDirection.Output; + + if (DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms)) + { + IsAlarm = Convert.ToInt32(thisParms[2].Value.ToString()); + AlarmStr = thisParms[3].Value.ToString(); + + if (IsAlarm == 0) + { + return true; + } + } + return false; + + } + + + + + + /// + /// 线外工位质量数据验证 + /// + /// + public static bool QualityVerifyStatusOutline(string OpName, out string AlarmStr) + { + int IsAlarm = 0; + AlarmStr = ""; + string procedureName; + procedureName = "测量数据工位_监控系统_线外质量数据验证"; + SqlParameter[] thisParms = new SqlParameter[3]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", OpName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@是否报警", IsAlarm); + thisParms[1].Direction = ParameterDirection.Output; + thisParms[2] = new System.Data.SqlClient.SqlParameter("@报警工位号", AlarmStr); + thisParms[2].Direction = ParameterDirection.Output; + + if (DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms)) + { + IsAlarm = Convert.ToInt32(thisParms[1].Value.ToString()); + AlarmStr = thisParms[2].Value.ToString(); + + if (IsAlarm == 0) + { + return true; + } + } + return false; + + } + + } +} diff --git a/Common/07WebBusinessFacade/BusinessFacade/05Biz/QualityData/GetQualityData_GoodBad.cs b/Common/07WebBusinessFacade/BusinessFacade/05Biz/QualityData/GetQualityData_GoodBad.cs new file mode 100644 index 0000000..85b79c0 --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/05Biz/QualityData/GetQualityData_GoodBad.cs @@ -0,0 +1,415 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Data; +using System.Data.SqlClient; +using DataLinkMesWork; +using System.Collections; + +using SystemFramework; +using DoWhatPlc; +//using BasicData; +//using OpcData; + +namespace bizFacade +{ + + public partial class BaseDataSystemMES + { + + + /// + /// 对应玉柴项目 + /// 20111101 + /// 质量数据的上限值,下限值,理论值来源于表[MES_基本数据_测量范围] + /// 通过TagID和engineTypeID。如果engineTypeID=0,上限值,下限值,理论值="" + /// 质量数据可以读数据 19 + /// 分散控制 + /// tagID_CF质量数据激发变量对应的质量数据列表 + /// + /// tagID_CF质量数据激发变量对应的质量数据列表(Hashtable) + /// 质量数据列表 + /// 质量数据列表 + /// + /// 质量数据列表 + /// 质量数据总成合格标志 21( =0 数据合格) (= 1数据不合格) + /// 质量数据发动机机型标志 9 + /// 质量数据发动机号 10 + /// 质量数据发动机机型 11 + /// + /// + /// 缸盖号[TagValue2] + /// 发动机类型转换表 + /// 发动机类型转换表 + /// 发动机类型转换表 + /// 发动机类型转换表 + /// 发动机类型转换表 + /// 发动机类型转换表 + static public void GetQualityDataTable_B5A(Hashtable valuList, string opName, DataTable BasicDataTagValue, + DataTable BasicDataTagValueUpDown, + out DataTable dt, + out int qualityMask, + out int engineTypeID, + out string engineID, + out string engineType,out string partPallet, out string engineTraceCode, out string engineCap, Hashtable hashtable_EngineTypeID, + out int mes_MustTest,out int onLineState,out int partMoveDirection, + out int pressIsOK, out int pressIsNoOK) + { + //78 0:屏蔽MES;1:启用MES(必须MIS) + //79 通过线体工位PC实现下达工位工作状态:工位有三种状态:在线、离线、屏蔽。在线;0正常状态,实现正常功能。1离线:2屏蔽。(必须MIS) + //41 机体流向标志(1 BYTE):0普通工位:1:上线(发动机上线);2:下线(发动机下线);(必须PLC) + //51 返修工位,修改后的数据MES将数据写入PLC ,MES通知PLC数据修改完成。(YN) + //8 只要返修,必须由mes发送此信号,plc接收此信号后才能放行 + //(暂时没用)用于有扳手拧紧工位。通知设备螺钉拧紧完成。PC已经将数据保存到数据库中。(B5A) + mes_MustTest = 0; + onLineState = 0; + partMoveDirection = 0; + pressIsOK = 0; + pressIsNoOK = 0; + QualityDataType qualityData; + //是否有数据 + //bool isUsing; + + DataRow dr; + DataRow[] dr_WWW; + //MES_基本数据_测量范围 + DataRow[] dr_WWW_UpDown; + + dt = BuildDataTables_WWW(); + qualityMask = 0; + engineTypeID = 0; + engineID = ""; + engineType = ""; + engineTraceCode = ""; + engineCap = ""; + partPallet = ""; + //测量位置 + string shaftID; + //测量项目 + string item; + //测量单位 + string unit; + //机体类型 + //原始数据中的机型代码 + int engineTypeID_Source; + //上限值 + string tagValueUp; + //下限值 + string tagValueDown; + //理论值 + string tagValeNormal; + //TagValue + // 合格标志 + //string IsGoodBad; + + + foreach (DictionaryEntry valueItem in valuList) //ht为一个Hashtable实例 + { + try + { + qualityData = (QualityDataType)valueItem.Value; + + switch (qualityData.tagValueType) + { + case 21: + qualityMask = Convert.ToInt32(qualityData.tagValue); + //转变一下 + //qualityMask = transferIsOK_OpName_2(Convert.ToInt32(qualityData.tagValue)); + break; + case 8: + //8 只要返修,必须由mes发送此信号,plc接收此信号后才能放行 + //(暂时没用)用于有扳手拧紧工位。通知设备螺钉拧紧完成。PC已经将数据保存到数据库中。(B5A) + pressIsNoOK = Convert.ToInt32(qualityData.tagValue); + break; + //质量数据发动机机型标志 22(玉柴) 发动机机型标志 9 (有MOBY)需要换算成2的n次幂的形式,以便生成报表 + case 9: + engineTypeID = Convert.ToInt32(qualityData.tagValue); + if (engineTypeID == 0) + { + engineTypeID = 1; + } + if (hashtable_EngineTypeID.ContainsKey(engineTypeID)) + { + string engineTypeIDString = hashtable_EngineTypeID[engineTypeID].ToString(); + engineTypeID = Convert.ToInt32(engineTypeIDString); + if (engineTypeID == 0) + { + engineTypeID = 1; + } + } + break; + //发动机编号 23 10 + //case 23: + case 10: + engineID = Convert.ToString(qualityData.tagValue); + break; + //质量数据发动机机型 24(玉柴) 11(有MOBY) + //case 24: + case 11: + engineType = Convert.ToString(qualityData.tagValue); + break; + case 41: + //41 机体流向标志(1 BYTE):0普通工位:1:上线(发动机上线); + //2:下线(发动机下线);(必须PLC) + partMoveDirection = Convert.ToInt32(qualityData.tagValue); + break; + case 51: + //51 返修工位,修改后的数据MES将数据写入PLC ,MES通知PLC数据修改完成。(YN) + pressIsOK = Convert.ToInt32(qualityData.tagValue); + break; + //78 0:屏蔽MES;1:启用MES(必须MIS) + case 78: + mes_MustTest = Convert.ToInt32(qualityData.tagValue); + break; + //79 通过线体工位PC实现下达工位工作状态:工位有三种状态:在线、离线、屏蔽。在线: + //0正常状态,实现正常功能。1离线:2屏蔽。(必须MIS) + case 79: + onLineState = Convert.ToInt32(qualityData.tagValue); + break; + //托盘编号(B5A) + case 80: + partPallet = Convert.ToString(qualityData.tagValue); + break; + } + //if ((qualityData.tagProperty != 2) || (qualityData.tagProperty != 6)) + //{ + // continue ; + //} + if ((qualityData.tagProperty == 2) || (qualityData.tagProperty == 6)) + { + if (engineTypeID == 0) + { + engineTypeID = 1; + } + dr_WWW = BasicDataTagValue.Select("TagID = " + qualityData.tagID); + try + { + dr_WWW_UpDown = BasicDataTagValueUpDown.Select("TagID = " + qualityData.tagID); + } + catch { dr_WWW_UpDown = null; } + + + if (dr_WWW.Length > 0) + { + { + engineTypeID_Source = Convert.ToInt32(dr_WWW[0]["机体类型"]); + int temp; + temp = engineTypeID_Source & engineTypeID; + if (temp == 0) + { + continue; + } + if (qualityData.isGoodBad == -1) + { + continue; + } + } + } + else + { + continue; + + } + + try + { + shaftID = dr_WWW[0]["测量位置"].ToString(); + } + catch + { + shaftID = ""; + } + try + { + item = dr_WWW[0]["测量项目"].ToString(); + } + catch + { + item = ""; + } + try + { + unit = dr_WWW[0]["测量单位"].ToString(); + } + catch + { + unit = ""; + } + try + { + tagValueUp = ""; + if (dr_WWW_UpDown != null&& dr_WWW_UpDown.Length >0) + { + tagValueUp = dr_WWW_UpDown[0]["值上限"].ToString(); + } + else + { + tagValueUp = ""; + } + } + catch + { + tagValueUp = ""; + } + try + { + tagValueDown = ""; + if (dr_WWW_UpDown != null && dr_WWW_UpDown.Length > 0) + { + tagValueDown = dr_WWW_UpDown[0]["值下限"].ToString(); + } + } + catch + { + tagValueDown = ""; + } + try + { + tagValeNormal = ""; + if (dr_WWW_UpDown != null && dr_WWW_UpDown.Length > 0) + { + tagValeNormal = dr_WWW_UpDown[0]["理论值"].ToString(); + } + + } + catch + { + tagValeNormal = ""; + } + + dr = dt.NewRow(); + + dr["TagID"] = qualityData.tagID; + dr["测量位置"] = shaftID; + dr["测量项目"] = item; + dr["测量单位"] = unit; + dr["上限值"] = tagValueUp; + dr["下限值"] = tagValueDown; + dr["理论值"] = tagValeNormal; + dr["工位号"] = opName; + dr["列位置"] = qualityData.tagOrderBy; + dr["变量排序"] = qualityData.tagItemOrderBy; + + dr["IsGoodBad"] = qualityData.isGoodBad; + + switch (qualityData.tagTypeID)// + { + //合格标志数组 + case 8203: + dr["TagValue"] = BaseDataSystemMES.GetQualityData_GoodBad_String((bool[])qualityData.tagValue); + break; + case 8209: + dr["TagValue"] = ""; + break; + //非标准REAL + case 8210: + dr["TagValue"] = GetNoNormalReal(qualityData.tagValue); + dt.Rows.Add(dr); + break; + default: + dr["TagValue"] = Convert.ToString(qualityData.tagValue); + dt.Rows.Add(dr); + break; + } + + + } + + + + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, err.Message); + } + } + } + + /// + /// 数据表 + /// + /// + static public DataTable BuildDataTables_WWW() + { + DataTable table; + DataColumnCollection columns; + table = new DataTable(); + columns = table.Columns; + table.Columns.Add("TagID", typeof(System.String)); + table.Columns.Add("TagValue", typeof(System.String)); + table.Columns.Add("IsGoodBad", typeof(System.Int32)); + table.Columns.Add("测量位置", typeof(System.String)); + table.Columns.Add("测量项目", typeof(System.String)); + table.Columns.Add("工位号", typeof(System.String)); + table.Columns.Add("理论值", typeof(System.String)); + table.Columns.Add("上限值", typeof(System.String)); + table.Columns.Add("下限值", typeof(System.String)); + table.Columns.Add("测量单位", typeof(System.String)); + table.Columns.Add("列位置", typeof(System.Int32)); + table.Columns.Add("变量排序", typeof(System.Int32)); + + return table; + } + /// + /// 返回非标准real + /// + /// + /// + static public string GetNoNormalReal(object vDataValue) + { + try + { + string real_a; + string real_b; + string groupValueString; + int length; + + //int real_b_Int; + + length = ((System.Array)(vDataValue)).Length; + groupValueString = ""; + if (length != 2) + return "0.0"; + + real_a = Convert.ToUInt16((((System.Array)(vDataValue)).GetValue(0))).ToString(); + real_b = Convert.ToUInt16((((System.Array)(vDataValue)).GetValue(1))).ToString("00"); + groupValueString = real_a + "." + real_b; + return groupValueString; + } + catch + { + ////ApplicationLog.WriteLog(err, "GetNoNormalReal"); + return "0.0"; + + } + } + + /// + /// 29 工位具体零件合格标志 + /// + /// + static public string GetQualityData_GoodBad_String(bool[] QualityData_GoodBad) + { + string str; + str = ""; + if (QualityData_GoodBad != null) + { + + for (int i = 0; i < QualityData_GoodBad.Length; i++) + { + str = str + (Convert.ToInt32(QualityData_GoodBad[i])).ToString() + "|"; + } + + } + return str; + + } + /// + /// 返回非标准real + /// + /// + /// + + + } +} diff --git a/Common/07WebBusinessFacade/BusinessFacade/07BusinessFacade.csproj b/Common/07WebBusinessFacade/BusinessFacade/07BusinessFacade.csproj new file mode 100644 index 0000000..6491263 --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/07BusinessFacade.csproj @@ -0,0 +1,147 @@ + + + + + Debug + AnyCPU + {F0A0C525-03FD-428A-9B17-7F54AA0E4475} + Library + Properties + BusinessFacade + 07BusinessFacade + v4.8 + 512 + true + + + + true + full + false + ..\..\dll\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + ..\..\dll\MQTTnet.dll + + + ..\..\dll\MQTTnet.Extensions.ManagedClient.dll + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + {f55da1a0-a982-4479-8c47-0d9a5aaf3e18} + 00MesWorkMqtt + + + {0d1af432-439a-4920-8692-43ae139f5530} + 01_01DoWhatPlc + + + {f434e066-4c59-47c8-aa82-6f48cc84501a} + 04-DataBaseAccess + + + + \ No newline at end of file diff --git a/Common/07WebBusinessFacade/BusinessFacade/Db2023/Order.cs b/Common/07WebBusinessFacade/BusinessFacade/Db2023/Order.cs new file mode 100644 index 0000000..66cc98b --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/Db2023/Order.cs @@ -0,0 +1,340 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Data; +using System.Data.SqlClient; + +using System.Data.OleDb; + + +using DataLinkMesWork; + +//using SystemFramework; + +namespace bizFacade +{ + public partial class BaseDataSystemMES + { + //[北汽福田变速器序列号总线上线_是否重号] + /// + /// + /// + /// + /// + public static bool EngineTypeID_IsNotRepeatedNumber(string sn) + { + DataTable dt = new DataTable(); + int count; + + + string produceName = "北汽福田变速器序列号总线上线_是否重号"; + SqlParameter[] thisParms = new SqlParameter[1]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@变速器序列号", sn); + + if (DataAccess.ExecuteStoredProcedure(produceName, ref thisParms, out dt)) + { + if (dt.Rows.Count > 0) + { + count = Convert.ToInt32(dt.Rows[0]["数量"]); + if (count == 0) + { + return true; + } + else + { + return false; + + } + } + } + return true; + + } + //北汽福田_配方内容_根据配方号查询 + public static bool PLCRcipeByOpName(string OpName, out byte[] bytes, out string tagStartAdr, int PLCRcipe) + { + DataTable dt = new DataTable(); + string produceName = "北汽福田_配方内容_根据配方号查询"; + tagStartAdr = ""; + bytes = new byte[0]; + SqlParameter[] thisParms = new SqlParameter[1]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@配方号", PLCRcipe); + + + if (DataAccess.ExecuteStoredProcedure(produceName, ref thisParms, dt)) + { + if (dt.Rows.Count > 0) + { + tagStartAdr = dt.Rows[0]["地址"].ToString(); + bytes = new byte[dt.Rows.Count]; + for (int i = 0; i < dt.Rows.Count; i++) + { + bytes[i] = Convert.ToByte(dt.Rows[0]["操作号码"]); + } + return true; + } + } + return false; + } + /// + /// 北汽福田_配方当前_查询 + /// + /// + /// + public static bool PLCRcipeCurrent(string opName, out byte[] bytes, out string tagStartAdr) + { + DataTable dt = new DataTable(); + string produceName = "北汽福田_配方当前_查询"; + tagStartAdr = ""; + bytes = null; + SqlParameter[] thisParms = new SqlParameter[1]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + if (DataAccess.ExecuteStoredProcedure(produceName, out dt)) + { + if (dt.Rows.Count > 0) + { + tagStartAdr = dt.Rows[0]["地址"].ToString(); + bytes = new byte[dt.Rows.Count]; + for (int i = 0; i < dt.Rows.Count; i++) + { + bytes[i] = Convert.ToByte(dt.Rows[0]["操作号码"]); + } + return true; + } + } + return false; + } + /// + /// 北汽福田BOM_上线需要数据_查询 + /// + /// 零件号 + /// PTO检测 + /// 空挡开关检测 + /// 倒挡开关检测 + /// 里程表检测 + /// 大机型扩展 + /// + public static bool UpLoadPTO(string sn, out int PTO, out int NgearSwitch, out int RgearSwitch, out int SpeedSensor, out string PartTypeMid, out int Tcu_V) + { + DataTable dt = new DataTable(); + int count; + PTO = 0; + NgearSwitch = 0; + RgearSwitch = 0; + SpeedSensor = 0; + Tcu_V = 0; + PartTypeMid = ""; + //select @倒挡开关 as RgearSwitch,@空挡开关 as NgearSwitch,@里程表 as SpeedSensor,@型号 as PartTypeMid,@PTO as PTO + // + string produceName = "北汽福田BOM_上线需要数据_查询"; + SqlParameter[] thisParms = new SqlParameter[1]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@零件号", sn); + + if (DataAccess.ExecuteStoredProcedure(produceName, ref thisParms, out dt)) + { + if (dt.Rows.Count > 0) + { + PTO = Convert.ToInt32(dt.Rows[0]["PTO"]); + NgearSwitch = Convert.ToInt32(dt.Rows[0]["NgearSwitch"]); + RgearSwitch = Convert.ToInt32(dt.Rows[0]["RgearSwitch"]); + SpeedSensor = Convert.ToInt32(dt.Rows[0]["SpeedSensor"]); + PartTypeMid = dt.Rows[0]["PartTypeMid"].ToString(); + Tcu_V = Convert.ToInt32(dt.Rows[0]["TCU"]); + return true; + } + } + return false; + + } + /// + /// 北汽福田变速器序列号总线上线_获得机型信息 + /// + /// + /// + /// + /// + /// + /// + /// + /// + public static bool GetEngineTypeUpLoadOpName(string sn, string OpName, out int EngineTypeID, out string EngineType, out string OrderForm, out int Recipe1, out int Recipe2) + { + DataTable dt = new DataTable(); + EngineTypeID = 0; + EngineType = ""; + OrderForm = ""; + Recipe1 = 0; + Recipe2 = 0; + + string produceName = "北汽福田变速器序列号总线上线_获得机型信息"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@变速箱总成号", sn); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@工位号", OpName); + + if (DataAccess.ExecuteStoredProcedure(produceName, ref thisParms, out dt)) + { + if (dt.Rows.Count > 0) + { + EngineTypeID = Convert.ToInt32(dt.Rows[0]["机型代码"]); + EngineType = dt.Rows[0]["零件号"].ToString(); + OrderForm = dt.Rows[0]["订单号"].ToString(); + return true; + } + } + return false; + } + //MES_计划BOM_工位与名称_查询_MQTT监控工位 + + public static DataTable GetCheckOpName_BQ() + { + DataTable dt = new DataTable(); + string produceName = "MES_计划BOM_工位与名称_查询_MQTT监控工位"; + SqlParameter[] thisParms = null; + + + DataAccess.ExecuteStoredProcedure(produceName, ref thisParms, out dt); + + return dt; + } + public static DataTable GetCheckOpName() + { + DataTable dt = new DataTable(); + string produceName = "MES_计划BOM_工位与名称_查询"; + SqlParameter[] thisParms = null; + + + DataAccess.ExecuteStoredProcedure(produceName, ref thisParms, out dt); + + return dt; + } + /// + /// 测量数据工位_监控系统_MOBY_查询 + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + public static DataTable GetOrder_BQ() + { + DataTable dt = new DataTable(); + string produceName = "北汽福田生产订单计划_查询"; + SqlParameter[] thisParms = null; + + + DataAccess.ExecuteStoredProcedure(produceName, ref thisParms, out dt); + + return dt; + } + + public static DataTable GetOrderOpName_BQ() + { + DataTable dt = new DataTable(); + string produceName = "MES_计划BOM_工位与名称_上线工位号查询"; + SqlParameter[] thisParms = null; + + + DataAccess.ExecuteStoredProcedure(produceName, ref thisParms, out dt); + + return dt; + } + /// + /// 北汽福田工位状态监控MOBY_增加_线首工位订单下达 + /// + /// + /// + /// + public static void DownOrderToOpName(string orderForm, string opName) + { + string produceName = "北汽福田工位状态监控MOBY_增加_线首工位订单下达"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new SqlParameter("@订单号", orderForm); + thisParms[1] = new SqlParameter("@工位号", opName); + DataAccess.ExecuteStoredProcedure(produceName, ref thisParms); + + } + + public static DataTable DownOrderToOpNameMobyList(string OpName) + { + DataTable dt = new DataTable(); + SqlParameter[] thisParms = new SqlParameter[1]; + thisParms[0] = new SqlParameter("@工位号", OpName); + string produceName = "北汽福田工位状态监控MOBY_查询_订单下达用"; + DataAccess.ExecuteStoredProcedure(produceName, ref thisParms, out dt); + + return dt; + } + + /// + /// PA30 40 获取数据 测量数据发动机在线状态_抽取记录_查询 + /// + /// + /// 排序方式 0 ASC 1 DESC + /// + public static DataTable lineOutTowBackWork_GetData(string OpName, int OrderType) + { + DataTable dt = new DataTable(); + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new SqlParameter("@工位号", OpName); + thisParms[1] = new SqlParameter("@排序方式", OrderType); + string produceName = "测量数据发动机在线状态_抽取记录_查询"; + DataAccess.ExecuteStoredProcedure(produceName, ref thisParms, out dt); + + return dt; + } + /// + /// PA40 获取数据 机型代码 测量数据发动机在线状态_抽取记录_查询 + /// + /// + /// 排序方式 0 ASC 1 DESC + /// + public static DataTable lineOutTowBackWorkEngineTypeCode_GetData(string OpName, string materialCode) + { + DataTable dt = new DataTable(); + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new SqlParameter("@工位号", OpName); + thisParms[1] = new SqlParameter("@零件编号", materialCode); + string produceName = "北汽福田工位状态监控_根据零件号获取型号_查询"; + DataAccess.ExecuteStoredProcedure(produceName, ref thisParms, out dt); + + return dt; + } + /// + /// 北汽福田工位状态监控MOBY历史数据_增加 + /// + /// + /// + public static void MobySaveData(string opName) + { + string produceName = "北汽福田工位状态监控MOBY历史数据_增加"; + SqlParameter[] thisParms = new SqlParameter[1]; + thisParms[0] = new SqlParameter("@工位号", opName); + DataAccess.ExecuteStoredProcedure(produceName, ref thisParms); + + } + + + public static string GetOrderDataBySn(string sn) + { + + DataTable dt = new DataTable(); + string orderForm = ""; + string produceName = "北汽福田变速器序列号_查询订单号"; + SqlParameter[] thisParms = new SqlParameter[1]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@变速器序列号", sn); + if (DataAccess.ExecuteStoredProcedure(produceName, out dt)) + { + if (dt.Rows.Count > 0) + { + orderForm = dt.Rows[0]["订单号"].ToString(); + } + } + return orderForm; + } + + } +} diff --git a/Common/07WebBusinessFacade/BusinessFacade/MES.B5A.Factory/Factory.cs b/Common/07WebBusinessFacade/BusinessFacade/MES.B5A.Factory/Factory.cs new file mode 100644 index 0000000..275ef7f --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/MES.B5A.Factory/Factory.cs @@ -0,0 +1,93 @@ +using System; +using System.Data; +using System.Data.SqlClient; +using System.Collections; +using System.Collections.Specialized; +//using SystemFramework; +using DataLinkMesWork; + +namespace bizFacade +{ + /// + /// 电子看板信息系统 + /// + public partial class BaseDataSystemMES + { + /// + /// 电子看板_零件图号_生产厂家_厂家_查询 + /// + /// + static public void Factory_Select(out DataTable dt) + { + string sql; + sql = " exec 电子看板_零件图号_生产厂家_厂家_查询"; + DataAccess.ExecuteDataTable(sql, out dt); + } + + + /// + /// 电子看板_零件图号_生产厂家_厂家_快速_查询 + /// + /// + /// + static public void Factory_kuaisu_Select(string str ,out DataTable dt) + { + string procedureName; + procedureName = "电子看板_零件图号_生产厂家_厂家_快速_查询"; + SqlParameter[] thisParms = new SqlParameter[1]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@零件图号", str); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out dt); + } + + /// + /// 电子看板_零件图号_生产厂家_厂家_增加 + /// + static public bool Factory_Insert(string Lingjian_tuhao, string Wuliaohao, + string Gongyingshang_number, string Gongyingshang_name, string Gongyingshang_shortname) + { + string procedureName; + procedureName = "电子看板_零件图号_生产厂家_厂家_增加"; + SqlParameter[] thisParms = new SqlParameter[5]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@零件图号", Lingjian_tuhao); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@物料号", Wuliaohao); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@供应商代码", Gongyingshang_number); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@供应商名称", Gongyingshang_name); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@供应商简称", Gongyingshang_shortname); + return DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } + + /// + /// 电子看板_零件图号_生产厂家_厂家_修改 + /// + static public bool Factory_Update(int Changjia_num, string Lingjian_tuhao, string Wuliaohao, + string Gongyingshang_number, string Gongyingshang_name, string Gongyingshang_shortname) + { + string procedureName; + procedureName = "电子看板_零件图号_生产厂家_厂家_修改"; + SqlParameter[] thisParms = new SqlParameter[6]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@厂家代码", Changjia_num); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@零件图号", Lingjian_tuhao); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@物料号", Wuliaohao); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@供应商代码", Gongyingshang_number); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@供应商名称", Gongyingshang_name); + thisParms[5] = new System.Data.SqlClient.SqlParameter("@供应商简称", Gongyingshang_shortname); + return DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } + + /// + /// 电子看板_零件图号_生产厂家_厂家_删除 + /// + /// 序号 + static public bool Factory_Delete(int Changjia_num) + { + string procedureName; + procedureName = "电子看板_零件图号_生产厂家_厂家_删除"; + SqlParameter[] thisParms = new SqlParameter[1]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@厂家代码", Changjia_num); + return DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } + + + + } +} diff --git a/Common/07WebBusinessFacade/BusinessFacade/MES.B5A.Factory/vssver2.scc b/Common/07WebBusinessFacade/BusinessFacade/MES.B5A.Factory/vssver2.scc new file mode 100644 index 0000000..c12a7f4 Binary files /dev/null and b/Common/07WebBusinessFacade/BusinessFacade/MES.B5A.Factory/vssver2.scc differ diff --git a/Common/07WebBusinessFacade/BusinessFacade/MES.B5A.MainForm/EngineIDCode.cs b/Common/07WebBusinessFacade/BusinessFacade/MES.B5A.MainForm/EngineIDCode.cs new file mode 100644 index 0000000..fa59789 --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/MES.B5A.MainForm/EngineIDCode.cs @@ -0,0 +1,405 @@ +using System; +using System.Data; +using System.Data.SqlClient; +using System.Collections; +using System.Collections.Specialized; +//using SystemFramework; +using DataLinkMesWork; + +namespace bizFacade +{ + /// + /// 电子看板信息系统 + /// select 重量1,重量2,重量差,允许重量差,合格标志 + /// + public partial class BaseDataSystemMES + { + /// + /// 测量数据合格_查询_称重 + /// + /// + /// + static public void ShowWeightData_Select(string engineID, out DataTable dt) + { + string procedureName; + procedureName = "测量数据合格_查询_称重"; + SqlParameter[] thisParms = new SqlParameter[1]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@发动机号", engineID); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out dt); + } + /// + ///测量数据合格_合并_视图_查询_照相 + /// select IsGoodBad as 合格标志, 列位置 + ///from 测量数据合格_合并_视图 + ///where EngineID=@工件编号 and 工位号=@工位号 + ///order by 列位置 + /// + /// + /// + /// + static public void ShowPicData_Select(string engineID, string opName, out DataTable dt) + { + string procedureName; + procedureName = "测量数据合格_合并_视图_查询_照相"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@发动机号", engineID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out dt); + } + + /// + /// insert into 电子看板_发动机号_分线组件装配关系 + ///(工位号,发动机号,机型代码,发动机型号,工位号_分线,发动机号_分线,机型代码_分线,发动机型号_分线) + ///values(@工位号,@发动机号,@机型代码,@发动机型号,@工位号_分线,@发动机号_分线,@机型代码_分线,@发动机型号_分线) + /// + /// + /// + /// + /// + /// + /// + /// + /// + static public void MailLineAndSubLineData_Insert(string opName, string engineID, int engineTypeID, string engineType, string opName_SubLine, string engineID_SubLine, int engineTypeID_SubLine, string engineType_SubLine) + { + string procedureName; + procedureName = "电子看板_发动机号_分线组件装配关系_增加"; + SqlParameter[] thisParms = new SqlParameter[8]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@发动机号", engineID); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@机型代码", engineTypeID); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@发动机型号", engineType); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@工位号_分线", opName_SubLine); + thisParms[5] = new System.Data.SqlClient.SqlParameter("@发动机号_分线", engineID_SubLine); + thisParms[6] = new System.Data.SqlClient.SqlParameter("@机型代码_分线", engineTypeID_SubLine); + thisParms[7] = new System.Data.SqlClient.SqlParameter("@发动机型号_分线", engineType_SubLine); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } + /// + /// 电子看板_发动机号_线首工位_查询_根据发动机号 + /// select 工位号,订单号,发动机号,基本机型,机型代码,发动机型号,托盘号, + /// 条码类型,零件流水号,零件流水号带空格,壳体编号型号,壳体编号型号带空格,QR码 + /// from dbo.电子看板_发动机号_线首工位 + /// where 发动机号=@发动机号 and 是否禁用=0 + /// + /// + /// + static public void GetEngineID_Select(string engineID, out DataTable dt) + { + string procedureName; + procedureName = "电子看板_发动机号_线首工位_查询_根据发动机号"; + SqlParameter[] thisParms = new SqlParameter[1]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@发动机号", engineID); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out dt); + } + /// + /// select 工位号,发动机号,机型代码,发动机型号,返修数据 + /// from 电子看板_发动机号_工件下线 + /// where 零件流水号=@零件流水号 --and 是否禁用=0 + /// + /// 零件流水号 + /// + static public void GetRepareData_Select(string partCode, out DataTable dt) + { + string procedureName; + procedureName = "电子看板_发动机号_工件下线_查询"; + SqlParameter[] thisParms = new SqlParameter[1]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@零件流水号", partCode); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out dt); + } + + /// + ///select '' as 工位号,发动机号,机型代码,发动机型号,'' as 返修数据 + ///from 电子看板_发动机号_线首工位 + ///where 零件流水号_返修=@零件流水号 and 是否禁用=0 + /// + /// 零件流水号 + /// + static public void GetRepareData_OtherLine_Select(string partCode, out DataTable dt) + { + string procedureName; + procedureName = "电子看板_发动机号_工件下线_其它装配线_查询"; + SqlParameter[] thisParms = new SqlParameter[1]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@零件流水号", partCode); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out dt); + } + + // + /// + /// 电子看板_发动机号_工件下线_增加 + /// @工位号 nvarchar(50) = null, + /// @发动机号 nvarchar(50) = null, + /// @机型代码 int = 1, + /// @发动机型号 nvarchar(50) = null, + /// @返修数据 nvarchar(4000) = null + /// + /// + /// 零件流水号 + /// + /// + /// + /// + static public void GetRepareData_Insert(string opName,string partCode, + string engineID, int engineTypeID, string engineType, string engineData) + { + string procedureName; + procedureName = "电子看板_发动机号_工件下线_增加"; + SqlParameter[] thisParms = new SqlParameter[6]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@零件流水号", partCode); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@发动机号", engineID); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@机型代码", engineTypeID); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@发动机型号", engineType); + thisParms[5] = new System.Data.SqlClient.SqlParameter("@返修数据", engineData); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } + /// + /// 电子看板_发动机号_线首工位_增加 + /// + /// 工位号 + /// 订单号 + /// 托盘号 + /// 工件机型 + /// 工件机型,机型代码,工件编号, 壳体编号型号,工件流水号,QR码,基本流水号 + static public bool GetEngineID_Save(string opName, string orderForm, string PartPalletCode, string engineType, DataTable dt) + { + string engineID; + int engineTypeID; + string partCode_Space; + string partCode; + string shellCode; + string shellCode_Space; + string QR_Code; + int engineCount; + int barCodeType; + string engineTypeBase; + string partCode_Text; + string partCode_BarCode; + string engineType_Text; + string engineType_BarCode; + string codeCreatetime; + try + { + GetEngineIDFromFirstOpName_Auto(out engineID, out engineTypeID, out partCode_Space, + out partCode, out shellCode, out shellCode_Space, out QR_Code, + out engineCount, out barCodeType, out engineTypeBase, + out partCode_Text, out partCode_BarCode, out engineType_Text, out engineType_BarCode, out codeCreatetime, dt); + + + string procedureName; + procedureName = "电子看板_发动机号_线首工位_增加"; + SqlParameter[] thisParms = new SqlParameter[19]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@订单号", orderForm); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@发动机号", engineID); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@发动机型号", engineType); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@基本机型", engineTypeBase); + thisParms[5] = new System.Data.SqlClient.SqlParameter("@机型代码", engineTypeID); + thisParms[6] = new System.Data.SqlClient.SqlParameter("@托盘号", PartPalletCode); + thisParms[7] = new System.Data.SqlClient.SqlParameter("@条码类型", barCodeType); + thisParms[8] = new System.Data.SqlClient.SqlParameter("@零件流水号", partCode); + thisParms[9] = new System.Data.SqlClient.SqlParameter("@零件流水号带空格", partCode_Space); + thisParms[10] = new System.Data.SqlClient.SqlParameter("@壳体编号型号", shellCode); + thisParms[11] = new System.Data.SqlClient.SqlParameter("@壳体编号型号带空格", shellCode_Space); + thisParms[12] = new System.Data.SqlClient.SqlParameter("@QR码", QR_Code); + thisParms[13] = new System.Data.SqlClient.SqlParameter("@基本流水号", engineCount); + thisParms[14] = new System.Data.SqlClient.SqlParameter("@流水号文本", partCode_Text); + thisParms[15] = new System.Data.SqlClient.SqlParameter("@流水号条码", partCode_BarCode); + thisParms[16] = new System.Data.SqlClient.SqlParameter("@型号文本", engineType_Text); + thisParms[17] = new System.Data.SqlClient.SqlParameter("@型号条码", engineType_BarCode); + thisParms[18] = new System.Data.SqlClient.SqlParameter("@条码创建时间", codeCreatetime); + return DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + // return DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out dt); + } + + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, err.Message); + return false; + + } + } + + /// + /// 电子看板_发动机号_线首工位_增加 + /// + /// 工位号 + /// 订单号 + /// 托盘号 + /// 工件机型 + /// 工件机型,机型代码,工件编号, 壳体编号型号,工件流水号,QR码,基本流水号 + static public bool GetEngineID_Save_SY(string opName, string engineID1, string orderForm, string PartPalletCode, string engineType, DataTable dt) + { + string engineID; + int engineTypeID; + string partCode_Space; + string partCode; + string shellCode; + string shellCode_Space; + string QR_Code; + int engineCount; + int barCodeType; + string engineTypeBase; + string partCode_Text; + string partCode_BarCode; + string engineType_Text; + string engineType_BarCode; + string codeCreatetime; + try + { + GetEngineIDFromFirstOpName_Auto(out engineID, out engineTypeID, out partCode_Space, + out partCode, out shellCode, out shellCode_Space, out QR_Code, + out engineCount, out barCodeType, out engineTypeBase, + out partCode_Text, out partCode_BarCode, out engineType_Text, out engineType_BarCode, out codeCreatetime, dt); + + + string procedureName; + procedureName = "电子看板_发动机号_线首工位_增加"; + SqlParameter[] thisParms = new SqlParameter[19]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@订单号", orderForm); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@发动机号", engineID1); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@发动机型号", engineType); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@基本机型", engineTypeBase); + thisParms[5] = new System.Data.SqlClient.SqlParameter("@机型代码", engineTypeID); + thisParms[6] = new System.Data.SqlClient.SqlParameter("@托盘号", PartPalletCode); + thisParms[7] = new System.Data.SqlClient.SqlParameter("@条码类型", barCodeType); + thisParms[8] = new System.Data.SqlClient.SqlParameter("@零件流水号", partCode); + thisParms[9] = new System.Data.SqlClient.SqlParameter("@零件流水号带空格", partCode_Space); + thisParms[10] = new System.Data.SqlClient.SqlParameter("@壳体编号型号", shellCode); + thisParms[11] = new System.Data.SqlClient.SqlParameter("@壳体编号型号带空格", shellCode_Space); + thisParms[12] = new System.Data.SqlClient.SqlParameter("@QR码", QR_Code); + thisParms[13] = new System.Data.SqlClient.SqlParameter("@基本流水号", engineCount); + thisParms[14] = new System.Data.SqlClient.SqlParameter("@流水号文本", partCode_Text); + thisParms[15] = new System.Data.SqlClient.SqlParameter("@流水号条码", partCode_BarCode); + thisParms[16] = new System.Data.SqlClient.SqlParameter("@型号文本", engineType_Text); + thisParms[17] = new System.Data.SqlClient.SqlParameter("@型号条码", engineType_BarCode); + thisParms[18] = new System.Data.SqlClient.SqlParameter("@条码创建时间", codeCreatetime); + return DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + // return DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out dt); + } + + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, err.Message); + return false; + + } + } + /// + /// 测量数据发动机在线状态_工件到位时间_查询 + /// + /// + /// + /// + static public void GetTime_Arrived(int EngineTypeID, string EngineID, out DataTable dt) + { + string procedureName; + procedureName = "测量数据发动机在线状态_工件到位时间_查询"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@机型代码", EngineTypeID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@发动机号", EngineID); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out dt); + } + + + + //2013-01-06 王可心 手动创建编号时调用 + /// + /// [电子看板_发动机号_线首工位_手动方式_增加] + /// + /// 工位号 + /// 订单号 + /// 托盘号 + /// 工件机型 + /// 工件机型,机型代码,工件编号, 壳体编号型号,工件流水号,QR码,基本流水号 + static public bool GetEngineID_ManulEngine_Save(string opName, string orderForm, string PartPalletCode, string engineType, string EngineID_DateTime, DataTable dt) + { + string engineID; + int engineTypeID; + string partCode_Space; + string partCode; + string shellCode; + string shellCode_Space; + string QR_Code; + int engineCount; + int barCodeType; + string engineTypeBase; + string partCode_Text; + string partCode_BarCode; + string engineType_Text; + string engineType_BarCode; + + try + { + GetEngineIDFromFirstOpName(out engineID, out engineTypeID, out partCode_Space, + out partCode, out shellCode, out shellCode_Space, out QR_Code, + out engineCount, out barCodeType, out engineTypeBase, + out partCode_Text, out partCode_BarCode, out engineType_Text, out engineType_BarCode, dt); + + + string procedureName; + procedureName = "电子看板_发动机号_线首工位_手动方式_增加"; + SqlParameter[] thisParms = new SqlParameter[19]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@订单号", orderForm); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@发动机号", engineID); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@发动机型号", engineType); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@基本机型", engineTypeBase); + thisParms[5] = new System.Data.SqlClient.SqlParameter("@机型代码", engineTypeID); + thisParms[6] = new System.Data.SqlClient.SqlParameter("@托盘号", PartPalletCode); + thisParms[7] = new System.Data.SqlClient.SqlParameter("@条码类型", barCodeType); + thisParms[8] = new System.Data.SqlClient.SqlParameter("@零件流水号", partCode); + thisParms[9] = new System.Data.SqlClient.SqlParameter("@零件流水号带空格", partCode_Space); + thisParms[10] = new System.Data.SqlClient.SqlParameter("@壳体编号型号", shellCode); + thisParms[11] = new System.Data.SqlClient.SqlParameter("@壳体编号型号带空格", shellCode_Space); + thisParms[12] = new System.Data.SqlClient.SqlParameter("@QR码", QR_Code); + thisParms[13] = new System.Data.SqlClient.SqlParameter("@基本流水号", engineCount); + thisParms[14] = new System.Data.SqlClient.SqlParameter("@流水号文本", partCode_Text); + thisParms[15] = new System.Data.SqlClient.SqlParameter("@流水号条码", partCode_BarCode); + thisParms[16] = new System.Data.SqlClient.SqlParameter("@型号文本", engineType_Text); + thisParms[17] = new System.Data.SqlClient.SqlParameter("@型号条码", engineType_BarCode); + thisParms[18] = new System.Data.SqlClient.SqlParameter("@工件编号时间", EngineID_DateTime); + + return DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + // return DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out dt); + } + + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, err.Message); + return false; + + } + } + + /// + /// 电子看板_发动机号_线首工位_查询_QR码返修 + /// + /// + /// + static public void GetRepareDataSelect_QR(string QR, out DataTable dt) + { + string procedureName; + procedureName = "电子看板_发动机号_线首工位_查询_QR码返修"; + SqlParameter[] thisParms = new SqlParameter[1]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@QR码", QR); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out dt); + } + /// + /// 电子看板_发动机号_线首工位_查询_两行条码返修 + /// + /// + /// + static public void GetRepareDataSelect_EngingeRepair(string barCode_EngineType, string barCode_EngineNum, out DataTable dt) + { + string procedureName; + procedureName = "电子看板_发动机号_线首工位_查询_两行条码返修"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@型号条码", barCode_EngineType); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@流水号条码", barCode_EngineNum); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out dt); + } + + } +} diff --git a/Common/07WebBusinessFacade/BusinessFacade/MES.B5A.MainForm/OpName.MainForm.Launch.cs b/Common/07WebBusinessFacade/BusinessFacade/MES.B5A.MainForm/OpName.MainForm.Launch.cs new file mode 100644 index 0000000..314135b --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/MES.B5A.MainForm/OpName.MainForm.Launch.cs @@ -0,0 +1,316 @@ +using System; +using System.Data; +using System.Data.SqlClient; +using DataLinkMesWork; +using System.Collections; +using System.Collections.Specialized; +//using SystemFramework; + +namespace bizFacade +{ + /// + /// 电子看板信息系统 + /// + public partial class BaseDataSystemMES + { + + /// + /// 获得总线发动机号 + /// + /// + /// + /// + static public void GetEngineID_MailLine(string opName, string engineType, out DataTable dt) + { + bool isSubLine; + isSubLine = false; + GetEngineID_Auto(opName, engineType, isSubLine, out dt); + } + /// + /// 获得分线发动机号 + /// + /// + /// + /// 工件机型,机型代码,工件编号,壳体编号型号,工件流水号,QR码,基本流水号 + static public void GetEngineID_SubLine(string opName, string engineType, out DataTable dt) + { + bool isSubLine; + isSubLine = true; + GetEngineID_Auto(opName, engineType, isSubLine, out dt); + } + /// + /// 电子看板_发动机号_线首工位_创建线首发动机号_根据输入机型代码 + /// 工件机型,机型代码,工件编号,壳体编号型号,工件流水号,QR码,基本流水号 + /// + /// 工位号 + /// 发动机型号 + /// 是否分线--@是否分线 = 0 总线线首(OP2010);=1分线线首(OP1010,OP2100) + /// 工件机型,机型代码,工件编号,壳体编号型号,工件流水号,QR码,基本流水号 + static public void GetEngineID_Auto(string opName, string engineType, bool isSubLine, out DataTable dt) + { + string procedureName; + procedureName = "电子看板_发动机号_线首工位_创建线首发动机号_根据输入机型代码"; + SqlParameter[] thisParms = new SqlParameter[3]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@发动机型号", engineType); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@是否分线", isSubLine); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out dt); + } + /// + /// 电子看板_发动机号_线首工位_创建线首发动机号_根据输入机型代码_手动方式 + /// + /// 工位号 + /// 发动机型号 + /// 年份 + /// 月份 + /// 日期 + /// 流水号 + /// + static public void GetEngineID_Manual_MainLine(string opName, string engineType, string engineYear, string engineMoon, string engineDay, int engineNumber, out DataTable dt) + { + //@是否分线 bit=0 @是否分线 = 0 总线线首(OP2010);=1分线线首(OP1010,OP2100) + bool isSubLine = false; + GetEngineID_Manual(opName, engineType, engineYear, engineMoon, engineDay, engineNumber, isSubLine, out dt); + } + /// + /// 电子看板_发动机号_线首工位_创建线首发动机号_根据输入机型代码_手动方式 + /// + /// 工位号 + /// 发动机型号 + /// 年份 + /// 月份 + /// 日期 + /// 流水号 + /// + static public void GetEngineID_Manual_SunLine(string opName, string engineType, string engineYear, string engineMoon, string engineDay, int engineNumber, out DataTable dt) + { + //@是否分线 bit=0 @是否分线 = 0 总线线首(OP2010);=1分线线首(OP1010,OP2100) + bool isSubLine = true; + GetEngineID_Manual(opName, engineType, engineYear, engineMoon, engineDay, engineNumber, isSubLine, out dt); + } + + /// + /// 电子看板_发动机号_线首工位_创建线首发动机号_根据输入机型代码_手动方式 + /// + /// 工位号 + /// 发动机型号 + /// 年份 + /// 月份 + /// 日期 + /// 流水号 + /// @是否分线 bit=0 @是否分线 = 0 总线线首(OP2010);=1分线线首(OP1010,OP2100) + /// + static public void GetEngineID_Manual(string opName, string engineType, string engineYear, string engineMoon, string engineDay, int engineNumber, bool isSubLine, out DataTable dt) + { + string procedureName; + procedureName = "电子看板_发动机号_线首工位_创建线首发动机号_根据输入机型代码_手动方式"; + SqlParameter[] thisParms = new SqlParameter[7]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@发动机型号", engineType); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@年份", engineYear); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@月份", engineMoon); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@日期", engineDay); + thisParms[5] = new System.Data.SqlClient.SqlParameter("@流水号", engineNumber); + thisParms[6] = new System.Data.SqlClient.SqlParameter("@是否分线", isSubLine); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out dt); + } + + /// + /// 电子看板_发动机号_线首工位_创建线首发动机号_根据输入机型代码_手动方式 + /// + /// 工位号 + /// 发动机型号 + /// 年份 + /// 月份 + /// 日期 + /// 流水号 + /// @是否分线 bit=0 @是否分线 = 0 总线线首(OP2010);=1分线线首(OP1010,OP2100) + /// + static public void GetEngineID_Manual_OldLineLoad(string opName, string engineType, string engineYear, string engineMoon, string engineDay, int engineNumber, bool isSubLine, out DataTable dt) + { + string procedureName; + procedureName = "电子看板_发动机号_线首工位_创建线首发动机号_根据输入机型代码_手动方式_老线上线用"; + SqlParameter[] thisParms = new SqlParameter[7]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@发动机型号", engineType); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@年份", engineYear); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@月份", engineMoon); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@日期", engineDay); + thisParms[5] = new System.Data.SqlClient.SqlParameter("@流水号", engineNumber); + thisParms[6] = new System.Data.SqlClient.SqlParameter("@是否分线", isSubLine); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out dt); + } + /// + /// [电子看板_发动机号_线首工位]信息手动用 + /// + /// 发动机号 + /// 机型代码 + /// 零件流水号带空格 + /// 零件流水号 + /// 壳体编号型号 + /// 壳体编号型号带空格 + /// QR码 + /// 基本流水号 + /// 条码类型 + /// 基本机型 + /// 流水号文本 + /// 流水号条码 + /// 型号文本 + /// 型号条码 + /// + static public void GetEngineIDFromFirstOpName(out string engineID, out int engineTypeID, out string partCode_Space, + out string partCode, out string shellCode, out string shellCode_Space, out string QR_Code, + out int engineCount, out int barCodeType, out string engineTypeBase, + out string partCode_Text, out string partCode_BarCode, + out string engineType_Text, out string engineType_BarCode, + DataTable dt) + { + engineID = ""; + engineTypeID = 0; + partCode_Space=""; + partCode=""; + shellCode=""; + shellCode_Space=""; + QR_Code=""; + engineCount=0; + barCodeType=0; + engineTypeBase=""; + partCode_Text=""; + partCode_BarCode=""; + engineType_Text=""; + engineType_BarCode = ""; + + engineID = dt.Rows[0]["发动机号"].ToString(); + engineTypeID = Convert.ToInt32(dt.Rows[0]["机型代码"]); + shellCode = dt.Rows[0]["壳体编号型号"].ToString(); + shellCode_Space = dt.Rows[0]["壳体编号型号带空格"].ToString(); + partCode = dt.Rows[0]["零件流水号"].ToString(); + partCode_Space = dt.Rows[0]["零件流水号带空格"].ToString(); + QR_Code = dt.Rows[0]["QR码"].ToString(); + engineCount = Convert.ToInt32(dt.Rows[0]["基本流水号"]); + engineTypeBase = dt.Rows[0]["基本机型"].ToString(); + barCodeType = Convert.ToInt32(dt.Rows[0]["条码类型"]); + partCode_Text = dt.Rows[0]["流水号文本"].ToString(); + partCode_BarCode = dt.Rows[0]["流水号条码"].ToString(); + engineType_Text = dt.Rows[0]["型号文本"].ToString(); + engineType_BarCode = dt.Rows[0]["型号条码"].ToString(); + + } + + /// + /// [电子看板_发动机号_线首工位]信息自动用 + /// + /// 发动机号 + /// 机型代码 + /// 零件流水号带空格 + /// 零件流水号 + /// 壳体编号型号 + /// 壳体编号型号带空格 + /// QR码 + /// 基本流水号 + /// 条码类型 + /// 基本机型 + /// 流水号文本 + /// 流水号条码 + /// 型号文本 + /// 型号条码 + /// + static public void GetEngineIDFromFirstOpName_Auto(out string engineID, out int engineTypeID, out string partCode_Space, + out string partCode, out string shellCode, out string shellCode_Space, out string QR_Code, + out int engineCount, out int barCodeType, out string engineTypeBase, + out string partCode_Text, out string partCode_BarCode, + out string engineType_Text, out string engineType_BarCode,out string CodeCreatetime, + DataTable dt) + { + engineID = ""; + engineTypeID = 0; + partCode_Space = ""; + partCode = ""; + shellCode = ""; + shellCode_Space = ""; + QR_Code = ""; + engineCount = 0; + barCodeType = 0; + engineTypeBase = ""; + partCode_Text = ""; + partCode_BarCode = ""; + engineType_Text = ""; + engineType_BarCode = ""; + + engineID = dt.Rows[0]["发动机号"].ToString(); + engineTypeID = Convert.ToInt32(dt.Rows[0]["机型代码"]); + shellCode = dt.Rows[0]["壳体编号型号"].ToString(); + shellCode_Space = dt.Rows[0]["壳体编号型号带空格"].ToString(); + partCode = dt.Rows[0]["零件流水号"].ToString(); + partCode_Space = dt.Rows[0]["零件流水号带空格"].ToString(); + QR_Code = dt.Rows[0]["QR码"].ToString(); + engineCount = Convert.ToInt32(dt.Rows[0]["基本流水号"]); + engineTypeBase = dt.Rows[0]["基本机型"].ToString(); + barCodeType = Convert.ToInt32(dt.Rows[0]["条码类型"]); + partCode_Text = dt.Rows[0]["流水号文本"].ToString(); + partCode_BarCode = dt.Rows[0]["流水号条码"].ToString(); + engineType_Text = dt.Rows[0]["型号文本"].ToString(); + engineType_BarCode = dt.Rows[0]["型号条码"].ToString(); + CodeCreatetime = dt.Rows[0]["条码创建时间"].ToString(); + + } + /// + /// [电子看板_发动机号_线首工位]信息 + /// + /// 发动机号 + /// 机型代码 + /// 零件流水号带空格 + /// 零件流水号 + /// 壳体编号型号 + /// 壳体编号型号带空格 + /// QR码 + /// 基本流水号 + /// 条码类型 + /// 基本机型 + /// 流水号文本 + /// 流水号条码 + /// 型号文本 + /// 型号条码 + /// 零件流水号_返修 + /// + static public void GetEngineIDFromFirstOpName(out string engineID, out int engineTypeID, out string partCode_Space, + out string partCode, out string shellCode, out string shellCode_Space, out string QR_Code, + out int engineCount, out int barCodeType, out string engineTypeBase, + out string partCode_Text, out string partCode_BarCode, + out string engineType_Text, out string engineType_BarCode, out string partCode_Repair, + DataTable dt) + { + engineID = ""; + engineTypeID = 0; + partCode_Space = ""; + partCode = ""; + shellCode = ""; + shellCode_Space = ""; + QR_Code = ""; + engineCount = 0; + barCodeType = 0; + engineTypeBase = ""; + partCode_Text = ""; + partCode_BarCode = ""; + engineType_Text = ""; + engineType_BarCode = ""; + + engineID = dt.Rows[0]["发动机号"].ToString(); + engineTypeID = Convert.ToInt32(dt.Rows[0]["机型代码"]); + shellCode = dt.Rows[0]["壳体编号型号"].ToString(); + shellCode_Space = dt.Rows[0]["壳体编号型号带空格"].ToString(); + partCode = dt.Rows[0]["零件流水号"].ToString(); + partCode_Space = dt.Rows[0]["零件流水号带空格"].ToString(); + QR_Code = dt.Rows[0]["QR码"].ToString(); + engineCount = Convert.ToInt32(dt.Rows[0]["基本流水号"]); + engineTypeBase = dt.Rows[0]["基本机型"].ToString(); + barCodeType = Convert.ToInt32(dt.Rows[0]["条码类型"]); + partCode_Text = dt.Rows[0]["流水号文本"].ToString(); + partCode_BarCode = dt.Rows[0]["流水号条码"].ToString(); + engineType_Text = dt.Rows[0]["型号文本"].ToString(); + engineType_BarCode = dt.Rows[0]["型号条码"].ToString(); + partCode_Repair = dt.Rows[0]["零件流水号_返修"].ToString(); + + } + } +} diff --git a/Common/07WebBusinessFacade/BusinessFacade/MES.B5A.MainForm/OpName.MainForm.Material.cs b/Common/07WebBusinessFacade/BusinessFacade/MES.B5A.MainForm/OpName.MainForm.Material.cs new file mode 100644 index 0000000..81896ca --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/MES.B5A.MainForm/OpName.MainForm.Material.cs @@ -0,0 +1,165 @@ +using System; +using System.Data; +using System.Data.SqlClient; +using DataLinkMesWork; +using System.Collections; +using System.Collections.Specialized; +//using SystemFramework; + +namespace bizFacade +{ + /// + /// 电子看板信息系统 + /// + public partial class BaseDataSystemMES + { + /// + /// MES_装配数据_零部件追溯_数据主表_增加_电子看板 + /// @发动机号 nvarchar(50)=null, + /// @发动机型号 nvarchar(50)=null, + /// @机型代码 int=null, + /// @订单号 nvarchar(50)=null, + /// @工位号 nvarchar(50)=null, + /// @到达时间 datetime, + /// @离开时间 datetime, + /// @操作者工号 nvarchar(50)=null, + /// @班次代码 nvarchar(50)=null, + /// @放行方式 int =null, + /// @工位类型 nvarchar(50)=null, + /// @追溯代码 int = null output + /// + /// 发动机号 + /// 发动机型号 + /// 机型代码 + /// 订单号 + /// 工位号 + /// 到达时间 + /// 离开时间 + /// 操作者工号 + /// 班次代码 + /// 放行方式 + /// 工位类型 + /// 追溯代码 + static public void MaterialMailTable_Insert(string engineID,string engineType,int engineTypeID,string orderForm,string opName, + DateTime arrivedTime,DateTime leavTime,string opperatorCode,string shiftCode, + int goOverType,string opNameType,out int traceCode) + { + + string procedureName; + try + { + procedureName = "MES_装配数据_零部件追溯_数据主表_增加_电子看板"; + SqlParameter[] thisParms = new SqlParameter[12]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@发动机号", engineID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@发动机型号", engineType); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@机型代码", engineTypeID); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@订单号", orderForm); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[5] = new System.Data.SqlClient.SqlParameter("@到达时间", arrivedTime); + thisParms[6] = new System.Data.SqlClient.SqlParameter("@离开时间", leavTime); + thisParms[7] = new System.Data.SqlClient.SqlParameter("@操作者工号", opperatorCode); + thisParms[8] = new System.Data.SqlClient.SqlParameter("@班次代码", shiftCode); + thisParms[9] = new System.Data.SqlClient.SqlParameter("@放行方式", goOverType); + thisParms[10] = new System.Data.SqlClient.SqlParameter("@工位类型", opNameType); + thisParms[11] = new System.Data.SqlClient.SqlParameter("@追溯代码", 0); + thisParms[11].Direction = ParameterDirection.Output; + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + + traceCode = Convert.ToInt32(thisParms[11].Value); + } + catch (Exception err) + { + traceCode = 0; + ////ApplicationLog.WriteLog(err, err.Message); + } + + } + + + /// + /// MES_装配数据_零部件追溯_增加_电子看板 + ///ALTER PROCEDURE MES_装配数据_零部件追溯_增加_电子看板 + ///@追溯代码 int = null, + ///@发动机号 nvarchar(50)=null, + ///@工位号 nvarchar(50)=null, + ///@零件图号 nvarchar(50)=null, + ///@零件名称 nvarchar(50)=null, + ///@零件数量 int=null, + ///@生产厂家 nvarchar(50)=null, + ///@物料条码批次 nvarchar(50)=null, + ///@操作者工号 nvarchar(50)=null, + ///@班次代码 nvarchar(50)=null + /// + /// + /// + /// + /// + /// + /// + static public void MaterialSubTable_Insert(int traceCode,string engineID, string opName,string opperatorCode,string shiftCode, + DataTable dt) + { + string procedureName; + procedureName = "MES_装配数据_零部件追溯_增加_电子看板"; + SqlParameter[] thisParms = new SqlParameter[10]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@追溯代码", traceCode); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@发动机号", engineID); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@操作者工号", opperatorCode); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@班次代码", shiftCode); + thisParms[5] = new System.Data.SqlClient.SqlParameter("@零件图号", SqlDbType.NVarChar, 50, "零件图号"); + thisParms[6] = new System.Data.SqlClient.SqlParameter("@零件名称", SqlDbType.NVarChar, 50, "零件名称"); + thisParms[7] = new System.Data.SqlClient.SqlParameter("@零件数量", SqlDbType.Int, 4, "零件数量"); + thisParms[8] = new System.Data.SqlClient.SqlParameter("@生产厂家", SqlDbType.NVarChar, 50, "生产厂家"); + thisParms[9] = new System.Data.SqlClient.SqlParameter("@物料条码批次", SqlDbType.NVarChar, 50, "零件批号"); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms,dt); + } + /// + /// 保存物料信息 + /// + /// 发动机号 + /// 发动机型号 + /// 机型代码 + /// 订单号 + /// 工位号 + /// 到达时间 + /// 离开时间 + /// 操作者工号 + /// 班次代码 + /// 放行方式 + /// 工位类型 + /// 装配物料列表 + static public void Material_Insert_B5A(string engineID, string engineType, int engineTypeID, string orderForm, string opName, + DateTime arrivedTime, DateTime leavTime, string opperatorCode, string shiftCode, + int goOverType, string opNameType, DataTable dt) + { + int traceCode; + //MES_装配数据_零部件追溯_数据主表_增加_电子看板 + MaterialMailTable_Insert( engineID, engineType, engineTypeID,orderForm,opName,arrivedTime, leavTime, opperatorCode, shiftCode,goOverType, opNameType,out traceCode); + //MES_装配数据_零部件追溯_增加_电子看板 + MaterialSubTable_Insert(traceCode, engineID, opName, opperatorCode, shiftCode, dt); + } + + /// + /// 电子看板_工位名称与产品型号工艺卡_查询 + /// + /// + /// + /// + static public void GetPdfSrc(string opName, string engineTypeID, out string PdfSrc) + { + string sql; + DataTable dt; + PdfSrc = null; + sql = "exec 电子看板_工位名称与产品型号工艺卡_查询 '" + opName + "'," + engineTypeID; + DataAccess.ExecuteDataTable(sql, out dt); + if (dt != null) + { + if (dt.Rows.Count > 0) + { + PdfSrc = dt.Rows[0]["工艺卡路径"].ToString(); + } + } + } + } +} diff --git a/Common/07WebBusinessFacade/BusinessFacade/MES.B5A.MainForm/OpName.MainForm.cs b/Common/07WebBusinessFacade/BusinessFacade/MES.B5A.MainForm/OpName.MainForm.cs new file mode 100644 index 0000000..68105fb --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/MES.B5A.MainForm/OpName.MainForm.cs @@ -0,0 +1,89 @@ +using System; +using System.Data; +using System.Data.SqlClient; +using DataLinkMesWork; +using System.Collections; +using System.Collections.Specialized; +//using SystemFramework; + +namespace bizFacade +{ + /// + /// 电子看板信息系统 + /// + public partial class BaseDataSystemMES + { + + /// + /// 基本数据_工作日历_查询 + /// 日期,班次代码,工位产量,工位节拍,在线产量,在线节拍 + /// + /// + /// + /// + /// + /// + /// + /// + static public void OpNameCount_Select(DateTime dateTime, string opName, + out int shiftCode,out int OpNameCount,out int opNameTargetTime,out int onlineCount,out int onlineTargetTime) + { + + DataTable dt; + OpNameCount = 0; + shiftCode = 1; + OpNameCount = 0; + opNameTargetTime = 0; + onlineCount = 0; + onlineTargetTime = 0; + + string procedureName; + procedureName = "基本数据_工作日历_查询"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@日期", dateTime); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms,out dt); + if (dt != null) + { + if (dt.Rows.Count > 0) + { + try + { + shiftCode = Convert.ToInt32(dt.Rows[0]["班次代码"]); + OpNameCount = Convert.ToInt32(dt.Rows[0]["工位产量"]); + opNameTargetTime = Convert.ToInt32(dt.Rows[0]["工位节拍"]); + onlineCount = Convert.ToInt32(dt.Rows[0]["在线产量"]); + onlineTargetTime = Convert.ToInt32(dt.Rows[0]["在线节拍"]); + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, err.Message); + } + } + } + } + /// + /// MES_操作着_生产班次_查询 + /// + /// + static public void Shift_Select(out DataTable dt) + { + string sql; + sql = "exec MES_操作着_生产班次_查询"; + DataAccess.ExecuteDataTable(sql, out dt); + } + /// + /// 电子看板_托盘编号_查询 + /// + /// + static public void PartPalletCode_Select(out DataTable dt) + { + string sql; + sql = "exec 电子看板_托盘编号_查询"; + DataAccess.ExecuteDataTable(sql,out dt); + } + + + + } +} diff --git a/Common/07WebBusinessFacade/BusinessFacade/MES.B5A.MainForm/UserManage.cs b/Common/07WebBusinessFacade/BusinessFacade/MES.B5A.MainForm/UserManage.cs new file mode 100644 index 0000000..9205e3e --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/MES.B5A.MainForm/UserManage.cs @@ -0,0 +1,223 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Data; +using System.Data.SqlClient; +using DataLinkMesWork; + +//using SystemFramework; + +namespace bizFacade +{ + public partial class BaseDataSystemMES + { + /// + /// 登录用户与工位校验 + /// + /// + /// + /// + /// + static public bool User_WorkCenter(string userName,string opName, out bool result) + { + string sql; + DataTable dt = null; + sql = "SELECT COUNT(*) as usercount FROM [dbo].[MES_Web_User]" + +"where[UserId] = (select top 1 ID from MES_用户管理_人员 where 用户名 = '"+userName+"') and OpName = '"+opName+"'"; + DataAccess.ExecuteDataTable(sql, out dt); + string usercount = dt.Rows[0]["usercount"].ToString(); + if (dt.Rows.Count > 0 && usercount == "1") + { + return result=true; + } + else { + return result=false; + } + } + + /// + /// MES_用户管理_人员信息_视图_显示_查询 + /// + /// + static public void UserInfo_Select(out DataTable dt) + { + dt = null; + string sql = "exec MES_用户管理_人员信息_视图_显示_查询"; + DataAccess.ExecuteDataTable(sql, out dt); + } + + /// + /// [MES_用户管理_人员信息_视图_显示车间操作员_查询] + /// + /// + static public void UserInfo_OPStaff_Select(out DataTable dt) + { + dt = null; + string sql = "exec MES_用户管理_人员信息_视图_显示车间操作员_查询"; + DataAccess.ExecuteDataTable(sql, out dt); + } + + /// + /// MES_用户管理_角色_查询 + /// + static public void StaffRole_select(out DataTable dt) + { + string sql; + sql = "exec MES_用户管理_角色_查询"; + DataAccess.ExecuteDataTable(sql, out dt); + } + + /// + /// [MES_用户管理_人员_增加_查询] + /// 执行后,返回count(*) + /// + /// + + public static int UserInfo_Select_ForInsert(string userID) + { + int count; + string sql; + sql = "exec MES_用户管理_人员_增加_查询 '" + userID + "'"; + DataAccess.ExecuteOutNum(sql, out count); + return count; + } + + /// + /// MES_用户管理_人员_增加 + /// + /// + /// + static public bool UserInfo_Insert(string userID, string userName, int roleNum) + { + string procedureName; + procedureName = "MES_用户管理_人员_增加"; + SqlParameter[] thisParms = new SqlParameter[3]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@用户名", userID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@员工姓名", userName); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@角色代码", roleNum); + return DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + + } + + /// + /// MES_用户管理_人员_修改 + /// + /// + /// + static public bool UserInfo_Update(int ID,string userID,string userPassword,string userName, int roleNum) + { + string procedureName; + procedureName = "MES_用户管理_人员_修改"; + SqlParameter[] thisParms = new SqlParameter[5]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@ID", ID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@用户名", userID); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@密码", userPassword); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@员工姓名", userName); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@角色代码", roleNum); + + return DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + + + } + + /// + /// MES_用户管理_人员_姓名_修改 + /// + /// + /// + static public bool UserInfo_Name_Update(int ID, string userID,string userName) + { + string procedureName; + procedureName = "MES_用户管理_人员_姓名_修改"; + SqlParameter[] thisParms = new SqlParameter[3]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@ID", ID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@用户名", userID); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@员工姓名", userName); + return DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + + + } + + /// + ///[MES_用户管理_人员_删除] + /// + static public bool UserInfo_Delete(int ID, string userID) + { + string procedureName; + procedureName = "MES_用户管理_人员_删除"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@ID", ID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@用户名", userID); + return DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + + } + + + /// + /// MES_用户管理_人员登录_查询 + /// + /// + /// + static public void UserInfo_Login(string userID, string userPassword, out DataTable dt) + { + string procedureName; + procedureName = "MES_用户管理_人员登录_查询"; + //procedureName = "权限管理_用户登录_查询数据"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@用户名", userID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@密码", userPassword); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out dt); + } + + + /// + /// MES_用户管理_人员登录_是否存在_查询 + /// 执行后,返回count(*) + /// + /// + /// + /// + public static int UserInfo_Login_Exist_Select(string userID,string userPassword) + { + int count; + string sql; + sql = "exec MES_用户管理_人员登录_是否存在_查询 '" + userID + "'" + ",'" + userPassword + "'"; + DataAccess.ExecuteOutNum(sql, out count); + return count; + } + + + /// + /// MES_用户管理_人员_密码_修改 + /// + /// + /// + static public bool UserInfo_Password_Update(string userID, string userPassword,string userNewPassword) + { + string procedureName; + procedureName = "MES_用户管理_人员_密码_修改"; + SqlParameter[] thisParms = new SqlParameter[3]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@用户名", userID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@密码", userPassword); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@新密码", userNewPassword); + + return DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + + + } + + /// + /// 基本数据_工作日历_班次查询 2013-11-07 查出当前时间班次 + /// + /// + /// + static public void UserShift_Select(out DataTable dt) + { + string procedureName; + procedureName = "基本数据_工作日历_班次查询"; + DataAccess.ExecuteStoredProcedure(procedureName,out dt); + } + + + } +} diff --git a/Common/07WebBusinessFacade/BusinessFacade/MES.B5A.MainForm/UserNamePassword.cs b/Common/07WebBusinessFacade/BusinessFacade/MES.B5A.MainForm/UserNamePassword.cs new file mode 100644 index 0000000..e43c876 --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/MES.B5A.MainForm/UserNamePassword.cs @@ -0,0 +1,127 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Data; +using System.Data.SqlClient; +using DataLinkMesWork; + +//using SystemFramework; + +namespace bizFacade +{ + public partial class BaseDataSystemMES + { + /// + /// MES_操作者_登录_增加 + /// + /// + /// + public static void UserNameLoginInsert(string opName,string userName) + { + string procedureName; + procedureName = "MES_操作者_登录_增加"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@操作者工号", userName); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } + /// + /// MES_操作者_用户_增加 2013-01-23 王可心 + /// + /// + /// + static public bool UserNameTableInsert(string userName, string user) + { + string procedureName; + procedureName = "MES_操作者_用户_增加"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@操作者工号", userName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@操作者姓名", user); + return DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + + } + /// + /// MES_操作者_用户_修改 + /// + /// + /// + /// + public static void UserNameTableUpdate(string userName,string password,string passwordNew) + { + string sql; + sql = "exec MES_操作者_用户_修改 '" + userName + "','" + password + "','"+passwordNew+"'"; + DataAccess.ExecuteSQL(sql); + } + /// + /// MES_操作者_用户_设置初始秘密 + /// + /// + static public bool UserNameTableUpdateInitPassword(string userName) + { + string procedureName; + procedureName = "MES_操作者_用户_设置初始秘密"; + SqlParameter[] thisParms = new SqlParameter[1]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@操作者工号", userName); + return DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + + } + /// + /// MES_操作者_用户_查询 + /// 执行后,返回count(*) + /// + /// + /// + public static int UserNameTableSelect(string userName, string password) + { + int count; + string sql; + sql = "exec MES_操作者_用户_查询 '"+ userName + "','" + password + "'"; + DataAccess.ExecuteOutNum(sql, out count); + return count; + } + /// + /// MES_操作者_用户_增加用_查询 + /// 执行后,返回count(*) + /// + /// + + public static int UserNameTableSelectForInsert(string userName) + { + int count; + string sql; + sql = "exec MES_操作者_用户_增加用_查询 '" + userName + "'"; + DataAccess.ExecuteOutNum(sql, out count); + return count; + } + + + /// + /// MES_操作者_用户_删除 2013-01-23 王可心 删除该用户 + /// + /// 用户工号 + static public bool UserNameTableSelectForDelete(string userName) + { + string procedureName; + procedureName = "MES_操作者_用户_删除"; + SqlParameter[] thisParms = new SqlParameter[1]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@操作者工号", userName); + return DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } + + /// + /// MES_操作者_用户_姓名_修改 2013-01-23 王可心 + /// + /// + /// + static public bool UserNameTableAlter(string userName, string user) + { + string procedureName; + procedureName = "MES_操作者_用户_姓名_修改"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@操作者工号", userName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@操作者姓名", user); + return DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + + } + } +} diff --git a/Common/07WebBusinessFacade/BusinessFacade/MES.B5A.MainForm/vssver2.scc b/Common/07WebBusinessFacade/BusinessFacade/MES.B5A.MainForm/vssver2.scc new file mode 100644 index 0000000..22fe44a Binary files /dev/null and b/Common/07WebBusinessFacade/BusinessFacade/MES.B5A.MainForm/vssver2.scc differ diff --git a/Common/07WebBusinessFacade/BusinessFacade/MES.B5A.Manager/EngineType.cs b/Common/07WebBusinessFacade/BusinessFacade/MES.B5A.Manager/EngineType.cs new file mode 100644 index 0000000..a197682 --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/MES.B5A.Manager/EngineType.cs @@ -0,0 +1,238 @@ +using System; +using System.Data; +using System.Data.SqlClient; +using DataLinkMesWork; +using System.Collections; +using System.Collections.Specialized; +//using SystemFramework; + +namespace bizFacade +{ + /// + /// 电子看板信息系统 + /// + public partial class BaseDataSystemMES + { + /// + /// 电子看板_工作时间与班次_删除 + /// + /// 序号 + static public bool WorkShift_Delete(int shiftNO) + { + string procedureName; + procedureName = "电子看板_工作时间与班次_删除"; + SqlParameter[] thisParms = new SqlParameter[1]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@序号", shiftNO); + return DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } + /// + /// 电子看板_工作时间与班次_修改 + /// + /// 序号 + /// 开始工作时间 + /// 结束工作时间 + /// 班次代码 + /// 是否工作 + static public bool WorkShift_Update(int shiftNO,string shiftStartTime, + string shiftEndTime, int shiftWorkNo, int shiftIsWork) + { + string procedureName; + procedureName = "电子看板_工作时间与班次_修改"; + SqlParameter[] thisParms = new SqlParameter[5]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@序号", shiftNO); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@开始工作时间", shiftStartTime); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@结束工作时间", shiftEndTime); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@班次代码", shiftWorkNo); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@是否工作", shiftIsWork); + return DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } + /// + /// 电子看板_工作时间与班次_增加 + /// + /// 序号 + /// 开始工作时间 + /// 结束工作时间 + /// 班次代码 + /// 是否工作 + static public bool WorkShift_Insert(int shiftNO, string shiftStartTime, + string shiftEndTime, int shiftWorkNo, int shiftIsWork) + { + string procedureName; + procedureName = "电子看板_工作时间与班次_增加"; + SqlParameter[] thisParms = new SqlParameter[5]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@序号", shiftNO); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@开始工作时间", shiftStartTime); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@结束工作时间", shiftEndTime); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@班次代码", shiftWorkNo); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@是否工作", shiftIsWork); + return DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } + /// + /// 电子看板_工作时间与班次_查询 + /// + /// + static public void WorkShift_Select(out DataTable dt) + { + string sql; + sql = " exec 电子看板_工作时间与班次_查询"; + DataAccess.ExecuteDataTable(sql, out dt); + } + /// + /// MES_基本变量_基本机型_增加 + /// @基本机型 nvarchar(50), + /// @机型代码 int + /// + static public bool EngineBasicType_Insert(string engineBasicType, + int engineBasicTypeID, double maxWeight, double minWeight, double Vp, double tm) + { + string procedureName; + procedureName = "MES_基本变量_基本机型_增加"; + SqlParameter[] thisParms = new SqlParameter[6]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@基本机型", engineBasicType); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@机型代码", engineBasicTypeID); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@重量差上限", maxWeight); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@重量差下限", minWeight); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@Vp", Vp); + thisParms[5] = new System.Data.SqlClient.SqlParameter("@tm", tm); + return DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } + /// + /// MES_基本变量_基本机型_修改 + /// @序号 int, + /// @基本机型 nvarchar(50), + /// @机型代码 int + /// + static public bool EngineBasicType_Update(int sn,string engineBasicType, + int engineBasicTypeID, double maxWeight, double minWeight, double Vp, double tm) + { + string procedureName; + procedureName = "MES_基本变量_基本机型_修改"; + SqlParameter[] thisParms = new SqlParameter[7]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@序号", sn); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@基本机型", engineBasicType); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@机型代码", engineBasicTypeID); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@重量差上限", maxWeight); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@重量差下限", minWeight); + thisParms[5] = new System.Data.SqlClient.SqlParameter("@Vp", Vp); + thisParms[6] = new System.Data.SqlClient.SqlParameter("@tm", tm); + return DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } + /// + /// MES_基本变量_基本机型_删除 + /// @序号 int + /// + static public bool EngineBasicType_Delete(int sn) + { + string procedureName; + procedureName = "MES_基本变量_基本机型_删除"; + SqlParameter[] thisParms = new SqlParameter[1]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@序号", sn); + return DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } + /// + /// MES_基本变量_机型代码_增加 + /// @发动机型号 nvarchar(50), + /// @发动机机型标志 int, + /// @条码类型 int , + /// @流水号类型 int, + /// @工厂编号 nvarchar(50), + /// @装配线班组号 nvarchar(50), + /// @壳体编号型号 nvarchar(50), + /// @壳体编号型号带空格 nvarchar(50), + /// @QR码读数标志 nvarchar(50), + /// @QR码产品型号 nvarchar(50) + /// + /// 发动机型号 + /// 发动机机型标志 + /// 条码类型 + /// 流水号类型 + /// 工厂编号 + /// 装配线班组号 + /// 壳体编号型号 + /// 壳体编号型号带空格 + /// QR码读数标志 + /// QR码产品型号 + /// + static public bool EngineType_Insert(string engineType, int engineTypeID, + int barCodeID,int snNumberID,string factoryID,string shiftID, + string shellCode, string shellCode_Space, string QR_Code, string QR_Type, string shellCode_downline) + { + string procedureName; + procedureName = "MES_基本变量_机型代码_增加_new"; + SqlParameter[] thisParms = new SqlParameter[11]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@发动机型号", engineType); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@发动机机型标志", engineTypeID); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@条码类型", barCodeID); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@流水号类型", snNumberID); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@工厂编号", factoryID); + thisParms[5] = new System.Data.SqlClient.SqlParameter("@装配线班组号", shiftID); + thisParms[6] = new System.Data.SqlClient.SqlParameter("@壳体编号型号", shellCode); + thisParms[7] = new System.Data.SqlClient.SqlParameter("@壳体编号型号带空格", shellCode_Space); + thisParms[8] = new System.Data.SqlClient.SqlParameter("@QR码读数标志", QR_Code); + thisParms[9] = new System.Data.SqlClient.SqlParameter("@QR码产品型号", QR_Type); + thisParms[10] = new System.Data.SqlClient.SqlParameter("@壳体编号型号条码", shellCode_downline); + return DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } + /// + /// MES_基本变量_机型代码_修改 + /// @序号 int, + /// @发动机型号 nvarchar(50), + /// @发动机机型标志 int, + /// @条码类型 int , + /// @流水号类型 int, + /// @工厂编号 nvarchar(50), + /// @装配线班组号 nvarchar(50), + /// @壳体编号型号 nvarchar(50), + /// @壳体编号型号带空格 nvarchar(50), + /// @QR码读数标志 nvarchar(50), + /// @QR码产品型号 nvarchar(50) + /// + /// 序号 + /// 发动机型号 + /// 发动机机型标志 + /// 条码类型 + /// 流水号类型 + /// 工厂编号 + /// 装配线班组号 + /// 壳体编号型号 + /// 壳体编号型号带空格 + /// QR码读数标志 + /// QR码产品型号 + /// + static public bool EngineType_Update(int sn,string engineType, int engineBasicTypeID, + int barCodeID, int snNumberID, string factoryID, string shiftID, + string shellCode, string shellCode_Space, string QR_Code, string QR_Type,string shellCode_downline) + { + string procedureName; + procedureName = "MES_基本变量_机型代码_修改_new"; + SqlParameter[] thisParms = new SqlParameter[12]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@序号", sn); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@发动机型号", engineType); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@发动机机型标志", engineBasicTypeID); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@条码类型", barCodeID); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@流水号类型", snNumberID); + thisParms[5] = new System.Data.SqlClient.SqlParameter("@工厂编号", factoryID); + thisParms[6] = new System.Data.SqlClient.SqlParameter("@装配线班组号", shiftID); + thisParms[7] = new System.Data.SqlClient.SqlParameter("@壳体编号型号", shellCode); + thisParms[8] = new System.Data.SqlClient.SqlParameter("@壳体编号型号带空格", shellCode_Space); + thisParms[9] = new System.Data.SqlClient.SqlParameter("@QR码读数标志", QR_Code); + thisParms[10] = new System.Data.SqlClient.SqlParameter("@QR码产品型号", QR_Type); + thisParms[11] = new System.Data.SqlClient.SqlParameter("@壳体编号型号条码", shellCode_downline); + return DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } + /// + /// MES_基本变量_机型代码_删除 + /// @序号 int, + /// + /// 序号 + /// + static public bool EngineType_Delete(int sn) + { + string procedureName; + procedureName = "MES_基本变量_机型代码_删除"; + SqlParameter[] thisParms = new SqlParameter[1]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@序号", sn); + return DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } + } +} diff --git a/Common/07WebBusinessFacade/BusinessFacade/MES.B5A.Manager/IsMES.cs b/Common/07WebBusinessFacade/BusinessFacade/MES.B5A.Manager/IsMES.cs new file mode 100644 index 0000000..040f267 --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/MES.B5A.Manager/IsMES.cs @@ -0,0 +1,59 @@ +using System; +using System.Data; +using System.Data.SqlClient; +using DataLinkMesWork; +using System.Collections; +using System.Collections.Specialized; +//using SystemFramework; + +namespace bizFacade +{ + /// + /// [MES_计划BOM_工位与名称_查询_是否启用MES] + /// + public partial class BaseDataSystemMES + { + /// + /// [MES_计划BOM_工位与名称_查询_是否启用MES] + /// + /// + public static int IsMES_Select(string opName) + { + int count; + string sql = "exec MES_计划BOM_工位与名称_查询_是否启用MES '" + opName + "'"; + DataAccess.ExecuteOutNum(sql, out count); + return count; + } + /// + /// [MES_计划BOM_工位与名称_查询_在线状态] + /// + /// + public static int IsOnLine_Select(string opName) + { + int count; + string sql = "exec MES_计划BOM_工位与名称_查询_在线状态 '" + opName + "'"; + DataAccess.ExecuteOutNum(sql, out count); + return count; + } + /// + /// [MES_计划BOM_工位与名称_查询_是否启用MES] + /// + /// + /// + public static void IsMES_Update(string opName,string tagValue) + { + string sql = "exec MES_计划BOM_工位与名称_更新_是否启用MES '" + opName + "'," + tagValue; + DataAccess.ExecuteSQL(sql); + } + /// + /// [MES_计划BOM_工位与名称_查询_在线状态] + /// + /// + /// + public static void IsOnLine_Update(string opName, string tagValue) + { + string sql = "exec MES_计划BOM_工位与名称_更新_在线状态 '" + opName + "'," + tagValue; + DataAccess.ExecuteSQL(sql); + } + } +} diff --git a/Common/07WebBusinessFacade/BusinessFacade/MES.B5A.Manager/OpName.Material.cs b/Common/07WebBusinessFacade/BusinessFacade/MES.B5A.Manager/OpName.Material.cs new file mode 100644 index 0000000..a0dca87 --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/MES.B5A.Manager/OpName.Material.cs @@ -0,0 +1,111 @@ +using System; +using System.Data; +using System.Data.SqlClient; +using DataLinkMesWork; +using System.Collections; +using System.Collections.Specialized; +////using SystemFramework; + +namespace bizFacade +{ + /// + /// 电子看板信息系统 + /// + public partial class BaseDataSystemMES + { + /// + /// MES_基本变量_厂家代码_查询 + /// + static public void MaterialFactory_Select(out DataTable dt) + { + string sql; + sql = "exec MES_基本变量_厂家代码_查询"; + DataAccess.ExecuteDataTable(sql, out dt); + } + ///// + ///// 电子看板_装配零件_查询 + ///// + ///// + ///// + ///// + //static public void PartMaterial_Select(string opName, string engineType,string engineTypeID, out DataTable dt) + //{ + // string sql; + // sql = "exec 电子看板_装配零件_查询 '" + opName + "'," + engineTypeID + ",'" + engineType+"'"; + // DataAccess.ExecuteDataTable(sql, out dt); + //} + /// + /// 电子看板_装配零件_增加 + /// + /// 工位号 + /// 产品型号代码 + /// 标号 + /// 零件图号 + /// 零件名称 + /// 零件数量 + /// 零件批号 + /// 生产厂家 + /// 备注 + /// 发动机型号 + static public void PartMaterial_Insert + (string opName, int engineTypeID, + int MaterialMark, string PartDrawNumber, string PartName, int PartCount, + string MaterialNumber, string PartFactor, string PartMemo, string engineType) + { + string procedureName; + procedureName = "电子看板_装配零件_增加"; + SqlParameter[] thisParms = new SqlParameter[10]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@产品型号代码", engineTypeID); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@标号", MaterialMark); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@零件图号", PartDrawNumber); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@零件名称", PartName); + thisParms[5] = new System.Data.SqlClient.SqlParameter("@零件数量", PartCount); + thisParms[6] = new System.Data.SqlClient.SqlParameter("@零件批号", MaterialNumber); + thisParms[7] = new System.Data.SqlClient.SqlParameter("@生产厂家", PartFactor); + thisParms[8] = new System.Data.SqlClient.SqlParameter("@备注", PartMemo); + thisParms[9] = new System.Data.SqlClient.SqlParameter("@发动机型号", engineType); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } + /// + /// 电子看板_装配零件_修改 + /// + /// 唯一标志 + /// 标号 + /// 零件图号 + /// 零件名称 + /// 零件数量 + /// 零件批号 + /// 生产厂家 + /// 备注 + static public void PartMaterial_Update + (int ID,int MaterialMark, string PartDrawNumber, string PartName, int PartCount, + string MaterialNumber, string PartFactor, string PartMemo) + { + string procedureName; + procedureName = "电子看板_装配零件_修改"; + SqlParameter[] thisParms = new SqlParameter[8]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@ID", ID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@标号", MaterialMark); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@零件图号", PartDrawNumber); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@零件名称", PartName); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@零件数量", PartCount); + thisParms[5] = new System.Data.SqlClient.SqlParameter("@零件批号", MaterialNumber); + thisParms[6] = new System.Data.SqlClient.SqlParameter("@生产厂家", PartFactor); + thisParms[7] = new System.Data.SqlClient.SqlParameter("@备注", PartMemo); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } + /// + /// 电子看板_装配零件_删除 + /// + /// + static public void PartMaterial_Delete(int ID) + { + string procedureName; + procedureName = "电子看板_装配零件_删除"; + SqlParameter[] thisParms = new SqlParameter[1]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@ID", ID); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } + } +} diff --git a/Common/07WebBusinessFacade/BusinessFacade/MES.B5A.Manager/OpName.Proccess.cs b/Common/07WebBusinessFacade/BusinessFacade/MES.B5A.Manager/OpName.Proccess.cs new file mode 100644 index 0000000..09bbbf5 --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/MES.B5A.Manager/OpName.Proccess.cs @@ -0,0 +1,113 @@ +using System; +using System.Data; +using System.Data.SqlClient; +using DataLinkMesWork; +using System.Collections; +using System.Collections.Specialized; +////using SystemFramework; + +namespace bizFacade +{ + /// + /// 电子看板信息系统 + /// + public partial class BaseDataSystemMES + { + /// + /// MES_计划BOM_工位与名称_修改_工序号和工序名称; + /// + /// 工位号 + /// 工序号 + /// 工序名称 + static public void OpNameWorkStepName_Update(string opName, string ProccessCode, string ProcessName) + { + string procedureName; + procedureName = "MES_计划BOM_工位与名称_修改_工序号和工序名称"; + SqlParameter[] thisParms = new SqlParameter[3]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@工序号", ProccessCode); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@工序名称", ProcessName); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } + /// + /// 电子看板_工序内容_工步属性_查询 + /// + static public void GetWorkStepPropurty(out DataTable dt) + { + string sql; + sql = "exec 电子看板_工序内容_工步属性_查询"; + DataAccess.ExecuteDataTable(sql, out dt); + } + + /// + /// 电子看板_工序内容_增加 + /// + /// + /// + /// + /// + /// + /// + static public void WorkStepPropurty_Insert(string opName, int engineTypeID, int workStep, string contend,string requare, int propurtyID) + { + string procedureName; + procedureName = "电子看板_工序内容_增加"; + SqlParameter[] thisParms = new SqlParameter[6]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@产品型号代码", engineTypeID); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@工步号", workStep); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@操作内容", contend); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@技术要求", requare); + thisParms[5] = new System.Data.SqlClient.SqlParameter("@工步属性", propurtyID); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } + /// + /// 电子看板_工序内容_修改 + /// + /// + /// + /// + /// + static public void WorkStepPropurty_Update(int ID, string contend, string requare, int propurtyID) + { + string procedureName; + procedureName = "电子看板_工序内容_修改"; + SqlParameter[] thisParms = new SqlParameter[4]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@ID", ID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@操作内容", contend); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@技术要求", requare); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@工步属性", propurtyID); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } + /// + /// 电子看板_工序内容_删除 + /// + /// + static public void WorkStepPropurty_Delete(int ID) + { + string procedureName; + procedureName = "电子看板_工序内容_删除"; + SqlParameter[] thisParms = new SqlParameter[1]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@ID", ID); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } + /// + /// 电子看板_工序内容_修改_修改序号 + /// + /// + /// + /// + /// + static public void WorkStepPropurty_Update_WorkStep(int ID,string opName, int engineTypeID, int workStep) + { + string procedureName; + procedureName = "电子看板_工序内容_修改_修改序号"; + SqlParameter[] thisParms = new SqlParameter[4]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@ID", ID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@产品型号代码", engineTypeID); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@工步号", workStep); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } + } +} diff --git a/Common/07WebBusinessFacade/BusinessFacade/MES.B5A.Manager/OpName.Shaft.cs b/Common/07WebBusinessFacade/BusinessFacade/MES.B5A.Manager/OpName.Shaft.cs new file mode 100644 index 0000000..1d63fbe --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/MES.B5A.Manager/OpName.Shaft.cs @@ -0,0 +1,244 @@ +using System; +using System.Data; +using System.Data.SqlClient; +using DataLinkMesWork; +using System.Collections; +using System.Collections.Specialized; +//using SystemFramework; + +namespace bizFacade +{ + /// + /// 电子看板信息系统 + /// + public partial class BaseDataSystemMES + { + /// + /// MES_计划BOM_工位与名称_查询 + /// + /// + static public void GetOpNameByOpName(string opName,out DataTable dt) + { + string procedureName; + procedureName = "MES_计划BOM_工位与名称_查询_根据工位号"; + SqlParameter[] thisParms = new SqlParameter[1]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms,out dt); + } + /// + /// MES_计划BOM_工位与名称_查询 + /// MES_计划BOM_工位与名称_查询_根据工位号 + /// + static public void GetOpName(out DataTable dt) + { + string sql; + sql = "exec MES_计划BOM_工位与名称_查询"; + DataAccess.ExecuteDataTable(sql, out dt); + } + /// + /// MES_计划BOM_工位与名称_查询_工位号_有工位计算机 + /// + static public void GetOpName_IsMEsPC(out DataTable dt) + { + string sql; + sql = "exec MES_计划BOM_工位与名称_查询_工位号_有工位计算机"; + DataAccess.ExecuteDataTable(sql, out dt); + } + /// + /// MES_计划BOM_工位与名称_查询_工位号_是否有测量数据_有拧紧数据 + /// + static public void GetOpName_IsNinJinOpName(out DataTable dt) + { + string sql; + sql = "exec MES_计划BOM_工位与名称_查询_工位号_是否有测量数据_有拧紧数据"; + DataAccess.ExecuteDataTable(sql, out dt); + } + /// + /// MES_基本变量_基本机型_查询 + /// + static public void GetEngineBasicType(out DataTable dt) + { + string sql; + sql = " exec MES_基本变量_基本机型_查询"; + DataAccess.ExecuteDataTable(sql, out dt); + } + /// + /// 电子看板_工位名称与产品型号产品图片_保存图片 + /// @工位号 nvarchar(50), + /// @产品型号代码 int =null, + /// @产品图片 image + /// + static public void SaveImageFile(string opName, int engineTypeID, byte[] pic) + { + string procedureName; + procedureName = "电子看板_工位名称与产品型号产品图片_保存图片"; + SqlParameter[] thisParms = new SqlParameter[3]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@产品型号代码", engineTypeID); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@产品图片", pic); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } + /// + /// + /// + /// + /// + /// + static public void GetImageFile(string opName, string engineTypeID, out byte[] pic) + { + string sql; + DataTable dt; + pic = null; + sql = "exec 电子看板_工位名称与产品型号产品图片_查询 '" + opName + "'," + engineTypeID; + DataAccess.ExecuteDataTable(sql, out dt); + if (dt != null) + { + if (dt.Rows.Count > 0) + { + pic = (byte[])dt.Rows[0]["产品图片"]; + } + } + } + /// + /// 电子看板_工位机型_质量数据测量位置_查询 + /// + /// + /// + /// + static public void ShaftPositionSelect(string opName, string engineTypeID, out DataTable dt) + { + string sql; + sql = "exec 电子看板_工位机型_质量数据测量位置_查询 '" + opName + "'," + engineTypeID; + DataAccess.ExecuteDataTable(sql, out dt); + } + + /// + /// 电子看板_工位机型_质量数据测量位置_套筒号_查询 + /// + /// + /// + /// + static public void ShaftPositionSelect_BoltCode(string opName, string engineTypeID, out DataTable dt) + { + string sql; + sql = "exec 电子看板_工位机型_质量数据测量位置_套筒号_查询 '" + opName + "'," + engineTypeID; + DataAccess.ExecuteDataTable(sql, out dt); + } + + /// + /// 电子看板_工位机型_质量数据测量位置_保存数据 + /// 完成增加和修改数据 + /// + /// + /// + /// + /// + /// + /// + /// + /// + static public void ShaftPositionSaveData(string opName, + int engineTypeID, int shaftSN,int workGroup, + int xPosition, int yPosition, int workStep, int taoTongHao, string Torque) + { + string procedureName; + procedureName = "电子看板_工位机型_质量数据测量位置_保存数据"; + SqlParameter[] thisParms = new SqlParameter[9]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@产品型号代码", engineTypeID); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@序号", shaftSN); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@组号", workGroup); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@测量位置X", xPosition); + thisParms[5] = new System.Data.SqlClient.SqlParameter("@测量位置Y", yPosition); + thisParms[6] = new System.Data.SqlClient.SqlParameter("@工作顺序", workStep); + thisParms[7] = new System.Data.SqlClient.SqlParameter("@套筒号", taoTongHao); + thisParms[8] = new System.Data.SqlClient.SqlParameter("@扭矩", Torque); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } + /// + /// 电子看板_工位机型_质量数据测量位置_修改 + /// 修改数据 电子看板_工位机型_质量数据测量位置_修改_修改序号 + /// + /// 工位号 + /// 产品型号代码 + /// 序号 + /// 组号 + /// 测量位置X + /// 测量位置Y + /// 工作顺序 + /// 工作顺序 + static public void ShaftPositionSaveUpdate(string opName, + int engineTypeID, int shaftSN, int workGroup,int xPosition, + int yPosition, int workStep, int taoTongHao, string Torque) + { + string procedureName; + procedureName = "电子看板_工位机型_质量数据测量位置_修改"; + SqlParameter[] thisParms = new SqlParameter[9]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@产品型号代码", engineTypeID); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@序号", shaftSN); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@组号", workGroup); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@测量位置X", xPosition); + thisParms[5] = new System.Data.SqlClient.SqlParameter("@测量位置Y", yPosition); + thisParms[6] = new System.Data.SqlClient.SqlParameter("@工作顺序", workStep); + thisParms[7] = new System.Data.SqlClient.SqlParameter("@套筒号", taoTongHao); + thisParms[8] = new System.Data.SqlClient.SqlParameter("@扭矩", Torque); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } + /// + /// 电子看板_工位机型_质量数据测量位置_修改_修改序号 + /// + /// + /// + /// + /// + static public void ShaftPositionSaveUpdate_OnlySN(int id,string opName, int engineTypeID, int shaftSN) + { + string procedureName; + procedureName = "电子看板_工位机型_质量数据测量位置_修改_修改序号"; + SqlParameter[] thisParms = new SqlParameter[4]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@ID", id); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@产品型号代码", engineTypeID); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@序号", shaftSN); + + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } + /// + /// 电子看板_工位机型_质量数据测量位置_删除 + /// + /// + /// + /// + static public void ShaftPositionSaveDelete(string opName, int engineTypeID, int shaftSN) + { + string procedureName; + procedureName = "电子看板_工位机型_质量数据测量位置_删除"; + SqlParameter[] thisParms = new SqlParameter[3]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@产品型号代码", engineTypeID); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@序号", shaftSN); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } + /// + /// 电子看板_工位机型_质量数据测量位置_修改_修改扭矩 + /// + /// + /// + /// + /// + static public void ShaftPositionSaveUpdate_OnlyTorque(int shaftSN, string opName, int engineTypeID, string Torque) + { + string procedureName; + procedureName = "电子看板_工位机型_质量数据测量位置_修改_修改扭矩"; + SqlParameter[] thisParms = new SqlParameter[4]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@序号", shaftSN); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@产品型号代码", engineTypeID); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@扭矩", Torque); + + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } + + } +} diff --git a/Common/07WebBusinessFacade/BusinessFacade/MES.B5A.Manager/vssver2.scc b/Common/07WebBusinessFacade/BusinessFacade/MES.B5A.Manager/vssver2.scc new file mode 100644 index 0000000..3e30640 Binary files /dev/null and b/Common/07WebBusinessFacade/BusinessFacade/MES.B5A.Manager/vssver2.scc differ diff --git a/Common/07WebBusinessFacade/BusinessFacade/MES.B5A.QualityData/QualityData.B5A.Pack.cs b/Common/07WebBusinessFacade/BusinessFacade/MES.B5A.QualityData/QualityData.B5A.Pack.cs new file mode 100644 index 0000000..507db5b --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/MES.B5A.QualityData/QualityData.B5A.Pack.cs @@ -0,0 +1,904 @@ +using System; +using System.Data; +using System.Data.SqlClient; +using DataLinkMesWork; +using System.Collections; +using System.Collections.Specialized; +//using SystemFramework; + +namespace bizFacade +{ + /// + /// 电子看板信息系统 + /// + public partial class BaseDataSystemMES + { + /// + /// 拧紧结束后,查询拧紧不合格轴的数量,[测量数据合格_合格标志_查询] + /// + /// 发动机号 + /// 工位号 + /// 不合格数量 + /// + public static bool BaseData_QualityData_B5A_IsGoodBad_select(string EngineID,string OPName,out int Count_NG) + { + Count_NG = 0; + string procedureName; + procedureName = "测量数据合格_合格标志_查询"; + SqlParameter[] thisParms = new SqlParameter[3]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@发动机号", EngineID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@工位号", OPName); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@不合格数", Count_NG); + thisParms[2].Direction = ParameterDirection.Output; + + if (DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms)) + { + Count_NG = Convert.ToInt32(thisParms[2].Value.ToString()); + return true; + } + return false; + + } + + /// + /// 测量数据合格索引_禁用 + /// + /// + /// + /// + public static bool BaseData_tagTable_QualityData_B5A_UnUsing + (string engineID, string opName) + { + string procedureName; + procedureName = "测量数据合格索引_禁用"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@EngineID", engineID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + return DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } + + /// + /// 测量数据合格索引_分线数据_删除 + /// + /// + /// + /// + public static bool BaseData_tagTable_QualityData_B5A_SubTable_Delete + (string engineID,string opName) + { + string procedureName; + procedureName = "测量数据合格索引_分线数据_删除"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@EngineID", engineID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + return DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } + + /// + /// alter PROCEDURE [dbo].[测量数据合格_手动拧紧_列位置_增加] + ///@EngineTypeID int =null, + ///@EngineType nvarchar(50)=null, + ///@EngineID nvarchar(100)=null, + ///@TagValue nvarchar(100)=null, + ///@合格标志 int=null, + ///@工位号 nvarchar(50)=null, + ///@托盘编号 nvarchar(50)=null, + ///@列位置 int=null, + ///@变量排序 int=null, + ///@TagID_CF int=null + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + public static bool BaseData_tagTable_QualityData_B5A_Insert +(int engineTypeID,string engineType,string engineID, + string tagValue, int isGoodBad, + string opName,string partPallet, + int shiftID,int orderBy,int tagID_CF + ) + { + string procedureName; + procedureName = "测量数据合格_手动拧紧_列位置_增加"; + SqlParameter[] thisParms = new SqlParameter[10]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@EngineTypeID", engineTypeID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@EngineType", engineType); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@EngineID", engineID); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@TagValue", tagValue); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@合格标志", isGoodBad); + thisParms[5] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[6] = new System.Data.SqlClient.SqlParameter("@托盘编号", partPallet); + thisParms[7] = new System.Data.SqlClient.SqlParameter("@列位置", shiftID); + thisParms[8] = new System.Data.SqlClient.SqlParameter("@变量排序", orderBy); + thisParms[9] = new System.Data.SqlClient.SqlParameter("@TagID_CF", tagID_CF); + return DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } + /// + /// alter PROCEDURE [dbo].[测量数据合格_手动拧紧_增加] + ///@EngineTypeID int =null, + ///@EngineType nvarchar(50)=null, + ///@EngineID nvarchar(100)=null, + ///@TagValue nvarchar(100)=null, + ///@合格标志 int=null, + ///@工位号 nvarchar(50)=null, + ///@托盘编号 nvarchar(50)=null, + ///@TagID int=null, + ///@TagID_CF int=null + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + public static bool BaseData_tagTable_QualityData_B5A_Insert +(int engineTypeID, string engineType, string engineID, + string tagValue, int isGoodBad, + string opName, string partPallet, int tagID, int tagID_CF) + { + string procedureName; + procedureName = "测量数据合格_手动拧紧_增加"; + SqlParameter[] thisParms = new SqlParameter[9]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@EngineTypeID", engineTypeID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@EngineType", engineType); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@EngineID", engineID); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@TagValue", tagValue); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@合格标志", isGoodBad); + thisParms[5] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[6] = new System.Data.SqlClient.SqlParameter("@托盘编号", partPallet); + thisParms[7] = new System.Data.SqlClient.SqlParameter("@TagID", tagID); + thisParms[8] = new System.Data.SqlClient.SqlParameter("@TagID_CF", tagID_CF); + return DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } + /// + /// alter PROCEDURE [dbo].[测量数据合格_增加_物料检测] + ///@EngineTypeID int =null, + ///@EngineType nvarchar(50)=null, + ///@EngineID nvarchar(100)=null, + ///@TagValue nvarchar(100)=null, + ///@合格标志 int=null, + ///@工位号 nvarchar(50)=null, + ///@托盘编号 nvarchar(50)=null, + ///@TagID int=null, + ///@TagID_CF int=null + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + public static bool BaseData_tagTable_QualityData_B5A_Insert_MaterialTest +(int engineTypeID, string engineType, string engineID, + string tagValue, int isGoodBad, + string opName, string partPallet, int tagID, int tagID_CF) + { + string procedureName; + procedureName = "测量数据合格_增加_物料检测"; + SqlParameter[] thisParms = new SqlParameter[9]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@EngineTypeID", engineTypeID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@EngineType", engineType); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@EngineID", engineID); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@TagValue", tagValue); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@合格标志", isGoodBad); + thisParms[5] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[6] = new System.Data.SqlClient.SqlParameter("@托盘编号", partPallet); + thisParms[7] = new System.Data.SqlClient.SqlParameter("@TagID", tagID); + thisParms[8] = new System.Data.SqlClient.SqlParameter("@TagID_CF", tagID_CF); + return DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } +// /// +// /// 测量数据合格_增加_物料检测 +// /// +// /// +// /// +// /// +// /// +// /// +// /// +// /// +// public static bool BaseData_tagTable_QualityData_B5A_Insert_MaterialTest +//(int Id_tagCF, int engineTypeID, string engineID, int tagID, string tagValue, int isGoodBad) +// { +// string procedureName; +// procedureName = "测量数据合格_增加_物料检测"; +// SqlParameter[] thisParms = new SqlParameter[6]; +// thisParms[0] = new System.Data.SqlClient.SqlParameter("@Id_tagCF", Id_tagCF); +// thisParms[1] = new System.Data.SqlClient.SqlParameter("@EngineTypeID", engineTypeID); +// thisParms[2] = new System.Data.SqlClient.SqlParameter("@EngineID", engineID); +// thisParms[3] = new System.Data.SqlClient.SqlParameter("@TagID", tagID); +// thisParms[4] = new System.Data.SqlClient.SqlParameter("@TagValue", tagValue); +// thisParms[5] = new System.Data.SqlClient.SqlParameter("@IsGoodBad", isGoodBad); +// return DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); +// } + /// + /// ALTER PROCEDURE [dbo].[电子看板_发动机号_总合格标志_增加] + ///@工位号 nvarchar(50) = null, + ///@发动机号 nvarchar(50) = null, + ///@合格标志 int = 0测量数据合格索引_增加 + ///0合格;1不合格 + /// + /// + /// + /// + /// + public static bool BaseData_tagTable_Engine_IsOK_Insert + (string opName, string EngineID, int isOK) + { + string procedureName; + procedureName = "电子看板_发动机号_总合格标志_增加"; + SqlParameter[] thisParms = new SqlParameter[3]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@发动机号", EngineID); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@合格标志", isOK); + + if (DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms)) + { + return true; + } + return false; + } + + /// + /// 测量数据合格索引 合格标志修改-2012-08-23 chenghai + /// + /// + /// + /// 0合格;1不合格 + /// + public static bool BaseData_tagTable_QualityData_B5A_IsOK_update + (string opName, string EngineID, int isOK) + { + string procedureName; + procedureName = "电子看板_测量数据合格索引_合格标志_修改"; + SqlParameter[] thisParms = new SqlParameter[3]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@发动机号", EngineID); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@合格标志", isOK); + + if (DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms)) + { + return true; + } + return false; + } + + + /// + /// ALTER PROCEDURE [dbo].[电子看板_发动机号_总合格标志_查询] + ///@工位号 nvarchar(50) = null, + ///@发动机号 nvarchar(50) = null, + ///@合格标志 int = 0 output + /// + /// + /// + /// 0合格;1不合格 + /// + public static bool BaseData_tagTable_Engine_IsOK_Select + (string opName, string EngineID, out int isOK) + { + isOK = 1; + string procedureName; + procedureName = "电子看板_发动机号_总合格标志_查询"; + SqlParameter[] thisParms = new SqlParameter[3]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@发动机号", EngineID); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@合格标志", isOK); + thisParms[2].Direction = ParameterDirection.Output; + + if (DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms)) + { + isOK = Convert.ToInt32(thisParms[2].Value.ToString()); + return true; + } + return false; + } + /// + /// 测量数据合格_发动机返修前数据_合格标志_查询,用于3010工位 + /// + /// 工件号 + /// + /// + public static bool TestData_EngineRework_IsOK_Select + (string EngineID, out int isOK_M, out int isOK_S) + { + isOK_M = 1; + isOK_S = 1; + string procedureName; + procedureName = "测量数据合格_发动机返修前数据_合格标志_查询"; + SqlParameter[] thisParms = new SqlParameter[3]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@发动机号", EngineID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@合格标志_M", isOK_M); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@合格标志_S", isOK_S); + thisParms[1].Direction = ParameterDirection.Output; + thisParms[2].Direction = ParameterDirection.Output; + + if (DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms)) + { + isOK_M = Convert.ToInt32(thisParms[1].Value.ToString()); + isOK_S = Convert.ToInt32(thisParms[2].Value.ToString()); + return true; + } + return false; + } + + /// + /// 电子看板_发动机号_不合格放行_查询 + /// + /// + /// + /// + /// + public static bool BaseData_tagTable_Engine_IsNG_Select + (string opName, string EngineID, out DataTable dt) + { + string procedureName; + procedureName = "电子看板_发动机号_不合格放行_查询"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@发动机号", EngineID); + + if (DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms,out dt)) + { + if (dt != null) + { + if(dt.Rows.Count==1) + return true; + } + return false; + } + return false; + } + /// + /// 电子看板_发动机号_不合格放行_增加 + /// + /// + /// + /// + /// + /// + public static bool BaseData_tagTable_Engine_IsNG_Insert + (string opName, string EngineID, string worker,string text) + { + string procedureName; + procedureName = "电子看板_发动机号_不合格放行_增加"; + SqlParameter[] thisParms = new SqlParameter[4]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@发动机号", EngineID); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@操作者编号", worker); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@不合格原因", text); + + if (DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms)) + { + return true; + } + return false; + } + /// + /// 电子看板_发动机号_不合格放行_删除 + /// + /// + /// + /// + public static bool BaseData_tagTable_Engine_IsNG_Delete +(string opName, string EngineID) + { + string procedureName; + procedureName = "电子看板_发动机号_不合格放行_删除"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@发动机号", EngineID); + + return DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } + + + /// + /// 电子看板_发动机号_不合格放行_删除_分线线首 + /// + /// + /// + /// + public static bool BaseData_tagTable_Engine_IsNG_Delete_fenxian_xianshou +(string opName, string EngineID) + { + string procedureName; + procedureName = "电子看板_发动机号_不合格放行_删除_分线线首"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@发动机号", EngineID); + + return DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } + + + /// + /// 电子看板_零件图号_生产厂家_查询 + /// + /// + /// + /// + public static bool MaterialFactory_Select(string partDrawCode,out DataTable dt) + { + string procedureName; + procedureName = "电子看板_零件图号_生产厂家_查询"; + SqlParameter[] thisParms = new SqlParameter[1]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@零件图号", partDrawCode); + + return DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms,out dt); + } + + /// + /// 派工订单_订单信息_查询 + /// + /// + /// + /// + public static bool Get_DataByOrderForm(string OrderForm, out DataTable dt) + { + string procedureName; + procedureName = "派工订单_订单信息_查询"; + SqlParameter[] thisParms = new SqlParameter[1]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@订单号", OrderForm); + + return DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out dt); + } + /// + /// 电子看板_零件图号_生产厂家_增加 + /// + /// + /// + /// + public static bool MaterialFactory_Insert(string partDrawCode,string factory) + { + string procedureName; + procedureName = "电子看板_零件图号_生产厂家_增加"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@零件图号", partDrawCode); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@生产厂家", factory); + + return DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } + /// + /// 电子看板_零件图号_生产厂家_修改 + /// + /// + /// + /// + /// + public static bool MaterialFactory_Update(int factoryCode, string partDrawCode, string factory) + { + string procedureName; + procedureName = "电子看板_零件图号_生产厂家_修改"; + SqlParameter[] thisParms = new SqlParameter[3]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@厂家代码", factoryCode); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@零件图号", partDrawCode); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@生产厂家", factory); + + return DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } + /// + /// 电子看板_零件图号_生产厂家_删除 + /// + /// + /// + public static bool MaterialFactory_Delete(int factoryCode) + { + string procedureName; + procedureName = "电子看板_零件图号_生产厂家_删除"; + SqlParameter[] thisParms = new SqlParameter[1]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@厂家代码", factoryCode); + + return DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } + /// + /// [电子看板_发动机号_不合格放行_返修下线_查询] + /// + /// + /// + /// + public static bool BaseData_tagTable_Engine_IsNG_PartUnLoad_Select + (string EngineID, out DataTable dt) + { + string procedureName; + procedureName = "电子看板_发动机号_不合格放行_返修下线_查询"; + SqlParameter[] thisParms = new SqlParameter[1]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@发动机号", EngineID); + + if (DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out dt)) + { + if (dt != null) + { + if (dt.Rows.Count == 1) + return true; + } + return false; + } + return false; + } + + + /// + /// [电子看板_发动机号_返修下线_查询]-2012-09-14-chenghai 以前只有不合格 才打印工位号 + /// + /// + /// + /// + public static bool BaseData_tagTable_Engine_fanxiu_PartUnLoad_Select + (string EngineID, out DataTable dt) + { + string procedureName; + procedureName = "电子看板_发动机号_返修下线_查询"; + SqlParameter[] thisParms = new SqlParameter[1]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@发动机号", EngineID); + + if (DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out dt)) + { + if (dt != null) + { + if (dt.Rows.Count == 1) + return true; + } + return false; + } + return false; + } + + + /// + /// 测量数据合格索引_不合格标志_查询-2012-12-05-kexin OP3024用 打印不合格工位 + /// + /// + /// + /// + public static bool BaseData_tagTable_Engine_buhege_PartUnLoad_Select + (string EngineID, out DataTable dt) + { + string procedureName; + procedureName = "测量数据合格索引_不合格标志_查询"; + SqlParameter[] thisParms = new SqlParameter[1]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@发动机号", EngineID); + + if (DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out dt)) + { + if (dt != null) + { + if (dt.Rows.Count == 1) + return true; + } + return false; + } + return false; + } + + + /// + /// [测量数据合格索引_返修上线信息_查询] OP3024 b6返修上线使用 + /// + /// + /// + /// + public static bool BaseData_Repair_PartUnLoad_Select + (string EngineID, out DataTable dt) + { + string procedureName; + procedureName = "测量数据合格索引_返修上线信息_查询"; + SqlParameter[] thisParms = new SqlParameter[1]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@发动机号", EngineID); + + if (DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out dt)) + { + if (dt != null) + { + if (dt.Rows.Count == 1) + return true; + } + return false; + } + return false; + } + + /// + ///电子看板_发动机号_人工合格放行记录_增加数据 + /// + /// + /// + /// + public static bool OKGo_Insert + (string Opname, string EngineID, string Enginetype,string headernum, string usernum) + { + string procedureName; + procedureName = "电子看板_发动机号_人工合格放行记录_增加数据"; + SqlParameter[] thisParms = new SqlParameter[5]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", Opname); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@发动机号", EngineID); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@机型", Enginetype); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@输入领班号", headernum); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@操作者编号", usernum); + if (DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms)) + { + return true; + } + return false; + } + + + + + /// + /// [显示测量数据_工位号] 王可心 2012-12-06 + /// + /// + /// + /// + public static bool BaseData_tagTable_Engine_ShowOpname + (string EngineID, int LineType,out DataTable dt) + { + string procedureName; + procedureName = "显示测量数据_工位号"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@发动机号", EngineID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@固定条形码扫描枪", LineType); + + if (DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out dt)) + { + if (dt != null) + { + if (dt.Rows.Count == 1) + return true; + } + return false; + } + return false; + } + /// + /// [显示测量数据_工位数据] 王可心 2012-12-06 + /// + /// + /// + /// + public static bool BaseData_tagTable_Engine_ShowOpname_Data + (string EngineID,string OpName,out DataTable dt) + { + string procedureName; + procedureName = "显示测量数据_工位数据"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@发动机号", EngineID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@工位号", OpName); + if (DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out dt)) + { + if (dt != null) + { + if (dt.Rows.Count == 1) + return true; + } + return false; + } + return false; + } + /// + /// 显示测量数据_工位数据_分线数据 王可心 2012-12-11 + /// + /// + /// + /// + public static bool BaseData_tagTable_Engine_ShowOpname_Data_SubLine + (string EngineID, string OpName, out DataTable dt) + { + string procedureName; + procedureName = "显示测量数据_工位数据_分线数据"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@发动机号", EngineID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@工位号", OpName); + if (DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out dt)) + { + if (dt != null) + { + if (dt.Rows.Count == 1) + return true; + } + return false; + } + return false; + } + /// + /// [显示测量数据_工位号_分线] 王可心 2012-12-11 + /// + /// + /// + /// + public static bool BaseData_tagTable_Engine_ShowOpname_SubLine + (string EngineID, int LineType, out DataTable dt) + { + string procedureName; + procedureName = "显示测量数据_工位号_分线"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@发动机号", EngineID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@固定条形码扫描枪", LineType); + + if (DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out dt)) + { + if (dt != null) + { + if (dt.Rows.Count == 1) + return true; + } + return false; + } + return false; + } + + /// + ///[电子看板_发动机号_线首工位_分线删除数据_根据发动机号] + /// + /// + /// + public static bool BaseData_tagTable_Engine_SubLine_DataDelete(string EngineID, string OpName) + { + string procedureName; + procedureName = "电子看板_发动机号_线首工位_分线删除数据_根据发动机号"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@发动机号", EngineID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@工位号_分线", OpName); + return DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } + + //2012-12-15 王可心 + /// + /// [测量数据合格_变速器总成称重_根据发动机号_删除] + /// + /// + /// + public static bool BaseData_tagTable_QualityData_B5A_Weight_Delete + (string engineID) + { + string procedureName; + procedureName = "测量数据合格_变速器总成称重_根据发动机号_删除"; + SqlParameter[] thisParms = new SqlParameter[1]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@发动机号", engineID); + return DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } + + /// + /// [测量数据合格索引_不合格标志_OP3100_查询] 用于3100工位 2012-12-21 + /// + /// 工件号 + /// + /// 合格返回true 不合格返回false + public static bool TestData_EngineRework_IsOK_Select_OP3100 + (string EngineID) + { + + int isOK_S = 1; + string procedureName; + procedureName = "测量数据合格索引_不合格标志_OP3100_查询"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@发动机号", EngineID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@数量", isOK_S); + + thisParms[1].Direction = ParameterDirection.Output; + + + if (DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms)) + { + isOK_S = Convert.ToInt32(thisParms[1].Value.ToString()); + if (isOK_S == 0) + { return true; } + else + { + return false; } + + } + return false; + } + + /// + /// 测量数据合格索引 合格标志修改-2012-12-22 王可心 应用于OP3020R + /// + /// + /// + /// 0合格;1不合格 + /// + public static bool BaseData_tagTable_QualityData_B5A_IsOK_OP3020_update + (string opName, string EngineID, int isOK) + { + string procedureName; + procedureName = "电子看板_测量数据合格索引_合格标志_返修工位_修改"; + SqlParameter[] thisParms = new SqlParameter[3]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@发动机号", EngineID); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@合格标志", isOK); + + if (DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms)) + { + return true; + } + return false; + } + + + /// + /// [测量数据合格索引_不合格标志_轴齿上线_查询] 王可心 2012-12-23 轴齿上线匹配时 分线工件合格标志查询 + /// + /// + /// + /// 0合格;1不合格 + /// + public static bool BaseData_tagTable_Engine_IsOK_SubLine_Select + (string EngineID, int mathType,out int CountNum) + { + CountNum = 0; + string procedureName; + procedureName = "测量数据合格索引_不合格标志_轴齿上线_查询"; + SqlParameter[] thisParms = new SqlParameter[3]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@发动机号", EngineID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@匹配方式", mathType); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@数量", CountNum); + thisParms[2].Direction = ParameterDirection.Output; + + if (DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms)) + { + CountNum = Convert.ToInt32(thisParms[2].Value.ToString()); + return true; + } + return false; + } + + + /// + /// [测量数据发动机在线状态_下线工位_OP3100_查询]2012-12-30-王可心 OP3100用 下线时查看该工件以前是否进行过下线 + /// + /// 发动机号 + /// + /// 以前下线过返回true ,否则返回false + static public void BaseData_tagTable_Engine_PartUnLoad_Select_OP3100(string EngineID, out DataTable dt) + { + string procedureName; + procedureName = "测量数据发动机在线状态_下线工位_OP3100_查询"; + SqlParameter[] thisParms = new SqlParameter[1]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@发动机号", EngineID); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out dt); + } + + /// + ///电子看板_发动机号_线首工位_查询发动机号 王可心 2013-11-07 + /// + /// + /// + /// + public static bool EngineNum_Select(DateTime BeginTime, DateTime EndTime, out DataTable dt) + { + string procedureName; + procedureName = "电子看板_发动机号_线首工位_查询发动机号"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@开始时间", BeginTime); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@结束时间", EndTime); + if (DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out dt)) + { + if (dt != null) + { + if (dt.Rows.Count == 1) + return true; + } + return false; + } + return false; + } + + } +} diff --git a/Common/07WebBusinessFacade/BusinessFacade/MES.B5A.QualityData/QualityData.B5A.Save.cs b/Common/07WebBusinessFacade/BusinessFacade/MES.B5A.QualityData/QualityData.B5A.Save.cs new file mode 100644 index 0000000..fa43d5a --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/MES.B5A.QualityData/QualityData.B5A.Save.cs @@ -0,0 +1,247 @@ +using System; +using System.Data; +using System.Data.SqlClient; +using DataLinkMesWork; +using System.Collections; +using System.Collections.Specialized; +//using SystemFramework; + +namespace bizFacade +{ + /// + /// 电子看板信息系统 + /// + public partial class BaseDataSystemMES + { + /// + /// 测量数据合格索引_增加 + /// 用于B5A项目 + /// ALTER PROCEDURE [dbo].[测量数据合格索引_增加] + ///@EngineID nvarchar(50)=null, + ///@TagID_CF int = null, + ///@EngineType nvarchar(50)=null, + ///@EngineTypeID int = null, + ///@工位号 nvarchar(50)=null, + ///@订单号 nvarchar(50)=null, + ///@合格标志 int=null, + ///@TagValue1 nvarchar(50)=null, + ///@TagValue2 nvarchar(50)=null, + ///@TagValue3 nvarchar(50)=null, + ///@TagValue4 nvarchar(50)=null, + ///@TagValue5 nvarchar(50)=null, + ///@TagValue6 nvarchar(50)=null, + ///@TagValue7 nvarchar(50)=null, + ///@TagValue8 nvarchar(50)=null, + ///@TagValue9 nvarchar(50)=null, + ///@TagValue10 nvarchar(50)=null, + ///@TagValue nvarchar(50)=null, + ///@Id_tagCF int=null output + /// + /// + public static bool BaseData_tagTable_QualityData_B5A_IndexInsert + (string EngineID, int tagID, string EngineType, int EngineTypeID, string opName, + int isGoodBad,string PartPalletCode, out int Id_tagCF) + { + string procedureName; + procedureName = "测量数据合格索引_增加"; + Id_tagCF = 0; + SqlParameter[] thisParms = new SqlParameter[8]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@EngineID", EngineID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@TagID_CF", tagID); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@EngineType", EngineType); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@EngineTypeID", EngineTypeID); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[5] = new System.Data.SqlClient.SqlParameter("@托盘编号", PartPalletCode); + thisParms[6] = new System.Data.SqlClient.SqlParameter("@合格标志", isGoodBad); + thisParms[7] = new System.Data.SqlClient.SqlParameter("@Id_tagCF", Id_tagCF); + thisParms[7].Direction = ParameterDirection.Output; + + if (DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms)) + { + Id_tagCF = Convert.ToInt32(thisParms[7].Value.ToString()); + return true; + } + return false; + } + + /// + /// alter PROCEDURE dbo.[测量数据合格_增加] + ///@Id_tagCF int = null, + ///@EngineTypeID int =null, + ///@EngineID nvarchar(100)=null, + ///@TagID int=null, + ///@TagValue nvarchar(100)=null, + ///@IsGoodBad int=null, + /// + /// + /// + /// + /// + /// + public static bool BaseData_tagTable_QualityData_B5A_Insert + (int Id_tagCF,int engineTypeID,string engineID,string opName,DataTable dt) + { + string procedureName; + procedureName = "测量数据合格_增加"; + SqlParameter[] thisParms = new SqlParameter[6]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@Id_tagCF", Id_tagCF); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@EngineTypeID", engineTypeID); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@EngineID", engineID); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@TagID", SqlDbType.Int, 4, "TagID"); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@TagValue", SqlDbType.NVarChar, 100, "TagValue"); + thisParms[5] = new System.Data.SqlClient.SqlParameter("@IsGoodBad", SqlDbType.Int, 4, "IsGoodBad"); + //thisParms[6] = new System.Data.SqlClient.SqlParameter("@测量位置", SqlDbType.NVarChar, 50, "测量位置"); + //thisParms[7] = new System.Data.SqlClient.SqlParameter("@测量项目", SqlDbType.NVarChar, 50, "测量项目"); + //thisParms[8] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + //thisParms[9] = new System.Data.SqlClient.SqlParameter("@理论值", SqlDbType.NVarChar, 50, "理论值"); + //thisParms[10] = new System.Data.SqlClient.SqlParameter("@上限值", SqlDbType.NVarChar, 50, "上限值"); + //thisParms[11] = new System.Data.SqlClient.SqlParameter("@下限值", SqlDbType.NVarChar, 50, "下限值"); + //thisParms[12] = new System.Data.SqlClient.SqlParameter("@测量单位", SqlDbType.NVarChar, 50, "测量单位"); + //thisParms[13] = new System.Data.SqlClient.SqlParameter("@列位置", SqlDbType.Int, 4, "列位置"); + //thisParms[14] = new System.Data.SqlClient.SqlParameter("@变量排序", SqlDbType.Int, 4, "变量排序"); + //table.Columns.Add("TagID", typeof(System.Int32)); + //table.Columns.Add("TagValue", typeof(System.String)); + //table.Columns.Add("IsGoodBad", typeof(System.Int32)); + //table.Columns.Add("测量位置", typeof(System.String)); + //table.Columns.Add("测量项目", typeof(System.String)); + //table.Columns.Add("工位号", typeof(System.String)); + //table.Columns.Add("理论值", typeof(System.String)); + //table.Columns.Add("上限值", typeof(System.String)); + //table.Columns.Add("下限值", typeof(System.String)); + //table.Columns.Add("测量单位", typeof(System.String)); + //table.Columns.Add("列位置", typeof(System.Int32)); + //table.Columns.Add("变量排序", typeof(System.Int32)); + return DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, dt); + } + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + public static bool BaseData_tagTable_QualityData_B5A_Insert +(int Id_tagCF, int engineTypeID, string engineID,int tagID,string tagValue,int isGoodBad) + { + string procedureName; + procedureName = "测量数据合格_增加"; + SqlParameter[] thisParms = new SqlParameter[6]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@Id_tagCF", Id_tagCF); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@EngineTypeID", engineTypeID); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@EngineID", engineID); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@TagID", tagID); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@TagValue", tagValue); + thisParms[5] = new System.Data.SqlClient.SqlParameter("@IsGoodBad", isGoodBad); + return DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } + + //2012-12-12 离线状态时 只保存合格索引 + /// + /// 测量数据合格索引_增加_工位离线状态 2012-12-26 + /// 用于B5A项目 + /// ALTER PROCEDURE [dbo].[测量数据合格索引_增加_工位离线状态] + ///@EngineID nvarchar(50)=null, + ///@TagID_CF int = null, + ///@EngineType nvarchar(50)=null, + ///@EngineTypeID int = null, + ///@工位号 nvarchar(50)=null, + ///@订单号 nvarchar(50)=null, + ///@合格标志 int=null, + ///@TagValue1 nvarchar(50)=null, + ///@TagValue2 nvarchar(50)=null, + ///@TagValue3 nvarchar(50)=null, + ///@TagValue4 nvarchar(50)=null, + ///@TagValue5 nvarchar(50)=null, + ///@TagValue6 nvarchar(50)=null, + ///@TagValue7 nvarchar(50)=null, + ///@TagValue8 nvarchar(50)=null, + ///@TagValue9 nvarchar(50)=null, + ///@TagValue10 nvarchar(50)=null, + ///@TagValue nvarchar(50)=null, + ///@Id_tagCF int=null output + /// + /// + public static bool BaseData_tagTable_QualityData_B5A_IndexInsert_OffLine + (string EngineID, int tagID, string EngineType, int EngineTypeID, string opName, + int isGoodBad, string PartPalletCode, out int Id_tagCF) + { + string procedureName; + procedureName = "测量数据合格索引_增加_工位离线状态"; + Id_tagCF = 0; + SqlParameter[] thisParms = new SqlParameter[8]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@EngineID", EngineID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@TagID_CF", tagID); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@EngineType", EngineType); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@EngineTypeID", EngineTypeID); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[5] = new System.Data.SqlClient.SqlParameter("@托盘编号", PartPalletCode); + thisParms[6] = new System.Data.SqlClient.SqlParameter("@合格标志", isGoodBad); + thisParms[7] = new System.Data.SqlClient.SqlParameter("@Id_tagCF", Id_tagCF); + thisParms[7].Direction = ParameterDirection.Output; + + if (DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms)) + { + Id_tagCF = Convert.ToInt32(thisParms[7].Value.ToString()); + return true; + } + return false; + } + + //2012-12-16 + /// + /// [测量数据合格索引_增加_只装配物料工位] + /// 用于B5A项目 + /// ALTER PROCEDURE [dbo].[[测量数据合格索引_增加_只装配物料工位]] + ///@EngineID nvarchar(50)=null, + ///@TagID_CF int = null, + ///@EngineType nvarchar(50)=null, + ///@EngineTypeID int = null, + ///@工位号 nvarchar(50)=null, + ///@托盘编号 nvarchar(50)=null, + ///@合格标志 int=null, + ///@TagValue1 nvarchar(50)=null, + ///@TagValue2 nvarchar(50)=null, + ///@TagValue3 nvarchar(50)=null, + ///@TagValue4 nvarchar(50)=null, + ///@TagValue5 nvarchar(50)=null, + ///@TagValue6 nvarchar(50)=null, + ///@TagValue7 nvarchar(50)=null, + ///@TagValue8 nvarchar(50)=null, + ///@TagValue9 nvarchar(50)=null, + ///@TagValue10 nvarchar(50)=null, + ///@TagValue nvarchar(50)=null, + ///@Id_tagCF int=null output + /// + /// + public static bool BaseData_tagTable_QualityData_B5A_IndexInsert_OnlyMaterial + (string EngineID, int tagID, string EngineType, int EngineTypeID, string opName, + int isGoodBad, string PartPalletCode, out int Id_tagCF) + { + string procedureName; + procedureName = "测量数据合格索引_增加_只装配物料工位"; + Id_tagCF = 0; + SqlParameter[] thisParms = new SqlParameter[8]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@EngineID", EngineID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@TagID_CF", tagID); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@EngineType", EngineType); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@EngineTypeID", EngineTypeID); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[5] = new System.Data.SqlClient.SqlParameter("@托盘编号", PartPalletCode); + thisParms[6] = new System.Data.SqlClient.SqlParameter("@合格标志", isGoodBad); + thisParms[7] = new System.Data.SqlClient.SqlParameter("@Id_tagCF", Id_tagCF); + thisParms[7].Direction = ParameterDirection.Output; + + if (DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms)) + { + //Id_tagCF = Convert.ToInt32(thisParms[7].Value.ToString()); + return true; + } + return false; + } + + + } +} diff --git a/Common/07WebBusinessFacade/BusinessFacade/MES.B5A.QualityData/QualityData.B5A.cs b/Common/07WebBusinessFacade/BusinessFacade/MES.B5A.QualityData/QualityData.B5A.cs new file mode 100644 index 0000000..8afc559 --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/MES.B5A.QualityData/QualityData.B5A.cs @@ -0,0 +1,162 @@ +using System; +using System.Data; +using System.Data.SqlClient; +using DataLinkMesWork; +using System.Collections; +using System.Collections.Specialized; +//using SystemFramework; + +namespace bizFacade +{ + /// + /// 电子看板信息系统 + /// + public partial class BaseDataSystemMES + { + /// + /// 测量数据项目 + /// 用于B5A项目 + /// + /// + public static DataTable BaseData_tagTable_QualityData_Item_B5A() + { + DataTable dt; + string sql; + sql = "SELECT TagID,0 as TagValue,TagName,工位号,数据来源,TagTypeID,TagLong,列位置,测量位置,变量类型代码,测量项目,TagAdr,TagAdrDemo,变量特点,变量排序 FROM [MES_基本变量_原始数据] " + + " where (TagID <> 0 ) and " + + " ((变量类型代码 = 9) " + + " or (变量类型代码 = 10) " + + " or (变量类型代码 = 11) " + + " or (变量类型代码 = 80) " + + " or (变量类型代码 = 101) " + + " or (变量类型代码 = 102) " + + + " or (变量类型代码 = 78) " + + " or (变量类型代码 = 79) " + + " or (变量类型代码 = 41) " + + " or (变量类型代码 = 51) " + + " or (变量类型代码 = 8) " + + " or (变量类型代码 = 21) " + + + " or (变量类型代码 = 105)) " + + " and (是否启用 = 1)"; + + DataAccess.ExecuteDataTable(sql, out dt); + return dt; + } + /// + /// 测量工位 + /// 变量特点=1001需要自动测量工位 + /// + /// + public static DataTable BaseData_tagTable_QualityData_OpName_B5A() + { + DataTable dt; + string sql = "SELECT distinct 工位号 as 工位代码,[工位号] FROM [MES_基本变量_原始数据] " + + " where ((变量类型代码 >= 19 and 变量类型代码 <= 24) or (变量类型代码 = 101) or (变量类型代码 = 102)) and (是否启用 = 1) and (变量特点=1001)"; + DataAccess.ExecuteDataTable(sql, out dt); + return dt; + } + /// + /// 变量特点=1001需要自动测量工位 + /// sql = "SELECT TagID,0 as TagValue,TagName,工位号,TagTypeID,TagLong,列位置,测量位置,变量类型代码,测量项目,TagAdr,TagAdrDemo " + /// + " FROM MES_基本变量_原始数据 " + /// + " where 变量类型代码 = 19 and 是否启用 = 1 and 变量特点=8 "; + /// + /// + public static DataTable BaseData_tagTable_QualityData_Read_CF_MIS_B5A() + { + DataTable dt; + string sql; + sql = "SELECT TagID,0 as TagValue,TagName,工位号,数据来源,TagTypeID,TagLong,列位置,测量位置,变量类型代码,测量项目,TagAdr,TagAdrDemo,变量特点,变量排序 " + + " FROM MES_基本变量_原始数据 " + + " where 变量类型代码 = 19 and 是否启用 = 1 and (变量特点=1001 )"; + // + " and OpcServer_OPNAME='" + opName + "'"; + DataAccess.ExecuteDataTable(sql, out dt); + return dt; + } + /// + /// 质量数据保存完数据 20 + /// + /// + public static DataTable BaseData_tagTable_QualityData_Write_CF_B5A() + { + DataTable dt; + string sql; + sql = "SELECT TagID,0 as TagValue,TagName,工位号,数据来源,TagTypeID,TagLong,列位置,测量位置,变量类型代码,测量项目,TagAdr,TagAdrDemo,变量特点,变量排序 FROM [MES_基本变量_原始数据] where 变量类型代码 = 20 and 是否启用 = 1 and (变量特点=1001) "; + DataAccess.ExecuteDataTable(sql, out dt); + return dt; + } + + /// + /// 测量数据项目 + /// 用于B5A项目 + /// + /// + public static DataTable BaseData_tagTable_QualityData_Item_B5A(string opName) + { + DataTable dt; + string sql; + sql = "SELECT TagID,0 as TagValue,TagName,工位号,数据来源,TagTypeID,TagLong,列位置,测量位置,变量类型代码,测量项目,TagAdr,TagAdrDemo,变量特点,变量排序 FROM [MES_基本变量_原始数据] " + + " where (TagID <> 0 ) and " + + " ((变量类型代码 = 9) " + + " or (变量类型代码 = 10) " + + " or (变量类型代码 = 11) " + + " or (变量类型代码 = 101) " + + " or (变量类型代码 = 102) " + + " or (变量类型代码 = 105)) " + + " and (是否启用 = 1)" + + " and (工位号 = '"+opName+"')"; + + DataAccess.ExecuteDataTable(sql, out dt); + return dt; + } + /// + /// 测量工位 + /// 变量特点=1001自动测量工位 + /// + /// + public static DataTable BaseData_tagTable_QualityData_OpName_B5A(string opName) + { + DataTable dt; + string sql = "SELECT distinct 工位号 as 工位代码,[工位号] FROM [MES_基本变量_原始数据] " + + " where ((变量类型代码 >= 19 and 变量类型代码 <= 24) or (变量类型代码 = 101) or (变量类型代码 = 102)) and (是否启用 = 1) " + + " and 工位号 = '" + opName+"'"; + DataAccess.ExecuteDataTable(sql, out dt); + return dt; + } + /// + /// sql = "SELECT TagID,0 as TagValue,TagName,工位号,TagTypeID,TagLong,列位置,测量位置,变量类型代码,测量项目,TagAdr,TagAdrDemo " + /// + " FROM MES_基本变量_原始数据 " + /// + " where 变量类型代码 = 19 and 是否启用 = 1 and 变量特点=8 "; + /// + /// + public static DataTable BaseData_tagTable_QualityData_Read_CF_MIS_B5A(string opName) + { + DataTable dt; + string sql; + sql = "SELECT TagID,0 as TagValue,TagName,工位号,数据来源,TagTypeID,TagLong,列位置,测量位置,变量类型代码,测量项目,TagAdr,TagAdrDemo,变量特点,变量排序 " + + " FROM MES_基本变量_原始数据 " + + " where 变量类型代码 = 19 and 是否启用 = 1 " + + " and 工位号 = '" + opName + "'"; + ; + // + " and OpcServer_OPNAME='" + opName + "'"; + DataAccess.ExecuteDataTable(sql, out dt); + return dt; + } + /// + /// 质量数据保存完数据 + /// 20 + /// + /// + public static DataTable BaseData_tagTable_QualityData_Write_CF_B5A(string opName) + { + DataTable dt; + string sql; + sql = "SELECT TagID,0 as TagValue,TagName,工位号,数据来源,TagTypeID,TagLong,列位置,测量位置,变量类型代码,测量项目,TagAdr,TagAdrDemo,变量特点,变量排序 FROM [MES_基本变量_原始数据] where 变量类型代码 = 20 and 是否启用 = 1 " + + " and 工位号 = '" + opName + "'"; + DataAccess.ExecuteDataTable(sql, out dt); + return dt; + } + } +} diff --git a/Common/07WebBusinessFacade/BusinessFacade/MES.B5A.QualityData/vssver2.scc b/Common/07WebBusinessFacade/BusinessFacade/MES.B5A.QualityData/vssver2.scc new file mode 100644 index 0000000..422e5eb Binary files /dev/null and b/Common/07WebBusinessFacade/BusinessFacade/MES.B5A.QualityData/vssver2.scc differ diff --git a/Common/07WebBusinessFacade/BusinessFacade/MES.B5A.ShaftPosition/OpNameCount.cs b/Common/07WebBusinessFacade/BusinessFacade/MES.B5A.ShaftPosition/OpNameCount.cs new file mode 100644 index 0000000..db84766 --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/MES.B5A.ShaftPosition/OpNameCount.cs @@ -0,0 +1,40 @@ +using System; +using System.Data; +using System.Data.SqlClient; +using DataLinkMesWork; +using System.Collections; +using System.Collections.Specialized; +//using SystemFramework; + +namespace bizFacade +{ + /// + /// 电子看板信息系统 + /// + public partial class BaseDataSystemMES + { + /// + /// 计算工位产量 + /// + /// @班次代码 + /// @工位节拍 + /// @当前时间 + /// @工位产量 + static public void OpNameCount(int shiftCode,int opNameTime,DateTime currentTime,out int opNameCount) + { + //exec 电子看板_工作时间与班次_工作时间 1,45,'2011-11-30 13:11:00', @工位产量 out + opNameCount = 0; + string procedureName; + procedureName = "电子看板_工作时间与班次_工作时间"; + SqlParameter[] thisParmsSql = new SqlParameter[4]; + thisParmsSql[0] = new SqlParameter("@班次代码", shiftCode); + thisParmsSql[1] = new SqlParameter("@工位节拍", opNameTime); + thisParmsSql[2] = new SqlParameter("@当前时间", currentTime); + thisParmsSql[3] = new SqlParameter("@工位产量", opNameCount); + thisParmsSql[3].Direction = ParameterDirection.Output; + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParmsSql); + + opNameCount = Convert.ToInt32(thisParmsSql[3].Value); + } + } +} diff --git a/Common/07WebBusinessFacade/BusinessFacade/MES.B5A.ShaftPosition/OpNameRepair.cs b/Common/07WebBusinessFacade/BusinessFacade/MES.B5A.ShaftPosition/OpNameRepair.cs new file mode 100644 index 0000000..8003493 --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/MES.B5A.ShaftPosition/OpNameRepair.cs @@ -0,0 +1,33 @@ +using System; +using System.Data; +using System.Data.SqlClient; +using DataLinkMesWork; +using System.Collections; +using System.Collections.Specialized; +//using SystemFramework; + +namespace bizFacade +{ + /// + /// + /// + public partial class BaseDataSystemMES + { + /// + /// 测量数据合格_返修工位_查询 + /// + /// + /// + /// + static public void GetOpNameRepairData(string engineID,string opName,out DataTable dt) + { + string procedureName; + procedureName = "测量数据合格_返修工位_查询"; + SqlParameter[] thisParmsSql = new SqlParameter[2]; + thisParmsSql[0] = new SqlParameter("@EngineID", engineID); + thisParmsSql[1] = new SqlParameter("@工位号", opName); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParmsSql, out dt); + + } + } +} diff --git a/Common/07WebBusinessFacade/BusinessFacade/MES.B5A.ShaftPosition/ShaftPosition.cs b/Common/07WebBusinessFacade/BusinessFacade/MES.B5A.ShaftPosition/ShaftPosition.cs new file mode 100644 index 0000000..e74de5e --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/MES.B5A.ShaftPosition/ShaftPosition.cs @@ -0,0 +1,203 @@ +using System; +using System.Data; +using System.Data.SqlClient; +using DataLinkMesWork; +using System.Collections; +using System.Collections.Specialized; +//using SystemFramework; + +namespace bizFacade +{ + /// + /// 电子看板信息系统 + /// + public partial class ShaftPosition + { + /// + /// 电子看板_工位机型_质量数据测量位置_查询_工作顺序 + /// + /// + /// + /// + static public void ShaftPosition_Select_WorkingStep(string opName, int engineTypeID, out DataTable dt) + { + dt = null; + + string sql = "exec 电子看板_工位机型_质量数据测量位置_查询_工作顺序 '" + opName + "'," + engineTypeID.ToString(); + DataAccess.ExecuteDataTable(sql, out dt); + } + + /// + /// 电子看板_工位机型_质量数据测量位置_查询 + /// + /// 工位号 + /// 产品型号代码 + /// + static public void ShaftPosition_Select(string opName,int engineTypeID,out DataTable dt) + { + dt = null; + + string sql = "exec 电子看板_工位机型_质量数据测量位置_查询 '" + opName + "'," + engineTypeID.ToString(); + DataAccess.ExecuteDataTable(sql, out dt); + } + /// + /// 电子看板_装配零件_查询 + /// + /// 工位号 + /// 产品型号代码 + /// 产品型号代码 + /// + static public void Material_Select(string opName, string engineTypeID, string engineType, out DataTable dt) + { + dt = null; + string sql = "exec 电子看板_装配零件_查询 '" + opName + "'," + engineTypeID.ToString() + ",'" + engineType + "'"; ; + DataAccess.ExecuteDataTable(sql, out dt); + } + /// + /// 电子看板_装配零件_查询 + /// + /// 工位号 + /// 产品型号代码 + /// + static public void Material_Select_1(string opName, int engineTypeID, out DataTable dt) + { + dt = null; + + string sql = "exec 电子看板_装配零件_查询 '" + opName + "'," + engineTypeID.ToString() ; + DataAccess.ExecuteDataTable(sql, out dt); + } + /// + /// 电子看板_工序内容_查询 + /// + /// 工位号 + /// 产品型号代码 + /// + static public void Process_Select(string opName, int engineTypeID, out DataTable dt) + { + dt = null; + + string sql = "exec 电子看板_工序内容_查询 '" + opName + "'," + engineTypeID.ToString(); + DataAccess.ExecuteDataTable(sql, out dt); + } + /// + /// 电子看板_工序内容_查询 + /// + /// 工位号 + /// 产品型号代码 + /// + static public void Process_Select_NeedDealWith(string opName, int engineTypeID, out DataTable dt) + { + dt = null; + + string sql = "exec 电子看板_工序内容_查询_需要处理 '" + opName + "'," + engineTypeID.ToString(); + DataAccess.ExecuteDataTable(sql, out dt); + } + /// + /// MES_基本变量_机型代码_查询 + /// + /// + static public void EngineType_Select(out DataTable dt) + { + dt = null; + string sql = "exec MES_基本变量_机型代码_查询"; + DataAccess.ExecuteDataTable(sql, out dt); + } + + /// + /// 电子看板_MES_基本变量_原始数据_更新测量数据 + /// + /// + /// + /// + /// + /// + /// + /// + static public void ShaftDataUpdate(string opName, string engineTypeID, string shaftNo, string value1, string value2, string value3, string value4) + { + + string sql = "exec 电子看板_MES_基本变量_原始数据_更新测量数据 "; + sql = sql + " '" + opName + "',"; + sql = sql + " '" + engineTypeID + "',"; + sql = sql + " " + shaftNo.ToString() + ","; + sql = sql + " '" + value1 + "',"; + sql = sql + " '" + value2 + "',"; + sql = sql + " '" + value3 + "',"; + sql = sql + " " + value4.ToString() +""; + DataAccess.ExecuteSQL(sql); + } + /// + /// 电子看板_MES_基本变量_原始数据_清零测量数据 + /// + /// + static public void ShaftDataClear(string opName) + { + + string sql = "exec 电子看板_MES_基本变量_原始数据_更新测量数据 "; + sql = sql + " '" + opName + "'"; + DataAccess.ExecuteSQL(sql); + } + + /// + /// 电子看板_MES_基本变量_原始数据_增加测量数据 + /// + /// + /// + /// + /// + /// + /// + static public void ShaftDataInsert(string opName, string engineID, string engineType, string engineTypeID, + string isGood, string dateTime) + { + + string sql = "exec 电子看板_MES_基本变量_原始数据_增加测量数据 "; + sql = sql + " '" + opName + "',"; + sql = sql + " '" + engineID + "',"; + sql = sql + " '" + engineType + "',"; + sql = sql + " " + engineTypeID + ","; + sql = sql + " " + isGood + ","; + sql = sql + " '" + dateTime + "'"; + DataAccess.ExecuteSQL(sql); + } + + + /// + /// [电子看板_工位机型_质量数据测量位置_查询_OP3010] 2012-12-13 + /// + /// 工位号 + /// 产品型号代码 + /// + static public void ShaftPosition_Select_OP3010(string opName, int engineTypeID,int IsUsing ,out DataTable dt) + { + dt = null; + + string sql = "exec 电子看板_工位机型_质量数据测量位置_查询_OP3010 '" + opName + "','" + engineTypeID.ToString() + "','" + IsUsing+ "'"; + DataAccess.ExecuteDataTable(sql, out dt); + } + /// + /// [电子看板_工位机型_质量数据测量位置_查询_工作顺序_OP3010] 2012-12-13 + /// + /// + /// + /// + static public void ShaftPosition_Select_WorkingStep_OP3010(string opName, int engineTypeID,int IsUsing, out DataTable dt) + { + dt = null; + string sql = "exec 电子看板_工位机型_质量数据测量位置_查询_工作顺序_OP3010 '" + opName + "','" + engineTypeID.ToString() + "','" + IsUsing + "'"; + DataAccess.ExecuteDataTable(sql, out dt); + } + + + /// + /// [MES_操作者_用户_显示_查询] 2013-01-23 王可心 用户名增加用 + /// + /// + static public void UserName_Select(out DataTable dt) + { + dt = null; + string sql = "exec MES_操作者_用户_显示_查询 "; + DataAccess.ExecuteDataTable(sql, out dt); + } + } +} diff --git a/Common/07WebBusinessFacade/BusinessFacade/MES.B5A.ShaftPosition/ShaftPositionData.cs b/Common/07WebBusinessFacade/BusinessFacade/MES.B5A.ShaftPosition/ShaftPositionData.cs new file mode 100644 index 0000000..4e86e08 --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/MES.B5A.ShaftPosition/ShaftPositionData.cs @@ -0,0 +1,199 @@ +using System; +using System.Data; +using System.Data.SqlClient; +using DataLinkMesWork; +using System.Collections; +using System.Collections.Specialized; +//using SystemFramework; + +namespace bizFacade +{ + /// + /// 电子看板信息系统 + /// + public partial class ShaftPosition + { + /// + /// 测量数据合格_电子看板_质量数据_临时表_增加_返修工位 + /// @EngineID nvarchar(50)=null, + /// @EngineType nvarchar(50)=null, + /// @EngineTypeID int = null, + /// @工位号 nvarchar(50)=null, + /// @工位号返修工位 nvarchar(50)=null, + /// @订单号 nvarchar(50)=null, + /// @合格标志 int + /// + /// 工件号 + /// 机型 + /// 机型代码 + /// 工位号(被返修的工位号) + /// 工位号返修工位 + /// 订单号 + /// 合格标志 + static public void ShaftPosition_Data_OpNameRepair_Insert(string engineID, string engineType, int engineTypeID, string opName, string opNameRepair,string orderForm, int isOK) + { + string procedureName; + procedureName = "测量数据合格_电子看板_质量数据_临时表_增加_返修工位"; + SqlParameter[] thisParmsSql = new SqlParameter[7]; + thisParmsSql[0] = new SqlParameter("@EngineID", engineID); + thisParmsSql[1] = new SqlParameter("@EngineType", engineType); + thisParmsSql[2] = new SqlParameter("@EngineTypeID", engineTypeID); + thisParmsSql[3] = new SqlParameter("@工位号", opName); + thisParmsSql[4] = new SqlParameter("@工位号返修工位", opNameRepair); + thisParmsSql[5] = new SqlParameter("@订单号", orderForm); + thisParmsSql[6] = new SqlParameter("@合格标志", isOK); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParmsSql); + } + /// + /// 测量数据合格_电子看板_质量数据_临时表_增加 + /// @EngineID nvarchar(50)=null, + /// @EngineType nvarchar(50)=null, + /// @EngineTypeID int = null, + /// @工位号 nvarchar(50)=null, + /// @订单号 nvarchar(50)=null, + /// @合格标志 int + /// + /// 工件号 + /// 机型 + /// 机型代码 + /// 工位号 + /// 订单号 + /// 合格标志 + static public void ShaftPosition_Data_Insert(string engineID, string engineType, int engineTypeID, string opName, string orderForm, int isOK) + { + string procedureName; + procedureName = "测量数据合格_电子看板_质量数据_临时表_增加"; + SqlParameter[] thisParmsSql = new SqlParameter[6]; + thisParmsSql[0] = new SqlParameter("@EngineID", engineID); + thisParmsSql[1] = new SqlParameter("@EngineType", engineType); + thisParmsSql[2] = new SqlParameter("@EngineTypeID", engineTypeID); + thisParmsSql[3] = new SqlParameter("@工位号", opName); + thisParmsSql[4] = new SqlParameter("@订单号", orderForm); + thisParmsSql[5] = new SqlParameter("@合格标志", isOK); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParmsSql); + } + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + static public void ShaftPosition_Data_Insert_RepairOpName(string opName, int shaftStep, string engineID, string engineType, int engineTypeID, int orderBy, string tagValue, int isOK) + { + string procedureName; + procedureName = "电子看板_质量数据_临时表_增加_备用拧紧工位"; + SqlParameter[] thisParmsSql = new SqlParameter[8]; + thisParmsSql[0] = new SqlParameter("@工位号", opName); + thisParmsSql[1] = new SqlParameter("@序号", shaftStep); + thisParmsSql[2] = new SqlParameter("@EngineID", engineID); + thisParmsSql[3] = new SqlParameter("@EngineType", engineType); + thisParmsSql[4] = new SqlParameter("@EngineTypeID", engineTypeID); + thisParmsSql[5] = new SqlParameter("@变量排序", orderBy); + thisParmsSql[6] = new SqlParameter("@测量值", tagValue); + thisParmsSql[7] = new SqlParameter("@合格标志", isOK); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParmsSql); + } + /// + /// 电子看板_质量数据_临时表_增加 + /// + /// 工位号 + /// 序号 + /// 工件号 + /// 机型 + /// 机型代码 + /// 变量代码 + /// 变量值 + /// 合格标志 + static public void ShaftPosition_Data_Insert(string opName,int shaftStep, string engineID,string engineType, int engineTypeID, int tagID,string tagValue, int isOK) + { + string procedureName; + procedureName = "电子看板_质量数据_临时表_增加"; + SqlParameter[] thisParmsSql = new SqlParameter[8]; + thisParmsSql[0] = new SqlParameter("@工位号", opName); + thisParmsSql[1] = new SqlParameter("@序号", shaftStep); + thisParmsSql[2] = new SqlParameter("@EngineID", engineID); + thisParmsSql[3] = new SqlParameter("@EngineType", engineType); + thisParmsSql[4] = new SqlParameter("@EngineTypeID", engineTypeID); + thisParmsSql[5] = new SqlParameter("@TagID", tagID); + thisParmsSql[6] = new SqlParameter("@测量值", tagValue); + thisParmsSql[7] = new SqlParameter("@合格标志", isOK); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParmsSql); + } + /// + /// 电子看板_质量数据_临时表_增加 + /// + /// 工位号 + /// 序号 + /// 工件号 + /// 机型 + /// 机型代码 + /// 变量代码 + /// 变量值 + /// 合格标志 + //static public void ShaftPosition_Data_Insert_Access(string opName, int shaftStep, string engineID, string engineType, + // int engineTypeID, int tagID, string tagValue, int isOK) + //{ + // string sql; + // string sql_Delete; + // sql = "insert into 电子看板_质量数据_临时表(EngineID,EngineType,EngineTypeID,工位号,TagID,测量值,合格标志) "; + // sql = sql+" values("; + // sql = sql + "'" + engineID + "',"; + // sql = sql + "'" + engineType + "',"; + // sql = sql + "" + engineTypeID.ToString() + ","; + // sql = sql + "'" + opName + "',"; + // sql = sql + "" + tagID.ToString() + ","; + // sql = sql + "'" + tagValue + "',"; + // sql = sql + "" + isOK.ToString() + ")"; + + // sql_Delete = "delete from 电子看板_质量数据_临时表"; + // sql_Delete = sql_Delete + " where tagID=" + tagID.ToString(); + // DataAccess.ExecuteSQL_OleDb_Access(sql_Delete); + // DataAccess.ExecuteSQL_OleDb_Access(sql); + //} + /// + /// 查询[电子看板_质量数据_临时表]数据 + /// + /// 工位号 + /// 合格标志 + //static public void ShaftPosition_Data_Select_Access(string opName, out DataTable dt) + //{ + // string sql; + // sql = "select EngineID,EngineType,EngineTypeID,工位号,TagID,测量值 as TagValue,合格标志 as IsGoodBad"; + // sql=sql+" from 电子看板_质量数据_临时表 "; + // sql = sql+" where 工位号='"+opName+"'"; + // DataAccess.ExecuteDataTable_OleDb_Access(sql, out dt); + //} + /// + /// 删除[电子看板_质量数据_临时表]数据 + /// + /// 工位号 + //static public void ShaftPosition_Data_Delete_Access(string opName) + //{ + // string sql; + // sql = "delete from 电子看板_质量数据_临时表 "; + // sql = sql + " where 工位号='" + opName + "'"; + // DataAccess.ExecuteSQL_OleDb_Access(sql); + //} + /// + /// 电子看板_质量数据_临时表_删除 + /// + /// 工位号 + /// 列位置 + /// EngineID + static public void ShaftPosition_Data_Delete(string opName, int shaftStep, string engineID) + { + string procedureName; + procedureName = "电子看板_质量数据_临时表_删除"; + SqlParameter[] thisParmsSql = new SqlParameter[3]; + thisParmsSql[0] = new SqlParameter("@工位号", opName); + thisParmsSql[1] = new SqlParameter("@列位置", shaftStep); + thisParmsSql[2] = new SqlParameter("@EngineID", engineID); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParmsSql); + } + } +} diff --git a/Common/07WebBusinessFacade/BusinessFacade/MES.B5A.ShaftPosition/vssver2.scc b/Common/07WebBusinessFacade/BusinessFacade/MES.B5A.ShaftPosition/vssver2.scc new file mode 100644 index 0000000..ec4119f Binary files /dev/null and b/Common/07WebBusinessFacade/BusinessFacade/MES.B5A.ShaftPosition/vssver2.scc differ diff --git a/Common/07WebBusinessFacade/BusinessFacade/MES.Biz.TraceTable/MES.Biz.TraceTable.Cap.cs b/Common/07WebBusinessFacade/BusinessFacade/MES.Biz.TraceTable/MES.Biz.TraceTable.Cap.cs new file mode 100644 index 0000000..a0df331 --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/MES.Biz.TraceTable/MES.Biz.TraceTable.Cap.cs @@ -0,0 +1,60 @@ +using System; +using System.IO; +using System.Collections.Generic; +using System.Text; +using System.Data; +using System.Data.SqlClient; +using DataLinkMesWork; +using System.Data.OleDb; + +//using SystemFramework; + +namespace bizFacade +{ + public partial class BaseDataSystemMES + { + ///// + ///// MES_装配数据_发动机号_追踪代码 + ///// 追踪代码 SqlServer和Access + ///// + ///// + ///// + ///// + ///// + //public static bool TraceTable_Select_SqlServerAndAccess(string traceCode, string opName, out DataTable dt) + //{ + // string sql; + // sql = "SELECT top 1 * FROM MES_装配数据_发动机号_追踪代码 " + // + " WHERE 追踪代码 = '" + traceCode + "' and 工位号='" + opName + "' order by 操作时间 desc "; + // if (!SQLCommon.SqlServerConnectionStatus) + // { + // return DataAccess.ExecuteDataTable_OleDb_Access(sql, out dt); + // } + // else + // { + // return DataAccess.ExecuteDataTable(sql, out dt); + // } + //} + /// + /// MES_装配数据_发动机号_追踪代码 + /// 追踪代码 SqlServer和Access + /// + /// + /// + /// + public static bool TraceTable_Select_SqlServerAndAccess(string traceCode, out DataTable dt) + { + string sql; + sql = "SELECT top 1 * FROM MES_装配数据_发动机号_追踪代码 " + + " WHERE 追踪代码 = '" + traceCode + "' order by 操作时间 desc "; + //if (!SQLCommon.SqlServerConnectionStatus) + //{ + // return DataAccess.ExecuteDataTable_OleDb_Access(sql, out dt); + //} + //else + { + return DataAccess.ExecuteDataTable(sql, out dt); + } + } + } +} diff --git a/Common/07WebBusinessFacade/BusinessFacade/MES.Biz.TraceTable/MES.Biz.TraceTable.Cylinder.cs b/Common/07WebBusinessFacade/BusinessFacade/MES.Biz.TraceTable/MES.Biz.TraceTable.Cylinder.cs new file mode 100644 index 0000000..c541e81 --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/MES.Biz.TraceTable/MES.Biz.TraceTable.Cylinder.cs @@ -0,0 +1,388 @@ +using System; +using System.IO; +using System.Collections.Generic; +using System.Text; +using System.Data; +using System.Data.SqlClient; +using DataLinkMesWork; +using System.Data.OleDb; + +//using SystemFramework; + +namespace bizFacade +{ + public partial class BaseDataSystemMES + { + /// + /// 检测表 [MES_装配数据_发动机号_追踪代码] 中的扫描挂牌码[追踪代码]是否存在 + /// 不存在 返回 true 否则返回 false + ///分线活塞连杆上线工位流程:(活塞连杆OP3800)MachineType=“S”, + ///ScannerType = “1”,OpType=“F103”。每个发动机装配六个活塞连杆。 + ///六个活塞连杆分别放在三个连续的活塞连杆托盘上,每个托盘放两个活塞连杆, + ///每个工位完成一个托盘两个活塞连杆的安装。 + ///三个连续的活塞连杆托盘上的描挂牌码(物料追踪号[追踪代码])相同。 + ///活塞连杆上托盘: + ///1:PLC向MES发送工件到位,开始扫描信号。WorkStart=1 + ///2:扫描挂牌码(物料追踪号[追踪代码]) + ///3:检测表 [MES_装配数据_发动机号_追踪代码] 中的扫描挂牌码[追踪代码]是否存在(是否禁用 + ///3 and追踪代码 = ‘’)。 + ///3.1:如果不存在或存在并且验证完成(是否禁用=3), + ///显示当前生产计划对应的活塞连杆信息(物料表和需要验证的物料表); + ///保存[追踪代码]和[追踪标识](追踪标识=HL+时间标签) + ///到表[MES_装配数据_发动机号_追踪代码]中。[追踪标识]对应表[MES_装配数据_发动机号_追踪代码]的 + ///[发动机号]字段。MES向PLC写入发动机号、机型、机型标志、追踪代码; + ///MES向PLC写入MES激发变量扫描完成,EngineGetOver=1 + ///3.2:如果存在并且验证完成(是否禁用3),使用[MES_装配数据_发动机号_追踪代码], + ///显示扫描挂牌码对应的活塞连杆信息(物料表和需要验证的物料表)。 + ///MES向PLC写入发动机号、机型、机型标志、追踪代码; + ///MES向PLC写入MES激发变量扫描完成,EngineGetOver=1 + ///3.3:如果物料验证完成,追踪代码对应的[是否禁用]=3 + ///(每验证完成一个托盘对应活塞连杆物料增加1)。 + ///3.4:显示每一个托盘对应的验证物料。 + ///4物料验证:每验证完成一个托盘对应活塞连杆物料,如果没有全部完成验证, + ///MaterialVerifyOver=1,不清空表[MES_装配数据_零部件追溯_临时状态]。 + ///PLC向MES发送工件离开信号WorkStart=0,保存数据到信息管理系统, + ///完成工件当日计数和工作开始时间和结束时间。 + ///5:如果全部完成验证,MaterialVerifyOver=1,清空表[MES_装配数据_零部件追溯_临时状态]。 + ///每验证完成一个托盘对应活塞连杆物料,追踪代码对应的[是否禁用]增加1, + ///作为活塞连杆分组验证标识。每验证一个物料,保存数据到表[MES_装配数据_零部件追溯_数据主表] + ///和[MES_装配数据_零部件追溯],发动机号=追踪标识。PLC向MES发送工件离开信号WorkStart=0, + ///保存数据到信息管理系统,完成工件当日计数和工作开始时间和结束时间。 + ///6:通过OpNameMainLine(总线活塞连杆上线工位)工位数据表和本工位的装配指南, + ///获得当前工位的装配指南,订单号、机型、机型标志。 + ///7:显示活塞连杆订单号、活塞连杆、机型、机型标志 + ///-1 不合理 + ///0 没记录 + ///1 验证完成第一组 + ///2 验证完成第二组 + ///3 验证完成第三组 + /// + //public static int TraceTableCheck_F3_New(string opName, string TraceCode) + //{ + // DataTable dt; + // int isFalse; + // string sql; + // //存在,并且没有验证完成条件 + // sql = "SELECT top 1 是否禁用 FROM [MES_装配数据_发动机号_追踪代码] " + // + " where (追踪代码='" + TraceCode + "'" + // + " and 工位号='" + opName + "')" + // +" order by 操作时间 desc "; + // //if (!SQLCommon.SqlServerConnectionStatus) + // //{ + // // DataAccess.ExecuteDataTable_OleDb_Access(sql, out dt); + // //} + // //else + // { + // DataAccess.ExecuteDataTable(sql, out dt); + + // } + // if (dt == null) + // { + // //读[MES_装配数据_发动机号_追踪代码]数据失败 + // isFalse = -1; + // } + // if (dt.Rows.Count > 0) + // { + // isFalse = Convert.ToInt32(dt.Rows[0]["是否禁用"]); + // } + // else + // { + // isFalse = 0; + // } + + // return isFalse; + + //} + ///// + ///// 检测表 [MES_装配数据_发动机号_追踪代码] 中的扫描挂牌码[追踪代码]是否存在 + ///// 不存在 返回 true 否则返回 false + /////分线活塞连杆上线工位流程:(活塞连杆OP3800)MachineType=“S”, + /////ScannerType = “1”,OpType=“F103”。每个发动机装配六个活塞连杆。 + /////六个活塞连杆分别放在三个连续的活塞连杆托盘上,每个托盘放两个活塞连杆, + /////每个工位完成一个托盘两个活塞连杆的安装。 + /////三个连续的活塞连杆托盘上的描挂牌码(物料追踪号[追踪代码])相同。 + /////活塞连杆上托盘: + /////1:PLC向MES发送工件到位,开始扫描信号。WorkStart=1 + /////2:扫描挂牌码(物料追踪号[追踪代码]) + /////3:检测表 [MES_装配数据_发动机号_追踪代码] 中的扫描挂牌码[追踪代码]是否存在(是否禁用 + /////3 and追踪代码 = ‘’)。 + /////3.1:如果不存在或存在并且验证完成(是否禁用=3), + /////显示当前生产计划对应的活塞连杆信息(物料表和需要验证的物料表); + /////保存[追踪代码]和[追踪标识](追踪标识=HL+时间标签) + /////到表[MES_装配数据_发动机号_追踪代码]中。[追踪标识]对应表[MES_装配数据_发动机号_追踪代码]的 + /////[发动机号]字段。MES向PLC写入发动机号、机型、机型标志、追踪代码; + /////MES向PLC写入MES激发变量扫描完成,EngineGetOver=1 + /////3.2:如果存在并且验证完成(是否禁用3),使用[MES_装配数据_发动机号_追踪代码], + /////显示扫描挂牌码对应的活塞连杆信息(物料表和需要验证的物料表)。 + /////MES向PLC写入发动机号、机型、机型标志、追踪代码; + /////MES向PLC写入MES激发变量扫描完成,EngineGetOver=1 + /////3.3:如果物料验证完成,追踪代码对应的[是否禁用]=3 + /////(每验证完成一个托盘对应活塞连杆物料增加1)。 + /////3.4:显示每一个托盘对应的验证物料。 + /////4物料验证:每验证完成一个托盘对应活塞连杆物料,如果没有全部完成验证, + /////MaterialVerifyOver=1,不清空表[MES_装配数据_零部件追溯_临时状态]。 + /////PLC向MES发送工件离开信号WorkStart=0,保存数据到信息管理系统, + /////完成工件当日计数和工作开始时间和结束时间。 + /////5:如果全部完成验证,MaterialVerifyOver=1,清空表[MES_装配数据_零部件追溯_临时状态]。 + /////每验证完成一个托盘对应活塞连杆物料,追踪代码对应的[是否禁用]增加1, + /////作为活塞连杆分组验证标识。每验证一个物料,保存数据到表[MES_装配数据_零部件追溯_数据主表] + /////和[MES_装配数据_零部件追溯],发动机号=追踪标识。PLC向MES发送工件离开信号WorkStart=0, + /////保存数据到信息管理系统,完成工件当日计数和工作开始时间和结束时间。 + /////6:通过OpNameMainLine(总线活塞连杆上线工位)工位数据表和本工位的装配指南, + /////获得当前工位的装配指南,订单号、机型、机型标志。 + /////7:显示活塞连杆订单号、活塞连杆、机型、机型标志 + /////-1 不合理 + /////0 没记录 + /////1 验证完成第一组 + /////2 验证完成第二组 + /////3 验证完成第三组 + ///// + //public static int TraceTableCheck_F3(string opName, string TraceCode) + //{ + // DataTable dt; + // int isFalse; + // string sql; + // //存在,并且没有验证完成条件 + // sql = "SELECT top 1 是否禁用 FROM [MES_装配数据_发动机号_追踪代码] " + // + " where (追踪代码='" + TraceCode + "'" + // + " and 工位号='" + opName + "')" + // +" order by 操作时间 desc "; + // //if (!SQLCommon.SqlServerConnectionStatus) + // //{ + // // DataAccess.ExecuteDataTable_OleDb_Access(sql, out dt); + // //} + // //else + // { + // DataAccess.ExecuteDataTable(sql, out dt); + + // } + // if (dt == null) + // { + // //读[MES_装配数据_发动机号_追踪代码]数据失败 + // isFalse = -1; + // } + // if (dt.Rows.Count > 0) + // { + // isFalse = Convert.ToInt32(dt.Rows[0]["是否禁用"]); + // } + // else + // { + // isFalse = 0; + // } + + // return isFalse; + + //} + ///// + ///// 用于:活塞连杆上线 + ///// 活塞连杆分三组,验证完成一组(包括将验证的物料保存以后), + ///// [MES_装配数据_发动机号_追踪代码] 表中的字段“是否禁用”=1; + ///// 验证完成二组(包括将验证的物料保存以后), + ///// [MES_装配数据_发动机号_追踪代码] 表中的字段“是否禁用”=2; + ///// 验证完成三组(包括将验证的物料保存以后), + ///// [MES_装配数据_发动机号_追踪代码] 表中的字段“是否禁用”=3。 + ///// 当第三组验证完成后,表[MES_计划BOM_发动机号]的字段“是否装配代码”=1, + ///// 表示已经完成一个发动机的活塞连杆装配。 + ///// + ///// + ///// + ///// + ///// + //public static int TraceTableCheck(string opName, string TraceCode, string strConnectionstring) + //{ + // DataTable dt; + // int isFalse; + // string sql; + // //存在,并且没有验证完成条件 + // sql = "SELECT 是否禁用 FROM [MES_装配数据_发动机号_追踪代码] " + // + " where (追踪代码='" + TraceCode + "'" + // + " and 工位号='" + opName + "')"; + // DataAccess.ExecuteDataTable_OleDb_Access(sql, strConnectionstring, out dt); + // if (dt == null) + // { + // isFalse = -1; + // } + // if (dt.Rows.Count > 0) + // { + // isFalse = Convert.ToInt32(dt.Rows[0]["是否禁用"]); + // } + // else + // { + // isFalse = -1; + // } + + // return isFalse; + + //} + ///// + ///// 用于:活塞连杆上线 + ///// 活塞连杆分三组,验证完成一组(包括将验证的物料保存以后), + ///// [MES_装配数据_发动机号_追踪代码] 表中的字段“是否禁用”=1; + ///// 验证完成二组(包括将验证的物料保存以后), + ///// [MES_装配数据_发动机号_追踪代码] 表中的字段“是否禁用”=2; + ///// 验证完成三组(包括将验证的物料保存以后), + ///// [MES_装配数据_发动机号_追踪代码] 表中的字段“是否禁用”=3。 + ///// 当第三组验证完成后,表[MES_计划BOM_发动机号]的字段“是否装配代码”=1, + ///// 表示已经完成一个发动机的活塞连杆装配。 + ///// + ///// + ///// + ///// + //public static int TraceTableCheck(string opName, string TraceCode) + //{ + // DataTable dt; + // int isFalse; + // string sql; + // //存在,并且没有验证完成条件 + // sql = "SELECT 是否禁用 FROM [MES_装配数据_发动机号_追踪代码] " + // + " where (追踪代码='" + TraceCode + "'" + // + " and 工位号='" + opName + "')"; + // DataAccess.ExecuteDataTable_OleDb_Access(sql, out dt); + // if (dt == null) + // { + // isFalse = -1; + // } + // if (dt.Rows.Count > 0) + // { + // isFalse = Convert.ToInt32(dt.Rows[0]["是否禁用"]); + // } + // else + // { + // isFalse = -1; + // } + + // return isFalse; + + //} + ///// + ///// 更新活塞连杆验证状态(是否禁用加"1") + ///// 是否禁用 =0 开始验证新的活塞连杆 + ///// =1第一组验证完成 + ///// =2第二组验证完成 + ///// =3第三组验证完成 + ///// 6.5 活塞连杆分三组,验证完成一组(包括将验证的物料保存以后), + ///// [MES_装配数据_发动机号_追踪代码] 表中的字段“是否禁用”=1; + ///// 验证完成二组(包括将验证的物料保存以后), + ///// [MES_装配数据_发动机号_追踪代码] 表中的字段“是否禁用”=2; + ///// 验证完成三组(包括将验证的物料保存以后), + ///// [MES_装配数据_发动机号_追踪代码] 表中的字段“是否禁用”=3。 + ///// 当第三组验证完成后, + ///// 表[MES_计划BOM_发动机号]的字段“是否装配代码”=1, + ///// 表示已经完成一个发动机的活塞连杆装配。 + ///// + ///// + ///// + ///// + ///// + //public static bool TraceTableUpdate_AddOne_F3(string opName, string TraceCode, string EngineID) + //{ + // string sql; + // DataTable dt; + // int count; + // sql = "SELECT top 1 是否禁用 FROM [MES_装配数据_发动机号_追踪代码] " + // + " where (追踪代码='" + TraceCode + "'" + // + " and 工位号='" + opName + "')" + // + " order by 操作时间 desc "; + // DataAccess.ExecuteDataTable_OleDb_Access(sql, out dt); + // if (dt == null) return false; + // if (dt.Rows.Count > 0) + // { + // count = Convert.ToInt32(dt.Rows[0]["是否禁用"]); + // } + // else + // { + // count = 0; + // } + // count = count + 1; + // sql = "UPDATE [MES_装配数据_发动机号_追踪代码] " + // + " SET 是否禁用=" + count.ToString() + // + " where (追踪代码='" + TraceCode + "'" + // + " and 工位号='" + opName + "')"; + // //[MES_计划BOM_发动机号]的字段“是否装配代码”=1, + // if (count == 3) + // { + // try + // { + // BaseDataSystemMES.BaseData_tagTable_EngineID_UpDate(EngineID); + // } + // catch (Exception err) + // { + // ////ApplicationLog.WriteLog(err, "更新活塞连杆验证状态"); + // } + // } + // return DataAccess.ExecuteSQL_OleDb_Access(sql); + //} + ///// + ///// 更新活塞连杆验证状态 + ///// 是否禁用 =0 开始验证新的活塞连杆 + ///// =1第一组验证完成 + ///// =2第二组验证完成 + ///// =3第三组验证完成 + ///// + ///// + ///// + ///// + ///// + //public static bool TraceTableUpdate_F3_New(string opName, string TraceCode, int isFalse) + //{ + // string sql; + // sql = "UPDATE [MES_装配数据_发动机号_追踪代码] " + // + " SET 是否禁用=" + isFalse.ToString() + // + " where ( 是否禁用<=2 and 追踪代码='" + TraceCode + "'" + // + " and 工位号='" + opName + "')"; + // //if (!SQLCommon.SqlServerConnectionStatus) + // //{ + // // return DataAccess.ExecuteSQL_OleDb_Access(sql); + // //} + // //else + // { + // return DataAccess.ExecuteSQL(sql); + + // } + //} + ///// + ///// 更新活塞连杆验证状态 + ///// 是否禁用 =0 开始验证新的活塞连杆 + ///// =1第一组验证完成 + ///// =2第二组验证完成 + ///// =3第三组验证完成 + ///// + ///// + ///// + ///// + ///// + //public static bool TraceTableUpdate_F3(string opName, string TraceCode, int isFalse) + //{ + // string sql; + // sql = "UPDATE [MES_装配数据_发动机号_追踪代码] " + // + " SET 是否禁用=" + isFalse.ToString() + // + " where (追踪代码='" + TraceCode + "'" + // + " and 工位号='" + opName + "')"; + // return DataAccess.ExecuteSQL_OleDb_Access(sql); + //} + ///// + ///// 线首,用于物料追踪 + ///// (3.2.2.1)如果表[MES_装配数据_发动机号_追踪代码]中 + ///// 不存在字段“是否禁用” 小于“3”的记录, + ///// 说明活塞连杆工位已经全部验证完成, + ///// 开始全新验证流程。同(2)基本流程。 + ///// + ///// + //public static bool TableTraceSelectIsFalse() + //{ + // DataTable dt; + // string sql = null; + // sql = "SELECT * FROM MES_装配数据_发动机号_追踪代码 WHERE 是否禁用 < 3"; + // DataAccess.ExecuteDataTable_OleDb_Access(sql, out dt); + // if (dt == null) + // { + // return true; + // } + // if (dt.Rows.Count == 0) + // { + // return true; + // } + // return false; + //} + } +} diff --git a/Common/07WebBusinessFacade/BusinessFacade/MES.Biz.TraceTable/MES.Biz.TraceTable.ToOpName.cs b/Common/07WebBusinessFacade/BusinessFacade/MES.Biz.TraceTable/MES.Biz.TraceTable.ToOpName.cs new file mode 100644 index 0000000..390c0df --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/MES.Biz.TraceTable/MES.Biz.TraceTable.ToOpName.cs @@ -0,0 +1,66 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Data; +using System.Data.SqlClient; +using System.Data.OleDb; +using DataLinkMesWork; + +//using SystemFramework; + +namespace bizFacade +{ + public partial class BaseDataSystemMES + { + /// + /// + /// + /// + /// + /// + //public static void GetOpNameByLineType(string lineType,string transferLineType, DataTable dt) + //{ + // dt = null; + // string sql; + // sql = "SELECT * FROM MES_计划BOM_工位与名称 WHERE PC=1 " + // + " AND 线体类型 ='"+transferLineType+"'"; + // DataAccess.ExecuteDataTable_OleDb_Access(sql, out dt); + + //} + /// + /// 获得上线工位对应线体类型的工位文件列表 + /// + /// + /// + //public static void GetFileNameListByOpName(string opName, out string[] fileNameList) + //{ + // string transferLineType; + // fileNameList = null; + // DataTable dt = null; + // string sql; + // sql = "SELECT 线体类型 FROM MES_计划BOM_工位与名称 WHERE 工位号='" + opName + "'"; + // DataAccess.ExecuteDataTable_OleDb_Access(sql, out dt); + // if (dt != null) + // { + // if (dt.Rows.Count > 0) + // { + // transferLineType = dt.Rows[0]["线体类型"].ToString(); + // sql = "SELECT 文件名称 FROM MES_计划BOM_工位与名称 WHERE 线体类型 ='" + transferLineType + "'" + // + " AND 工位号<>'" + opName+"'"; + // DataAccess.ExecuteDataTable_OleDb_Access(sql, out dt); + // if (dt != null) + // { + // if (dt.Rows.Count > 0) + // { + // fileNameList = new string[dt.Rows.Count]; + // for (int i = 0; i < dt.Rows.Count; i++) + // { + // fileNameList[i] = dt.Rows[i]["文件名称"].ToString(); + // } + // } + // } + // } + // } + //} + } +} diff --git a/Common/07WebBusinessFacade/BusinessFacade/MES.Biz.TraceTable/MES.Biz.TraceTable.cs b/Common/07WebBusinessFacade/BusinessFacade/MES.Biz.TraceTable/MES.Biz.TraceTable.cs new file mode 100644 index 0000000..4cb2664 --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/MES.Biz.TraceTable/MES.Biz.TraceTable.cs @@ -0,0 +1,817 @@ +using System; +using System.IO; +using System.Collections.Generic; +using System.Text; +using System.Data; +using System.Data.SqlClient; +using DataLinkMesWork; +using System.Data.OleDb; + +//using SystemFramework; + +namespace bizFacade +{ + public partial class BaseDataSystemMES + { + + /// + /// 删除[追踪代码] + /// + /// + /// + /// + //public static bool TraceTableDelete(string opName, string TraceCode) + //{ + // string sql; + // sql = "DELETE FROM [MES_装配数据_发动机号_追踪代码] " + // + " where (追踪代码='" + TraceCode + "'" + // + " and 工位号='" + opName + "')"; + // return DataAccess.ExecuteSQL_OleDb_Access(sql); + //} + /// + /// MES_装配数据_发动机号_追踪代码 + /// 订单号 + /// Access + /// + /// + /// + /// + /// + //public static bool TraceTable_Select(string traceCode, string connectionString_Access,out DataTable dt) + //{ + // string sql; + // sql = "SELECT top 1 * FROM MES_装配数据_发动机号_追踪代码 " + // + " WHERE 追踪代码 = '" + traceCode + "'"; + // return DataAccess.ExecuteDataTable_OleDb_Access(sql, connectionString_Access, out dt); + //} + + /// + /// MES_装配数据_发动机号_追踪代码 + /// Access + /// + /// + /// + /// + public static bool TraceTable_Select(string EngineTraceCode, out DataTable dt) + { + string sql; + //sql = "SELECT * FROM MES_装配数据_发动机号_追踪代码 " + // + " WHERE 发动机号 = '" + EngineTraceCode + "'"; + sql = "SELECT top 1 * FROM MES_装配数据_发动机号_追踪代码 " + + " WHERE 追踪代码 = '" + EngineTraceCode + "'" + +" order by 操作时间 desc "; + //if (!SQLCommon.SqlServerConnectionStatus) + //{ + // return DataAccess.ExecuteDataTable_OleDb_Access(sql, out dt); + //} + //else + { + return DataAccess.ExecuteDataTable(sql, out dt); + + } + } + /// + /// [MES_装配数据_零部件追溯_发动机号与缸盖号] + /// + private static string GetSqlString_EngineID_CapNumber() + { + string sql = null; + sql = "INSERT INTO [MES_装配数据_零部件追溯_发动机号与缸盖号] " + + "(订单号,发动机号,追踪代码,工位号,到达时间,离开时间,操作者工号,班次代码," + + "[SAP物料号],[发动机型号],[发动机型号代码], [发动机机型], " + + "[发动机数量], [厂牌编号起始号], [客户名称],[投料日期],[文件编号],[集团名称],[通知号]," + + "[功率],[指南文件编号],[装机状态],[适用状态],[物料描述],[计划下达日期],[计划完工日期],[主配厂家],[零件类型])" + + " VALUES (" + //订单号,发动机号,追踪代码,工位号,到达时间,离开时间,操作者工号,班次代码 + + "'" + MaterialData.orderForm + "'," + + "'" + MaterialData.engineNumber + "'," + + "'" + MaterialData.engineTraceCode + "'," + + "'" + MaterialData.opName + "'," + + "'" + MaterialData.arrivedTime.ToString("G") + "'," + + "'" + MaterialData.leavedTime.ToString("G") + "'," + + "'" + MaterialData.operatorCode + "'," + + "'" + MaterialData.operatorShift + "'," + //+ "[SAP物料号],[发动机型号],[发动机型号代码], [发动机机型], " + + + "'" + MaterialData.sAPMaterialNumber + "'," + + "'" + MaterialData.engineNumberType + "'," + + "" + MaterialData.engineNumberCode + ","//int + + "'" + MaterialData.engineNumberBasicType + "'," + //+ "[发动机数量], [厂牌编号起始号], [客户名称],[投料日期],[文件编号],[集团名称],[通知号]," + + + "" + MaterialData.engineCount + ","//int + + "" + MaterialData.engineNumberFirstID + ","//int + + "'" + MaterialData.customesName + "'," + + "'" + MaterialData.prepareMaterialDateTime.ToString("G") + "'," + + "'" + MaterialData.fileCode + "'," + + "'" + MaterialData.groupName + "'," + + "'" + MaterialData.notifyCode + "'," + //+ "[功率],[指南文件编号],[装机状态],[适用状态],[物料描述],[计划下达日期],[计划完工日期],主配厂家,零件类型" + + "'" + MaterialData.n_Force + "'," + + "'" + MaterialData.directFileCode + "'," + + "'" + MaterialData.workEngineStatus + "'," + + "'" + MaterialData.adaptDateTime.ToString("G") + "'," + + "'" + MaterialData.materialDescript + "'," + + "'" + MaterialData.planSendedDateTime.ToString("G") + "'," + + "'" + MaterialData.planFinishDateTime.ToString("G") + "'," + + "'" + MaterialData.mainPruduceFatory + "'," + + "" + MaterialData.partType.ToString() + ") "; + return sql; + } + ///// + ///// 获得增加表[MES_装配数据_发动机号_追踪代码]的SQL语句 + ///// + //private static string GetSqlStringFirstOpNameTableTrace_F2() + //{ + // string sql = null; + // sql = "INSERT INTO [MES_装配数据_零部件追溯_发动机号与缸盖号] " + + // "(订单号,发动机号,追踪代码,工位号,到达时间,离开时间,操作者工号,班次代码," + // + "[SAP物料号],[发动机型号],[发动机型号代码], [发动机机型], " + // + "[发动机数量], [厂牌编号起始号], [客户名称],[投料日期],[文件编号],[集团名称],[通知号]," + // + "[功率],[指南文件编号],[装机状态],[适用状态],[物料描述],[计划下达日期],[计划完工日期],[主配厂家],[零件类型])" + // + " VALUES (" + // //订单号,发动机号,追踪代码,工位号,到达时间,离开时间,操作者工号,班次代码 + // + "'" + MaterialData.orderForm + "'," + // + "'" + MaterialData.engineNumber + "'," + // + "'" + MaterialData.engineTraceCode + "'," + // + "'" + MaterialData.opName + "'," + // + "'" + MaterialData.arrivedTime.ToString("G") + "'," + // + "'" + MaterialData.leavedTime.ToString("G") + "'," + // + "'" + MaterialData.operatorCode + "'," + // + "'" + MaterialData.operatorShift + "'," + // //+ "[SAP物料号],[发动机型号],[发动机型号代码], [发动机机型], " + + // + "'" + MaterialData.sAPMaterialNumber + "'," + // + "'" + MaterialData.engineNumberType + "'," + // + "" + MaterialData.engineNumberCode + ","//int + // + "'" + MaterialData.engineNumberBasicType + "'," + // //+ "[发动机数量], [厂牌编号起始号], [客户名称],[投料日期],[文件编号],[集团名称],[通知号]," + + // + "" + MaterialData.engineCount + ","//int + // + "" + MaterialData.engineNumberFirstID + ","//int + // + "'" + MaterialData.customesName + "'," + // + "'" + MaterialData.prepareMaterialDateTime.ToString("G") + "'," + // + "'" + MaterialData.fileCode + "'," + // + "'" + MaterialData.groupName + "'," + // + "'" + MaterialData.notifyCode + "'," + // //+ "[功率],[指南文件编号],[装机状态],[适用状态],[物料描述],[计划下达日期],[计划完工日期],主配厂家,零件类型" + // + "'" + MaterialData.n_Force + "'," + // + "'" + MaterialData.directFileCode + "'," + // + "'" + MaterialData.workEngineStatus + "'," + // + "'" + MaterialData.adaptDateTime.ToString("G") + "'," + // + "'" + MaterialData.materialDescript + "'," + // + "'" + MaterialData.planSendedDateTime.ToString("G") + "'," + // + "'" + MaterialData.planFinishDateTime.ToString("G") + "'," + // + "'" + MaterialData.mainPruduceFatory + "'," + // + "" + MaterialData.partType.ToString() + ") "; + // return sql; + //} + /// + /// 线首,用于物料追踪 + /// 传递到总线上线工位的数据成功,更新isOK=1 + /// MES_装配数据_发动机号_物料追踪 + /// SELECT * FROM [MES_装配数据_发动机号_追踪代码] WHERE IsOK = 0 + /// + /// 上线工位追溯代码 + /// + //public static bool TableTraceUpdate(int firstOpNameTraceCode) + //{ + // string sql = null; + // sql = "UPDATE MES_装配数据_发动机号_追踪代码 SET IsOK = 1 WHERE 上线工位追溯代码 = " + firstOpNameTraceCode.ToString(); + // return DataAccess.ExecuteSQL_OleDb_Access(sql); + //} + /// + /// 线首,用于物料追踪 + /// 查询没有被传递到总线上线工位的数据 + /// MES_装配数据_发动机号_追踪代码 + /// SELECT * FROM [MES_装配数据_发动机号_追踪代码] WHERE IsOK = 0 + /// + /// + //public static bool TableTraceSelect(out DataTable dt) + //{ + // string sql = null; + // sql = "SELECT * FROM MES_装配数据_发动机号_追踪代码 WHERE IsOK = 0"; + // return DataAccess.ExecuteDataTable_OleDb_Access(sql, out dt); + //} + + /// + /// 总线上线工位,用于物料追踪 + /// 增加数据到Access数据库 + /// MES_装配数据_发动机号_追踪代码 + /// INSERT INTO [MES_装配数据_发动机号_追踪代码] + /// + /// 零件类型(1缸体)(2缸盖)(3活塞连杆) + /// + //public static bool TableTraceInsert_MainLine(string connectionString_Access_OpNameMainLine) + //{ + // // + // // 上线工位追溯代码 + // // + // int firstOpNameTraceCode; + // string sql = null; + // string sql2 = null; + // DataTable dt; + // DataRow dr; + // try + // { + // // 测试 connectionString_Access_OpNameMainLine 文件是否存在? + // if (!File.Exists(connectionString_Access_OpNameMainLine)) + // { + // ////ApplicationLog.WriteLog("file not exists filename=:" + connectionString_Access_OpNameMainLine); + // return false; + // } + + // // 线首,用于物料追踪 + // // 查询没有被传递到总线上线工位的数据 + // // MES_装配数据_发动机号_追踪代码 + // // SELECT * FROM [MES_装配数据_发动机号_追踪代码] WHERE IsOK = 0 + // TableTraceSelect(out dt); + // if (dt == null) return false; + // for (int i = 0; i < dt.Rows.Count; i++) + // { + // dr = dt.Rows[i]; + // sql = GetSqlString_TableTraceInsert_MainLine(dr); + // if (sql != null) + // { + // string engineTraceCode = dr[MaterialData.EngineTraceCodeField].ToString(); + // sql2 = "DELETE FROM MES_装配数据_发动机号_追踪代码 WHERE 追踪代码='" + engineTraceCode + "'"; + // DataAccess.ExecuteSQL_OleDb_Access(connectionString_Access_OpNameMainLine, sql2); + // if (DataAccess.ExecuteSQL_OleDb_Access(connectionString_Access_OpNameMainLine, sql)) + // { + // if (!Convert.IsDBNull(dr[MaterialData.FirstOpNameTraceCodeField])) + // { + // firstOpNameTraceCode = Convert.ToInt32(dr[MaterialData.FirstOpNameTraceCodeField]); + // TableTraceUpdate(firstOpNameTraceCode); + // } + // } + // } + // } + // return true; + // } + // catch (Exception err) + // { + // ////ApplicationLog.WriteLog(err.Message); + // return false; + // } + //} + /// + /// 线首,用于物料追踪 + /// 增加数据到Access数据库 + /// MES_装配数据_发动机号_追踪代码 + /// INSERT INTO [MES_装配数据_发动机号_追踪代码] + /// + /// + //public static bool TableTraceInsert() + //{ + // string sql = null; + // sql = GetSqlString_TableTraceInsert(); + // return DataAccess.ExecuteSQL_OleDb_Access(sql); + //} + /// + /// 线首,用于物料追踪 + /// 增加数据到SqlServer数据库 + /// MES_装配数据_发动机号_追踪代码 + /// INSERT INTO [MES_装配数据_发动机号_追踪代码] + /// + /// + public static bool TableTraceInsert_SqlServer() + { + string sql = null; + sql = GetSqlString_TableTraceInsert(); + return DataAccess.ExecuteSQL(sql); + } + /// + /// 应用于总线上线工位 + /// 获得增加表[MES_装配数据_发动机号_追踪代码]的SQL语句 + /// + private static string GetSqlString_TableTraceInsert_MainLine(DataRow dr) + { + // + // 上线工位追溯代码 + // + int firstOpNameTraceCode; + // + // 订单号 + // + string orderForm; + // + // 主配厂家 + // + string mainPruduceFatory; + // + // 发动号 + // + string engineNumber; + // + // 订单计划发动机号 + // + string engineNumber_OrderPlan; + // + // 追踪代码 + // + string engineTraceCode; + // + // 主物料号 + // + string mainMaterialNumber; + // + // 工位号 + // + string opName; + // + // 到达时间 + // + DateTime arrivedTime; + // + // 离开时间 + // + DateTime leavedTime; + // + // 操作者工号 + // + string operatorCode; + // + // 班次代码 + // + string operatorShift; + // + // SAP物料号 + // + string sAPMaterialNumber; + // + // 发动机型号 + // + string engineNumberType; + // + // 发动机型号代码 + // + int engineNumberCode; + // + // 发动机机型 + // + string engineNumberBasicType; + // + // 发动机数量 + // + string engineCount; + // + // 厂牌编号起始号 + // + string engineNumberFirstID; + // + // 客户名称 + // + string customesName; + // + // 投料日期 + // + DateTime prepareMaterialDateTime; + // + // 文件编号 + // + string fileCode; + // + // 集团名称 + // + string groupName; + // + // 通知号 + // + string notifyCode; + // + // 功率 + // + string n_Force; + // + // 指南文件编号 + // + string directFileCode; + // + // 装机状态 + // + string workEngineStatus; + // + // 适用状态 + // + DateTime adaptDateTime; + // + // 物料描述 + // + string materialDescript; + // + // 计划下达日期 + // + DateTime planSendedDateTime; + // + // 计划完工日期 + // + DateTime planFinishDateTime; + // + // 零件类型 + // + int partType; + + string sql = null; + try + { + if (Convert.IsDBNull(dr[MaterialData.FirstOpNameTraceCodeField])) + { + firstOpNameTraceCode = 0; + } + else + { + firstOpNameTraceCode = Convert.ToInt32(dr[MaterialData.FirstOpNameTraceCodeField]); + } + + if (Convert.IsDBNull(dr[MaterialData.OrderFormField])) + { + orderForm = ""; + } + else + { + orderForm = dr[MaterialData.OrderFormField].ToString(); + } + + // + if (Convert.IsDBNull(dr[MaterialData.EngineNumber_OrderPlanField])) + { + engineNumber_OrderPlan = ""; + } + else + { + engineNumber_OrderPlan = dr[MaterialData.EngineNumber_OrderPlanField].ToString(); + } + if (Convert.IsDBNull(dr[MaterialData.EngineNumberField])) + { + engineNumber = ""; + } + else + { + engineNumber = dr[MaterialData.EngineNumberField].ToString(); + } + if (Convert.IsDBNull(dr[MaterialData.EngineTraceCodeField])) + { + engineTraceCode = ""; + } + else + { + engineTraceCode = dr[MaterialData.EngineTraceCodeField].ToString(); + } + + if (Convert.IsDBNull(dr[MaterialData.MainMaterialNumberField])) + { + mainMaterialNumber = ""; + } + else + { + mainMaterialNumber = dr[MaterialData.MainMaterialNumberField].ToString(); + } + + + if (Convert.IsDBNull(dr[MaterialData.OpNameField])) + { + opName = ""; + } + else + { + opName = dr[MaterialData.OpNameField].ToString(); + } + + + if (Convert.IsDBNull(dr[MaterialData.ArrivedTimeField])) + { + arrivedTime = DateTime.Now; + } + else + { + arrivedTime = Convert.ToDateTime(dr[MaterialData.ArrivedTimeField]); + } + + + if (Convert.IsDBNull(dr[MaterialData.LeavedTimeField])) + { + leavedTime = DateTime.Now; + } + else + { + leavedTime = Convert.ToDateTime(dr[MaterialData.LeavedTimeField]); + } + + + if (Convert.IsDBNull(dr[MaterialData.OperatorCodeField])) + { + operatorCode = ""; + } + else + { + operatorCode = dr[MaterialData.OperatorCodeField].ToString(); + } + + if (Convert.IsDBNull(dr[MaterialData.OperatorShiftField])) + { + operatorShift = ""; + } + else + { + operatorShift = dr[MaterialData.OperatorShiftField].ToString(); + } + + //+ "[SAP物料号],[发动机型号],[发动机型号代码], [发动机机型], " + + + if (Convert.IsDBNull(dr[MaterialData.SAPMaterialNumberField])) + { + sAPMaterialNumber = ""; + } + else + { + sAPMaterialNumber = dr[MaterialData.SAPMaterialNumberField].ToString(); + } + + + if (Convert.IsDBNull(dr[MaterialData.EngineNumberTypeField])) + { + engineNumberType = ""; + } + else + { + engineNumberType = dr[MaterialData.EngineNumberTypeField].ToString(); + } + + if (Convert.IsDBNull(dr[MaterialData.EngineNumberCodeField])) + { + engineNumberCode = 1; + } + else + { + engineNumberCode = Convert.ToInt32(dr[MaterialData.EngineNumberCodeField]); + } + + + if (Convert.IsDBNull(dr[MaterialData.EngineNumberBasicTypeField])) + { + engineNumberBasicType = ""; + } + else + { + engineNumberBasicType = dr[MaterialData.EngineNumberBasicTypeField].ToString(); + } + + //+ "[发动机数量], [厂牌编号起始号], [客户名称],[投料日期],[文件编号],[集团名称],[通知号]," + + if (Convert.IsDBNull(dr[MaterialData.EngineCountField])) + { + engineCount = ""; + } + else + { + engineCount = dr[MaterialData.EngineCountField].ToString(); + } + + if (Convert.IsDBNull(dr[MaterialData.EngineNumberFirstIDField])) + { + engineNumberFirstID = ""; + } + else + { + engineNumberFirstID = dr[MaterialData.EngineNumberFirstIDField].ToString(); + } + + if (Convert.IsDBNull(dr[MaterialData.CustomesNameField])) + { + customesName = ""; + } + else + { + customesName = dr[MaterialData.CustomesNameField].ToString(); + } + + + if (Convert.IsDBNull(dr[MaterialData.PrepareMaterialDateTimeField])) + { + prepareMaterialDateTime = DateTime.Now; + } + else + { + prepareMaterialDateTime = Convert.ToDateTime(dr[MaterialData.PrepareMaterialDateTimeField]); + } + + + if (Convert.IsDBNull(dr[MaterialData.EngineCountField])) + { + fileCode = ""; + } + else + { + fileCode = dr[MaterialData.EngineCountField].ToString(); + } + + + if (Convert.IsDBNull(dr[MaterialData.GroupNameField])) + { + groupName = ""; + } + else + { + groupName = dr[MaterialData.GroupNameField].ToString(); + } + + + if (Convert.IsDBNull(dr[MaterialData.NotifyCodeField])) + { + notifyCode = ""; + } + else + { + notifyCode = dr[MaterialData.NotifyCodeField].ToString(); + } + + //+ "[功率],[指南文件编号],[装机状态],[适用状态],[物料描述],[计划下达日期],[计划完工日期],主配厂家,零件类型" + + if (Convert.IsDBNull(dr[MaterialData.N_ForceField])) + { + n_Force = ""; + } + else + { + n_Force = dr[MaterialData.N_ForceField].ToString(); + } + + if (Convert.IsDBNull(dr[MaterialData.DirectFileCodeField])) + { + directFileCode = ""; + } + else + { + directFileCode = dr[MaterialData.DirectFileCodeField].ToString(); + } + + + if (Convert.IsDBNull(dr[MaterialData.WorkEngineStatusField])) + { + workEngineStatus = ""; + } + else + { + workEngineStatus = dr[MaterialData.WorkEngineStatusField].ToString(); + } + + + if (Convert.IsDBNull(dr[MaterialData.AdaptDateTimeField])) + { + adaptDateTime = DateTime.Now; + } + else + { + adaptDateTime = Convert.ToDateTime(dr[MaterialData.AdaptDateTimeField]); + } + + if (Convert.IsDBNull(dr[MaterialData.MaterialDescriptField])) + { + materialDescript = ""; + } + else + { + materialDescript = dr[MaterialData.MaterialDescriptField].ToString(); + } + + if (Convert.IsDBNull(dr[MaterialData.PlanSendedDateTimeField])) + { + planSendedDateTime = DateTime.Now; + } + else + { + planSendedDateTime = Convert.ToDateTime(dr[MaterialData.PlanSendedDateTimeField]); + } + + + if (Convert.IsDBNull(dr[MaterialData.PlanFinishDateTimeField])) + { + planFinishDateTime = DateTime.Now; + } + else + { + planFinishDateTime = Convert.ToDateTime(dr[MaterialData.PlanFinishDateTimeField]); + } + + + if (Convert.IsDBNull(dr[MaterialData.MainPruduceFatoryField])) + { + mainPruduceFatory = ""; + } + else + { + mainPruduceFatory = dr[MaterialData.MainPruduceFatoryField].ToString(); + } + + + if (Convert.IsDBNull(dr[MaterialData.PartTypeField])) + { + partType = 1; + } + else + { + partType = Convert.ToInt32(dr[MaterialData.PartTypeField]); + } + + sql = "INSERT INTO [MES_装配数据_发动机号_追踪代码] " + + "(订单号,订单计划发动机号,发动机号,追踪代码,工位号,到达时间,离开时间,操作者工号,班次代码," + + "[SAP物料号],[发动机型号],[发动机型号代码], [发动机机型], " + + "[发动机数量], [厂牌编号起始号], [客户名称],[投料日期],[文件编号],[集团名称],[通知号]," + + "[功率],[指南文件编号],[装机状态],[适用状态],[物料描述],[计划下达日期],[计划完工日期],[主配厂家],[零件类型])" + + " VALUES (" + //上线工位追溯代码,订单号,发动机号,追踪代码,工位号,到达时间,离开时间,操作者工号,班次代码 + //+ "" + firstOpNameTraceCode + "," + + "'" + orderForm + "'," + + "'" + engineNumber_OrderPlan + "'," + + "'" + engineNumber + "'," + + "'" + engineTraceCode + "'," + + "'" + opName + "'," + + "'" + arrivedTime.ToString("G") + "'," + + "'" + leavedTime.ToString("G") + "'," + + "'" + operatorCode + "'," + + "'" + operatorShift + "'," + //+ "[SAP物料号],[发动机型号],[发动机型号代码], [发动机机型], " + + + "'" + sAPMaterialNumber + "'," + + "'" + engineNumberType + "'," + + "" + engineNumberCode + ","//int + + "'" + engineNumberBasicType + "'," + //+ "[发动机数量], [厂牌编号起始号], [客户名称],[投料日期],[文件编号],[集团名称],[通知号]," + + + "" + engineCount + ","//int + + "'" + engineNumberFirstID + "'," + + "'" + customesName + "'," + + "'" + prepareMaterialDateTime.ToString("G") + "'," + + "'" + fileCode + "'," + + "'" + groupName + "'," + + "'" + notifyCode + "'," + //+ "[功率],[指南文件编号],[装机状态],[适用状态],[物料描述],[计划下达日期],[计划完工日期],主配厂家,零件类型" + + "'" + n_Force + "'," + + "'" + directFileCode + "'," + + "'" + workEngineStatus + "'," + + "'" + adaptDateTime.ToString("G") + "'," + + "'" + materialDescript + "'," + + "'" + planSendedDateTime.ToString("G") + "'," + + "'" + planFinishDateTime.ToString("G") + "'," + + "'" + mainPruduceFatory + "'," + + "" + partType.ToString() + ") "; + return sql; + } + catch { return null; } + } + /// + /// 应用于分线上线工位 + /// 获得增加表[MES_装配数据_发动机号_追踪代码]的SQL语句 + /// + private static string GetSqlString_TableTraceInsert() + { + string sql = null; + sql = "INSERT INTO [MES_装配数据_发动机号_追踪代码] " + + "(订单号,订单计划发动机号,发动机号,追踪代码,主物料号,工位号,到达时间,离开时间,操作者工号,班次代码," + + "[SAP物料号],[发动机型号],[发动机型号代码], [发动机机型], " + + "[发动机数量], [厂牌编号起始号], [客户名称],[投料日期],[文件编号],[集团名称],[通知号]," + + "[功率],[指南文件编号],[装机状态],[适用状态],[物料描述],[计划下达日期],[计划完工日期],[主配厂家],[零件类型])" + + " VALUES (" + //订单号,发动机号,追踪代码,工位号,到达时间,离开时间,操作者工号,班次代码 + + "'" + MaterialData.orderForm + "'," + + "'" + MaterialData.engineNumber_OrderPlan + "'," + + "'" + MaterialData.engineNumber + "'," + + "'" + MaterialData.engineTraceCode + "'," + + "'" + MaterialData.mainMaterialNumber + "'," + + "'" + MaterialData.opName + "'," + + "'" + MaterialData.arrivedTime.ToString("G") + "'," + + "'" + MaterialData.leavedTime.ToString("G") + "'," + + "'" + MaterialData.operatorCode + "'," + + "'" + MaterialData.operatorShift + "'," + //+ "[SAP物料号],[发动机型号],[发动机型号代码], [发动机机型], " + + + "'" + MaterialData.sAPMaterialNumber + "'," + + "'" + MaterialData.engineNumberType + "'," + + "" + MaterialData.engineNumberCode + ","//int + + "'" + MaterialData.engineNumberBasicType + "'," + //+ "[发动机数量], [厂牌编号起始号], [客户名称],[投料日期],[文件编号],[集团名称],[通知号]," + + + "" + MaterialData.engineCount + ","//int + + "'" + MaterialData.engineNumberFirstID + "'," + + "'" + MaterialData.customesName + "'," + + "'" + MaterialData.prepareMaterialDateTime.ToString("G") + "'," + + "'" + MaterialData.fileCode + "'," + + "'" + MaterialData.groupName + "'," + + "'" + MaterialData.notifyCode + "'," + //+ "[功率],[指南文件编号],[装机状态],[适用状态],[物料描述],[计划下达日期],[计划完工日期],主配厂家,零件类型" + + "'" + MaterialData.n_Force + "'," + + "'" + MaterialData.directFileCode + "'," + + "'" + MaterialData.workEngineStatus + "'," + + "'" + MaterialData.adaptDateTime.ToString("G") + "'," + + "'" + MaterialData.materialDescript + "'," + + "'" + MaterialData.planSendedDateTime.ToString("G") + "'," + + "'" + MaterialData.planFinishDateTime.ToString("G") + "'," + + "'" + MaterialData.mainPruduceFatory + "'," + + "" + MaterialData.partType.ToString() + ") "; + return sql; + } + + + } +} diff --git a/Common/07WebBusinessFacade/BusinessFacade/MES.Biz.TraceTable/vssver2.scc b/Common/07WebBusinessFacade/BusinessFacade/MES.Biz.TraceTable/vssver2.scc new file mode 100644 index 0000000..c0b85a3 Binary files /dev/null and b/Common/07WebBusinessFacade/BusinessFacade/MES.Biz.TraceTable/vssver2.scc differ diff --git a/Common/07WebBusinessFacade/BusinessFacade/MES.Data.GetData/GetOpNameOrderForm.cs b/Common/07WebBusinessFacade/BusinessFacade/MES.Data.GetData/GetOpNameOrderForm.cs new file mode 100644 index 0000000..3c2d9b8 --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/MES.Data.GetData/GetOpNameOrderForm.cs @@ -0,0 +1,281 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Data; +using System.Data.SqlClient; + +using System.Data.OleDb; +using DataLinkMesWork; +//using SystemFramework; + +namespace bizFacade +{ + /// + /// 关键零部件追溯 + /// + public partial class BaseDataSystemMES + { + /// + /// 根据工位号,将计划下达到工位PC + /// [MES_计划BOM_订单计划下达_执行顺序] + /// [MES_计划BOM_发动机号] + /// [MES_计划BOM_发动机装配指南] + /// + /// + //public static void GetOrderForm(string opName) + //{ + // //订单号 + // string orderForm; + // //1:获得需要下达的订单列表 + // DataTable dt_orderForm; + // OrderFormOpName_Select(opName, out dt_orderForm); + // if (dt_orderForm != null) + // { + // for (int i = 0; i < dt_orderForm.Rows.Count; i++) + // { + // try + // { + // orderForm = dt_orderForm.Rows[i]["订单号"].ToString(); + // //2:根据订单号,工位号,获得[MES_计划BOM_订单计划下达_执行顺序] + // //[MES_计划BOM_发动机号] + // //[MES_计划BOM_发动机装配指南] + // DataTable dt_OrderFormOrderBy; + // DataTable dt_EngineID; + // DataTable dt_OperationGuid; + // GetOrderPlanEngineNumber_OrderForm(orderForm, out dt_OrderFormOrderBy); + // GetOrderPlanEngineNumberToPcStation(orderForm, out dt_EngineID); + // GetOperationGuid(orderForm, opName, out dt_OperationGuid); + + // //3将数据导入到工位PC + + // if (!GetOrderPlanEngineNumberToPcStation_OrderForm_Delete(orderForm)) continue; + // if(!GetOrderPlanEngineNumberToPcStation_Delete(orderForm)) continue; + // if(!GetOperationGuidToPcStation_Delete(orderForm)) continue; + + // if(!GetOrderPlanEngineNumberToPcStation_OrderForm(dt_OrderFormOrderBy)) continue; + // if(!GetOrderPlanEngineNumberToPcStation(dt_EngineID)) continue; + // if(!GetOperationGuidToPcStation(dt_OperationGuid)) continue; + + // OrderFormOpName_Update(orderForm, opName); + // } + // catch (Exception err) + // { + // //ApplicationLog.WriteLog(err,err.Message); + // } + + // } + // } + //} + /// + /// "delete from [MES_计划BOM_订单计划下达_执行顺序] where 订单号='" + orderForm + "'"; + /// + /// + //private static bool GetOrderPlanEngineNumberToPcStation_OrderForm_Delete(string orderForm) + //{ + // string sql; + // sql = "delete from [MES_计划BOM_订单计划下达_执行顺序] where 订单号='" + orderForm + "'"; + // return DataAccess.ExecuteSQL_OleDb_Access(sql); + //} + /// + /// "delete from [MES_计划BOM_发动机号] where 订单号='" + orderForm + "'"; + /// + /// + //private static bool GetOrderPlanEngineNumberToPcStation_Delete(string orderForm) + //{ + // string sql; + // sql = "delete from [MES_计划BOM_发动机号] where 订单号='" + orderForm + "'"; + // return DataAccess.ExecuteSQL_OleDb_Access(sql); + //} + /// + /// "delete from [MES_计划BOM_订单计划下达_执行顺序] where 订单号='" + orderForm + "'"; + /// + /// + //private static bool GetOperationGuidToPcStation_Delete(string orderForm) + //{ + // string sql; + // sql = "delete from [MES_计划BOM_发动机装配指南] where 订单号='" + orderForm + "'"; + // return DataAccess.ExecuteSQL_OleDb_Access(sql); + //} + /// + /// exec MES_计划BOM_发动机订单计划_下达工位_修改 + /// set 同步状态=1,同步日期=getdate() + /// + /// + /// + public static void OrderFormOpName_Update(string orderForm,string opName) + { + string sql; + sql = "exec MES_计划BOM_发动机订单计划_下达工位_修改 '"+orderForm+"','"+opName+"'"; + DataAccess.ExecuteSQL(sql); + } + /// + /// 获得工位对应的订单号 + /// MES_计划BOM_发动机订单计划_下达工位 + /// + /// + /// + public static void OrderFormOpName_Select(string opName, out DataTable dt) + { + string sql; + + + + sql = "select 订单号 from MES_计划BOM_发动机订单计划_下达工位 " + + " where 同步状态 = 0 and 工位号='" + opName + "'"; + DataAccess.ExecuteDataTable(sql, out dt); + + + + } + /// + /// 下达装配BOM到工位Access文件 INSERT INTO [MES_计划BOM_发动机装配指南] + /// + /// + //static public bool GetOperationGuidToPcStation(DataTable dt) + //{ + // string sql; + // sql = + // "INSERT INTO [MES_计划BOM_发动机装配指南]" + + // "([订单号], [主配厂家],[工位号], [工位名称], [物料号], [零件图号], [零件名称]," + + // " [零件数量],[是否扫描],[扫描方式],[是否主物料],[厂家代码], [生产厂家],[操作指导] )" + + // "VALUES(@订单号,@主配厂家,@工位号,@工位名称,@物料号,@零件图号,@零件名称," + + // "@零件数量,@是否扫描,@扫描方式,@是否主物料,@厂家代码,@生产厂家,@操作指导)"; + // OleDbParameter[] thisParms = new OleDbParameter[14]; + // thisParms[0] = new OleDbParameter("@订单号", OleDbType.VarChar, 50, "订单号"); + // thisParms[1] = new OleDbParameter("@主配厂家", OleDbType.VarChar, 50, "主配厂家"); + // thisParms[2] = new OleDbParameter("@工位号", OleDbType.VarChar, 50, "工位号"); + // thisParms[3] = new OleDbParameter("@工位名称", OleDbType.VarChar, 255, "工位名称"); + // thisParms[4] = new OleDbParameter("@物料号", OleDbType.VarChar, 50, "物料号"); + // thisParms[5] = new OleDbParameter("@零件图号", OleDbType.VarChar, 50, "零件图号"); + // thisParms[6] = new OleDbParameter("@零件名称", OleDbType.VarChar, 255, "零件名称"); + // thisParms[7] = new OleDbParameter("@零件数量", OleDbType.Integer, 4, "零件数量"); + // thisParms[8] = new OleDbParameter("@是否扫描", OleDbType.Integer, 4, "是否扫描"); + // thisParms[9] = new OleDbParameter("@扫描方式", OleDbType.Integer, 4, "扫描方式"); + // thisParms[10] = new OleDbParameter("@是否主物料", OleDbType.Integer, 4, "是否主物料"); + // thisParms[11] = new OleDbParameter("@厂家代码", OleDbType.VarChar, 255, "厂家代码"); + // thisParms[12] = new OleDbParameter("@生产厂家", OleDbType.VarChar, 255, "生产厂家"); + // thisParms[13] = new OleDbParameter("@操作指导", OleDbType.VarChar, 255, "操作指导"); + + // return DataAccess.ExecuteDataTable_OleDb_Insert_Access(sql, dt, ref thisParms); + + //} + /// + /// 下达装配BOM的发动机号到工位Access文件 INSERT INTO [MES_计划BOM_发动机号] + /// + /// + //static public bool GetOrderPlanEngineNumberToPcStation(DataTable dt) + //{ + // string sql; + // sql = + // "INSERT INTO [MES_计划BOM_发动机号]" + + // "([发动机号], [订单号], [SAP物料号], [发动机型号], [发动机型号代码], [发动机机型]," + + // "[发动机数量], [厂牌编号起始号], [客户名称], [投料日期], [文件编号], [集团名称], [通知号], " + + // "[功率], [指南文件编号], [装机状态], [适用状态], [物料描述],[计划下达日期])" + + // "VALUES(@发动机号,@订单号,@SAP物料号,@发动机型号,@发动机型号代码,@发动机机型," + + // "@发动机数量,@厂牌编号起始号,@客户名称,@投料日期,@文件编号,@集团名称,@通知号," + + // "@功率,@指南文件编号,@装机状态,@适用状态,@物料描述,@计划下达日期)"; + // OleDbParameter[] thisParms = new OleDbParameter[19]; + // thisParms[0] = new OleDbParameter("@发动机号", OleDbType.VarChar, 50, "发动机号"); + // thisParms[1] = new OleDbParameter("@订单号", OleDbType.VarChar, 50, "订单号"); + // thisParms[2] = new OleDbParameter("@SAP物料号", OleDbType.VarChar, 50, "SAP物料号"); + // thisParms[3] = new OleDbParameter("@发动机型号", OleDbType.VarChar, 50, "发动机型号"); + // thisParms[4] = new OleDbParameter("@发动机型号代码", OleDbType.Integer, 4, "发动机型号代码"); + // thisParms[5] = new OleDbParameter("@发动机机型", OleDbType.VarChar, 50, "发动机机型"); + + // thisParms[6] = new OleDbParameter("@发动机数量", OleDbType.Integer, 4, "发动机数量"); + // thisParms[7] = new OleDbParameter("@厂牌编号起始号", OleDbType.VarChar, 50, "厂牌编号起始号"); + // thisParms[8] = new OleDbParameter("@客户名称", OleDbType.VarChar, 255, "客户名称"); + // thisParms[9] = new OleDbParameter("@投料日期", OleDbType.DBDate, 8, "投料日期"); + // thisParms[10] = new OleDbParameter("@文件编号", OleDbType.VarChar, 50, "文件编号"); + // thisParms[11] = new OleDbParameter("@集团名称", OleDbType.VarChar, 255, "集团名称"); + // thisParms[12] = new OleDbParameter("@通知号", OleDbType.VarChar, 50, "通知号"); + + // thisParms[13] = new OleDbParameter("@功率", OleDbType.VarChar, 50, "功率"); + // thisParms[14] = new OleDbParameter("@指南文件编号", OleDbType.VarChar, 50, "指南文件编号"); + // thisParms[15] = new OleDbParameter("@装机状态", OleDbType.VarChar, 50, "装机状态"); + // thisParms[16] = new OleDbParameter("@适用状态", OleDbType.VarChar, 50, "适用状态"); + // thisParms[17] = new OleDbParameter("@物料描述", OleDbType.VarChar, 255, "物料描述"); + // thisParms[18] = new OleDbParameter("@计划下达日期", OleDbType.DBDate, 8, "计划下达日期"); + + // return DataAccess.ExecuteDataTable_OleDb_Insert_Access(sql, dt, ref thisParms); + + //} + /// + /// 下达装配BOM的发动机号到工位Access文件 INSERT INTO [MES_计划BOM_订单计划下达_执行顺序] + /// + /// + //static public bool GetOrderPlanEngineNumberToPcStation_OrderForm(DataTable dt) + //{ + // string sql; + // sql = + // "INSERT INTO [MES_计划BOM_订单计划下达_执行顺序]" + + // "([订单号],[执行顺序],[SAP物料号], [发动机型号], [发动机型号代码], [发动机机型]," + + // "[发动机数量], [厂牌编号起始号], [客户名称], [投料日期], [文件编号], [集团名称], [通知号], " + + // "[功率], [指南文件编号], [装机状态], [适用状态], [物料描述],[计划下达日期])" + + // "VALUES(@订单号,@执行顺序,@SAP物料号,@发动机型号,@发动机型号代码,@发动机机型," + + // "@发动机数量,@厂牌编号起始号,@客户名称,@投料日期,@文件编号,@集团名称,@通知号," + + // "@功率,@指南文件编号,@装机状态,@适用状态,@物料描述,@计划下达日期)"; + // OleDbParameter[] thisParms = new OleDbParameter[19]; + // thisParms[0] = new OleDbParameter("@订单号", OleDbType.VarChar, 50, "订单号"); + // thisParms[1] = new OleDbParameter("@执行顺序", OleDbType.Integer, 4, "执行顺序"); + // thisParms[2] = new OleDbParameter("@SAP物料号", OleDbType.VarChar, 50, "SAP物料号"); + // thisParms[3] = new OleDbParameter("@发动机型号", OleDbType.VarChar, 50, "发动机型号"); + // thisParms[4] = new OleDbParameter("@发动机型号代码", OleDbType.Integer, 4, "发动机型号代码"); + // thisParms[5] = new OleDbParameter("@发动机机型", OleDbType.VarChar, 50, "发动机机型"); + + // thisParms[6] = new OleDbParameter("@发动机数量", OleDbType.Integer, 4, "发动机数量"); + // thisParms[7] = new OleDbParameter("@厂牌编号起始号", OleDbType.VarChar, 50, "厂牌编号起始号"); + // thisParms[8] = new OleDbParameter("@客户名称", OleDbType.VarChar, 255, "客户名称"); + // thisParms[9] = new OleDbParameter("@投料日期", OleDbType.DBDate, 8, "投料日期"); + // thisParms[10] = new OleDbParameter("@文件编号", OleDbType.VarChar, 50, "文件编号"); + // thisParms[11] = new OleDbParameter("@集团名称", OleDbType.VarChar, 255, "集团名称"); + // thisParms[12] = new OleDbParameter("@通知号", OleDbType.VarChar, 50, "通知号"); + + // thisParms[13] = new OleDbParameter("@功率", OleDbType.VarChar, 50, "功率"); + // thisParms[14] = new OleDbParameter("@指南文件编号", OleDbType.VarChar, 50, "指南文件编号"); + // thisParms[15] = new OleDbParameter("@装机状态", OleDbType.VarChar, 50, "装机状态"); + // thisParms[16] = new OleDbParameter("@适用状态", OleDbType.VarChar, 50, "适用状态"); + // thisParms[17] = new OleDbParameter("@物料描述", OleDbType.VarChar, 255, "物料描述"); + // thisParms[18] = new OleDbParameter("@计划下达日期", OleDbType.DBDate, 8, "计划下达日期"); + + // return DataAccess.ExecuteDataTable_OleDb_Insert_Access(sql, dt, ref thisParms); + + //} + /// + /// 根据订单号,工位号获得[MES_计划BOM_发动机装配指南] + /// + /// 订单号 + /// 工位号 + /// MES_计划BOM_发动机装配指南 + /// + static public bool GetOperationGuid(string orderForm,string opName,out DataTable dt) + { + string sql; + sql = "exec MES_计划BOM_发动机装配指南_查询_下达到工位 '" + orderForm + "','" + opName + "'"; + return DataAccess.ExecuteDataTable(sql, out dt); + } + /// + /// 根据订单号 [MES_计划BOM_订单计划下达_执行顺序] + /// + /// 订单号 + /// [MES_计划BOM_订单计划下达_执行顺序] + static public bool GetOrderPlanEngineNumber_OrderForm(string orderForm, out DataTable dt) + { + string sql; + sql = "exec MES_计划BOM_发动机订单计划_查询_下达到工位 '" + orderForm + "'"; + return DataAccess.ExecuteDataTable(sql, out dt); + + } + /// + /// 根据订单号 [MES_计划BOM_发动机号] + /// + /// 订单号 + /// [MES_计划BOM_发动机号] + static public bool GetOrderPlanEngineNumberToPcStation(string orderForm, out DataTable dt) + { + string sql; + sql = "exec MES_计划BOM_发动机号_查询_下达到工位 '" + orderForm + "'"; + return DataAccess.ExecuteDataTable(sql, out dt); + } + } +} diff --git a/Common/07WebBusinessFacade/BusinessFacade/MES.Data.GetData/MES.Biz.TraceTable.GetData.cs b/Common/07WebBusinessFacade/BusinessFacade/MES.Data.GetData/MES.Biz.TraceTable.GetData.cs new file mode 100644 index 0000000..d5a4b1d --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/MES.Data.GetData/MES.Biz.TraceTable.GetData.cs @@ -0,0 +1,86 @@ +using System; +using System.IO; +using System.Collections.Generic; +using System.Text; +using System.Data; +using System.Data.SqlClient; +using System.Data.OleDb; + +//using SystemFramework; +using DataLinkMesWork; +namespace bizFacade +{ + public partial class BaseDataSystemMES + { + + /// + /// 从数据库服务器获得[数据MES_装配数据_发动机号_追踪代码_下达工位]数据, + /// 保存到Access中,同时更新[是否同步]标志。 + /// + /// 线首工位 + /// 当前工位 + /// + //public static void GetTraceCodeDataTableFromSqlServer_OpName_InsertIntoAccess(string opNameTraceCode, string opName) + //{ + // DataTable dt; + // if (GetTraceCodeDataTableFromSqlServer_OpName(opNameTraceCode, opName, out dt)) + // { + // if (dt != null) + // { + // if (dt.Rows.Count > 0) + // { + // if (TableTraceInsert_Access(dt)) + // { + // GetTraceCodeDataTableFromSqlServer_OpName_Update(opNameTraceCode, opName); + // } + // } + // } + // } + //} + /// + /// 上线工位的[MES_装配数据_发动机号_追踪代码]数据 + /// 从数据库服务器 + /// + /// + private DataTable GetTraceCodeDataTableFromSqlServer(string opName) + { + DataTable dt; + string sql; + sql = "select 订单号,订单计划发动机号,发动机号,追踪代码,主物料号,工位号,操作者工号,班次代码,SAP物料号,发动机型号,发动机型号代码,发动机机型" + + " from MES_装配数据_发动机号_追踪代码 where IsOK=0 and 工位号='" + opName + "'"; + DataAccess.ExecuteDataTable(sql, out dt); + return dt; + } + + /// + /// 从数据库服务器获得[数据MES_装配数据_发动机号_追踪代码_下达工位]数据 + /// + /// 线首工位 + /// 当前工位 + /// + /// + private static bool GetTraceCodeDataTableFromSqlServer_OpName(string opNameTraceCode, string opName, out DataTable dt) + { + string sql; + sql = "select 订单号,订单计划发动机号,发动机号,追踪代码,主物料号,工位号,操作者工号,班次代码,SAP物料号,发动机型号,发动机型号代码,发动机机型" + + " from MES_装配数据_发动机号_追踪代码_下达工位 where 是否同步=0 " + " and 下达工位='" + opName + "'"; + return DataAccess.ExecuteDataTable(sql, out dt); + } + + + /// + /// 从数据库服务器获得[数据MES_装配数据_发动机号_追踪代码_下达工位]数据 + /// update 数据MES_装配数据_发动机号_追踪代码_下达工位 set 是否同步=1 + /// + /// 线首工位 + /// 当前工位 + /// + private static bool GetTraceCodeDataTableFromSqlServer_OpName_Update(string opNameTraceCode, string opName) + { + string sql; + sql = "update MES_装配数据_发动机号_追踪代码_下达工位 set 是否同步=1 where 是否同步=0 and 工位号='" + opNameTraceCode + "' and 下达工位='" + opName + "'"; + return DataAccess.ExecuteSQL(sql); + } + + } +} diff --git a/Common/07WebBusinessFacade/BusinessFacade/MES.Data.GetData/OpNameGuid.cs b/Common/07WebBusinessFacade/BusinessFacade/MES.Data.GetData/OpNameGuid.cs new file mode 100644 index 0000000..a0b1324 --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/MES.Data.GetData/OpNameGuid.cs @@ -0,0 +1,124 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Data; +using System.Data.SqlClient; + +using System.Data.OleDb; +using DataLinkMesWork; +//using SystemFramework; + +namespace bizFacade +{ + /// + /// MES_计划BOM_工位操作指南 + /// + public partial class BaseDataSystemMES + { + /// + /// + /// + public static void TestConnection() + { + //SQLCommon.TestConnection(); + } + /// + /// 更新 "update [MES_计划BOM_工位操作指南] set 工位操作指导=?,工位指导图片=? where 发动机型号代码=? + /// + /// + //public static void OpNameGuidPic_Update(string opName) + //{ + // DataTable dt; + // OpNameGuidPic_Select(opName, out dt); + // OpNameGuidPic_Update(opName, dt); + //} + /// + /// 更新 MES_计划BOM_工位与名称 工位基本指导图片 + /// + /// + //public static void OpNameGuidBasicPic_Update(string opName) + //{ + // DataTable dt; + // OpNameGuidBasicPic_Select(opName, out dt); + // if (dt != null) + // { + // if (dt.Rows.Count > 0) + // { + // OpNameGuidBasicPic_Update(opName, dt); + // } + // } + //} + /// + /// select 工位基本指导图片 MES_计划BOM_工位与名称 + /// + /// + /// + public static void OpNameGuidBasicPic_Select(string opName, out DataTable dt) + { + string sql; + sql = "select 工位基本指导图片 from MES_计划BOM_工位与名称 where 工位号='" + opName + "'"; + //如果与SqlServer数据库通讯正常(同步通讯) + //if (SQLCommon.SqlServerConnectionStatus) + { + if (!DataAccess.ExecuteDataTable(sql, out dt)) + { + //DataAccess.ExecuteDataTable_OleDb_Access(sql, out dt); + + } + + } + ////如果与SqlServer数据库通讯不正常(异步通讯) + //else + //{ + // DataAccess.ExecuteDataTable_OleDb_Access(sql, out dt); + //} + } + + /// + /// update [MES_计划BOM_工位与名称] set 工位基本指导图片=@工位基本指导图片 where 工位号 + /// + /// + /// + //static public bool OpNameGuidBasicPic_Update(string opName, DataTable dt) + //{ + // string sql; + // sql = + // "update [MES_计划BOM_工位与名称] set 工位基本指导图片=? where 工位号='" + opName + "'"; + // OleDbParameter[] thisParms = new OleDbParameter[1]; + // //thisParms[0] = new OleDbParameter("@工位基本指导图片", dt.Rows[0]["工位基本指导图片"]); + // thisParms[0] = new OleDbParameter("@工位基本指导图片", OleDbType.Binary, 0, "工位基本指导图片"); + // return DataAccess.ExecuteDataTable_OleDb_Update(sql, dt, ref thisParms); + + //} + + /// + /// select 工位基本指导图片 MES_计划BOM_工位与名称 + /// + /// + /// + public static void OpNameGuidPic_Select(string opName, out DataTable dt) + { + string sql; + sql = "select 发动机型号代码,工位操作指导,工位指导图片 from [MES_计划BOM_工位操作指南] where 工位号='" + opName + "'"; + DataAccess.ExecuteDataTable(sql, out dt); + } + /// + /// update [MES_计划BOM_工位与名称] set 工位基本指导图片=@工位基本指导图片 where 工位号 + /// + /// + /// + //static public bool OpNameGuidPic_Update(string opName, DataTable dt) + //{ + // string sql; + // sql = "update [MES_计划BOM_工位操作指南] set 工位操作指导=?,工位指导图片=? where 发动机型号代码=? and 工位号='" + opName + "'"; + // OleDbParameter[] thisParms = new OleDbParameter[3]; + // //thisParms[0] = new OleDbParameter("@工位基本指导图片", dt.Rows[0]["工位基本指导图片"]); + // thisParms[0] = new OleDbParameter("@工位操作指导", OleDbType.VarChar, 255, "工位操作指导"); + // thisParms[1] = new OleDbParameter("@工位指导图片", OleDbType.Binary, 0, "工位指导图片"); + // thisParms[2] = new OleDbParameter("@发动机型号代码", OleDbType.Integer, 4, "发动机型号代码"); + + // return DataAccess.ExecuteDataTable_OleDb_Update(sql, dt, ref thisParms); + + //} + } +} diff --git a/Common/07WebBusinessFacade/BusinessFacade/MES.Data.GetData/vssver2.scc b/Common/07WebBusinessFacade/BusinessFacade/MES.Data.GetData/vssver2.scc new file mode 100644 index 0000000..6d844a5 Binary files /dev/null and b/Common/07WebBusinessFacade/BusinessFacade/MES.Data.GetData/vssver2.scc differ diff --git a/Common/07WebBusinessFacade/BusinessFacade/MES.Data.SaveData/MES.Biz.Material.SaveData.cs b/Common/07WebBusinessFacade/BusinessFacade/MES.Data.SaveData/MES.Biz.Material.SaveData.cs new file mode 100644 index 0000000..17abc84 --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/MES.Data.SaveData/MES.Biz.Material.SaveData.cs @@ -0,0 +1,338 @@ +using System; +using System.IO; +using System.Collections.Generic; +using System.Text; +using System.Data; +using System.Data.SqlClient; +using System.Data.OleDb; + +//using SystemFramework; +using DataLinkMesWork; +namespace bizFacade +{ + public partial class BaseDataSystemMES + { + /// + /// MES_装配数据_零部件追溯_数据主表 + /// + /// + static public void AssemblyPartIndexTableInsert(out long traceID) + { + traceID = 0; + try + { + string sql = GetSqlStringAssemblyPartIndexTable(); + //if (SQLCommon.SqlServerConnectionStatus) + { + DataAccess.ExecuteNonQuery_newID(sql, out traceID); + + } + //if (!SQLCommon.SqlServerConnectionStatus) + //{ + // DataAccess.ExecuteNonQuery_newID_OleDb(sql, out traceID); + //} + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, err.Message); + } + } + /// + /// MES_装配数据_零部件追溯_增加 + /// + /// + /// + public static void VerifyAssemblyPartTableInsert(DataTable dt) + { + + //if (SQLCommon.SqlServerConnectionStatus) + { + //如果与SQL Server 数据库通讯失败,ApplicationConfig.connectionStringPIS_NEW_Value = "0" + VerifyAssemblyPartTableInsert_SqlServer(dt); + } + //if (!SQLCommon.SqlServerConnectionStatus) + //{ + // VerifyAssemblyPartTableInsert_Access(dt); + //} + + } + /// + /// 同步通讯方式 + /// MES_装配数据_零部件追溯_增加 + /// SQL Server 数据库 + /// + /// + /// + public static bool VerifyAssemblyPartTableInsert_SqlServer(DataTable dt) + { + string sql; + sql = "INSERT INTO [MES_装配数据_零部件追溯]" + + "([追溯代码],[订单号],[SAP物料号],[发动机型号],[发动机型号代码], [发动机机型], " + + "[发动机数量], [厂牌编号起始号], [客户名称],[投料日期],[文件编号],[集团名称],[通知号]," + + "[功率],[指南文件编号],[装机状态],[适用状态],[物料描述],[计划下达日期],[计划完工日期]," + + "[主配厂家],[工位号], [工位名称],[物料号], [零件图号], [零件名称], [零件数量]," + + "[是否扫描],[扫描方式代码], [扫描方式], [是否主物料],[厂家代码],[生产厂家], " + + "[操作指导],[发动机号],[追踪代码],[主物料号],[物料号表索引号],[零件数量验证]," + + "[物料条码], [物料条码物料号], [物料条码批次],[验证结果], [操作者工号], [操作者姓名], [班次代码], " + + "物料来源代码,物料来源,是否禁用代码,是否禁用,被强制验证物料号," + + "更改代码,更改原因,零件类型,操作时间)" + + + "VALUES(@追溯代码,@订单号,@SAP物料号,@发动机型号,@发动机型号代码,@发动机机型," + + "@发动机数量,@厂牌编号起始号,@客户名称,@投料日期,@文件编号,@集团名称,@通知号," + + "@功率,@指南文件编号,@装机状态,@适用状态,@物料描述,@计划下达日期,@计划完工日期," + + "@主配厂家,@工位号,@工位名称,@物料号,@零件图号,@零件名称,@零件数量," + + " @是否扫描,@扫描方式代码,@扫描方式,@是否主物料,@厂家代码,@生产厂家," + + "@操作指导,@发动机号,@追踪代码,@主物料号,@物料号表索引号,@零件数量验证," + + "@物料条码,@物料条码物料号,@物料条码批次,@验证结果,@操作者工号,@操作者姓名,@班次代码," + + "@物料来源代码,@物料来源,@是否禁用代码,@是否禁用,@被强制验证物料号," + + "@更改代码,@更改原因,@零件类型,@操作时间)"; + + + + SqlParameter[] thisParmsSql = new SqlParameter[55]; + // + "([订单号],[SAP物料号],[发动机型号],[发动机型号代码], [发动机机型], " + thisParmsSql[0] = new SqlParameter("@追溯代码", SqlDbType.Int, 4, "追溯代码"); + thisParmsSql[1] = new SqlParameter("@订单号", SqlDbType.NVarChar, 50, "订单号"); + thisParmsSql[2] = new SqlParameter("@SAP物料号", SqlDbType.NVarChar, 50, "SAP物料号"); + thisParmsSql[3] = new SqlParameter("@发动机型号", SqlDbType.NVarChar, 50, "发动机型号"); + thisParmsSql[4] = new SqlParameter("@发动机型号代码", SqlDbType.Int, 4, "发动机型号代码"); + thisParmsSql[5] = new SqlParameter("@发动机机型", SqlDbType.NVarChar, 50, "发动机机型"); + + // + "@发动机数量,@厂牌编号起始号,@客户名称,@投料日期,@文件编号,@集团名称,@通知号," + thisParmsSql[6] = new SqlParameter("@发动机数量", SqlDbType.Int, 4, "发动机数量"); + thisParmsSql[7] = new SqlParameter("@厂牌编号起始号", SqlDbType.Int, 4, "厂牌编号起始号"); + thisParmsSql[8] = new SqlParameter("@客户名称", SqlDbType.NVarChar, 50, "客户名称"); + thisParmsSql[9] = new SqlParameter("@投料日期", SqlDbType.DateTime, 8, "投料日期"); + thisParmsSql[10] = new SqlParameter("@文件编号", SqlDbType.NVarChar, 50, "文件编号"); + thisParmsSql[11] = new SqlParameter("@集团名称", SqlDbType.NVarChar, 50, "集团名称"); + thisParmsSql[12] = new SqlParameter("@通知号", SqlDbType.NVarChar, 50, "通知号"); + + // + "@功率,@指南文件编号,@装机状态,@适用状态,@物料描述,@计划下达日期,@计划完工日期," + thisParmsSql[13] = new SqlParameter("@功率", SqlDbType.NVarChar, 50, "功率"); + thisParmsSql[14] = new SqlParameter("@指南文件编号", SqlDbType.NVarChar, 50, "指南文件编号"); + thisParmsSql[15] = new SqlParameter("@装机状态", SqlDbType.NVarChar, 50, "装机状态"); + thisParmsSql[16] = new SqlParameter("@适用状态", SqlDbType.DateTime, 8, "适用状态"); + thisParmsSql[17] = new SqlParameter("@物料描述", SqlDbType.NVarChar, 255, "物料描述"); + thisParmsSql[18] = new SqlParameter("@计划下达日期", SqlDbType.DateTime, 8, "计划下达日期"); + thisParmsSql[19] = new SqlParameter("@计划完工日期", SqlDbType.DateTime, 8, "计划完工日期"); + + // + "@主配厂家,@工位号,@工位名称,@物料号,@零件图号,@零件名称,@零件数量," + + thisParmsSql[20] = new SqlParameter("@主配厂家", SqlDbType.NVarChar, 50, "主配厂家"); + thisParmsSql[21] = new SqlParameter("@工位号", SqlDbType.NVarChar, 50, "工位号"); + thisParmsSql[22] = new SqlParameter("@工位名称", SqlDbType.NVarChar, 50, "工位名称"); + thisParmsSql[23] = new SqlParameter("@物料号", SqlDbType.NVarChar, 50, "物料号"); + thisParmsSql[24] = new SqlParameter("@零件图号", SqlDbType.NVarChar, 50, "零件图号"); + thisParmsSql[25] = new SqlParameter("@零件名称", SqlDbType.NVarChar, 50, "零件名称"); + thisParmsSql[26] = new SqlParameter("@零件数量", SqlDbType.Int, 4, "零件数量"); + + // +"[是否扫描],扫描方式代码, [扫描方式], [厂家代码],[生产厂家], " + + thisParmsSql[27] = new SqlParameter("@是否扫描", SqlDbType.Int, 4, "是否扫描"); + thisParmsSql[28] = new SqlParameter("@扫描方式代码", SqlDbType.Int, 4, "扫描方式代码"); + thisParmsSql[29] = new SqlParameter("@扫描方式", SqlDbType.NVarChar, 50, "扫描方式"); + thisParmsSql[30] = new SqlParameter("@是否主物料", SqlDbType.Int, 4, "是否主物料"); + thisParmsSql[31] = new SqlParameter("@厂家代码", SqlDbType.NVarChar, 50, "厂家代码"); + thisParmsSql[32] = new SqlParameter("@生产厂家", SqlDbType.NVarChar, 50, "生产厂家"); + + //+ "@操作指导,@发动机号,@物料号表索引号,@零件数量验证," + + thisParmsSql[33] = new SqlParameter("@操作指导", SqlDbType.NVarChar, 255, "操作指导"); + thisParmsSql[34] = new SqlParameter("@发动机号", SqlDbType.NVarChar, 50, "发动机号"); + thisParmsSql[35] = new SqlParameter("@追踪代码", SqlDbType.NVarChar, 50, "追踪代码"); + thisParmsSql[36] = new SqlParameter("@主物料号", SqlDbType.NVarChar, 50, "主物料号"); + thisParmsSql[37] = new SqlParameter("@物料号表索引号", SqlDbType.Int, 4, "物料号表索引号"); + thisParmsSql[38] = new SqlParameter("@零件数量验证", SqlDbType.Int, 4, "零件数量验证"); + + // +"[物料条码], [物料条码物料号], [物料条码批次],@验证结果, [操作者工号], [操作者姓名], [班次代码], " + thisParmsSql[39] = new SqlParameter("@物料条码", SqlDbType.NVarChar, 50, "物料条码"); + thisParmsSql[40] = new SqlParameter("@物料条码物料号", SqlDbType.NVarChar, 50, "物料条码物料号"); + thisParmsSql[41] = new SqlParameter("@物料条码批次", SqlDbType.NVarChar, 50, "物料条码批次"); + thisParmsSql[42] = new SqlParameter("@验证结果", SqlDbType.Int, 4, "验证结果"); + thisParmsSql[43] = new SqlParameter("@操作者工号", SqlDbType.NVarChar, 50, "操作者工号"); + thisParmsSql[44] = new SqlParameter("@操作者姓名", SqlDbType.NVarChar, 50, "操作者姓名"); + thisParmsSql[45] = new SqlParameter("@班次代码", SqlDbType.NVarChar, 50, "班次代码"); + + // +"物料来源代码,物料来源,是否禁用代码,是否禁用,被强制验证物料号,更改代码,更改原因)" + + thisParmsSql[46] = new SqlParameter("@物料来源代码", SqlDbType.Int, 4, "物料来源代码"); + thisParmsSql[47] = new SqlParameter("@物料来源", SqlDbType.NVarChar, 50, "物料来源"); + thisParmsSql[48] = new SqlParameter("@是否禁用代码", SqlDbType.Int, 4, "是否禁用代码"); + thisParmsSql[49] = new SqlParameter("@是否禁用", SqlDbType.NVarChar, 50, "是否禁用"); + thisParmsSql[50] = new SqlParameter("@被强制验证物料号", SqlDbType.NVarChar, 50, "被强制验证物料号"); + thisParmsSql[51] = new SqlParameter("@更改代码", SqlDbType.NVarChar, 50, "更改代码"); + thisParmsSql[52] = new SqlParameter("@更改原因", SqlDbType.NVarChar, 255, "更改原因"); + thisParmsSql[53] = new SqlParameter("@零件类型", SqlDbType.Int, 4, "零件类型"); + thisParmsSql[54] = new SqlParameter("@操作时间", SqlDbType.DateTime, 8, "操作时间"); + if (dt == null) return false; + //如果与SQL Server 数据库通讯失败,ApplicationConfig.connectionStringPIS_NEW_Value = "0" + + return DataAccess.ExecuteSQL(sql, ref thisParmsSql, dt); + + + + } + /// + /// 异步通讯方式 + /// 增加数据到Access数据库 + /// MES_装配数据_零部件追溯 + /// INSERT INTO [MES_装配数据_零部件追溯] + /// + /// + /// + //public static bool VerifyAssemblyPartTableInsert_Access(DataTable dt) + //{ + // string sql; + // sql = "INSERT INTO [MES_装配数据_零部件追溯]" + // + "([追溯代码],[订单号],[SAP物料号],[发动机型号],[发动机型号代码], [发动机机型], " + // + "[发动机数量], [厂牌编号起始号], [客户名称],[投料日期],[文件编号],[集团名称],[通知号]," + // + "[功率],[指南文件编号],[装机状态],[适用状态],[物料描述],[计划下达日期],[计划完工日期]," + // + "[主配厂家],[工位号], [工位名称],[物料号], [零件图号], [零件名称], [零件数量]," + // + "[是否扫描],[扫描方式代码], [扫描方式], [是否主物料],[厂家代码],[生产厂家], " + // + "[操作指导],[发动机号],[追踪代码],[主物料号],[物料号表索引号],[零件数量验证]," + // + "[物料条码], [物料条码物料号], [物料条码批次],[验证结果], [操作者工号], [操作者姓名], [班次代码], " + // + "物料来源代码,物料来源,是否禁用代码,是否禁用,被强制验证物料号,更改代码,更改原因,零件类型,操作时间)" + + // + "VALUES(@追溯代码,@订单号,@SAP物料号,@发动机型号,@发动机型号代码,@发动机机型," + // + "@发动机数量,@厂牌编号起始号,@客户名称,@投料日期,@文件编号,@集团名称,@通知号," + // + "@功率,@指南文件编号,@装机状态,@适用状态,@物料描述,@计划下达日期,@计划完工日期," + // + "@主配厂家,@工位号,@工位名称,@物料号,@零件图号,@零件名称,@零件数量," + // + " @是否扫描,@扫描方式代码,@扫描方式,@是否主物料,@厂家代码,@生产厂家," + // + "@操作指导,@发动机号,@追踪代码,@主物料号,@物料号表索引号,@零件数量验证," + // + "@物料条码,@物料条码物料号,@物料条码批次,@验证结果,@操作者工号,@操作者姓名,@班次代码," + // + "@物料来源代码,@物料来源,@是否禁用代码,@是否禁用,@被强制验证物料号," + // + "@更改代码,@更改原因,@零件类型,@操作时间)"; + + + // OleDbParameter[] thisParms1 = new OleDbParameter[55]; + // // + "([追溯代码],[订单号],[SAP物料号],[发动机型号],[发动机型号代码], [发动机机型], " + // thisParms1[0] = new OleDbParameter("@追溯代码", OleDbType.Integer, 4, "追溯代码"); + // thisParms1[1] = new OleDbParameter("@订单号", OleDbType.VarChar, 50, "订单号"); + // thisParms1[2] = new OleDbParameter("@SAP物料号", OleDbType.VarChar, 50, "SAP物料号"); + // thisParms1[3] = new OleDbParameter("@发动机型号", OleDbType.VarChar, 50, "发动机型号"); + // thisParms1[4] = new OleDbParameter("@发动机型号代码", OleDbType.Integer, 4, "发动机型号代码"); + // thisParms1[5] = new OleDbParameter("@发动机机型", OleDbType.VarChar, 50, "发动机机型"); + + // // + "@发动机数量,@厂牌编号起始号,@客户名称,@投料日期,@文件编号,@集团名称,@通知号," + // thisParms1[6] = new OleDbParameter("@发动机数量", OleDbType.Integer, 4, "发动机数量"); + // thisParms1[7] = new OleDbParameter("@厂牌编号起始号", OleDbType.Integer, 4, "厂牌编号起始号"); + // thisParms1[8] = new OleDbParameter("@客户名称", OleDbType.VarChar, 50, "客户名称"); + // thisParms1[9] = new OleDbParameter("@投料日期", OleDbType.DBDate, 8, "投料日期"); + // thisParms1[10] = new OleDbParameter("@文件编号", OleDbType.VarChar, 50, "文件编号"); + // thisParms1[11] = new OleDbParameter("@集团名称", OleDbType.VarChar, 50, "集团名称"); + // thisParms1[12] = new OleDbParameter("@通知号", OleDbType.VarChar, 50, "通知号"); + + // // + "@功率,@指南文件编号,@装机状态,@适用状态,@物料描述,@计划下达日期,@计划完工日期," + // thisParms1[13] = new OleDbParameter("@功率", OleDbType.VarChar, 50, "功率"); + // thisParms1[14] = new OleDbParameter("@指南文件编号", OleDbType.VarChar, 50, "指南文件编号"); + // thisParms1[15] = new OleDbParameter("@装机状态", OleDbType.VarChar, 50, "装机状态"); + // thisParms1[16] = new OleDbParameter("@适用状态", OleDbType.DBDate, 8, "适用状态"); + // thisParms1[17] = new OleDbParameter("@物料描述", OleDbType.VarChar, 255, "物料描述"); + // thisParms1[18] = new OleDbParameter("@计划下达日期", OleDbType.DBDate, 8, "计划下达日期"); + // thisParms1[19] = new OleDbParameter("@计划完工日期", OleDbType.DBDate, 8, "计划完工日期"); + + // // + "@主配厂家,@工位号,@工位名称,@物料号,@零件图号,@零件名称,@零件数量," + + // thisParms1[20] = new OleDbParameter("@主配厂家", OleDbType.VarChar, 50, "主配厂家"); + // thisParms1[21] = new OleDbParameter("@工位号", OleDbType.VarChar, 50, "工位号"); + // thisParms1[22] = new OleDbParameter("@工位名称", OleDbType.VarChar, 50, "工位名称"); + // thisParms1[23] = new OleDbParameter("@物料号", OleDbType.VarChar, 50, "物料号"); + // thisParms1[24] = new OleDbParameter("@零件图号", OleDbType.VarChar, 50, "零件图号"); + // thisParms1[25] = new OleDbParameter("@零件名称", OleDbType.VarChar, 50, "零件名称"); + // thisParms1[26] = new OleDbParameter("@零件数量", OleDbType.Integer, 4, "零件数量"); + + // // +"[是否扫描],扫描方式代码, [扫描方式], [厂家代码],[生产厂家], " + + // thisParms1[27] = new OleDbParameter("@是否扫描", OleDbType.Integer, 4, "是否扫描"); + // thisParms1[28] = new OleDbParameter("@扫描方式代码", OleDbType.Integer, 4, "扫描方式代码"); + // thisParms1[29] = new OleDbParameter("@扫描方式", OleDbType.VarChar, 50, "扫描方式"); + // thisParms1[30] = new OleDbParameter("@是否主物料", OleDbType.Integer, 4, "是否主物料"); + // thisParms1[31] = new OleDbParameter("@厂家代码", OleDbType.VarChar, 50, "厂家代码"); + // thisParms1[32] = new OleDbParameter("@生产厂家", OleDbType.VarChar, 50, "生产厂家"); + + // //+ "@操作指导,@发动机号,@物料号表索引号,@零件数量验证," + + // thisParms1[33] = new OleDbParameter("@操作指导", OleDbType.VarChar, 255, "操作指导"); + // thisParms1[34] = new OleDbParameter("@发动机号", OleDbType.VarChar, 50, "发动机号"); + // thisParms1[35] = new OleDbParameter("@追踪代码", OleDbType.VarChar, 50, "追踪代码"); + // thisParms1[36] = new OleDbParameter("@主物料号", OleDbType.VarChar, 50, "主物料号"); + // thisParms1[37] = new OleDbParameter("@物料号表索引号", OleDbType.Integer, 4, "物料号表索引号"); + // thisParms1[38] = new OleDbParameter("@零件数量验证", OleDbType.Integer, 4, "零件数量验证"); + + // // +"[物料条码], [物料条码物料号], [物料条码批次],@验证结果, [操作者工号], [操作者姓名], [班次代码], " + // thisParms1[39] = new OleDbParameter("@物料条码", OleDbType.VarChar, 50, "物料条码"); + // thisParms1[40] = new OleDbParameter("@物料条码物料号", OleDbType.VarChar, 50, "物料条码物料号"); + // thisParms1[41] = new OleDbParameter("@物料条码批次", OleDbType.VarChar, 50, "物料条码批次"); + // thisParms1[42] = new OleDbParameter("@验证结果", OleDbType.Integer, 4, "验证结果"); + // thisParms1[43] = new OleDbParameter("@操作者工号", OleDbType.VarChar, 50, "操作者工号"); + // thisParms1[44] = new OleDbParameter("@操作者姓名", OleDbType.VarChar, 50, "操作者姓名"); + // thisParms1[45] = new OleDbParameter("@班次代码", OleDbType.VarChar, 50, "班次代码"); + + // // +"物料来源代码,物料来源,是否禁用代码,是否禁用,被强制验证物料号,更改代码,更改原因)" + + // thisParms1[46] = new OleDbParameter("@物料来源代码", OleDbType.Integer, 4, "物料来源代码"); + // thisParms1[47] = new OleDbParameter("@物料来源", OleDbType.VarChar, 50, "物料来源"); + // thisParms1[48] = new OleDbParameter("@是否禁用代码", OleDbType.Integer, 4, "是否禁用代码"); + // thisParms1[49] = new OleDbParameter("@是否禁用", OleDbType.VarChar, 50, "是否禁用"); + // thisParms1[50] = new OleDbParameter("@被强制验证物料号", OleDbType.VarChar, 50, "被强制验证物料号"); + // thisParms1[51] = new OleDbParameter("@更改代码", OleDbType.VarChar, 50, "更改代码"); + // thisParms1[52] = new OleDbParameter("@更改原因", OleDbType.VarChar, 255, "更改原因"); + // thisParms1[53] = new OleDbParameter("@零件类型", OleDbType.Integer, 4, "零件类型"); + // thisParms1[54] = new OleDbParameter("@操作时间", OleDbType.DBTimeStamp, 8, "操作时间"); + + // return DataAccess.ExecuteDataTable_OleDb_Insert_Access(sql, dt, ref thisParms1); + //} + /// + /// 获得增加表[MES_装配数据_零部件追溯_数据主表]的SQL语句 + /// + private static string GetSqlStringAssemblyPartIndexTable() + { + string sql = null; + sql = "INSERT INTO [MES_装配数据_零部件追溯_数据主表] " + + "(订单号,订单计划发动机号,发动机号,追踪代码,主物料号,工位号,到达时间,离开时间,操作者工号,班次代码," + + "[SAP物料号],[发动机型号],[发动机型号代码], [发动机机型], " + + "[发动机数量], [厂牌编号起始号], [客户名称],[投料日期],[文件编号],[集团名称],[通知号]," + + "[功率],[指南文件编号],[装机状态],[适用状态],[物料描述],[计划下达日期],[计划完工日期],[主配厂家],[零件类型],[是否禁用],[返修标志])" + + " VALUES (" + //订单号,发动机号,追踪代码,工位号,到达时间,离开时间,操作者工号,班次代码 + + "'" + MaterialData.orderForm + "'," + + "'" + MaterialData.engineNumber_OrderPlan + "'," + + "'" + MaterialData.engineNumber + "'," + + "'" + MaterialData.engineTraceCode + "'," + + "'" + MaterialData.mainMaterialNumber + "'," + + "'" + MaterialData.opName + "'," + + "'" + MaterialData.arrivedTime.ToString("G") + "'," + + "'" + MaterialData.leavedTime.ToString("G") + "'," + + "'" + MaterialData.operatorCode + "'," + + "'" + MaterialData.operatorShift + "'," + //+ "[SAP物料号],[发动机型号],[发动机型号代码], [发动机机型], " + + + "'" + MaterialData.sAPMaterialNumber + "'," + + "'" + MaterialData.engineNumberType + "'," + + "" + MaterialData.engineNumberCode + ","//int + + "'" + MaterialData.engineNumberBasicType + "'," + //+ "[发动机数量], [厂牌编号起始号], [客户名称],[投料日期],[文件编号],[集团名称],[通知号]," + + + "" + MaterialData.engineCount + ","//int + + "'" + MaterialData.engineNumberFirstID + "',"//int + + "'" + MaterialData.customesName + "'," + + "'" + MaterialData.prepareMaterialDateTime.ToString("G") + "'," + + "'" + MaterialData.fileCode + "'," + + "'" + MaterialData.groupName + "'," + + "'" + MaterialData.notifyCode + "'," + //+ "[功率],[指南文件编号],[装机状态],[适用状态],[物料描述],[计划下达日期],[计划完工日期],主配厂家,零件类型,是否禁用,返修标志" + + "'" + MaterialData.n_Force + "'," + + "'" + MaterialData.directFileCode + "'," + + "'" + MaterialData.workEngineStatus + "'," + + "'" + MaterialData.adaptDateTime.ToString("G") + "'," + + "'" + MaterialData.materialDescript + "'," + + "'" + MaterialData.planSendedDateTime.ToString("G") + "'," + + "'" + MaterialData.planFinishDateTime.ToString("G") + "'," + + "'" + MaterialData.mainPruduceFatory + "'," + + "" + MaterialData.partType.ToString() + "," + + "" + MaterialData.isMainMaterial.ToString() + "," + + "" + MaterialData.isRepairID.ToString() + ") "; + return sql; + } + } +} diff --git a/Common/07WebBusinessFacade/BusinessFacade/MES.Data.SaveData/MES.Biz.TraceTable.SaveData.cs b/Common/07WebBusinessFacade/BusinessFacade/MES.Data.SaveData/MES.Biz.TraceTable.SaveData.cs new file mode 100644 index 0000000..e64eafd --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/MES.Data.SaveData/MES.Biz.TraceTable.SaveData.cs @@ -0,0 +1,222 @@ +using System; +using System.IO; +using System.Collections.Generic; +using System.Text; +using System.Data; +using System.Data.SqlClient; +using System.Data.OleDb; + +//using SystemFramework; +using DataLinkMesWork; +namespace bizFacade +{ + public partial class BaseDataSystemMES + { + /// + /// 保存[MES_装配数据_发动机号_追踪代码] + /// 与SqlServer连接正常,保存到SqlServer数据库中; + /// 与SqlServer连接不正常,保存到SqlServer数据库中; + /// + public static void TableTraceInsert_SaveData() + { + DataTable dt; + dt = TraceCodeDataTableUpdate_Access(); + //if (!SQLCommon.SqlServerConnectionStatus) + //{ + // TableTraceInsert_Access(dt); + //} + //else + { + TableTraceInsert_SqlServer(dt); + } + } + + + /// + /// [MES_装配数据_发动机号_追踪代码]数据保存到本地PC的Access数据库中 + /// + //private static bool TableTraceInsert_Access(DataTable dt) + //{ + // string sql = null; + // sql = + // "INSERT INTO [MES_装配数据_发动机号_追踪代码] " + + // "(订单号,订单计划发动机号,发动机号,追踪代码,主物料号,工位号,操作者工号,班次代码," + + // "[SAP物料号],[发动机型号],[发动机型号代码], [发动机机型])" + + // "VALUES(@订单号,@订单计划发动机号,@发动机号,@追踪代码,@主物料号,@工位号,@操作者工号,@班次代码," + + // "@SAP物料号,@发动机型号,@发动机型号代码,@发动机机型)"; + // OleDbParameter[] thisParms = new OleDbParameter[12]; + // thisParms[0] = new OleDbParameter("@订单号", OleDbType.VarChar, 50, "订单号"); + // thisParms[1] = new OleDbParameter("@订单计划发动机号", OleDbType.VarChar, 50, "订单计划发动机号"); + // thisParms[2] = new OleDbParameter("@发动机号", OleDbType.VarChar, 50, "发动机号"); + // thisParms[3] = new OleDbParameter("@追踪代码", OleDbType.VarChar, 50, "追踪代码"); + // thisParms[4] = new OleDbParameter("@主物料号", OleDbType.VarChar, 50, "主物料号"); + // thisParms[5] = new OleDbParameter("@工位号", OleDbType.VarChar, 50, "工位号"); + // thisParms[6] = new OleDbParameter("@操作者工号", OleDbType.VarChar, 50, "操作者工号"); + // thisParms[7] = new OleDbParameter("@班次代码", OleDbType.VarChar, 50, "班次代码"); + // thisParms[8] = new OleDbParameter("@SAP物料号", OleDbType.VarChar, 50, "SAP物料号"); + // thisParms[9] = new OleDbParameter("@发动机型号", OleDbType.VarChar, 50, "发动机型号"); + // thisParms[10] = new OleDbParameter("@发动机型号代码", OleDbType.Integer, 4, "发动机型号代码"); + // thisParms[11] = new OleDbParameter("@发动机机型", OleDbType.VarChar, 50, "发动机机型"); + // return DataAccess.ExecuteDataTable_OleDb_Insert_Access(sql, dt, ref thisParms); + //} + /// + /// [MES_装配数据_发动机号_追踪代码]保存到SqlServer数据库服务器 + /// + /// + /// + private static bool TableTraceInsert_SqlServer(DataTable dt) + { + string sql = null; + sql = + "INSERT INTO [MES_装配数据_发动机号_追踪代码] " + + "(订单号,订单计划发动机号,发动机号,追踪代码,主物料号,工位号,操作者工号,班次代码," + + "[SAP物料号],[发动机型号],[发动机型号代码], [发动机机型])" + + "VALUES(@订单号,@订单计划发动机号,@发动机号,@追踪代码,@主物料号,@工位号,@操作者工号,@班次代码," + + "@SAP物料号,@发动机型号,@发动机型号代码,@发动机机型)"; + SqlParameter[] thisParms = new SqlParameter[12]; + thisParms[0] = new SqlParameter("@订单号", SqlDbType.NVarChar, 50, "订单号"); + thisParms[1] = new SqlParameter("@订单计划发动机号", SqlDbType.NVarChar, 50, "订单计划发动机号"); + thisParms[2] = new SqlParameter("@发动机号", SqlDbType.NVarChar, 50, "发动机号"); + thisParms[3] = new SqlParameter("@追踪代码", SqlDbType.NVarChar, 50, "追踪代码"); + thisParms[4] = new SqlParameter("@主物料号", SqlDbType.NVarChar, 50, "主物料号"); + thisParms[5] = new SqlParameter("@工位号", SqlDbType.NVarChar, 50, "工位号"); + thisParms[6] = new SqlParameter("@操作者工号", SqlDbType.NVarChar, 50, "操作者工号"); + thisParms[7] = new SqlParameter("@班次代码", SqlDbType.NVarChar, 50, "班次代码"); + thisParms[8] = new SqlParameter("@SAP物料号", SqlDbType.NVarChar, 50, "SAP物料号"); + thisParms[9] = new SqlParameter("@发动机型号", SqlDbType.NVarChar, 50, "发动机型号"); + thisParms[10] = new SqlParameter("@发动机型号代码", SqlDbType.Int, 4, "发动机型号代码"); + thisParms[11] = new SqlParameter("@发动机机型", SqlDbType.NVarChar, 50, "发动机机型"); + return DataAccess.ExecuteSQL(sql, ref thisParms, dt); + //OleDbParameter[] thisParms = new OleDbParameter[12]; + //thisParms[0] = new OleDbParameter("@订单号", OleDbType.VarChar, 50, "订单号"); + //thisParms[1] = new OleDbParameter("@订单计划发动机号", OleDbType.VarChar, 50, "订单计划发动机号"); + //thisParms[2] = new OleDbParameter("@发动机号", OleDbType.VarChar, 50, "发动机号"); + //thisParms[3] = new OleDbParameter("@追踪代码", OleDbType.VarChar, 50, "追踪代码"); + //thisParms[4] = new OleDbParameter("@主物料号", OleDbType.VarChar, 50, "主物料号"); + //thisParms[5] = new OleDbParameter("@工位号", OleDbType.VarChar, 50, "工位号"); + //thisParms[6] = new OleDbParameter("@操作者工号", OleDbType.VarChar, 50, "操作者工号"); + //thisParms[7] = new OleDbParameter("@班次代码", OleDbType.VarChar, 50, "班次代码"); + //thisParms[8] = new OleDbParameter("@SAP物料号", OleDbType.VarChar, 50, "SAP物料号"); + //thisParms[9] = new OleDbParameter("@发动机型号", OleDbType.VarChar, 50, "发动机型号"); + //thisParms[10] = new OleDbParameter("@发动机型号代码", OleDbType.Integer, 4, "发动机型号代码"); + //thisParms[11] = new OleDbParameter("@发动机机型", OleDbType.VarChar, 50, "发动机机型"); + //return DataAccess.ExecuteDataTable_OleDb_Insert_SqlServer(sql, dt, ref thisParms); + } + /// + /// 创建临时表[MES_装配数据_发动机号_追踪代码] + /// + /// + private static DataTable CreateEngineTraceCodeDataTable() + { + DataTable dt; + dt = new DataTable(); + dt.Columns.Add("订单号", typeof(string)); + dt.Columns.Add("订单计划发动机号", typeof(string)); + dt.Columns.Add("发动机号", typeof(string)); + dt.Columns.Add("追踪代码", typeof(string)); + dt.Columns.Add("主物料号", typeof(string)); + dt.Columns.Add("工位号", typeof(string)); + dt.Columns.Add("操作者工号", typeof(string)); + dt.Columns.Add("班次代码", typeof(string)); + dt.Columns.Add("SAP物料号", typeof(string)); + dt.Columns.Add("发动机型号", typeof(string)); + dt.Columns.Add("发动机型号代码", typeof(int)); + dt.Columns.Add("发动机机型", typeof(string)); + return dt; + } + /// + /// 上线工位的[MES_装配数据_发动机号_追踪代码]数据 + /// + /// + private DataTable GetTraceCodeDataTable() + { + DataTable dt; + dt = CreateEngineTraceCodeDataTable(); + DataRow dr; + dr = dt.NewRow(); + dr["订单号"] = MaterialData.orderForm; + dr["订单计划发动机号"] = MaterialData.engineNumber_OrderPlan; + dr["发动机号"] = MaterialData.engineNumber; + dr["追踪代码"] = MaterialData.engineTraceCode; + dr["主物料号"] = MaterialData.mainMaterialNumber; + dr["工位号"] = MaterialData.opName; + dr["操作者工号"] = MaterialData.operatorCode; + dr["班次代码"] = MaterialData.operatorShift; + dr["SAP物料号"] = MaterialData.sAPMaterialNumber; + dr["发动机型号"] = MaterialData.engineNumberType; + dr["发动机型号代码"] = MaterialData.engineNumberCode; + dr["发动机机型"] = MaterialData.engineNumberBasicType; + dt.Rows.Add(dr); + return dt; + } + /// + /// 上线工位的[MES_装配数据_发动机号_追踪代码]数据 + /// 从本工位 + /// + /// + //public static bool GetTraceCodeDataTableFromAccess(string opName, out DataTable dt) + //{ + // string sql; + // sql = "select 订单号,订单计划发动机号,发动机号,追踪代码,主物料号,工位号,操作者工号,班次代码,SAP物料号,发动机型号,发动机型号代码,发动机机型" + // + " from MES_装配数据_发动机号_追踪代码 where IsOK=0 and 工位号='" + opName + "'"; + // return DataAccess.ExecuteDataTable_OleDb_Access(sql, out dt); + //} + /// + /// 更新IsOK = 1 [MES_装配数据_发动机号_追踪代码]数据 + /// + /// + //public static bool GetTraceCodeDataTableFromAccess_Update(string opName) + //{ + // string sql; + // sql = "update MES_装配数据_发动机号_追踪代码 set IsOK = 1 where IsOK=0 and 工位号='" + opName + "'"; + // return DataAccess.ExecuteSQL_OleDb_Access(sql); + //} + + /// + /// 数据库同步,应用于分装线线首工位 + /// [数据MES_装配数据_发动机号_追踪代码_下达工位] + /// 从到Access中获得[数据MES_装配数据_发动机号_追踪代码_下达工位]数据, + /// 保存SqlServer数据库服务器,同时更新[是否同步]标志。 + /// + /// 当前工位 + /// + //public static void GetTraceCodeDataTableFromAccess_OpName_InsertIntoSqlServer(string opName) + //{ + // DataTable dt; + // if (GetTraceCodeDataTableFromAccess(opName, out dt)) + // { + // if (TableTraceInsert_SqlServer(dt)) + // { + // GetTraceCodeDataTableFromAccess_Update(opName); + // } + // } + //} + /// + /// 上线工位的[MES_装配数据_发动机号_追踪代码] + /// 对于分线上线工位,要将IsOK=0的行上传到分装部件的总线上线工位;上传后,该值置1。 + /// + /// + private static DataTable TraceCodeDataTableUpdate_Access() + { + + DataTable dt; + dt = CreateEngineTraceCodeDataTable(); + DataRow dr; + dr = dt.NewRow(); + dr["订单号"] = MaterialData.orderForm; + dr["订单计划发动机号"] = MaterialData.engineNumber_OrderPlan; + dr["发动机号"] = MaterialData.engineNumber; + dr["追踪代码"] = MaterialData.engineTraceCode; + dr["主物料号"] = MaterialData.mainMaterialNumber; + dr["工位号"] = MaterialData.opName; + dr["操作者工号"] = MaterialData.operatorCode; + dr["班次代码"] = MaterialData.operatorShift; + dr["SAP物料号"] = MaterialData.sAPMaterialNumber; + dr["发动机型号"] = MaterialData.engineNumberType; + dr["发动机型号代码"] = MaterialData.engineNumberCode; + dr["发动机机型"] = MaterialData.engineNumberBasicType; + dt.Rows.Add(dr); + return dt; + } + } +} diff --git a/Common/07WebBusinessFacade/BusinessFacade/MES.Data.SaveData/vssver2.scc b/Common/07WebBusinessFacade/BusinessFacade/MES.Data.SaveData/vssver2.scc new file mode 100644 index 0000000..c778a5a Binary files /dev/null and b/Common/07WebBusinessFacade/BusinessFacade/MES.Data.SaveData/vssver2.scc differ diff --git a/Common/07WebBusinessFacade/BusinessFacade/MES.HL/MesFunctions.cs b/Common/07WebBusinessFacade/BusinessFacade/MES.HL/MesFunctions.cs new file mode 100644 index 0000000..20a938f --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/MES.HL/MesFunctions.cs @@ -0,0 +1,83 @@ +using DataLinkMesWork; +using System; +using System.Collections.Generic; +using System.Data.SqlClient; +using System.Data; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace bizFacade +{ + public class MesFunctions + { + /// + /// 工件入站 + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + public static bool EnginePart_Incoming(string OpName, int EngineTypeID, string EngineType, int PartPallet_Code, string EngineID, string Big_EnginTypeID, int MES_QualityMask, string OrderForm) + { + var procedureName = "MES_合装控制_工件入站"; + var sqlParameters = new SqlParameter[] + { + new SqlParameter("@OP_Name", OpName), + new SqlParameter("@Engine_TypeID", EngineTypeID), + new SqlParameter("@Engine_Type", EngineType), + new SqlParameter("@Pallet_Code", PartPallet_Code), + new SqlParameter("@Product_Code", EngineID), + new SqlParameter("@Big_EnginTypeID", int.Parse(Big_EnginTypeID)), + new SqlParameter("@Product_QualityOK", MES_QualityMask), + new SqlParameter("@OrderForm", OrderForm) + }; + return DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters); + } + /// + /// 工件出站 + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + public static bool EnginePart_OutStation(string OpName, string EngineID, int MES_QualityMask) + { + var procedureName = "MES_合装控制_工件出站"; + var sqlParameters = new SqlParameter[] + { + new SqlParameter("@OP_Name", OpName), + new SqlParameter("@Product_Code", EngineID), + new SqlParameter("@Product_QualityOK", MES_QualityMask) + }; + return DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters); + } + /// + /// Condition_Type:1、判断该工位是否在业务范围内(停用);2、机型匹配,3、获取OPA90的匹配结果 + /// + /// + /// + public static int GetCondition_AssemblyControl(int Condition_Type) + { + //Condition_Type:1、判断该工位是否在业务范围内;2、根据OPA90第一个入站工件进行机型判断;3、获取报警信息 + string procedureName = "MES_合装控制_控制条件"; + var sqlParameters = new SqlParameter[] + { + new SqlParameter("@Condition_Type", Condition_Type), + new SqlParameter("@OP_Name", "OPA90") + }; + var result = DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out DataTable dt); + return int.Parse(dt.Rows[0][0].ToString()); + } + } +} diff --git a/Common/07WebBusinessFacade/BusinessFacade/MES.Material/Materials.cs b/Common/07WebBusinessFacade/BusinessFacade/MES.Material/Materials.cs new file mode 100644 index 0000000..a10f1d9 --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/MES.Material/Materials.cs @@ -0,0 +1,1037 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Data; +using System.Data.SqlClient; + +using System.Data.OleDb; + + +using DataLinkMesWork; + +//using SystemFramework; +namespace bizFacade +{ + public class MobyTagType + { + /// + /// 配方号 + /// + public static string PLCRcipe = "配方号"; + /// + /// 工位号 + /// + public static string OpName = "工位号"; + /// + /// 订单号 + /// + public static string OrderForm = "订单号"; + /// + /// 订单号 + /// + public static string OrderForm_MES = "订单号_MES"; + /// + /// 产品型号代码 + /// + public static string EngineTypeID = "产品型号代码"; + /// + /// 变速器序列号 + /// 变速器序列号 + public static string EngineID = "变速器序列号"; + + /// + /// 发动机型号 + /// + public static string EngineType = "发动机型号"; + /// + /// 机型基本代码 + /// + public static string EngineTypeBasicID = "机型基本代码"; + /// + /// 机型基本代码 + /// + public static string EngineTypeBasic = "基本机型"; + /// + /// 变速器总成号 + /// + public static string EngineIDPrinte = "变速器总成号"; + /// + /// 托盘号 + /// + public static string PartPallet_Code = "托盘号"; + /// + /// 产品型号代码_MES + /// + public static string EngineTypeID_MES = "产品型号代码_MES"; + /// + /// 变速器序列号_MES + /// + public static string EngineID_MES = "变速器序列号_MES"; + /// + /// 发动机型号_MES + /// + public static string EngineType_MES = "发动机型号_MES"; + /// + /// 到达时间线外工位 + /// + public static string WorkStartOutSideIn = "到达时间线外工位"; + /// + /// 离开时间线外工位 + /// + public static string WorkStartOutSideOut = "离开时间线外工位"; + /// + /// 到达时间 + /// + public static string WorkStartIn = "到达时间"; + /// + /// 离开时间 + /// + public static string WorkStartOut = "离开时间"; + /// + /// 持续时间 + /// + public static string WorkStartTime = "持续时间"; + /// + /// 扫描条码 + /// + public static string BarCode = "扫描条码"; + /// + /// 工件到位 2 + /// + public static string WorkStart = "工件到位"; + /// + /// 传递机型 44 + /// + public static string EngineTypeGetOverPLC = "传递机型"; + /// + /// 申请上件 43 + /// + public static string PartLoad = "申请上件"; + /// + /// 允许保存 19 + /// + public static string MesRead = "允许保存"; + /// + /// 保存完成 20 + /// + public static string MesReadOver = "保存完成"; + + + + + /// [机床上电],[循环开始],[机床故障],[上料无件],[下料堵塞],[工件到位] + /// [传递机型],[申请上件],[允许保存],[保存完成],[合格标志],[前序合格] + /// [工号],[班次],[是否返修件],[合格放行],[不合格放行] + /// [到达时间],[离开时间],[持续时间] + // engineTypeID = Convert.ToInt32(thisParms[2].Value); + //engineType = thisParms[3].Value.ToString(); + //engineID = thisParms[4].Value.ToString(); + //palletCode = thisParms[5].Value.ToString(); + } + public partial class BaseDataSystemMES + { + /// + /// 测量数据工位_监控系统_MOBY_查询 + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + public static bool OpName_MIS_Moby_Select(string opName, + out string orderForm, out int engineTypeID, out string engineType, + out string engineID, out string palletCode, out int isRepair, out string repairCode) + { + orderForm = ""; + engineTypeID = 0; + engineType = ""; + engineID = ""; + palletCode = ""; + isRepair = 0; + repairCode = ""; + + string produceName = "测量数据工位_监控系统_MOBY_查询"; + SqlParameter[] thisParms = new SqlParameter[8]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@订单号", SqlDbType.NVarChar, 50); + thisParms[1].Direction = ParameterDirection.Output; + thisParms[2] = new System.Data.SqlClient.SqlParameter("@产品型号代码", SqlDbType.Int, 4); + thisParms[2].Direction = ParameterDirection.Output; + thisParms[3] = new System.Data.SqlClient.SqlParameter("@发动机型号", SqlDbType.NVarChar, 50); + thisParms[3].Direction = ParameterDirection.Output; + thisParms[4] = new System.Data.SqlClient.SqlParameter("@发动机号", SqlDbType.NVarChar, 50); + thisParms[4].Direction = ParameterDirection.Output; + thisParms[5] = new System.Data.SqlClient.SqlParameter("@托盘号", SqlDbType.NVarChar, 50); + thisParms[5].Direction = ParameterDirection.Output; + thisParms[6] = new System.Data.SqlClient.SqlParameter("@拆解标志", SqlDbType.Int, 4); + thisParms[6].Direction = ParameterDirection.Output; + thisParms[7] = new System.Data.SqlClient.SqlParameter("@拆解返修条码", SqlDbType.NVarChar, 50); + thisParms[7].Direction = ParameterDirection.Output; + if (DataAccess.ExecuteStoredProcedure(produceName, ref thisParms)) + { + orderForm = thisParms[1].Value.ToString(); + engineTypeID = Convert.ToInt32(thisParms[2].Value); + engineType = thisParms[3].Value.ToString(); + engineID = thisParms[4].Value.ToString(); + palletCode = thisParms[5].Value.ToString(); + isRepair = Convert.ToInt32(thisParms[6].Value); + repairCode = thisParms[7].Value.ToString(); + return true; + } + return false; + } + + /// + /// 测量数据工位_获得订单_查询 + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + public static bool OrderFormByOpName_Select(string opName, + out string orderForm, out int engineTypeID, out string engineType, + out string engineID, out string palletCode, out int isRepair, out string repairCode) + { + orderForm = ""; + engineTypeID = 0; + engineType = ""; + engineID = ""; + palletCode = ""; + isRepair = 0; + repairCode = ""; + + string produceName = "测量数据工位_获得订单_查询"; + SqlParameter[] thisParms = new SqlParameter[8]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@订单号", SqlDbType.NVarChar, 50); + thisParms[1].Direction = ParameterDirection.Output; + thisParms[2] = new System.Data.SqlClient.SqlParameter("@产品型号代码", SqlDbType.Int, 4); + thisParms[2].Direction = ParameterDirection.Output; + thisParms[3] = new System.Data.SqlClient.SqlParameter("@发动机型号", SqlDbType.NVarChar, 50); + thisParms[3].Direction = ParameterDirection.Output; + thisParms[4] = new System.Data.SqlClient.SqlParameter("@发动机号", SqlDbType.NVarChar, 50); + thisParms[4].Direction = ParameterDirection.Output; + thisParms[5] = new System.Data.SqlClient.SqlParameter("@托盘号", SqlDbType.NVarChar, 50); + thisParms[5].Direction = ParameterDirection.Output; + thisParms[6] = new System.Data.SqlClient.SqlParameter("@拆解标志", SqlDbType.Int, 4); + thisParms[6].Direction = ParameterDirection.Output; + thisParms[7] = new System.Data.SqlClient.SqlParameter("@拆解返修条码", SqlDbType.NVarChar, 50); + thisParms[7].Direction = ParameterDirection.Output; + if (DataAccess.ExecuteStoredProcedure(produceName, ref thisParms)) + { + orderForm = thisParms[1].Value.ToString(); + engineTypeID = Convert.ToInt32(thisParms[2].Value); + engineType = thisParms[3].Value.ToString(); + engineID = thisParms[4].Value.ToString(); + palletCode = thisParms[5].Value.ToString(); + isRepair = Convert.ToInt32(thisParms[6].Value); + repairCode = thisParms[7].Value.ToString(); + return true; + } + return false; + } + + /// + /// 北汽福田工位状态监控MOBY_增加 + /// 工位号],[订单号],[产品型号代码],[变速器序列号],[发动机型号],[机型基本代码],[变速器总成号] ,[托盘号] + /// [产品型号代码_MES],[变速器序列号_MES],[发动机型号_MES] + /// [机床上电],[循环开始],[机床故障],[上料无件],[下料堵塞],[工件到位] + /// [传递机型],[申请上件],[允许保存],[保存完成],[合格标志],[前序合格] + /// [工号],[班次],[是否返修件],[合格放行],[不合格放行],[扫描条码] + /// [到达时间],[离开时间],[持续时间] + /// + /// + /// + /// + /// + public static bool OpName_MIS_MOBY_Insert(string opName, string tagType, string tagValue) + { + string produceName = "北汽福田工位状态监控MOBY_增加"; + SqlParameter[] thisParms = new SqlParameter[3]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@变量类型", tagType); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@变量值", tagValue); + + return DataAccess.ExecuteStoredProcedure(produceName, ref thisParms); + + } + + + + /// + /// 测量数据工位_监控系统_MOBY_增加 + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + public static bool OpName_MIS_MOBY_Insert(string opName, string orderForm, + int engineTypeID, string engineType, string engineID, int palletCode, int repairCode, int Is_repairBarcode, string repairBarcode) + { + string produceName = "测量数据工位_监控系统_MOBY_增加"; + SqlParameter[] thisParms = new SqlParameter[9]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@订单号", orderForm); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@产品型号代码", engineTypeID); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@发动机型号", engineType); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@发动机号", engineID); + thisParms[5] = new System.Data.SqlClient.SqlParameter("@托盘号", palletCode); + thisParms[6] = new System.Data.SqlClient.SqlParameter("@返修标志", repairCode); + thisParms[7] = new System.Data.SqlClient.SqlParameter("@拆解标志", Is_repairBarcode); + thisParms[8] = new System.Data.SqlClient.SqlParameter("@拆解返修条码", repairBarcode); + return DataAccess.ExecuteStoredProcedure(produceName, ref thisParms); + } + + public static bool OpName_MIS_MOBY_Insert_FirstOpName(string opName, + int engineTypeID, string engineType, string engineID, int palletCode, int repairCode, int Is_repairBarcode, string repairBarcode) + { + string produceName = "测量数据工位_监控系统_MOBY_线首_增加"; + SqlParameter[] thisParms = new SqlParameter[8]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@产品型号代码", engineTypeID); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@发动机型号", engineType); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@发动机号", engineID); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@托盘号", palletCode); + thisParms[5] = new System.Data.SqlClient.SqlParameter("@返修标志", repairCode); + thisParms[6] = new System.Data.SqlClient.SqlParameter("@拆解标志", Is_repairBarcode); + thisParms[7] = new System.Data.SqlClient.SqlParameter("@拆解返修条码", repairBarcode); + return DataAccess.ExecuteStoredProcedure(produceName, ref thisParms); + } + + /// + /// 测量数据工位_监控系统_订单号_增加 + /// + /// + /// + /// + public static bool OpName_MIS_OrderForm_Insert(string opName, string orderForm) + { + string produceName = "测量数据工位_监控系统_订单号_增加"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@订单号", orderForm); + return DataAccess.ExecuteStoredProcedure(produceName, ref thisParms); + } + + /// + /// 测量数据工位_监控系统_操作者工号_增加 + /// + /// + /// + /// + public static bool OpName_MIS_Operator_Insert(string opName, string opperatorCode) + { + string produceName = "AMES_物料拉动_测量数据工位_监控系统_操作者工号_增加"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@操作者工号", opperatorCode); + return DataAccess.ExecuteStoredProcedure(produceName, ref thisParms); + } + + /// + /// 测量数据工位_监控系统_发动机号_增加 + /// + /// + /// + /// + public static bool OpName_MIS_EngineID_Insert(string opName, string engineID) + { + string produceName = "测量数据工位_监控系统_发动机号_增加"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@发动机号", engineID); + return DataAccess.ExecuteStoredProcedure(produceName, ref thisParms); + } + /// + /// 测量数据工位_监控系统_订单号_发动机型号_修改 + /// + /// + /// + /// + /// + /// + public static bool OpName_MIS_OrderForm_EngineType_Update(string opName, int engineTypeID, string engineType, string engineID) + { + string produceName = "测量数据工位_监控系统_订单号_发动机型号_修改"; + SqlParameter[] thisParms = new SqlParameter[4]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@产品型号代码", engineTypeID); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@发动机型号", engineType); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@发动机号", engineID); + return DataAccess.ExecuteStoredProcedure(produceName, ref thisParms); + } + /// + /// 测量数据工位_监控系统_发动机型号_增加 + /// + /// + /// + /// + /// + public static bool OpName_MIS_EngineType_Insert(string opName, int engineTypeID, string engineType) + { + string produceName = "测量数据工位_监控系统_发动机型号_增加"; + SqlParameter[] thisParms = new SqlParameter[3]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@产品型号代码", engineTypeID); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@发动机型号", engineType); + return DataAccess.ExecuteStoredProcedure(produceName, ref thisParms); + } + + /// + /// 测量数据工位_监控系统_托盘号_增加 + /// + /// + /// + /// + public static bool OpName_MIS_PalletCode_Insert(string opName, int palletCode) + { + string produceName = "测量数据工位_监控系统_托盘号_增加"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@托盘号", palletCode); + return DataAccess.ExecuteStoredProcedure(produceName, ref thisParms); + } + + /// + /// 测量数据工位_监控系统_返修_增加 + /// + /// + /// + /// + /// + public static bool OpName_MIS_Repair_Insert(string opName, int repairCode, int Is_repairBarcode, string repairBarcode) + { + string produceName = "测量数据工位_监控系统_返修_增加"; + SqlParameter[] thisParms = new SqlParameter[4]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@返修标志", repairCode); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@拆解标志", Is_repairBarcode); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@拆解返修条码", repairBarcode); + return DataAccess.ExecuteStoredProcedure(produceName, ref thisParms); + } + + /// + /// 电子看板_装配零件_临时表_增加 + /// + /// + /// + public static bool MesServer_Process_EngineTypeOver(string opName) + { + string produceName = "电子看板_装配零件_临时表_增加"; + SqlParameter[] thisParms = new SqlParameter[1]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + return DataAccess.ExecuteStoredProcedure(produceName, ref thisParms); + } + /// + /// [电子看板_装配零件_临时表_增加_北汽] + /// + /// + /// + public static bool MesServer_Process_EngineTypeOverBQ(string opName) + { + string produceName = "电子看板_装配零件_临时表_增加_北汽"; + SqlParameter[] thisParms = new SqlParameter[1]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + return DataAccess.ExecuteStoredProcedure(produceName, ref thisParms); + } + /// + /// [电子看板_装配零件_临时表_增加_北汽线首] + /// + /// + /// + public static bool MesServer_Process_EngineTypeOver_BQ_FirstOP(string opName) + { + string produceName = "电子看板_装配零件_临时表_增加_北汽线首"; + SqlParameter[] thisParms = new SqlParameter[1]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + return DataAccess.ExecuteStoredProcedure(produceName, ref thisParms); + } + /// + /// 自制件条码记录_创建 + /// + /// + /// + public static DataTable Create_OutLineBarCode(string EngineID, string OrderForm) + { + DataTable dt; + string produceName = "自制件条码记录_创建"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@总成号", EngineID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@订单号", OrderForm); + DataAccess.ExecuteStoredProcedure(produceName, ref thisParms, out dt); + return dt; + } + + /// + /// 合力_OPA90是否允许工作_判断 如果允许工作则将两个轮毂状态设为待匹配 + /// + /// + /// + /// + /// + /// + /// + /// + public static bool OP50_OPA90_MatchResult(int EngineTypeID, int EngineTypeID_QiaoKe, string EngineID, string OrderForm, out int MatchResult, out string MatchResultStr) + { + DataTable dt = new DataTable(); + MatchResult = 3;// 默认是报警 程序出错 + MatchResultStr = "默认是报警 程序出错";// 默认是报警 程序出错 + string produceName = "合力_OPA90是否允许工作_判断"; + SqlParameter[] thisParms = new SqlParameter[4]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@轮毂机型", EngineTypeID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@轮毂总成号", EngineID); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@桥壳_机型", EngineTypeID_QiaoKe); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@订单号", OrderForm); + if (DataAccess.ExecuteStoredProcedure(produceName, ref thisParms, out dt)) + { + if (dt.Rows.Count > 0) + { + MatchResult = Convert.ToInt32(dt.Rows[0]["最终结果"]); + MatchResultStr = dt.Rows[0]["最终结果说明"].ToString(); + return true; + } + } + return false; + } + + public static bool OP051_OP050_NeedWork(string EngineID, string opName, string orderForm, out int MatchResult, out string resultMsg) + { + DataTable dt = new DataTable(); + MatchResult = 0; + resultMsg = ""; + + string produceName = "合力_OP050前停判断_下工位是否需要工作"; + SqlParameter[] thisParms = new SqlParameter[3]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@桥壳总成号", EngineID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@订单号", orderForm); + if (DataAccess.ExecuteStoredProcedure(produceName, ref thisParms, out dt)) + { + if (dt.Rows.Count > 0) + { + MatchResult = Convert.ToInt32(dt.Rows[0]["是否需要工作"]); + resultMsg = dt.Rows[0]["msg"].ToString(); + return true; + } + } + return false; + } + + public static bool OP051_OP050_NeedWork_Save(string EngineID, int MatchResult, string Cause) + { + + string produceName = "合力_OP050是否需要工作_插入"; + SqlParameter[] thisParms = new SqlParameter[3]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@桥壳总成号", EngineID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@是否需要工作", MatchResult); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@原因", Cause); + return DataAccess.ExecuteStoredProcedure(produceName, ref thisParms); + } + + /// + /// 合力_工位报警记录表_增加 + /// + /// + /// + public static bool HeLi_OoNameAlarmRecord_Add(string opName, string EngineID, string alarmText) + { + string produceName = "合力_工位报警记录表_增加"; + SqlParameter[] thisParms = new SqlParameter[3]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@总成号", EngineID); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@报警内容", alarmText); + return DataAccess.ExecuteStoredProcedure(produceName, ref thisParms); + } + + /// + /// 电子看板_装配零件_临时表_线首_增加 + /// + /// + /// + public static bool MesServer_Process_EngineTypeOver_FirstOpName(string opName) + { + string produceName = "电子看板_装配零件_临时表_线首_增加"; + SqlParameter[] thisParms = new SqlParameter[1]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + return DataAccess.ExecuteStoredProcedure(produceName, ref thisParms); + } + + public static bool GetEngineTypeByEngineID(string engineID, out DataTable dt) + { + string procedureName = "测量数据发动机在线状态_下线工位_是否存在_查询"; + SqlParameter[] thisParms = new SqlParameter[1]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@EngineID", engineID); + //return DataAccess.ExecuteStoredProcedure(produceName, ref thisParms); + return DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out dt); + + + } + //测量数据发动机在线状态_下线工位_是否存在_查询 + + + /// + /// 测量数据发动机在线状态_跟踪发动机条码状态_增加 + /// + /// + /// + public static bool MaterialPush_EngineIDStatus_Insert(string opName) + { + string produceName = "测量数据发动机在线状态_跟踪发动机条码状态_增加"; + SqlParameter[] thisParms = new SqlParameter[1]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + return DataAccess.ExecuteStoredProcedure(produceName, ref thisParms); + } + + /// + /// 物料拉动_电子看板_装配零件_修改 + /// + /// + /// + public static bool PartMaterialUseNum_Update(string opName) + { + string produceName = "物料拉动_电子看板_装配零件_修改"; + SqlParameter[] thisParms = new SqlParameter[1]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + return DataAccess.ExecuteStoredProcedure(produceName, ref thisParms); + } + + /// + /// 电子看板_装配零件_临时表_判断_是否允许工作 + /// + /// + /// + /// + public static bool MesServer_Judge_IsCanWork(string opName, out int IsAllowWork) + { + IsAllowWork = 0; + string produceName = "电子看板_装配零件_临时表_判断_是否允许工作"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@是否允许工作", IsAllowWork); + thisParms[1].Direction = ParameterDirection.Output; + if (DataAccess.ExecuteStoredProcedure(produceName, ref thisParms)) + { + IsAllowWork = Convert.ToInt32(thisParms[1].Value); + return true; + } + return false; + } + + public static DataTable Get_AGV_CallRecord(string opName,string position,string engineType,string type) + { + string procedureName = "HL_AGV送叫料记录_新增"; + SqlParameter[] thisParms = new SqlParameter[4]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[0] = new System.Data.SqlClient.SqlParameter("@位置号", position); + thisParms[0] = new System.Data.SqlClient.SqlParameter("@型号", engineType); + thisParms[0] = new System.Data.SqlClient.SqlParameter("@操作类型", type); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out DataTable dt); + return dt; + } + + /// + ///[北汽福田工位J07MA40_验证线外工位零件是否与工位J07MA20匹配] @EngineID nvarchar(50),@BarCode nvarchar(50) + /// + /// + /// + /// + /// + public static bool MesServer_J07MA20_Judge_IsCanWork(string EngineID, string BarCode, out int IsAllowWork) + { + IsAllowWork = 0; + string produceName = "北汽福田工位J07MA40_验证线外工位零件是否与工位J07MA20匹配"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@EngineID", EngineID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@BarCode", BarCode); + if (DataAccess.ExecuteStoredProcedure(produceName, ref thisParms, out DataTable dt)) + { + IsAllowWork = Convert.ToInt32(dt.Rows[0][0]); + return true; + } + return false; + } + + /// + /// 条码扫描_判断条码类型 + /// + /// + /// + /// + /// + public static bool GetBarcodeType(string opName, string barCode, out string barCodeType) + { + barCodeType = ""; + string produceName = "条码扫描_判断条码类型"; + SqlParameter[] thisParms = new SqlParameter[3]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@条码", barCode); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@条码类型", barCodeType); + thisParms[2].Direction = ParameterDirection.Output; + if (DataAccess.ExecuteStoredProcedure(produceName, ref thisParms)) + { + barCodeType = thisParms[2].Value.ToString(); + return true; + } + return false; + } + + /// + /// 物料拉动_线边库存_修改 + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + public static bool ReceiveCard_Update(string OpName, string barcode, + out bool MaterialIsExsit, out bool BarCodeIsExsit, out bool IsBillOk, out bool IsCanUpdateBetch, out bool IsScaningMulti, out bool IsMultiPC) + { + MaterialIsExsit = true;//@物料是否存在 + BarCodeIsExsit = true;//@条码是否存在 + IsBillOk = true;//@扫描是否符合订单 + IsCanUpdateBetch = true;//@是否可以更新批次 + IsScaningMulti = false;//@是否重复扫描 + IsMultiPC = false;//是否多箱追踪批次 + + + string produceName = "物料拉动_线边库存_修改"; + SqlParameter[] thisParms = new SqlParameter[8]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", OpName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@卡片条码", barcode); + + thisParms[2] = new System.Data.SqlClient.SqlParameter("@物料是否存在", MaterialIsExsit); + thisParms[2].Direction = ParameterDirection.Output; + thisParms[3] = new System.Data.SqlClient.SqlParameter("@条码是否存在", BarCodeIsExsit); + thisParms[3].Direction = ParameterDirection.Output; + thisParms[4] = new System.Data.SqlClient.SqlParameter("@扫描是否符合订单", IsBillOk); + thisParms[4].Direction = ParameterDirection.Output; + thisParms[5] = new System.Data.SqlClient.SqlParameter("@是否可以更新批次", IsCanUpdateBetch); + thisParms[5].Direction = ParameterDirection.Output; + thisParms[6] = new System.Data.SqlClient.SqlParameter("@是否重复扫描", IsScaningMulti); + thisParms[6].Direction = ParameterDirection.Output; + thisParms[7] = new System.Data.SqlClient.SqlParameter("@是否多箱消耗", IsMultiPC); + thisParms[7].Direction = ParameterDirection.Output; + + if (DataAccess.ExecuteStoredProcedure(produceName, ref thisParms)) + { + MaterialIsExsit = Convert.ToBoolean(thisParms[2].Value); + BarCodeIsExsit = Convert.ToBoolean(thisParms[3].Value); + IsBillOk = Convert.ToBoolean(thisParms[4].Value); + IsCanUpdateBetch = Convert.ToBoolean(thisParms[5].Value); + IsScaningMulti = Convert.ToBoolean(thisParms[6].Value); + IsMultiPC = Convert.ToBoolean(thisParms[7].Value); + return true; + } + return false; + } + + /// + /// 电子看板_装配零件_临时表_修改_零件条码 + /// + /// + /// + /// + /// + public static bool PartMaterial_DM_Update(string opName, string barCode, out bool IsSuccess) + { + IsSuccess = false; + string produceName = "电子看板_装配零件_临时表_修改_零件条码"; + SqlParameter[] thisParms = new SqlParameter[3]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@条码", barCode); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@条码是否符合", IsSuccess); + thisParms[2].Direction = ParameterDirection.Output; + if (DataAccess.ExecuteStoredProcedure(produceName, ref thisParms)) + { + IsSuccess = Convert.ToBoolean(thisParms[2].Value); + return true; + } + return false; + } + + + + /// + /// 北汽福田_总分线对应表_验证 + /// + /// + /// + /// + /// + public static bool BusPartLine_Check(string PartCode, string OpName, string orderForm, out bool IsSuccess) + { + IsSuccess = false; + string produceName = "北汽福田_总分线对应表_验证"; + SqlParameter[] thisParms = new SqlParameter[4]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@分线总成号", PartCode); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@工位号", OpName); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@订单号", orderForm); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@Count", IsSuccess); + thisParms[3].Direction = ParameterDirection.Output; + if (DataAccess.ExecuteStoredProcedure(produceName, ref thisParms)) + { + IsSuccess = Convert.ToBoolean(thisParms[3].Value); + return true; + } + return false; + } + + /// + /// 北汽福田_总分线对应表_增加 + /// + /// + /// + /// + /// + public static void BusPartLine_Add(string BusCode, string PartCode, string opName, string orderForm, string EngineID) + { + string produceName = "北汽福田_总分线对应表_增加"; + SqlParameter[] thisParms = new SqlParameter[5]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@主线总成号", BusCode); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@分线总成号", PartCode); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@订单号", orderForm); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@机型号", EngineID); + DataAccess.ExecuteStoredProcedure(produceName, ref thisParms); + } + + /// + /// AMES_MES_装配数据_零部件追溯_增加 + /// + /// + /// + /// + public static bool Material_Insert(string opName, int m_ConfirmOkGo) + { + string produceName = "MES_装配数据_零部件追溯_增加"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@放行方式", m_ConfirmOkGo); + return DataAccess.ExecuteStoredProcedure(produceName, ref thisParms); + } + + /// + /// 合力_扫码记录_增加 + /// + /// + /// + /// + public static bool HeLi_BarCodeData_Add(string opName, string EngineType,string EngineID,string OrderFrom,string BarCode) + { + string produceName = "合力_扫码记录_增加"; + SqlParameter[] thisParms = new SqlParameter[5]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@机型", EngineType); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@总成号", EngineID); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@订单号", OrderFrom); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@码值", BarCode); + return DataAccess.ExecuteStoredProcedure(produceName, ref thisParms); + } + + /// + /// 合力_HMI物料厂家_生产记录_增加 + /// + /// + /// + /// + public static bool HeLi_HMIMaterialFactory_Add(string opName, string EngineID, string OrderFrom,int byte1, int byte2, int byte3, int byte4, int byte5, int byte6, int byte7, int byte8, int byte9, int byte10) + { + string produceName = "合力_HMI物料厂家_生产记录_增加"; + SqlParameter[] thisParms = new SqlParameter[13]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@工件编号", EngineID); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@订单号", OrderFrom); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@物料排序1编号", byte1); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@物料排序2编号", byte2); + thisParms[5] = new System.Data.SqlClient.SqlParameter("@物料排序3编号", byte3); + thisParms[6] = new System.Data.SqlClient.SqlParameter("@物料排序4编号", byte4); + thisParms[7] = new System.Data.SqlClient.SqlParameter("@物料排序5编号", byte5); + thisParms[8] = new System.Data.SqlClient.SqlParameter("@物料排序6编号", byte6); + thisParms[9] = new System.Data.SqlClient.SqlParameter("@物料排序7编号", byte7); + thisParms[10] = new System.Data.SqlClient.SqlParameter("@物料排序8编号", byte8); + thisParms[11] = new System.Data.SqlClient.SqlParameter("@物料排序9编号", byte9); + thisParms[12] = new System.Data.SqlClient.SqlParameter("@物料排序10编号", byte10); + return DataAccess.ExecuteStoredProcedure(produceName, ref thisParms); + } + + /// + /// 北汽福田工位BOM换型比对 + /// + /// + /// 新零件号(机型) + /// + public static DataTable EngineTypeChange(string opName, string engineType) + { + DataTable dt = new DataTable(); + string produceName = "北汽福田工位BOM换型比对"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@新零件号", engineType); + DataAccess.ExecuteStoredProcedure(produceName, ref thisParms, out dt); + return dt; + } + + /// + /// 测量数据发动机在线状态_查询_是否已工作 + /// + /// + /// 新零件号(机型) + /// + public static DataTable EngineIsTwoWork(string opName, string OrderForm, string EngineID) + { + DataTable dt = new DataTable(); + string produceName = "测量数据发动机在线状态_查询_是否已工作"; + SqlParameter[] thisParms = new SqlParameter[3]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@订单号", OrderForm); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@总成号", EngineID); + DataAccess.ExecuteStoredProcedure(produceName, ref thisParms, out dt); + return dt; + } + + /// + /// 北汽福田_TCU_增加 + /// + /// + /// + /// + /// + /// + public static DataTable TCU_Add(string opName, string nameplate, string EngineID, string EngineTypeID) + { + DataTable dt = new DataTable(); + string produceName = "北汽福田_TCU_增加"; + SqlParameter[] thisParms = new SqlParameter[4]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@变速器总成码", EngineID); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@物料码", nameplate); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@机型代码", EngineTypeID); + DataAccess.ExecuteStoredProcedure(produceName, ref thisParms, out dt); + return dt; + } + // + /// + /// MES_装配数据_零部件追溯_增加 + /// + /// + /// + public static bool Material_Insert(string opName) + { + string produceName = "MES_装配数据_零部件追溯_增加"; + SqlParameter[] thisParms = new SqlParameter[1]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + return DataAccess.ExecuteStoredProcedure(produceName, ref thisParms); + } + + + /// + /// 电子看板_工位机型_质量数据测量位置_临时表_增加 + /// + /// + /// + public static bool MesServer_ShaftPosition_EngineTypeOver(string opName) + { + string produceName = "电子看板_工位机型_质量数据测量位置_临时表_增加"; + SqlParameter[] thisParms = new SqlParameter[1]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + return DataAccess.ExecuteStoredProcedure(produceName, ref thisParms); + } + + /// + /// 电子看板_工位机型_质量数据测量位置_临时表_查询_完成情况 + /// + /// + /// + /// + /// + /// + public static bool MesServer_ShaftPosition_Select_FinishResult(string opName, out int workGroupIndex, out string BoltCode, out bool sn_WorkingStepIsOver) + { + workGroupIndex = 0; + BoltCode = ""; + sn_WorkingStepIsOver = true; + + string produceName = "电子看板_工位机型_质量数据测量位置_临时表_查询_完成情况"; + SqlParameter[] thisParms = new SqlParameter[4]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@组号", SqlDbType.Int, 4); + thisParms[1].Direction = ParameterDirection.Output; + thisParms[2] = new System.Data.SqlClient.SqlParameter("@套筒号", SqlDbType.NVarChar, 50); + thisParms[2].Direction = ParameterDirection.Output; + thisParms[3] = new System.Data.SqlClient.SqlParameter("@是否全部完成", SqlDbType.Int, 4); + thisParms[3].Direction = ParameterDirection.Output; + if (DataAccess.ExecuteStoredProcedure(produceName, ref thisParms)) + { + workGroupIndex = Convert.ToInt32(thisParms[1].Value); + BoltCode = thisParms[2].Value.ToString(); + sn_WorkingStepIsOver = Convert.ToBoolean(thisParms[3].Value); + return true; + } + return false; + } + + + /// + /// 电子看板_工位机型_质量数据测量位置_临时表_修改 + /// + /// + /// + /// + /// + /// + public static bool MesServer_ShaftPosition_Update(string opName, int workGroupIndex, int IsOK, out bool IsFinish) + { + IsFinish = true; + string produceName = "电子看板_工位机型_质量数据测量位置_临时表_修改"; + SqlParameter[] thisParms = new SqlParameter[4]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@组号", workGroupIndex); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@合格标志", IsOK); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@是否全部完成", SqlDbType.Int, 4); + thisParms[3].Direction = ParameterDirection.Output; + if (DataAccess.ExecuteStoredProcedure(produceName, ref thisParms)) + { + IsFinish = Convert.ToBoolean(thisParms[3].Value); + return true; + } + return false; + } + + + /// + /// MES界面显示_弹窗消息_增加 + /// + /// + /// + /// + public static bool Web_Notice_Insert(string opName, string notice) + { + string produceName = "MES界面显示_弹窗消息_增加"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@Notice", notice); + return DataAccess.ExecuteStoredProcedure(produceName, ref thisParms); + } + + } +} diff --git a/Common/07WebBusinessFacade/BusinessFacade/MES.Material/vssver2.scc b/Common/07WebBusinessFacade/BusinessFacade/MES.Material/vssver2.scc new file mode 100644 index 0000000..ab96d34 Binary files /dev/null and b/Common/07WebBusinessFacade/BusinessFacade/MES.Material/vssver2.scc differ diff --git a/Common/07WebBusinessFacade/BusinessFacade/MES/BaseDataSystemMES.AssemblyPartTrace.Repair.cs b/Common/07WebBusinessFacade/BusinessFacade/MES/BaseDataSystemMES.AssemblyPartTrace.Repair.cs new file mode 100644 index 0000000..3f13871 --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/MES/BaseDataSystemMES.AssemblyPartTrace.Repair.cs @@ -0,0 +1,509 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Data; +using System.Data.SqlClient; + +using System.Data.OleDb; +using DataLinkMesWork; + + +//using SystemFramework; + +namespace bizFacade +{ + /// + /// 关键零部件追溯 + /// + public partial class BaseDataSystemMES + { + /// + /// 向数据库写入返修数据 + /// + /// + /// + /// + public static bool UpdateRepairStatusTo_SQL(string opname, string status) + { + string produceName = "测量数据_返修工位_工位状态_修改"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opname); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@返修状态", status); + + return DataAccess.ExecuteStoredProcedure(produceName, ref thisParms); + } + + /// + /// 返修上线_返修工位及返修路径_增加 + /// + /// + /// + /// + public static bool RepairStatusInsert(string engineID, string RepairStatus, string RepairMethod, string engineType) + { + string produceName = "返修上线_返修工位及返修路径_增加"; + SqlParameter[] thisParms = new SqlParameter[4]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@总成编号", engineID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@返修状态", RepairStatus); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@返修路径", RepairMethod); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@发动机型号", engineType); + return DataAccess.ExecuteStoredProcedure(produceName, ref thisParms); + } + + /// + /// 上传数据 + /// MES_装配数据_零部件追溯_返修工位_数据主表 + /// 一般情况追踪代码等于发动机号() + /// + /// 订单号 + /// 发动机号 + /// 追踪代码 + /// 工位号 + /// 人员代码 + /// 返修原因代码 + /// 返修原因内容 + /// 返修内容 + /// 操作时间 + static public bool AssemblyPartTraceMainTableRepairInsert_OnlySqlServer(string orderForm, + string engineNumber, string engineTraceCode, string opName, + string operatorCode, string reasonCode, string reason, string repareContent,string operationTime) + { + string sql_Insert; + sql_Insert = "INSERT INTO [MES_装配数据_零部件追溯_返修工位_数据主表] " + + "(订单号,发动机号,追踪代码,工位号,人员代码, 返修原因代码, 返修原因内容, 返修内容,操作时间)" + + " VALUES (" + + "'" + orderForm + "'," + + "'" + engineNumber + "'," + + "'" + engineTraceCode + "'," + + "'" + opName + "'," + + "'" + operatorCode + "'," + + "'" + reasonCode + "'," + + "'" + reason + "'," + + "'" + repareContent + "'," + + "'" + operationTime + "') "; + + return DataAccess.ExecuteSQL(sql_Insert); + + } + /// + /// 数据上传 + /// 删除数据 + /// MES_装配数据_零部件追溯_返修工位_数据主表 + /// + /// 追溯代码 + //static public bool PartTraceTableRepareDelete(long traceID) + //{ + // string sql; + // sql = "DELETE FROM [MES_装配数据_零部件追溯_返修工位_数据主表] " + // + " WHERE 追溯代码=" + traceID.ToString(); + // return DataAccess.ExecuteSQL_OleDb_Access(sql); + //} + /// + /// 数据上传 + /// 查询数据 + /// MES_装配数据_零部件追溯_返修工位_数据主表 + /// + //static public bool PartTraceMainTableRepareSelect(out DataTable dt) + //{ + // string sql; + // dt = null; + // sql = "SELECT * FROM [MES_装配数据_零部件追溯_返修工位_数据主表] "; + // return DataAccess.ExecuteDataTable_OleDb_Access(sql, out dt); + //} + + + /// + /// 查询返修原因代码,返修内容 + /// + /// 追踪代码 + /// 工位号 + /// + /// + static public bool AssemblyPartTraceTableRepairSelect(string engineTraceCode, string opName, out DataTable dt) + { + string sql; + dt = null; + sql = "SELECT 返修原因代码,返修内容 FROM [MES_装配数据_零部件追溯_返修工位_数据主表] " + + " where 追踪代码='" + engineTraceCode + "'" + + " and 工位号 = '" + opName + "'" + + " and 返修状态 = 0"; + //if (SQLCommon.SqlServerConnectionStatus) + { + return DataAccess.ExecuteDataTable(sql, out dt); + } + //if (!SQLCommon.SqlServerConnectionStatus) + //{ + // return DataAccess.ExecuteDataTable_OleDb_Access(sql, out dt); + //} + //return false; + } + + /// + /// 测试是否填写返修原因数据 + /// 已经填写,返回true + /// 没有填写,返回false + /// + /// + /// + /// + /// + static public bool AssemblyPartTraceTableRepairIsSave(string orderForm,string engineTraceCode, string opName) + { + string sql_Count; + int count = 0; + sql_Count = "SELECT COUNT (*) FROM [MES_装配数据_零部件追溯_返修工位_数据主表] " + + " where 追踪代码='" + engineTraceCode + "'" + + " and 工位号 = '" + opName + "'" + + " and 返修状态 = 0"; + //if (SQLCommon.SqlServerConnectionStatus) + { + DataAccess.ExecuteOutNum(sql_Count, out count); + } + //if (!SQLCommon.SqlServerConnectionStatus) + //{ + // DataAccess.ExecuteOutNum_OleDb_Access(sql_Count, out count); + //} + if (count == 0) + { + return false; + } + else + { + return true; + } + } + + + /// + /// + /// + /// + /// + //static public bool AssemblyPartTraceTableRepairReasonSelect(out DataTable dt) + //{ + // string sql; + // sql = "SELECT 返修原因代码,返修原因内容 FROM MES_基本数据_返修原因"; + // return DataAccess.ExecuteDataTable_OleDb_Access(sql, out dt); + //} + + + /// + /// 同步通讯方式 + /// 增加数据,返回自动编号 + /// MES_装配数据_零部件追溯_返修工位_数据主表 + /// 一般情况追踪代码等于发动机号() + /// + /// 订单号 + /// 发动机号 + /// 追踪代码 + /// 工位号 + /// 人员代码 + /// 返修原因代码 + /// 返修原因内容 + /// 返修内容 + static public bool AssemblyPartTraceMainTableRepairInsert(string orderForm, + string engineNumber, string engineTraceCode, string opName, + string operatorCode, string reasonCode, string reason,string repareContent) + { + string sql_Insert; + string sql_Update; + string sql_Count; + sql_Insert = "INSERT INTO [MES_装配数据_零部件追溯_返修工位_数据主表] " + + "(订单号,发动机号,追踪代码,工位号,人员代码, 返修原因代码, 返修原因内容, 返修内容)" + + " VALUES (" + + "'" + orderForm + "'," + + "'" + engineNumber + "'," + + "'" + engineTraceCode + "'," + + "'" + opName + "'," + + "'" + operatorCode + "'," + + "'" + reasonCode + "'," + + "'" + reason + "'," + + "'" + repareContent + "') "; + sql_Update = "UPDATE [MES_装配数据_零部件追溯_返修工位_数据主表] " + + "SET 人员代码 ='" + operatorCode + "'," + + " 返修原因代码 ='" + reasonCode + "'," + + " 返修原因内容 ='" + reason + "'," + + " 返修内容 ='" + repareContent + "'" + + " where 追踪代码='" + engineTraceCode + "'" + + " and 工位号 = '" + opName + "'" + + " and 返修状态 = 0"; + + sql_Count = "SELECT COUNT (*) FROM [MES_装配数据_零部件追溯_返修工位_数据主表] " + + " where 追踪代码='" + engineTraceCode + "'" + + " and 工位号 = '" + opName + "'" + + " and 返修状态 = 0"; + + int count=0; + //if (SQLCommon.SqlServerConnectionStatus) + { + DataAccess.ExecuteOutNum(sql_Count, out count); + if (count == 0) + { + return DataAccess.ExecuteSQL(sql_Insert); + } + else + //MES_装配数据_零部件追溯_返修工位_数据主表 + //存在发动机号,工位号 + { + return DataAccess.ExecuteSQL(sql_Update); + } + } + //if (!SQLCommon.SqlServerConnectionStatus) + //{ + // DataAccess.ExecuteOutNum_OleDb_Access(sql_Count, out count); + // if (count == 0) + // { + // return DataAccess.ExecuteSQL_OleDb_Access(sql_Insert); + // } + // else + // //MES_装配数据_零部件追溯_返修工位_数据主表 + // //存在发动机号,工位号 + // { + // return DataAccess.ExecuteSQL_OleDb_Access(sql_Update); + // } + //} + //return false; + + } + + /// + ///MES_装配数据_零部件追溯_返修工位 + ///INSERT INTO [MES_装配数据_零部件追溯_返修工位] + ///增加数据, + /// + /// + /// + public static void VerifyAssemblyPartTableRepairInsert(DataTable dt) + { + //if (ApplicationConfig.connectionStringPIS_NEW_Value == "1") + //{ + // //如果与SQL Server 数据库通讯失败,ApplicationConfig.connectionStringPIS_NEW_Value = "0" + // VerifyAssemblyPartTableRepairInsert_SqlServer(dt); + //} + //if (ApplicationConfig.connectionStringPIS_NEW_Value == "0") + //{ + // VerifyAssemblyPartTableRepairInsert_Access(dt); + //} + + } + /// + /// 同步操作方式 + ///MES_装配数据_零部件追溯_返修工位 + ///INSERT INTO [MES_装配数据_零部件追溯_返修工位] + ///增加数据, + /// + /// + /// + public static void VerifyAssemblyPartTableRepairInsert_SqlServer(DataTable dt) + { + string sql; + sql = "INSERT INTO [MES_装配数据_零部件追溯_返修工位]" + + "([追溯代码],[订单号],[SAP物料号],[发动机型号],[发动机型号代码], [发动机机型], " + + "[发动机数量], [厂牌编号起始号], [客户名称],[投料日期],[文件编号],[集团名称],[通知号]," + + "[功率],[指南文件编号],[装机状态],[适用状态],[物料描述],[计划下达日期],[计划完工日期]," + + "[主配厂家],[工位号], [工位名称],[物料号], [零件图号], [零件名称], [零件数量]," + + "[是否扫描],[扫描方式代码], [扫描方式], [厂家代码],[生产厂家], " + + "[操作指导],[发动机号],[追踪代码],[物料号表索引号],[零件数量验证]," + + "[物料条码], [物料条码物料号], [物料条码批次],[验证结果], [操作者工号], [操作者姓名], [班次代码], " + + "物料来源代码,物料来源,是否禁用代码,是否禁用,被强制验证物料号," + +"更改代码,更改原因,操作时间)" + + + "VALUES(@追溯代码,@订单号,@SAP物料号,@发动机型号,@发动机型号代码,@发动机机型," + + "@发动机数量,@厂牌编号起始号,@客户名称,@投料日期,@文件编号,@集团名称,@通知号," + + "@功率,@指南文件编号,@装机状态,@适用状态,@物料描述,@计划下达日期,@计划完工日期," + + "@主配厂家,@工位号,@工位名称,@物料号,@零件图号,@零件名称,@零件数量," + + " @是否扫描,@扫描方式代码,@扫描方式,@厂家代码,@生产厂家," + + "@操作指导,@发动机号,@追踪代码,@物料号表索引号,@零件数量验证," + + "@物料条码,@物料条码物料号,@物料条码批次,@验证结果,@操作者工号,@操作者姓名,@班次代码," + + "@物料来源代码,@物料来源,@是否禁用代码,@是否禁用,@被强制验证物料号," + +"@更改代码,@更改原因,@操作时间)"; + + + + SqlParameter[] thisParmsSql = new SqlParameter[52]; + // + "([订单号],[SAP物料号],[发动机型号],[发动机型号代码], [发动机机型], " + thisParmsSql[0] = new SqlParameter("@追溯代码", SqlDbType.Int, 4, "追溯代码"); + thisParmsSql[1] = new SqlParameter("@订单号", SqlDbType.NVarChar, 50, "订单号"); + thisParmsSql[2] = new SqlParameter("@SAP物料号", SqlDbType.NVarChar, 50, "SAP物料号"); + thisParmsSql[3] = new SqlParameter("@发动机型号", SqlDbType.NVarChar, 50, "发动机型号"); + thisParmsSql[4] = new SqlParameter("@发动机型号代码", SqlDbType.Int, 4, "发动机型号代码"); + thisParmsSql[5] = new SqlParameter("@发动机机型", SqlDbType.NVarChar, 50, "发动机机型"); + + // + "@发动机数量,@厂牌编号起始号,@客户名称,@投料日期,@文件编号,@集团名称,@通知号," + thisParmsSql[6] = new SqlParameter("@发动机数量", SqlDbType.Int, 4, "发动机数量"); + thisParmsSql[7] = new SqlParameter("@厂牌编号起始号", SqlDbType.Int, 4, "厂牌编号起始号"); + thisParmsSql[8] = new SqlParameter("@客户名称", SqlDbType.NVarChar, 50, "客户名称"); + thisParmsSql[9] = new SqlParameter("@投料日期", SqlDbType.DateTime, 8, "投料日期"); + thisParmsSql[10] = new SqlParameter("@文件编号", SqlDbType.NVarChar, 50, "文件编号"); + thisParmsSql[11] = new SqlParameter("@集团名称", SqlDbType.NVarChar, 50, "集团名称"); + thisParmsSql[12] = new SqlParameter("@通知号", SqlDbType.NVarChar, 50, "通知号"); + + // + "@功率,@指南文件编号,@装机状态,@适用状态,@物料描述,@计划下达日期,@计划完工日期," + thisParmsSql[13] = new SqlParameter("@功率", SqlDbType.NVarChar, 50, "功率"); + thisParmsSql[14] = new SqlParameter("@指南文件编号", SqlDbType.NVarChar, 50, "指南文件编号"); + thisParmsSql[15] = new SqlParameter("@装机状态", SqlDbType.NVarChar, 50, "装机状态"); + thisParmsSql[16] = new SqlParameter("@适用状态", SqlDbType.DateTime, 8, "适用状态"); + thisParmsSql[17] = new SqlParameter("@物料描述", SqlDbType.NVarChar, 255, "物料描述"); + thisParmsSql[18] = new SqlParameter("@计划下达日期", SqlDbType.DateTime, 8, "计划下达日期"); + thisParmsSql[19] = new SqlParameter("@计划完工日期", SqlDbType.DateTime, 8, "计划完工日期"); + + // + "@主配厂家,@工位号,@工位名称,@物料号,@零件图号,@零件名称,@零件数量," + + thisParmsSql[20] = new SqlParameter("@主配厂家", SqlDbType.NVarChar, 50, "主配厂家"); + thisParmsSql[21] = new SqlParameter("@工位号", SqlDbType.NVarChar, 50, "工位号"); + thisParmsSql[22] = new SqlParameter("@工位名称", SqlDbType.NVarChar, 50, "工位名称"); + thisParmsSql[23] = new SqlParameter("@物料号", SqlDbType.NVarChar, 50, "物料号"); + thisParmsSql[24] = new SqlParameter("@零件图号", SqlDbType.NVarChar, 50, "零件图号"); + thisParmsSql[25] = new SqlParameter("@零件名称", SqlDbType.NVarChar, 50, "零件名称"); + thisParmsSql[26] = new SqlParameter("@零件数量", SqlDbType.Int, 4, "零件数量"); + + // +"[是否扫描],扫描方式代码, [扫描方式], [厂家代码],[生产厂家], " + + thisParmsSql[27] = new SqlParameter("@是否扫描", SqlDbType.Int, 4, "是否扫描"); + thisParmsSql[28] = new SqlParameter("@扫描方式代码", SqlDbType.Int, 4, "扫描方式代码"); + thisParmsSql[29] = new SqlParameter("@扫描方式", SqlDbType.NVarChar, 50, "扫描方式"); + thisParmsSql[30] = new SqlParameter("@厂家代码", SqlDbType.NVarChar, 50, "厂家代码"); + thisParmsSql[31] = new SqlParameter("@生产厂家", SqlDbType.NVarChar, 50, "生产厂家"); + + //+ "@操作指导,@发动机号,@物料号表索引号,@零件数量验证," + + thisParmsSql[32] = new SqlParameter("@操作指导", SqlDbType.NVarChar, 255, "操作指导"); + thisParmsSql[33] = new SqlParameter("@发动机号", SqlDbType.NVarChar, 50, "发动机号"); + thisParmsSql[34] = new SqlParameter("@追踪代码", SqlDbType.NVarChar, 50, "追踪代码"); + thisParmsSql[35] = new SqlParameter("@物料号表索引号", SqlDbType.Int, 4, "物料号表索引号"); + thisParmsSql[36] = new SqlParameter("@零件数量验证", SqlDbType.Int, 4, "零件数量验证"); + + // +"[物料条码], [物料条码物料号], [物料条码批次],@验证结果, [操作者工号], [操作者姓名], [班次代码], " + thisParmsSql[37] = new SqlParameter("@物料条码", SqlDbType.NVarChar, 50, "物料条码"); + thisParmsSql[38] = new SqlParameter("@物料条码物料号", SqlDbType.NVarChar, 50, "物料条码物料号"); + thisParmsSql[39] = new SqlParameter("@物料条码批次", SqlDbType.NVarChar, 50, "物料条码批次"); + thisParmsSql[40] = new SqlParameter("@验证结果", SqlDbType.Int, 4, "验证结果"); + thisParmsSql[41] = new SqlParameter("@操作者工号", SqlDbType.NVarChar, 50, "操作者工号"); + thisParmsSql[42] = new SqlParameter("@操作者姓名", SqlDbType.NVarChar, 50, "操作者姓名"); + thisParmsSql[43] = new SqlParameter("@班次代码", SqlDbType.NVarChar, 50, "班次代码"); + + // +"物料来源代码,物料来源,是否禁用代码,是否禁用,被强制验证物料号,更改代码,更改原因)" + + thisParmsSql[44] = new SqlParameter("@物料来源代码", SqlDbType.Int, 4, "物料来源代码"); + thisParmsSql[45] = new SqlParameter("@物料来源", SqlDbType.NVarChar, 50, "物料来源"); + thisParmsSql[46] = new SqlParameter("@是否禁用代码", SqlDbType.Int, 4, "是否禁用代码"); + thisParmsSql[47] = new SqlParameter("@是否禁用", SqlDbType.NVarChar, 50, "是否禁用"); + thisParmsSql[48] = new SqlParameter("@被强制验证物料号", SqlDbType.NVarChar, 50, "被强制验证物料号"); + thisParmsSql[49] = new SqlParameter("@更改代码", SqlDbType.NVarChar, 50, "更改代码"); + thisParmsSql[50] = new SqlParameter("@更改原因", SqlDbType.NVarChar, 255, "更改原因"); + thisParmsSql[51] = new SqlParameter("@操作时间", SqlDbType.DateTime, 8, "操作时间"); + + DataAccess.ExecuteSQL(sql, ref thisParmsSql, dt); + + } + /// + /// 异步操作方式 + /// _Access + ///MES_装配数据_零部件追溯_返修工位 + ///INSERT INTO [MES_装配数据_零部件追溯_返修工位] + ///增加数据, + /// + /// + /// + //public static void VerifyAssemblyPartTableRepairInsert_Access(DataTable dt) + //{ + // string sql; + // sql = "INSERT INTO [MES_装配数据_零部件追溯_返修工位]" + // + "([追溯代码],[订单号],[SAP物料号],[发动机型号],[发动机型号代码], [发动机机型], " + // + "[发动机数量], [厂牌编号起始号], [客户名称],[投料日期],[文件编号],[集团名称],[通知号]," + // + "[功率],[指南文件编号],[装机状态],[适用状态],[物料描述],[计划下达日期],[计划完工日期]," + // + "[主配厂家],[工位号], [工位名称],[物料号], [零件图号], [零件名称], [零件数量]," + // + "[是否扫描],[扫描方式代码], [扫描方式], [厂家代码],[生产厂家], " + // + "[操作指导],[发动机号],[追踪代码],[物料号表索引号],[零件数量验证]," + // + "[物料条码], [物料条码物料号], [物料条码批次],[验证结果], [操作者工号], [操作者姓名], [班次代码], " + // + "物料来源代码,物料来源,是否禁用代码,是否禁用,被强制验证物料号," + // +"更改代码,更改原因,操作时间)" + + // + "VALUES(@追溯代码,@订单号,@SAP物料号,@发动机型号,@发动机型号代码,@发动机机型," + // + "@发动机数量,@厂牌编号起始号,@客户名称,@投料日期,@文件编号,@集团名称,@通知号," + // + "@功率,@指南文件编号,@装机状态,@适用状态,@物料描述,@计划下达日期,@计划完工日期," + // + "@主配厂家,@工位号,@工位名称,@物料号,@零件图号,@零件名称,@零件数量," + // + " @是否扫描,@扫描方式代码,@扫描方式,@厂家代码,@生产厂家," + // + "@操作指导,@发动机号,@追踪代码,@物料号表索引号,@零件数量验证," + // + "@物料条码,@物料条码物料号,@物料条码批次,@验证结果,@操作者工号,@操作者姓名,@班次代码," + // + "@物料来源代码,@物料来源,@是否禁用代码,@是否禁用,@被强制验证物料号," + // +"@更改代码,@更改原因,@操作时间)"; + + + // OleDbParameter[] thisParms1 = new OleDbParameter[52]; + // // + "([追溯代码],[订单号],[SAP物料号],[发动机型号],[发动机型号代码], [发动机机型], " + // thisParms1[0] = new OleDbParameter("@追溯代码", OleDbType.Integer, 4, "追溯代码"); + // thisParms1[1] = new OleDbParameter("@订单号", OleDbType.VarChar, 50, "订单号"); + // thisParms1[2] = new OleDbParameter("@SAP物料号", OleDbType.VarChar, 50, "SAP物料号"); + // thisParms1[3] = new OleDbParameter("@发动机型号", OleDbType.VarChar, 50, "发动机型号"); + // thisParms1[4] = new OleDbParameter("@发动机型号代码", OleDbType.Integer, 4, "发动机型号代码"); + // thisParms1[5] = new OleDbParameter("@发动机机型", OleDbType.VarChar, 50, "发动机机型"); + + // // + "@发动机数量,@厂牌编号起始号,@客户名称,@投料日期,@文件编号,@集团名称,@通知号," + // thisParms1[6] = new OleDbParameter("@发动机数量", OleDbType.Integer, 4, "发动机数量"); + // thisParms1[7] = new OleDbParameter("@厂牌编号起始号", OleDbType.Integer, 4, "厂牌编号起始号"); + // thisParms1[8] = new OleDbParameter("@客户名称", OleDbType.VarChar, 50, "客户名称"); + // thisParms1[9] = new OleDbParameter("@投料日期", OleDbType.DBDate, 8, "投料日期"); + // thisParms1[10] = new OleDbParameter("@文件编号", OleDbType.VarChar, 50, "文件编号"); + // thisParms1[11] = new OleDbParameter("@集团名称", OleDbType.VarChar, 50, "集团名称"); + // thisParms1[12] = new OleDbParameter("@通知号", OleDbType.VarChar, 50, "通知号"); + + // // + "@功率,@指南文件编号,@装机状态,@适用状态,@物料描述,@计划下达日期,@计划完工日期," + // thisParms1[13] = new OleDbParameter("@功率", OleDbType.VarChar, 50, "功率"); + // thisParms1[14] = new OleDbParameter("@指南文件编号", OleDbType.VarChar, 50, "指南文件编号"); + // thisParms1[15] = new OleDbParameter("@装机状态", OleDbType.VarChar, 50, "装机状态"); + // thisParms1[16] = new OleDbParameter("@适用状态", OleDbType.DBDate, 8, "适用状态"); + // thisParms1[17] = new OleDbParameter("@物料描述", OleDbType.VarChar, 255, "物料描述"); + // thisParms1[18] = new OleDbParameter("@计划下达日期", OleDbType.DBDate, 8, "计划下达日期"); + // thisParms1[19] = new OleDbParameter("@计划完工日期", OleDbType.DBDate, 8, "计划完工日期"); + + // // + "@主配厂家,@工位号,@工位名称,@物料号,@零件图号,@零件名称,@零件数量," + + // thisParms1[20] = new OleDbParameter("@主配厂家", OleDbType.VarChar, 50, "主配厂家"); + // thisParms1[21] = new OleDbParameter("@工位号", OleDbType.VarChar, 50, "工位号"); + // thisParms1[22] = new OleDbParameter("@工位名称", OleDbType.VarChar, 50, "工位名称"); + // thisParms1[23] = new OleDbParameter("@物料号", OleDbType.VarChar, 50, "物料号"); + // thisParms1[24] = new OleDbParameter("@零件图号", OleDbType.VarChar, 50, "零件图号"); + // thisParms1[25] = new OleDbParameter("@零件名称", OleDbType.VarChar, 50, "零件名称"); + // thisParms1[26] = new OleDbParameter("@零件数量", OleDbType.Integer, 4, "零件数量"); + + // // +"[是否扫描],扫描方式代码, [扫描方式], [厂家代码],[生产厂家], " + + // thisParms1[27] = new OleDbParameter("@是否扫描", OleDbType.Integer, 4, "是否扫描"); + // thisParms1[28] = new OleDbParameter("@扫描方式代码", OleDbType.Integer, 4, "扫描方式代码"); + // thisParms1[29] = new OleDbParameter("@扫描方式", OleDbType.VarChar, 50, "扫描方式"); + // thisParms1[30] = new OleDbParameter("@厂家代码", OleDbType.VarChar, 50, "厂家代码"); + // thisParms1[31] = new OleDbParameter("@生产厂家", OleDbType.VarChar, 50, "生产厂家"); + + // //+ "@操作指导,@发动机号,@物料号表索引号,@零件数量验证," + + // thisParms1[32] = new OleDbParameter("@操作指导", OleDbType.VarChar, 255, "操作指导"); + // thisParms1[33] = new OleDbParameter("@发动机号", OleDbType.VarChar, 50, "发动机号"); + // thisParms1[34] = new OleDbParameter("@追踪代码", OleDbType.VarChar, 50, "追踪代码"); + // thisParms1[35] = new OleDbParameter("@物料号表索引号", OleDbType.Integer, 4, "物料号表索引号"); + // thisParms1[36] = new OleDbParameter("@零件数量验证", OleDbType.Integer, 4, "零件数量验证"); + + // // +"[物料条码], [物料条码物料号], [物料条码批次],@验证结果, [操作者工号], [操作者姓名], [班次代码], " + // thisParms1[37] = new OleDbParameter("@物料条码", OleDbType.VarChar, 50, "物料条码"); + // thisParms1[38] = new OleDbParameter("@物料条码物料号", OleDbType.VarChar, 50, "物料条码物料号"); + // thisParms1[39] = new OleDbParameter("@物料条码批次", OleDbType.VarChar, 50, "物料条码批次"); + // thisParms1[40] = new OleDbParameter("@验证结果", OleDbType.Integer, 4, "验证结果"); + // thisParms1[41] = new OleDbParameter("@操作者工号", OleDbType.VarChar, 50, "操作者工号"); + // thisParms1[42] = new OleDbParameter("@操作者姓名", OleDbType.VarChar, 50, "操作者姓名"); + // thisParms1[43] = new OleDbParameter("@班次代码", OleDbType.VarChar, 50, "班次代码"); + + // // +"物料来源代码,物料来源,是否禁用代码,是否禁用,被强制验证物料号,更改代码,更改原因)" + + // thisParms1[44] = new OleDbParameter("@物料来源代码", OleDbType.Integer, 4, "物料来源代码"); + // thisParms1[45] = new OleDbParameter("@物料来源", OleDbType.VarChar, 50, "物料来源"); + // thisParms1[46] = new OleDbParameter("@是否禁用代码", OleDbType.Integer, 4, "是否禁用代码"); + // thisParms1[47] = new OleDbParameter("@是否禁用", OleDbType.VarChar, 50, "是否禁用"); + // thisParms1[48] = new OleDbParameter("@被强制验证物料号", OleDbType.VarChar, 50, "被强制验证物料号"); + // thisParms1[49] = new OleDbParameter("@更改代码", OleDbType.VarChar, 50, "更改代码"); + // thisParms1[50] = new OleDbParameter("@更改原因", OleDbType.VarChar, 255, "更改原因"); + // thisParms1[51] = new OleDbParameter("@操作时间", OleDbType.DBTimeStamp, 8, "操作时间"); + + // DataAccess.ExecuteDataTable_OleDb_Insert_Access(sql, dt, ref thisParms1); + //} + } +} diff --git a/Common/07WebBusinessFacade/BusinessFacade/MES/BaseDataSystemMES.AssemblyPartTrace.cs b/Common/07WebBusinessFacade/BusinessFacade/MES/BaseDataSystemMES.AssemblyPartTrace.cs new file mode 100644 index 0000000..1952886 --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/MES/BaseDataSystemMES.AssemblyPartTrace.cs @@ -0,0 +1,687 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Data; +using System.Data.SqlClient; +using System.Data.OleDb; +using DataLinkMesWork; +//using SystemFramework; + +namespace bizFacade +{ + /// + /// 关键零部件追溯 + /// + public partial class BaseDataSystemMES + { + + /// + /// 数据上传 + /// 删除数据 + /// MES_装配数据_零部件追溯 + /// + /// 追溯代码 + //static public bool PartTraceTableDelete(long traceID) + //{ + // string sql; + // sql = "DELETE FROM [MES_装配数据_零部件追溯] " + // + " WHERE 追溯代码=" + traceID.ToString(); + // return DataAccess.ExecuteSQL_OleDb_Access(sql); + //} + /// + /// 数据上传 + /// 删除数据 + /// MES_装配数据_零部件追溯_数据主表 + /// + /// 追溯代码 + //static public bool PartTraceMainTableDelete(long traceID) + //{ + // string sql; + // sql = "DELETE FROM [MES_装配数据_零部件追溯_数据主表] " + // + " WHERE 追溯代码=" + traceID.ToString(); + // return DataAccess.ExecuteSQL_OleDb_Access(sql); + //} + /// + /// 数据上传 + /// 查询数据 + /// MES_装配数据_零部件追溯 + /// + /// 追溯代码 + /// + //static public bool PartTraceTableSelect(long traceID, out DataTable dt) + //{ + // string sql; + // dt = null; + // sql = "SELECT * FROM [MES_装配数据_零部件追溯] " + // + " WHERE 追溯代码=" + traceID.ToString(); + // return DataAccess.ExecuteDataTable_OleDb_Access(sql, out dt); + //} + + /// + /// 数据上传 + /// 查询数据 + /// MES_装配数据_零部件追溯_数据主表 + /// + //static public bool PartTraceMainTableSelect(out DataTable dt) + //{ + // string sql; + // dt = null; + // sql = "SELECT * FROM [MES_装配数据_零部件追溯_数据主表] "; + // return DataAccess.ExecuteDataTable_OleDb_Access(sql, out dt); + //} + /// + /// 数据上传 + /// 查询数据 + /// [MES_装配数据_零部件追溯_发动机号与缸盖号] + /// + //static public bool EngineID_CapNumber_Select(out DataTable dt) + //{ + // string sql; + // dt = null; + // sql = "SELECT * FROM [MES_装配数据_零部件追溯_发动机号与缸盖号] "; + // return DataAccess.ExecuteDataTable_OleDb_Access(sql, out dt); + //} + /// + /// 数据上传 + /// 删除数据 + /// [MES_装配数据_零部件追溯_发动机号与缸盖号] + /// + //static public bool EngineID_CapNumber_Delete(int traceID) + //{ + // string sql; + // sql = "DELETE FROM [MES_装配数据_零部件追溯_发动机号与缸盖号] " + // + " WHERE 追溯代码=" + traceID.ToString()+""; + // return DataAccess.ExecuteSQL_OleDb_Access(sql); + //} + + /// + /// 数据上传 + /// MES_装配数据_零部件追溯_增加 + /// + /// + /// + public static bool VerifyAssemblyPartTableInsert_OnlySqlServer(DataTable dt) + { + return VerifyAssemblyPartTableInsert_SqlServer(dt); + } + /// + /// 数据上传 + /// 增加数据 + /// MES_装配数据_零部件追溯_数据主表 + /// 工件到达时间离开时间 + /// 返回“追溯代码” + /// + static public bool AssemblyPartIndexTableInsert_OnlySqlServer(out long traceID) + { + traceID = 0; + string sql = GetSqlStringAssemblyPartIndexTable(); + //if (SQLCommon.SqlServerConnectionStatus) + { + return DataAccess.ExecuteNonQuery_newID(sql, out traceID); + } + //return false; + } + + /// + /// 数据上传 + /// MES_装配数据_零部件追溯_增加 + /// + /// + /// + //public static bool VerifyAssemblyPartTableInsert_OnlyAccess(DataTable dt) + //{ + // return VerifyAssemblyPartTableInsert_Access(dt); + //} + + + /// + /// 分装线物料追踪 + /// 增加数据 + /// MES_装配数据_零部件追溯_数据主表 + /// 工件到达时间离开时间 + /// 返回“追溯代码” + /// + /// + /// + //static public bool AssemblyPartIndexTableInsert_OnlyAccess(out long traceID) + //{ + // traceID = 0; + // string sql = GetSqlStringAssemblyPartIndexTable(); + // DataAccess.ExecuteNonQuery_newID_OleDb(sql, out traceID); + // return false; + //} + + /// + /// MES_装配数据_零部件追溯_数据主表 + /// 删除物料数据 + /// + /// + /// + static public void AssemblyPartIndexTableDelete(string opName,string engineID) + { + DataTable dt; + int traceID = 0; + try + { + //获得 traceID; + + string sql; + sql = "SELECT top 1 追溯代码 From [MES_装配数据_零部件追溯_数据主表]" + + " WHERE 工位号='" + opName+"'" + + " and 发动机号 = '" + engineID+"'"; + + //if (SQLCommon.SqlServerConnectionStatus) + { + DataAccess.ExecuteDataTable( sql, out dt); + if (dt != null) + { + if (dt.Rows.Count > 0) + { + traceID = Convert.ToInt32(dt.Rows[0]["追溯代码"]); + sql = " DELETE FROM MES_装配数据_零部件追溯 " + + " WHERE 追溯代码 = " + traceID.ToString(); + DataAccess.ExecuteSQL(sql); + sql = " DELETE FROM MES_装配数据_零部件追溯_数据主表 " + + " WHERE 追溯代码 = " + traceID.ToString(); + DataAccess.ExecuteSQL(sql); + } + } + } + //if (!SQLCommon.SqlServerConnectionStatus) + //{ + // DataAccess.ExecuteDataTable_OleDb_Access(sql, out dt); + + // if (dt != null) + // { + // if (dt.Rows.Count > 0) + // { + // traceID = Convert.ToInt32(dt.Rows[0]["追溯代码"]); + // sql = " DELETE FROM MES_装配数据_零部件追溯 " + // + " WHERE 追溯代码 = " + traceID.ToString(); + // DataAccess.ExecuteSQL_OleDb_Access(sql); + // sql = " DELETE FROM MES_装配数据_零部件追溯_数据主表 " + // + " WHERE 追溯代码 = " + traceID.ToString(); + // DataAccess.ExecuteSQL_OleDb_Access(sql); + // } + // } + //} + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, err.Message); + } + } + + + + + /// + /// 获得增加表[MES_装配数据_工位返修]的SQL语句 + /// [订单号], [发动机号], [工位号], [操作者工号], [班次代码], + ///[返修原因代码], [返修原因内容] + /// 1:设备返修 2:MES放行 + /// + private static string GetSqlStringRepairReasonTable() + { + string sql = null; + sql = "INSERT INTO [MES_装配数据_工位返修] " + + "(订单号,发动机号,发动机型号代码,工位号,操作者工号,班次代码,返修原因代码,返修原因内容)" + + " VALUES (" + + "'" + MaterialData.orderForm + "'," + + "'" + MaterialData.engineNumber + "'," + + "" + MaterialData.engineNumberCode + "," + + "'" + MaterialData.opName + "'," + + "'" + MaterialData.operatorCode + "'," + + "'" + MaterialData.operatorShift + "'," + + + "" + MaterialData.RepairReasonID.ToString() + "," + + "'" + MaterialData.RepairReasonText.ToString() + "') "; + return sql; + } + /// + /// MES_装配数据_工位返修 + /// + static public void AssemblyRepairReasonTableInsert() + { + try + { + string sql = GetSqlStringRepairReasonTable(); + //if (SQLCommon.SqlServerConnectionStatus) + { + DataAccess.ExecuteSQL(sql); + + } + //if (!SQLCommon.SqlServerConnectionStatus) + //{ + // DataAccess.ExecuteSQL_OleDb_Access(sql); + //} + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, err.Message); + } + } + + /// + /// MES_装配数据_零部件追溯_删除 + /// + /// + /// + /// + public static void VerifyAssemblyPartTableDelete(string opName, string engineID) + { + + string sql; + sql = "DELETE FROM [MES_装配数据_零部件追溯]" + + " where 工位号='" + opName + "'" + + " and 发动机号='" + engineID + "'"; + + //if (SQLCommon.SqlServerConnectionStatus) + { + DataAccess.ExecuteSQL(sql); + + } + //if (!SQLCommon.SqlServerConnectionStatus) + //{ + // DataAccess.ExecuteSQL_OleDb_Access(sql); + //} + } + + + /// + /// MES_装配数据_零部件追溯_返修工位 + /// + /// + /// + public static void VerifyAssemblyPartTableInsert_Repair(DataTable dt) + { + + //if (SQLCommon.SqlServerConnectionStatus) + { + //如果与SQL Server 数据库通讯失败,ApplicationConfig.connectionStringPIS_NEW_Value = "0" + VerifyAssemblyPartTableInsert_SqlServer_Repair(dt); + } + //if (!SQLCommon.SqlServerConnectionStatus) + //{ + // VerifyAssemblyPartTableInsert_Access_Repair(dt); + //} + + } + + /// + /// 同步通讯方式 + /// MES_装配数据_零部件追溯_返修工位 + /// SQL Server 数据库 + /// + /// + /// + public static bool VerifyAssemblyPartTableInsert_SqlServer_Repair(DataTable dt) + { + string sql; + sql = "INSERT INTO [MES_装配数据_零部件追溯_返修工位]" + + "([追溯代码],[订单号],[SAP物料号],[发动机型号],[发动机型号代码], [发动机机型], " + + "[发动机数量], [厂牌编号起始号], [客户名称],[投料日期],[文件编号],[集团名称],[通知号]," + + "[功率],[指南文件编号],[装机状态],[适用状态],[物料描述],[计划下达日期],[计划完工日期]," + + "[主配厂家],[工位号], [工位名称],[物料号], [零件图号], [零件名称], [零件数量]," + + "[是否扫描],[扫描方式代码], [扫描方式], [是否主物料],[厂家代码],[生产厂家], " + + "[操作指导],[发动机号],[追踪代码],[主物料号],[物料号表索引号],[零件数量验证]," + + "[物料条码], [物料条码物料号], [物料条码批次],[验证结果], [操作者工号], [操作者姓名], [班次代码], " + + "物料来源代码,物料来源,是否禁用代码,是否禁用,被强制验证物料号," + + "更改代码,更改原因,零件类型,操作时间)" + + + "VALUES(@追溯代码,@订单号,@SAP物料号,@发动机型号,@发动机型号代码,@发动机机型," + + "@发动机数量,@厂牌编号起始号,@客户名称,@投料日期,@文件编号,@集团名称,@通知号," + + "@功率,@指南文件编号,@装机状态,@适用状态,@物料描述,@计划下达日期,@计划完工日期," + + "@主配厂家,@工位号,@工位名称,@物料号,@零件图号,@零件名称,@零件数量," + + " @是否扫描,@扫描方式代码,@扫描方式,@是否主物料,@厂家代码,@生产厂家," + + "@操作指导,@发动机号,@追踪代码,@主物料号,@物料号表索引号,@零件数量验证," + + "@物料条码,@物料条码物料号,@物料条码批次,@验证结果,@操作者工号,@操作者姓名,@班次代码," + + "@物料来源代码,@物料来源,@是否禁用代码,@是否禁用,@被强制验证物料号," + + "@更改代码,@更改原因,@零件类型,@操作时间)"; + + + + SqlParameter[] thisParmsSql = new SqlParameter[55]; + // + "([订单号],[SAP物料号],[发动机型号],[发动机型号代码], [发动机机型], " + thisParmsSql[0] = new SqlParameter("@追溯代码", SqlDbType.Int, 4, "追溯代码"); + thisParmsSql[1] = new SqlParameter("@订单号", SqlDbType.NVarChar, 50, "订单号"); + thisParmsSql[2] = new SqlParameter("@SAP物料号", SqlDbType.NVarChar, 50, "SAP物料号"); + thisParmsSql[3] = new SqlParameter("@发动机型号", SqlDbType.NVarChar, 50, "发动机型号"); + thisParmsSql[4] = new SqlParameter("@发动机型号代码", SqlDbType.Int, 4, "发动机型号代码"); + thisParmsSql[5] = new SqlParameter("@发动机机型", SqlDbType.NVarChar, 50, "发动机机型"); + + // + "@发动机数量,@厂牌编号起始号,@客户名称,@投料日期,@文件编号,@集团名称,@通知号," + thisParmsSql[6] = new SqlParameter("@发动机数量", SqlDbType.Int, 4, "发动机数量"); + thisParmsSql[7] = new SqlParameter("@厂牌编号起始号", SqlDbType.Int, 4, "厂牌编号起始号"); + thisParmsSql[8] = new SqlParameter("@客户名称", SqlDbType.NVarChar, 50, "客户名称"); + thisParmsSql[9] = new SqlParameter("@投料日期", SqlDbType.DateTime, 8, "投料日期"); + thisParmsSql[10] = new SqlParameter("@文件编号", SqlDbType.NVarChar, 50, "文件编号"); + thisParmsSql[11] = new SqlParameter("@集团名称", SqlDbType.NVarChar, 50, "集团名称"); + thisParmsSql[12] = new SqlParameter("@通知号", SqlDbType.NVarChar, 50, "通知号"); + + // + "@功率,@指南文件编号,@装机状态,@适用状态,@物料描述,@计划下达日期,@计划完工日期," + thisParmsSql[13] = new SqlParameter("@功率", SqlDbType.NVarChar, 50, "功率"); + thisParmsSql[14] = new SqlParameter("@指南文件编号", SqlDbType.NVarChar, 50, "指南文件编号"); + thisParmsSql[15] = new SqlParameter("@装机状态", SqlDbType.NVarChar, 50, "装机状态"); + thisParmsSql[16] = new SqlParameter("@适用状态", SqlDbType.DateTime, 8, "适用状态"); + thisParmsSql[17] = new SqlParameter("@物料描述", SqlDbType.NVarChar, 255, "物料描述"); + thisParmsSql[18] = new SqlParameter("@计划下达日期", SqlDbType.DateTime, 8, "计划下达日期"); + thisParmsSql[19] = new SqlParameter("@计划完工日期", SqlDbType.DateTime, 8, "计划完工日期"); + + // + "@主配厂家,@工位号,@工位名称,@物料号,@零件图号,@零件名称,@零件数量," + + thisParmsSql[20] = new SqlParameter("@主配厂家", SqlDbType.NVarChar, 50, "主配厂家"); + thisParmsSql[21] = new SqlParameter("@工位号", SqlDbType.NVarChar, 50, "工位号"); + thisParmsSql[22] = new SqlParameter("@工位名称", SqlDbType.NVarChar, 50, "工位名称"); + thisParmsSql[23] = new SqlParameter("@物料号", SqlDbType.NVarChar, 50, "物料号"); + thisParmsSql[24] = new SqlParameter("@零件图号", SqlDbType.NVarChar, 50, "零件图号"); + thisParmsSql[25] = new SqlParameter("@零件名称", SqlDbType.NVarChar, 50, "零件名称"); + thisParmsSql[26] = new SqlParameter("@零件数量", SqlDbType.Int, 4, "零件数量"); + + // +"[是否扫描],扫描方式代码, [扫描方式], [厂家代码],[生产厂家], " + + thisParmsSql[27] = new SqlParameter("@是否扫描", SqlDbType.Int, 4, "是否扫描"); + thisParmsSql[28] = new SqlParameter("@扫描方式代码", SqlDbType.Int, 4, "扫描方式代码"); + thisParmsSql[29] = new SqlParameter("@扫描方式", SqlDbType.NVarChar, 50, "扫描方式"); + thisParmsSql[30] = new SqlParameter("@是否主物料", SqlDbType.Int, 4, "是否主物料"); + thisParmsSql[31] = new SqlParameter("@厂家代码", SqlDbType.NVarChar, 50, "厂家代码"); + thisParmsSql[32] = new SqlParameter("@生产厂家", SqlDbType.NVarChar, 50, "生产厂家"); + + //+ "@操作指导,@发动机号,@物料号表索引号,@零件数量验证," + + thisParmsSql[33] = new SqlParameter("@操作指导", SqlDbType.NVarChar, 255, "操作指导"); + thisParmsSql[34] = new SqlParameter("@发动机号", SqlDbType.NVarChar, 50, "发动机号"); + thisParmsSql[35] = new SqlParameter("@追踪代码", SqlDbType.NVarChar, 50, "追踪代码"); + thisParmsSql[36] = new SqlParameter("@主物料号", SqlDbType.NVarChar, 50, "主物料号"); + thisParmsSql[37] = new SqlParameter("@物料号表索引号", SqlDbType.Int, 4, "物料号表索引号"); + thisParmsSql[38] = new SqlParameter("@零件数量验证", SqlDbType.Int, 4, "零件数量验证"); + + // +"[物料条码], [物料条码物料号], [物料条码批次],@验证结果, [操作者工号], [操作者姓名], [班次代码], " + thisParmsSql[39] = new SqlParameter("@物料条码", SqlDbType.NVarChar, 50, "物料条码"); + thisParmsSql[40] = new SqlParameter("@物料条码物料号", SqlDbType.NVarChar, 50, "物料条码物料号"); + thisParmsSql[41] = new SqlParameter("@物料条码批次", SqlDbType.NVarChar, 50, "物料条码批次"); + thisParmsSql[42] = new SqlParameter("@验证结果", SqlDbType.Int, 4, "验证结果"); + thisParmsSql[43] = new SqlParameter("@操作者工号", SqlDbType.NVarChar, 50, "操作者工号"); + thisParmsSql[44] = new SqlParameter("@操作者姓名", SqlDbType.NVarChar, 50, "操作者姓名"); + thisParmsSql[45] = new SqlParameter("@班次代码", SqlDbType.NVarChar, 50, "班次代码"); + + // +"物料来源代码,物料来源,是否禁用代码,是否禁用,被强制验证物料号,更改代码,更改原因)" + + thisParmsSql[46] = new SqlParameter("@物料来源代码", SqlDbType.Int, 4, "物料来源代码"); + thisParmsSql[47] = new SqlParameter("@物料来源", SqlDbType.NVarChar, 50, "物料来源"); + thisParmsSql[48] = new SqlParameter("@是否禁用代码", SqlDbType.Int, 4, "是否禁用代码"); + thisParmsSql[49] = new SqlParameter("@是否禁用", SqlDbType.NVarChar, 50, "是否禁用"); + thisParmsSql[50] = new SqlParameter("@被强制验证物料号", SqlDbType.NVarChar, 50, "被强制验证物料号"); + thisParmsSql[51] = new SqlParameter("@更改代码", SqlDbType.NVarChar, 50, "更改代码"); + thisParmsSql[52] = new SqlParameter("@更改原因", SqlDbType.NVarChar, 255, "更改原因"); + thisParmsSql[53] = new SqlParameter("@零件类型", SqlDbType.Int, 4, "零件类型"); + thisParmsSql[54] = new SqlParameter("@操作时间", SqlDbType.DateTime, 8, "操作时间"); + + //如果与SQL Server 数据库通讯失败,ApplicationConfig.connectionStringPIS_NEW_Value = "0" + return DataAccess.ExecuteSQL(sql, ref thisParmsSql, dt); + + + + } + + + /// + /// 异步通讯方式 + /// 增加数据到Access数据库 + /// MES_装配数据_零部件追溯_返修工位 + /// INSERT INTO [MES_装配数据_零部件追溯_返修工位] + /// + /// + /// + //public static bool VerifyAssemblyPartTableInsert_Access_Repair(DataTable dt) + //{ + // string sql; + // sql = "INSERT INTO [MES_装配数据_零部件追溯_返修工位]" + // + "([追溯代码],[订单号],[SAP物料号],[发动机型号],[发动机型号代码], [发动机机型], " + // + "[发动机数量], [厂牌编号起始号], [客户名称],[投料日期],[文件编号],[集团名称],[通知号]," + // + "[功率],[指南文件编号],[装机状态],[适用状态],[物料描述],[计划下达日期],[计划完工日期]," + // + "[主配厂家],[工位号], [工位名称],[物料号], [零件图号], [零件名称], [零件数量]," + // + "[是否扫描],[扫描方式代码], [扫描方式], [是否主物料],[厂家代码],[生产厂家], " + // + "[操作指导],[发动机号],[追踪代码],[主物料号],[物料号表索引号],[零件数量验证]," + // + "[物料条码], [物料条码物料号], [物料条码批次],[验证结果], [操作者工号], [操作者姓名], [班次代码], " + // + "物料来源代码,物料来源,是否禁用代码,是否禁用,被强制验证物料号,更改代码,更改原因,零件类型,操作时间)" + + // + "VALUES(@追溯代码,@订单号,@SAP物料号,@发动机型号,@发动机型号代码,@发动机机型," + // + "@发动机数量,@厂牌编号起始号,@客户名称,@投料日期,@文件编号,@集团名称,@通知号," + // + "@功率,@指南文件编号,@装机状态,@适用状态,@物料描述,@计划下达日期,@计划完工日期," + // + "@主配厂家,@工位号,@工位名称,@物料号,@零件图号,@零件名称,@零件数量," + // + " @是否扫描,@扫描方式代码,@扫描方式,@是否主物料,@厂家代码,@生产厂家," + // + "@操作指导,@发动机号,@追踪代码,@主物料号,@物料号表索引号,@零件数量验证," + // + "@物料条码,@物料条码物料号,@物料条码批次,@验证结果,@操作者工号,@操作者姓名,@班次代码," + // + "@物料来源代码,@物料来源,@是否禁用代码,@是否禁用,@被强制验证物料号," + // + "@更改代码,@更改原因,@零件类型,@操作时间)"; + + + // OleDbParameter[] thisParms1 = new OleDbParameter[55]; + // // + "([追溯代码],[订单号],[SAP物料号],[发动机型号],[发动机型号代码], [发动机机型], " + // thisParms1[0] = new OleDbParameter("@追溯代码", OleDbType.Integer, 4, "追溯代码"); + // thisParms1[1] = new OleDbParameter("@订单号", OleDbType.VarChar, 50, "订单号"); + // thisParms1[2] = new OleDbParameter("@SAP物料号", OleDbType.VarChar, 50, "SAP物料号"); + // thisParms1[3] = new OleDbParameter("@发动机型号", OleDbType.VarChar, 50, "发动机型号"); + // thisParms1[4] = new OleDbParameter("@发动机型号代码", OleDbType.Integer, 4, "发动机型号代码"); + // thisParms1[5] = new OleDbParameter("@发动机机型", OleDbType.VarChar, 50, "发动机机型"); + + // // + "@发动机数量,@厂牌编号起始号,@客户名称,@投料日期,@文件编号,@集团名称,@通知号," + // thisParms1[6] = new OleDbParameter("@发动机数量", OleDbType.Integer, 4, "发动机数量"); + // thisParms1[7] = new OleDbParameter("@厂牌编号起始号", OleDbType.Integer, 4, "厂牌编号起始号"); + // thisParms1[8] = new OleDbParameter("@客户名称", OleDbType.VarChar, 50, "客户名称"); + // thisParms1[9] = new OleDbParameter("@投料日期", OleDbType.DBDate, 8, "投料日期"); + // thisParms1[10] = new OleDbParameter("@文件编号", OleDbType.VarChar, 50, "文件编号"); + // thisParms1[11] = new OleDbParameter("@集团名称", OleDbType.VarChar, 50, "集团名称"); + // thisParms1[12] = new OleDbParameter("@通知号", OleDbType.VarChar, 50, "通知号"); + + // // + "@功率,@指南文件编号,@装机状态,@适用状态,@物料描述,@计划下达日期,@计划完工日期," + // thisParms1[13] = new OleDbParameter("@功率", OleDbType.VarChar, 50, "功率"); + // thisParms1[14] = new OleDbParameter("@指南文件编号", OleDbType.VarChar, 50, "指南文件编号"); + // thisParms1[15] = new OleDbParameter("@装机状态", OleDbType.VarChar, 50, "装机状态"); + // thisParms1[16] = new OleDbParameter("@适用状态", OleDbType.DBDate, 8, "适用状态"); + // thisParms1[17] = new OleDbParameter("@物料描述", OleDbType.VarChar, 255, "物料描述"); + // thisParms1[18] = new OleDbParameter("@计划下达日期", OleDbType.DBDate, 8, "计划下达日期"); + // thisParms1[19] = new OleDbParameter("@计划完工日期", OleDbType.DBDate, 8, "计划完工日期"); + + // // + "@主配厂家,@工位号,@工位名称,@物料号,@零件图号,@零件名称,@零件数量," + + // thisParms1[20] = new OleDbParameter("@主配厂家", OleDbType.VarChar, 50, "主配厂家"); + // thisParms1[21] = new OleDbParameter("@工位号", OleDbType.VarChar, 50, "工位号"); + // thisParms1[22] = new OleDbParameter("@工位名称", OleDbType.VarChar, 50, "工位名称"); + // thisParms1[23] = new OleDbParameter("@物料号", OleDbType.VarChar, 50, "物料号"); + // thisParms1[24] = new OleDbParameter("@零件图号", OleDbType.VarChar, 50, "零件图号"); + // thisParms1[25] = new OleDbParameter("@零件名称", OleDbType.VarChar, 50, "零件名称"); + // thisParms1[26] = new OleDbParameter("@零件数量", OleDbType.Integer, 4, "零件数量"); + + // // +"[是否扫描],扫描方式代码, [扫描方式], [厂家代码],[生产厂家], " + + // thisParms1[27] = new OleDbParameter("@是否扫描", OleDbType.Integer, 4, "是否扫描"); + // thisParms1[28] = new OleDbParameter("@扫描方式代码", OleDbType.Integer, 4, "扫描方式代码"); + // thisParms1[29] = new OleDbParameter("@扫描方式", OleDbType.VarChar, 50, "扫描方式"); + // thisParms1[30] = new OleDbParameter("@是否主物料", OleDbType.Integer, 4, "是否主物料"); + // thisParms1[31] = new OleDbParameter("@厂家代码", OleDbType.VarChar, 50, "厂家代码"); + // thisParms1[32] = new OleDbParameter("@生产厂家", OleDbType.VarChar, 50, "生产厂家"); + + // //+ "@操作指导,@发动机号,@物料号表索引号,@零件数量验证," + + // thisParms1[33] = new OleDbParameter("@操作指导", OleDbType.VarChar, 255, "操作指导"); + // thisParms1[34] = new OleDbParameter("@发动机号", OleDbType.VarChar, 50, "发动机号"); + // thisParms1[35] = new OleDbParameter("@追踪代码", OleDbType.VarChar, 50, "追踪代码"); + // thisParms1[36] = new OleDbParameter("@主物料号", OleDbType.VarChar, 50, "主物料号"); + // thisParms1[37] = new OleDbParameter("@物料号表索引号", OleDbType.Integer, 4, "物料号表索引号"); + // thisParms1[38] = new OleDbParameter("@零件数量验证", OleDbType.Integer, 4, "零件数量验证"); + + // // +"[物料条码], [物料条码物料号], [物料条码批次],@验证结果, [操作者工号], [操作者姓名], [班次代码], " + // thisParms1[39] = new OleDbParameter("@物料条码", OleDbType.VarChar, 50, "物料条码"); + // thisParms1[40] = new OleDbParameter("@物料条码物料号", OleDbType.VarChar, 50, "物料条码物料号"); + // thisParms1[41] = new OleDbParameter("@物料条码批次", OleDbType.VarChar, 50, "物料条码批次"); + // thisParms1[42] = new OleDbParameter("@验证结果", OleDbType.Integer, 4, "验证结果"); + // thisParms1[43] = new OleDbParameter("@操作者工号", OleDbType.VarChar, 50, "操作者工号"); + // thisParms1[44] = new OleDbParameter("@操作者姓名", OleDbType.VarChar, 50, "操作者姓名"); + // thisParms1[45] = new OleDbParameter("@班次代码", OleDbType.VarChar, 50, "班次代码"); + + // // +"物料来源代码,物料来源,是否禁用代码,是否禁用,被强制验证物料号,更改代码,更改原因)" + + // thisParms1[46] = new OleDbParameter("@物料来源代码", OleDbType.Integer, 4, "物料来源代码"); + // thisParms1[47] = new OleDbParameter("@物料来源", OleDbType.VarChar, 50, "物料来源"); + // thisParms1[48] = new OleDbParameter("@是否禁用代码", OleDbType.Integer, 4, "是否禁用代码"); + // thisParms1[49] = new OleDbParameter("@是否禁用", OleDbType.VarChar, 50, "是否禁用"); + // thisParms1[50] = new OleDbParameter("@被强制验证物料号", OleDbType.VarChar, 50, "被强制验证物料号"); + // thisParms1[51] = new OleDbParameter("@更改代码", OleDbType.VarChar, 50, "更改代码"); + // thisParms1[52] = new OleDbParameter("@更改原因", OleDbType.VarChar, 255, "更改原因"); + // thisParms1[53] = new OleDbParameter("@零件类型", OleDbType.Integer, 4, "零件类型"); + // thisParms1[54] = new OleDbParameter("@操作时间", OleDbType.DBTimeStamp, 8, "操作时间"); + + // return DataAccess.ExecuteDataTable_OleDb_Insert_Access(sql, dt, ref thisParms1); + //} + /// + /// MES_装配数据_零部件追溯_返修工位_返修原因 + /// + /// + /// + public static void RepairReasonInsert(DataTable dt) + { + + //if (SQLCommon.SqlServerConnectionStatus) + { + //如果与SQL Server 数据库通讯失败,ApplicationConfig.connectionStringPIS_NEW_Value = "0" + RepairReasonInsert_SqlServer(dt); + } + //if (!SQLCommon.SqlServerConnectionStatus) + //{ + // RepairReasonInsert_Access(dt); + //} + + } + /// + /// MES_装配数据_零部件追溯_返修工位_返修原因 + /// + /// + /// + public static void RepairReasonInsert_OnlySqlServer(DataTable dt) + { + + //if (SQLCommon.SqlServerConnectionStatus) + { + //如果与SQL Server 数据库通讯失败,ApplicationConfig.connectionStringPIS_NEW_Value = "0" + RepairReasonInsert_SqlServer(dt); + } + } + /// + /// 同步通讯方式 + /// MES_装配数据_零部件追溯_返修工位_返修原因 + /// SQL Server 数据库 + /// + /// + /// + private static bool RepairReasonInsert_SqlServer(DataTable dt) + { + string sql; + sql = "INSERT INTO [MES_装配数据_零部件追溯_返修工位_返修原因]" + + "([追溯代码],[返修原因代码],[返修原因内容])" + + + "VALUES(@追溯代码,@返修原因代码,@返修原因内容)"; + SqlParameter[] thisParmsSql = new SqlParameter[3]; + thisParmsSql[0] = new SqlParameter("@追溯代码", SqlDbType.Int, 4, "追溯代码"); + thisParmsSql[1] = new SqlParameter("@返修原因代码", SqlDbType.Int, 4, "返修原因代码"); + thisParmsSql[2] = new SqlParameter("@返修原因内容", SqlDbType.NVarChar, 200, "返修原因内容"); + + return DataAccess.ExecuteSQL(sql, ref thisParmsSql, dt); + } + /// + /// 异步通讯方式 + /// INSERT INTO [MES_装配数据_零部件追溯_返修工位_返修原因] + /// + /// + /// + //private static bool RepairReasonInsert_Access(DataTable dt) + //{ + // string sql; + // sql = "INSERT INTO [MES_装配数据_零部件追溯_返修工位_返修原因]" + // + "([追溯代码],[返修原因代码],[返修原因内容])" + + // + "VALUES(@追溯代码,@返修原因代码,@返修原因内容)"; + + // OleDbParameter[] thisParms1 = new OleDbParameter[3]; + // // + "([追溯代码],[订单号],[SAP物料号],[发动机型号],[发动机型号代码], [发动机机型], " + // thisParms1[0] = new OleDbParameter("@追溯代码", OleDbType.Integer, 4, "追溯代码"); + // thisParms1[1] = new OleDbParameter("@返修原因代码", OleDbType.Integer, 4, "返修原因代码"); + // thisParms1[2] = new OleDbParameter("@返修原因内容", OleDbType.VarChar, 200, "返修原因内容"); + + // return DataAccess.ExecuteDataTable_OleDb_Insert_Access(sql, dt, ref thisParms1); + //} + /// + /// 异步通讯方式 + /// SELECT * FROM [MES_装配数据_零部件追溯_返修工位_返工原因_临时表] + /// + /// + /// + //public static bool RepairReasonSelect_Access_TempTable(out DataTable dt) + //{ + // string sql; + // sql = "SELECT * FROM [MES_装配数据_零部件追溯_返修工位_返工原因_临时表]"; + + // return DataAccess.ExecuteDataTable_OleDb_Access( sql, out dt); + //} + /// + /// 异步通讯方式 + /// INSERT INTO [MES_装配数据_零部件追溯_返修工位_返工原因_临时表] + /// + /// + //public static bool RepairReasonDelete_Access_TempTable() + //{ + // string sql; + // sql = "DELETE FROM [MES_装配数据_零部件追溯_返修工位_返工原因_临时表]"; + + // return DataAccess.ExecuteSQL_OleDb_Access(sql); + //} + /// + /// 数据上传 + /// SELECT * FROM [MES_装配数据_零部件追溯_返修工位_返修原因] + /// + /// + /// + //public static bool RepairReasonSelect_Access_Table(out DataTable dt) + //{ + // string sql; + // sql = "SELECT * FROM [MES_装配数据_零部件追溯_返修工位_返修原因]"; + + // return DataAccess.ExecuteDataTable_OleDb_Access(sql, out dt); + //} + /// + /// 数据上传 + /// DELETE FROM [MES_装配数据_零部件追溯_返修工位_返修原因] + /// + /// + /// + //public static bool RepairReasonDelete_Access_Table(int traceID) + //{ + // string sql; + // sql = "DELETE FROM [MES_装配数据_零部件追溯_返修工位_返修原因] WHERE 追溯代码 = " + traceID.ToString(); + + // return DataAccess.ExecuteSQL_OleDb_Access(sql); + //} + /// + /// INSERT INTO [MES_装配数据_零部件追溯_返修工位_返工原因_临时表] + /// + /// + /// + //public static bool RepairReasonInsert_Access_TempTable(DataTable dt) + //{ + // string sql; + // sql = "INSERT INTO [MES_装配数据_零部件追溯_返修工位_返工原因_临时表]" + // + "([追溯代码],[返修原因代码],[返修原因内容])" + + // + "VALUES(@追溯代码,@返修原因代码,@返修原因内容)"; + + // OleDbParameter[] thisParms1 = new OleDbParameter[3]; + + // thisParms1[0] = new OleDbParameter("@追溯代码", OleDbType.Integer, 4, "追溯代码"); + // thisParms1[1] = new OleDbParameter("@返修原因代码", OleDbType.Integer, 4, "返修原因代码"); + // thisParms1[2] = new OleDbParameter("@返修原因内容", OleDbType.VarChar, 200, "返修原因内容"); + + // return DataAccess.ExecuteDataTable_OleDb_Insert_Access(sql, dt, ref thisParms1); + //} + } +} diff --git a/Common/07WebBusinessFacade/BusinessFacade/MES/BaseDataSystemMES.CartTrace.cs b/Common/07WebBusinessFacade/BusinessFacade/MES/BaseDataSystemMES.CartTrace.cs new file mode 100644 index 0000000..8080bc8 --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/MES/BaseDataSystemMES.CartTrace.cs @@ -0,0 +1,124 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Data; +using System.Data.SqlClient; + +using System.Data.OleDb; + + +using DataLinkMesWork; + +//using SystemFramework; + +namespace bizFacade +{ + /// + /// 关键零部件追溯 + /// + public partial class BaseDataSystemMES + { + /// + /// 删除追踪代码 + /// + /// + //public static void CartTraceCodeCheck(string opName, string TraceCode) + //{ + // string sql; + // sql = "DELETE FROM [MES_装配数据_零部件追溯] " + // + " where 追踪代码='" + TraceCode + "'"; + + // DataAccess.ExecuteSQL_OleDb_Access(sql); + // sql = "DELETE FROM [MES_装配数据_零部件追溯_数据主表] " + // + " where 追踪代码='" + TraceCode + "'"; + // DataAccess.ExecuteSQL_OleDb_Access(sql); + //} + /// + /// 删除追踪代码 + /// 对于曲轴活塞上线工位,如果[MES_装配数据_零部件追溯_数据主表] 中[追踪代码]数量大于3删除 + /// + /// + //public static void CartTraceCodeCheck_F3(string opName, string TraceCode) + //{ + // int count; + // string sql; + + // sql = "SELECT COUNT(*) FROM [MES_装配数据_零部件追溯] " + // + " where 追踪代码='" + TraceCode + "'" + // + " and 工位号='" + opName+"'"; + // DataAccess.ExecuteOutNum_OleDb_Access(sql, out count); + // if (count >= 3) + // { + // sql = "DELETE FROM [MES_装配数据_零部件追溯] " + // + " where 追踪代码='" + TraceCode + "'"; + + // DataAccess.ExecuteSQL_OleDb_Access(sql); + // sql = "DELETE FROM [MES_装配数据_零部件追溯_数据主表] " + // + " where 追踪代码='" + TraceCode + "'"; + // DataAccess.ExecuteSQL_OleDb_Access(sql); + // } + //} + /// + /// 更改物料[发动机号][追踪号码] + /// [MES_装配数据_零部件追溯_临时状态] + /// + /// + //public static void CartTraceCodeUpdate_TraceCode(string engineID, string traceCode) + //{ + // string sql; + // sql = "UPDATE [MES_装配数据_零部件追溯_临时状态] " + // + " SET 发动机号 = '" + engineID + "'" + // + ",追踪代码 = '" + traceCode + "'"; + // DataAccess.ExecuteSQL_OleDb_Access(sql); + //} + /// + /// [MES_装配数据_零部件追溯_临时状态] + /// + /// + //public static void CartTraceCodeSelect_TraceCode(out DataTable dt) + //{ + // string sql; + // sql = "SELECT TOP 1 * FROM [MES_装配数据_零部件追溯_临时状态] "; + // DataAccess.ExecuteDataTable_OleDb_Access(sql, out dt); + //} + /// + /// 更改物料[追踪号码] + /// [MES_装配数据_零部件追溯_临时状态] + /// + /// + //public static void CartTraceCodeUpdate(string opName, string TraceCode) + //{ + // string sql; + // sql = "UPDATE [MES_装配数据_零部件追溯_临时状态] " + // + " SET 发动机号 = '" + TraceCode + "'" + // + ",追踪代码 = '" + TraceCode + "'" + // + " where 工位号='" + opName + "'"; + // DataAccess.ExecuteSQL_OleDb_Access(sql); + //} + /// + /// 总线缸盖上线工位 + /// 根据[追踪号码]获得验证物料 + /// + /// + //public static void CartTraceCodeGetVerifyMaterial(string opName, string TraceCode, string opNameOtherFileName,out DataTable dt) + //{ + // string sql; + // sql = "SELECT * FROM [MES_装配数据_零部件追溯] " + // + " WHERE 追踪代码 = '" + TraceCode + "'" + // + " AND 工位号 = '" + opName + "'"; + // DataAccess.ExecuteDataTable_OleDb_Access(sql, opNameOtherFileName, out dt); + //} + /// + /// 总线缸盖上线工位 + /// 根据[追踪号码]获得全部验证物料 + /// + /// + //public static void CartTraceCodeGetMaterial(string opName, string TraceCode, string opNameOtherFileName, out DataTable dt) + //{ + // string sql; + // sql = "SELECT * FROM [MES_装配数据_零部件追溯] " + // + " WHERE 追踪代码 = '" + TraceCode + "'"; + // DataAccess.ExecuteDataTable_OleDb_Access(sql, opNameOtherFileName, out dt); + //} + } +} diff --git a/Common/07WebBusinessFacade/BusinessFacade/MES/BaseDataSystemMES.FalseOverGo.cs b/Common/07WebBusinessFacade/BusinessFacade/MES/BaseDataSystemMES.FalseOverGo.cs new file mode 100644 index 0000000..a40c130 --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/MES/BaseDataSystemMES.FalseOverGo.cs @@ -0,0 +1,34 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Data; +using System.Data.SqlClient; +using DataLinkMesWork; + +//using SystemFramework; + +namespace bizFacade +{ + public partial class BaseDataSystemMES + { + /// + /// 不合格放行 + /// 不合格需要返修工位,MES记录原因,并将信息记录到需要不合格越过工位。 + /// 工件到位读取发动机号后,读取不合格越过信息, + /// mes发送此信号到PLC,plc接收此信号后,才能不合格放行。 + /// DBX2.5 + /// 33 + /// + /// + //public static DataTable BaseData_tagTable_FalseOverGo(string opName) + //{ + // DataTable dt; + // string sql; + // sql = "SELECT TagID,0 as TagValue,TagName,工位号,数据来源,TagTypeID,TagLong,列位置,测量位置,变量类型代码,测量项目,TagAdr,TagAdrDemo FROM [MES_基本变量_原始数据] " + // + " where 变量类型代码 = 33 and 是否启用 = 1 " + // + " and 工位号='" + opName + "'"; + // DataAccess.ExecuteDataTable_OleDb_Access(sql, out dt); + // return dt; + //} + } +} diff --git a/Common/07WebBusinessFacade/BusinessFacade/MES/BaseDataSystemMES.FirstOpName.cs b/Common/07WebBusinessFacade/BusinessFacade/MES/BaseDataSystemMES.FirstOpName.cs new file mode 100644 index 0000000..e71b757 --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/MES/BaseDataSystemMES.FirstOpName.cs @@ -0,0 +1,52 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Data; +using System.Data.SqlClient; +using System.Data.OleDb; +using DataLinkMesWork; + + +//using SystemFramework; + +namespace bizFacade +{ + public partial class BaseDataSystemMES + { + /// + /// 1、测试发动机号合理:在表[MES_计划BOM_发动机号]中存在 + /// SELECT COUNT(*) FROM MES_计划BOM_发动机号 + /// Access + /// + /// + /// + /// + //public static bool EngineID_Select_Count(string EngineID, out int count) + //{ + // count = 0; + // string sql; + // sql = "SELECT COUNT(*) FROM MES_计划BOM_发动机号 " + // + " WHERE 发动机号 = '" + EngineID + "'"; + // return DataAccess.ExecuteOutNum_OleDb_Access(sql, out count); + //} + + + + /// + /// 根据订单号,确定订单基本内容 + /// 返回订单对应的一行记录 + /// [MES_计划BOM_订单计划下达] + /// Access 数据库 + /// + /// + /// + /// + //public static bool FirstOpNameTableGetOrderFormOnlyOneLine(string orderFrom,out DataTable dt) + //{ + // string sql; + // sql = "SELECT TOP 1 * FROM [MES_计划BOM_订单计划下达]" + // + " WHERE 订单号='" + orderFrom + "'"; + // return DataAccess.ExecuteDataTable_OleDb_Access(sql, out dt); + //} + } +} diff --git a/Common/07WebBusinessFacade/BusinessFacade/MES/BaseDataSystemMES.KeyPart.KeyPartAssemblyTempTable.cs b/Common/07WebBusinessFacade/BusinessFacade/MES/BaseDataSystemMES.KeyPart.KeyPartAssemblyTempTable.cs new file mode 100644 index 0000000..377fef8 --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/MES/BaseDataSystemMES.KeyPart.KeyPartAssemblyTempTable.cs @@ -0,0 +1,395 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Data; +using System.Data.SqlClient; + +using System.Data.OleDb; + + +using DataLinkMesWork; + +//using SystemFramework; + +namespace bizFacade +{ + /// + /// 关键零部件追溯 + /// + public partial class BaseDataSystemMES + { + /// + /// 创建增加数据用表 + /// 获得物料已经验证的记录 + /// + /// + /// + public static DataTable GetInsertTableMaterialVerifyOver(DataTable dt) + { + DataTable dt1; + DataRow row; + + dt1 = dt.Clone(); + + for (int i = 0; i < dt.Rows.Count; i++) + { + row = dt1.NewRow(); + for (int j = 0; j < dt.Columns.Count; j++) + { + row[j] = dt.Rows[i][j]; + } + if (Convert.ToInt32(row["验证结果"]) != 0) + { + dt1.Rows.Add(row); + } + + } + + return dt1; + } + /// + /// 创建增加数据用表 + /// + /// + /// + public static DataTable GetInsertTable(DataTable dt) + { + DataTable dt1; + DataRow row; + + dt1 = dt.Clone(); + + for (int i = 0; i < dt.Rows.Count; i++) + { + row = dt1.NewRow(); + for (int j = 0; j < dt.Columns.Count; j++) + { + row[j] = dt.Rows[i][j]; + } + dt1.Rows.Add(row); + + } + + return dt1; + } + + /// + /// MES_装配数据_零部件追溯_临时状态_增加 + /// + /// + /// + //public static void VerifyAssemblyPartTempTableInsert(DataTable dt) + //{ + // string sql; + // sql = "INSERT INTO [MES_装配数据_零部件追溯_临时状态]" + // + "([订单号],[SAP物料号],[发动机型号],[发动机型号代码], [发动机机型], " + // + "[发动机数量], [厂牌编号起始号], [客户名称],[投料日期],[文件编号],[集团名称],[通知号]," + // + "[功率],[指南文件编号],[装机状态],[适用状态],[物料描述],[计划下达日期],[计划完工日期]," + // + "[主配厂家],[工位号], [工位名称],[物料号], [零件图号], [零件名称], [零件数量]," + // + "[是否扫描],[扫描方式代码], [扫描方式], [厂家代码],[生产厂家], " + // + "[操作指导],[发动机号],[追踪代码],[物料号表索引号],[零件数量验证]," + // + "[物料条码], [物料条码物料号], [物料条码批次],[验证结果], [操作者工号], [操作者姓名], [班次代码], " + // + "物料来源代码,物料来源,是否禁用代码,是否禁用,被强制验证物料号,更改代码,更改原因)" + + // + "VALUES(@订单号,@SAP物料号,@发动机型号,@发动机型号代码,@发动机机型," + // + "@发动机数量,@厂牌编号起始号,@客户名称,@投料日期,@文件编号,@集团名称,@通知号," + // + "@功率,@指南文件编号,@装机状态,@适用状态,@物料描述,@计划下达日期,@计划完工日期," + // + "@主配厂家,@工位号,@工位名称,@物料号,@零件图号,@零件名称,@零件数量," + // + " @是否扫描,@扫描方式代码,@扫描方式,@厂家代码,@生产厂家," + // + "@操作指导,@发动机号,@追踪代码,@物料号表索引号,@零件数量验证," + // + "@物料条码,@物料条码物料号,@物料条码批次,@验证结果,@操作者工号,@操作者姓名,@班次代码," + // + "@物料来源代码,@物料来源,@是否禁用代码,@是否禁用,@被强制验证物料号,@更改代码,@更改原因)"; + + + // OleDbParameter[] thisParms1 = new OleDbParameter[50]; + // // + "([订单号],[SAP物料号],[发动机型号],[发动机型号代码], [发动机机型], " + // thisParms1[0] = new OleDbParameter("@订单号", OleDbType.VarChar, 50, "订单号"); + // thisParms1[1] = new OleDbParameter("@SAP物料号", OleDbType.VarChar, 50, "SAP物料号"); + // thisParms1[2] = new OleDbParameter("@发动机型号", OleDbType.VarChar, 50, "发动机型号"); + // thisParms1[3] = new OleDbParameter("@发动机型号代码", OleDbType.Integer, 4, "发动机型号代码"); + // thisParms1[4] = new OleDbParameter("@发动机机型", OleDbType.VarChar, 50, "发动机机型"); + + // // + "@发动机数量,@厂牌编号起始号,@客户名称,@投料日期,@文件编号,@集团名称,@通知号," + // thisParms1[5] = new OleDbParameter("@发动机数量", OleDbType.Integer, 4, "发动机数量"); + // thisParms1[6] = new OleDbParameter("@厂牌编号起始号", OleDbType.Integer, 4, "厂牌编号起始号"); + // thisParms1[7] = new OleDbParameter("@客户名称", OleDbType.VarChar, 50, "客户名称"); + // thisParms1[8] = new OleDbParameter("@投料日期", OleDbType.DBDate, 8, "投料日期"); + // thisParms1[9] = new OleDbParameter("@文件编号", OleDbType.VarChar, 50, "文件编号"); + // thisParms1[10] = new OleDbParameter("@集团名称", OleDbType.VarChar, 50, "集团名称"); + // thisParms1[11] = new OleDbParameter("@通知号", OleDbType.VarChar, 50, "通知号"); + + // // + "@功率,@指南文件编号,@装机状态,@适用状态,@物料描述,@计划下达日期,@计划完工日期," + // thisParms1[12] = new OleDbParameter("@功率", OleDbType.VarChar, 50, "功率"); + // thisParms1[13] = new OleDbParameter("@指南文件编号", OleDbType.VarChar, 50, "指南文件编号"); + // thisParms1[14] = new OleDbParameter("@装机状态", OleDbType.VarChar, 50, "装机状态"); + // thisParms1[15] = new OleDbParameter("@适用状态", OleDbType.DBDate, 8, "适用状态"); + // thisParms1[16] = new OleDbParameter("@物料描述", OleDbType.VarChar, 255, "物料描述"); + // thisParms1[17] = new OleDbParameter("@计划下达日期", OleDbType.DBDate, 8, "计划下达日期"); + // thisParms1[18] = new OleDbParameter("@计划完工日期", OleDbType.DBDate, 8, "计划完工日期"); + + // // + "@主配厂家,@工位号,@工位名称,@物料号,@零件图号,@零件名称,@零件数量," + + // thisParms1[19] = new OleDbParameter("@主配厂家", OleDbType.VarChar, 50, "主配厂家"); + // thisParms1[20] = new OleDbParameter("@工位号", OleDbType.VarChar, 50, "工位号"); + // thisParms1[21] = new OleDbParameter("@工位名称", OleDbType.VarChar, 50, "工位名称"); + // thisParms1[22] = new OleDbParameter("@物料号", OleDbType.VarChar, 50, "物料号"); + // thisParms1[23] = new OleDbParameter("@零件图号", OleDbType.VarChar, 50, "零件图号"); + // thisParms1[24] = new OleDbParameter("@零件名称", OleDbType.VarChar, 50, "零件名称"); + // thisParms1[25] = new OleDbParameter("@零件数量", OleDbType.Integer, 4, "零件数量"); + + // // +"[是否扫描],扫描方式代码, [扫描方式], [厂家代码],[生产厂家], " + + // thisParms1[26] = new OleDbParameter("@是否扫描", OleDbType.Integer, 4, "是否扫描"); + // thisParms1[27] = new OleDbParameter("@扫描方式代码", OleDbType.Integer, 4, "扫描方式代码"); + // thisParms1[28] = new OleDbParameter("@扫描方式", OleDbType.VarChar, 50, "扫描方式"); + // thisParms1[29] = new OleDbParameter("@厂家代码", OleDbType.VarChar, 50, "厂家代码"); + // thisParms1[30] = new OleDbParameter("@生产厂家", OleDbType.VarChar, 50, "生产厂家"); + + // //+ "@操作指导,@发动机号,@物料号表索引号,@零件数量验证," + + // thisParms1[31] = new OleDbParameter("@操作指导", OleDbType.VarChar, 255, "操作指导"); + // thisParms1[32] = new OleDbParameter("@发动机号", OleDbType.VarChar, 50, "发动机号"); + // thisParms1[33] = new OleDbParameter("@追踪代码", OleDbType.VarChar, 50, "追踪代码"); + // thisParms1[34] = new OleDbParameter("@物料号表索引号", OleDbType.Integer, 4, "物料号表索引号"); + // thisParms1[35] = new OleDbParameter("@零件数量验证", OleDbType.Integer, 4, "零件数量验证"); + + // // +"[物料条码], [物料条码物料号], [物料条码批次],@验证结果, [操作者工号], [操作者姓名], [班次代码], " + // thisParms1[36] = new OleDbParameter("@物料条码", OleDbType.VarChar, 50, "物料条码"); + // thisParms1[37] = new OleDbParameter("@物料条码物料号", OleDbType.VarChar, 50, "物料条码物料号"); + // thisParms1[38] = new OleDbParameter("@物料条码批次", OleDbType.VarChar, 50, "物料条码批次"); + // thisParms1[39] = new OleDbParameter("@验证结果", OleDbType.Integer, 4, "验证结果"); + // thisParms1[40] = new OleDbParameter("@操作者工号", OleDbType.VarChar, 50, "操作者工号"); + // thisParms1[41] = new OleDbParameter("@操作者姓名", OleDbType.VarChar, 50, "操作者姓名"); + // thisParms1[42] = new OleDbParameter("@班次代码", OleDbType.VarChar, 50, "班次代码"); + + // // +"物料来源代码,物料来源,是否禁用代码,是否禁用,被强制验证物料号,更改代码,更改原因)" + + // thisParms1[43] = new OleDbParameter("@物料来源代码", OleDbType.Integer, 4, "物料来源代码"); + // thisParms1[44] = new OleDbParameter("@物料来源", OleDbType.VarChar, 50, "物料来源"); + // thisParms1[45] = new OleDbParameter("@是否禁用代码", OleDbType.Integer, 4, "是否禁用代码"); + // thisParms1[46] = new OleDbParameter("@是否禁用", OleDbType.VarChar, 50, "是否禁用"); + // thisParms1[47] = new OleDbParameter("@被强制验证物料号", OleDbType.VarChar, 50, "被强制验证物料号"); + // thisParms1[48] = new OleDbParameter("@更改代码", OleDbType.VarChar, 50, "更改代码"); + // thisParms1[49] = new OleDbParameter("@更改原因", OleDbType.VarChar, 255, "更改原因"); + + // DataAccess.ExecuteDataTable_OleDb_Insert_Access(sql, dt, ref thisParms1); + //} + /// + /// MES_装配数据_零部件追溯_临时状态_删除 + /// + /// + //public static bool VerifyAssemblyPartTempTableDelete() + //{ + // string sql; + // sql = "DELETE FROM [MES_装配数据_零部件追溯_临时状态] "; + + // return DataAccess.ExecuteSQL_OleDb_Access(sql); + //} + /// + /// MES_装配数据_零部件追溯_临时状态_删除 + /// + /// + /// + /// + //public static bool VerifyAssemblyPartTempTableDelete(string engineNumber, string opName) + //{ + // string sql; + // sql = "DELETE FROM [MES_装配数据_零部件追溯_临时状态] " + // + " where 发动机号='" + engineNumber + "' " + // + " and 工位号='" + opName + "'"; + + // return DataAccess.ExecuteSQL_OleDb_Access(sql); + //} + /// + /// MES_装配数据_零部件追溯_临时状态 + /// 符合条件的行数 + /// + /// + //public static int VerifyAssemblyPartTempTableCount() + //{ + // int count; + // string sql; + // sql = "SELECT COUNT(*) FROM [MES_装配数据_零部件追溯_临时状态] "; + + // DataAccess.ExecuteOutNum_OleDb_Access(sql, out count); + // return count; + + //} + /// + /// MES_装配数据_零部件追溯_临时状态 + /// 符合条件的行数 + /// + /// + /// + //public static int VerifyAssemblyPartTempTableCountByEngineID(string engineID) + //{ + // int count; + // string sql; + // sql = "SELECT COUNT(*) FROM [MES_装配数据_零部件追溯_临时状态] " + // +" where 发动机号='" + engineID + "' "; + // DataAccess.ExecuteOutNum_OleDb_Access(sql, out count); + // return count; + + //} + /// + /// MES_装配数据_零部件追溯_临时状态 + /// 符合条件的行数 + /// + /// + /// + //public static int VerifyAssemblyPartTempTableCountByEngineTraceCode(string engineTraceCode) + //{ + // int count; + // string sql; + // sql = "SELECT COUNT(*) FROM [MES_装配数据_零部件追溯_临时状态] " + // +" where 追踪代码='" + engineTraceCode + "' "; + + // DataAccess.ExecuteOutNum_OleDb_Access(sql, out count); + // return count; + //} + ///// + ///// MES_装配数据_零部件追溯_临时状态 + ///// 符合条件的行数 + ///// + ///// + ///// + //public static int VerifyAssemblyPartTempTableCount(string engineNumber, string opName) + //{ + // int count; + // string sql; + // sql = "SELECT COUNT(*) FROM [MES_装配数据_零部件追溯_临时状态] " + // + " where 发动机号='" + engineNumber + "' " + // + " and 工位号='" + opName + "'"; + + // DataAccess.ExecuteOutNum_OleDb_Access(sql, out count); + // return count; + + //} + /// + /// MES_装配数据_零部件追溯_临时状态_选择 + /// + /// + //public static DataTable VerifyAssemblyPartTempTableSelect() + //{ + // string sql; + // DataTable dt; + // sql = "SELECT * FROM [MES_装配数据_零部件追溯_临时状态] "; + + // DataAccess.ExecuteDataTable_OleDb_Access(sql, out dt); + + // return dt; + //} + /// + /// MES_装配数据_零部件追溯_临时状态_更新 + /// + /// 物料号表索引号 + /// 物料条码 + /// 物料条码物料号 + /// 物料条码批次 + /// 验证结果 + /// + //public static bool VerifyAssemblyPartTempTableUpdate(int ID,string barCode, string barCode_Material, + // string barCode_SerailNumber, int materialVerifyResult) + //{ + // string sql; + // sql = "UPDATE [MES_装配数据_零部件追溯_临时状态] " + // + "SET 物料条码='" + barCode + "'" + // + ",物料条码物料号='" + barCode_Material + "'" + // + ",物料条码批次='" + barCode_SerailNumber + "'" + // + ",验证结果=" + materialVerifyResult.ToString() + // + " where ID=" + Convert.ToString(ID); + + // return DataAccess.ExecuteSQL_OleDb_Access(sql); + //} + + /// + /// MES_装配数据_零部件追溯_临时状态_更新 + /// + /// 物料号表索引号 + /// 发动机号 + /// 工位号 + /// 物料条码 + /// 物料条码物料号 + /// 物料条码批次 + /// 验证结果 + /// + //public static bool VerifyAssemblyPartTempTableUpdate(int materialIndex, string engineNumber, string opName, + // string barCode, string barCode_Material, string barCode_SerailNumber, int materialVerifyResult) + //{ + // string sql; + // sql = "UPDATE [MES_装配数据_零部件追溯_临时状态] " + // + "SET 物料条码='" + barCode + "'" + // + ",物料条码物料号='" + barCode_Material + "'" + // + ",物料条码批次='" + barCode_SerailNumber + "'" + // + ",验证结果=" + materialVerifyResult.ToString() + // + " where ID=" + materialIndex.ToString(); + // //sql = "UPDATE [MES_装配数据_零部件追溯_临时状态] " + // // + "SET 物料条码='" + barCode + "'" + // // + ",物料条码物料号='" + barCode_Material + "'" + // // + ",物料条码批次='" + barCode_SerailNumber + "'" + // // + ",验证结果=" + materialVerifyResult.ToString() + // // + " where 物料号表索引号=" + materialIndex.ToString(); + + // return DataAccess.ExecuteSQL_OleDb_Access(sql); + //} + + /// + /// MES_装配数据_零部件追溯_临时状态_更新 + /// + /// 物料号表索引号 + /// 物料条码 + /// 物料条码物料号 + /// 物料条码批次 + /// + /// + /// 验证结果 + /// + //public static bool VerifyAssemblyPartTempTableUpdate_New(int materialIndex, + // string barCode, string barCode_Material, string barCode_SerailNumber,string engineID,string traceCode, int materialVerifyResult) + //{ + // string sql; + // sql = "UPDATE [MES_装配数据_零部件追溯_临时状态] " + // + "SET 物料条码='" + barCode + "'" + // + ",物料条码物料号='" + barCode_Material + "'" + // + ",物料条码批次='" + barCode_SerailNumber + "'" + // + ",发动机号='" + engineID + "'" + // + ",追踪代码='" + traceCode + "'" + // + ",验证结果=" + materialVerifyResult.ToString() + // + ",操作时间='" + DateTime.Now.ToString("G")+"'" + // + " where ID=" + materialIndex.ToString(); + + // return DataAccess.ExecuteSQL_OleDb_Access(sql); + //} + /// + /// + /// + /// + /// + //public static bool VerifyAssemblyPartTempTableSelectByMainMaterialCode(out DataTable dt) + //{ + // dt = null; + // string sql; + // sql = "SELECT * FROM [MES_装配数据_零部件追溯_临时状态] WHERE 是否主物料 = 1"; + + // return DataAccess.ExecuteDataTable_OleDb_Access(sql, out dt); + //} + /// + /// MES_装配数据_零部件追溯_临时状态_更新 + /// 取消验证 + /// + /// ID + /// + //public static bool VerifyAssemblyPartTempTableUpdate(int ID) + //{ + // string sql; + // sql = "UPDATE [MES_装配数据_零部件追溯_临时状态] " + // + "SET 物料条码=''" + // + ",物料条码物料号=''" + // + ",物料条码批次=''" + // + ",验证结果=0 " + // + " where ID=" + Convert.ToString(ID); + + // return DataAccess.ExecuteSQL_OleDb_Access(sql); + //} + } +} diff --git a/Common/07WebBusinessFacade/BusinessFacade/MES/BaseDataSystemMES.Load.cs b/Common/07WebBusinessFacade/BusinessFacade/MES/BaseDataSystemMES.Load.cs new file mode 100644 index 0000000..b9e4487 --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/MES/BaseDataSystemMES.Load.cs @@ -0,0 +1,47 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Data; +using System.Data.SqlClient; +using DataLinkMesWork; + + +//using SystemFramework; + +namespace bizFacade +{ + partial class BaseDataSystemMES + { + + public static DataTable dt_Signal() + { + DataTable dt; + string sql; + sql = "SELECT [TagID],[TagName] ,[工位号],[数据来源],[IP],[TagTypeID],[TagLong]"+ + " ,[DbName],[变量类型],[变量地址] ,[变量其它],[演示偏移] ,[列位置],[测量位置] ,[测量项目],[测量单位],[变量类型代码],[变量类型名称]"+ + " ,[机体类型],[线体类型],[TagAdr],[TagAdrDemo],[是否启用],[监控组] ,[监控时间间隔],[OpcServer_OPNAME],[变量特点],[是否监控]"+ + " ,[变量排序] ,[工序能力],[监控属性代码],[测量位置短],[上限值],[下限值] ,[理论值],[IsGoodBad] ,[IsSaveToSql]"+ + " ,[IsWebSocket] FROM [MES_基本变量_原始数据]"; + DataAccess.ExecuteDataTable(sql, out dt); + return dt; + } + + public static DataTable dt_Device() + { + DataTable dt; + string sql; + sql = "SELECT [设备IP] ,[设备类型],[是否启用] FROM [MES_基本变量设备类型对应表]"; + DataAccess.ExecuteDataTable(sql, out dt); + return dt; + } + + public static DataTable dt_TagTypeDataType() + { + DataTable dt; + string sql; + sql = "SELECT TOP (1000) [序号],[变量类型],[TagTypeDataType],[TagName],[变量类型代码],[TagTypeChange],[MesTagTypeChange],[WebTagTypeChange],[信号点名称][变量类型名称] FROM [MES_基本变量变量类型代码]"; + DataAccess.ExecuteDataTable(sql, out dt); + return dt; + } + } +} diff --git a/Common/07WebBusinessFacade/BusinessFacade/MES/BaseDataSystemMES.Login.cs b/Common/07WebBusinessFacade/BusinessFacade/MES/BaseDataSystemMES.Login.cs new file mode 100644 index 0000000..fbac0bf --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/MES/BaseDataSystemMES.Login.cs @@ -0,0 +1,76 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Data; +using System.Data.SqlClient; +using DataLinkMesWork; + + +//using SystemFramework; + +namespace bizFacade +{ + public partial class BaseDataSystemMES + { + /// + /// û룬֤¼Ϣ + /// + /// + /// + /// + /// + //public static bool GetUserName(string userName,string password,out DataTable dt) + //{ + // //string errorMessage; + // string sql; + // sql = "SELECT top 1 * FROM [MES__û] " + // + "where ߹='" + userName + "'" + // + " and ='" + password + "'" ; + // return DataAccess.ExecuteDataTable_OleDb_Access(sql, out dt); + // //SQLCommon.ExecuteDataTable_OleDb(sql, ApplicationConfig.ConnectionString_Access, out dt, out errorMessage); + //} + /// + /// û + /// + /// + /// + /// + //public static bool UpdateUserName(string userName, string password) + //{ + // //string errorMessage; + // string sql; + // sql = "UPDATE [MES__û] " + // + "SET ='" + password+"'" + // + "where ߹='" + userName + "'"; + // return DataAccess.ExecuteSQL_OleDb_Access(sql); + // //return SQLCommon.ExecuteNonQuery_OleDb(sql, ApplicationConfig.ConnectionString_Access, out errorMessage); + //} + + /// + /// MES__¼ + /// + /// λ + /// ߹ + /// + /// δ + /// ¼˳ (=1¼) (=0˳) + /// + //public static bool InsertLoginAndLogoutUserName(string opName, string operatorCode, + // string operatorName,int operatorShift, int LogType) + //{ + // //string errorMessage; + // string sql; + // sql = "INSERT INTO [MES__û] ([λ], [߹], [], [δ], [¼˳])" + // + "VALUES(" + // + "'" + opName + "'," + // + "'" + operatorCode + "'," + // + "'" + operatorName + "'," + // + operatorShift.ToString() + "," + // + LogType.ToString() + // + ")"; + // return DataAccess.ExecuteSQL_OleDb_Access(sql); + + // // return SQLCommon.ExecuteNonQuery_OleDb(sql, ApplicationConfig.ConnectionString_Access, out errorMessage); + //} + } +} diff --git a/Common/07WebBusinessFacade/BusinessFacade/MES/BaseDataSystemMES.MOBY.cs b/Common/07WebBusinessFacade/BusinessFacade/MES/BaseDataSystemMES.MOBY.cs new file mode 100644 index 0000000..39f3bf1 --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/MES/BaseDataSystemMES.MOBY.cs @@ -0,0 +1,98 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Data; +using System.Data.SqlClient; +using DataLinkMesWork; + + +//using SystemFramework; + +namespace bizFacade +{ + public partial class BaseDataSystemMES + { + /// + /// MES__DBݽṹ_ѯ + /// + public static DataTable MobyDataStructureSelect() + { + DataTable dt; + string sql; + sql = "SELECT * FROM MES__DBݽṹ ORDER BY [] "; + DataAccess.ExecuteDataTable(sql, out dt); + return dt; + } + + /// + /// MES_ģMOBY_ + /// һ̨ + /// ظ̨ + /// + public static DataTable MobyInsert() + { + DataTable dt; + string procedureName; + procedureName = "MES_ģMOBY_"; + DataAccess.ExecuteStoredProcedure(procedureName, out dt); + return dt; + } + + /// + /// MES_ģMOBY_ѯ + /// + /// + /// + public static DataTable MobySelect(string engineNumber) + { + DataTable dt; + string procedureName; + procedureName = "MES_ģMOBY_ѯ"; + SqlParameter[] thisParms = new SqlParameter[1]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@", engineNumber); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out dt); + return dt; + } + + /// + /// MES_ģMOBY_ѯ + /// + /// + /// + /// + /// + public static void MobyUpdate(string engineNumber, int number, string tagValue) + { + string procedureName; + procedureName = "MES_ģMOBY_ѯ"; + SqlParameter[] thisParms = new SqlParameter[3]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@", engineNumber); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@", engineNumber); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@ֵ", engineNumber); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + return; + } + /// + /// MES_ģMOBY_޸ + /// =27 λ + /// + /// + /// + /// + public static void MobyUpdate(string engineNumber, string tagValue) + { + int number; + + number = 27; + + string procedureName; + procedureName = "MES_ģMOBY_޸"; + SqlParameter[] thisParms = new SqlParameter[3]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@", engineNumber); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@", number); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@ֵ", tagValue); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + return; + } + } +} diff --git a/Common/07WebBusinessFacade/BusinessFacade/MES/BaseDataSystemMES.MaterialList.cs b/Common/07WebBusinessFacade/BusinessFacade/MES/BaseDataSystemMES.MaterialList.cs new file mode 100644 index 0000000..865bd2b --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/MES/BaseDataSystemMES.MaterialList.cs @@ -0,0 +1,216 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Data; +using System.Data.SqlClient; +using System.Data.OleDb; +using DataLinkMesWork; + +//using SystemFramework; + +namespace bizFacade +{ + public partial class BaseDataSystemMES + { + ///// + ///// MES_计划BOM_发动机号 + ///// 获得订单号 + ///// + ///// + //static public void WorkPositionGuidOnLine_OrderForm(out DataTable dt) + //{ + // string sql; + // sql = "SELECT distinct 订单号 from MES_计划BOM_订单计划下达_执行顺序 "; + // DataAccess.ExecuteDataTable_OleDb_Access(sql, out dt); + //} + ///// + ///// 物料清单 + ///// 根据ID号获得物料清单 + ///// 一行 + ///// + ///// + ///// + //static public void WorkPositionGuidOnLine_MaterialList(int ID, out DataTable dt) + //{ + // string sql; + + // sql = "SELECT [订单号], [SAP物料号], [发动机型号], [发动机型号代码], [发动机机型]," + + // "[发动机数量], [厂牌编号起始号], [客户名称], [投料日期], [文件编号], [集团名称], [通知号], " + + // "[功率], [指南文件编号], [装机状态], [适用状态], [物料描述],[计划下达日期], [计划完工日期],[实际完成日期],[实际结束日期],[操作时间]," + + // "[主配厂家],[工位号], [工位名称], [物料号], [零件图号], [零件名称], [零件数量],[是否扫描],扫描方式,[厂家代码], [生产厂家], " + + // "[操作指导],[工位基本操作指导],[工位基本指导图片],[日计划产量], [工位操作指导],[工位指导图片],[物料来源代码],[是否禁用代码],[被强制验证物料号],更改代码,更改原因" + + // " FROM MES_计划BOM_订单计划下达 " + + // " WHERE ID =" + Convert.ToString(ID); + + // DataAccess.ExecuteDataTable_OleDb_Access(sql, out dt); + //} + + ///// + ///// 物料清单 + ///// 根据订单号和工位号 + ///// + ///// + ///// + ///// + //static public void WorkPositionGuidOnLine_MaterialList(string orderForm, string opName, out DataTable dt) + //{ + // string sql; + // //sql = "SELECT [ID], [订单号], [SAP物料号], [发动机型号], [发动机型号代码], [发动机机型]," + + // // "[发动机数量], [厂牌编号起始号], [客户名称], [投料日期], [文件编号], [集团名称], [通知号], " + + // // "[功率], [指南文件编号], [装机状态], [适用状态], [物料描述],[计划下达日期], [计划完工日期],[实际完成日期],[实际结束日期],[操作时间], " + + // // "[主配厂家],[工位号], [工位名称], [物料号], [零件图号], [零件名称], [零件数量],[是否扫描],d.扫描方式代码,d.扫描方式,[厂家代码], [生产厂家], " + + // // "[操作指导],[工位基本操作指导],[工位基本指导图片],[日计划产量], [工位操作指导],[工位指导图片],b.物料来源代码, b.物料来源, a.是否禁用代码, a.是否禁用,被强制验证物料号,更改代码,更改原因 " + // // + " FROM MES_计划BOM_订单计划下达_扫描方式 AS d INNER JOIN (MES_计划BOM_订单计划下达_是否禁用 AS a INNER JOIN (MES_计划BOM_订单计划下达_物料来源 AS b INNER JOIN MES_计划BOM_订单计划下达 AS c ON b.物料来源代码 = c.物料来源代码) ON a.是否禁用代码 = c.是否禁用代码) ON c.扫描方式=d.扫描方式代码 " + // // + " WHERE 订单号 ='" + orderForm + "'" + // // + " AND 工位号 = '" + opName + "' " + // // + " ORDER BY 物料号 "; + // sql = " SELECT a.订单号, a.执行顺序,a.SAP物料号,a.发动机型号,a.发动机型号代码,a.发动机机型," + // + "a.发动机数量,a.厂牌编号起始号,a.客户名称,a.投料日期,a.文件编号,a.集团名称,a.通知号,a.功率," + // + "a.指南文件编号,a.装机状态,a.适用状态,a.物料描述,a.计划下达日期,a.计划完工日期,a.实际完成日期," + // + "a.实际结束日期,a.完成情况代码,a.完成数量,a.订单完成日期 ," + // + "b.主配厂家, b.工位号, b.工位名称, b.物料号,b.零件图号,b.零件名称,b.零件数量," + // + "b.是否扫描,b.扫描方式,b.是否主物料,b.厂家代码,b.生产厂家,b.操作指导,b.物料来源代码," + // + "b.是否禁用代码,b.被强制验证物料号,b.更改代码,b.更改原因," + // + "c.工位基本指导图片,d.工位操作指导, d.工位指导图片 " + // + " FROM MES_计划BOM_订单计划下达_执行顺序 AS a INNER JOIN " + // + "(MES_计划BOM_工位操作指南 AS d INNER JOIN " + // + "(MES_计划BOM_发动机装配指南 AS b INNER JOIN MES_计划BOM_工位基本指导 AS c ON b.工位号 = c.工位号)" + // + "ON d.工位号 = b.工位号) ON a.订单号 = b.订单号" + // + " WHERE a.发动机型号代码=d.发动机型号代码 " + // + " AND a.订单号 = '" + orderForm + "' " + // + " AND b.工位号 = '" + opName + "' " + // + " ORDER BY 物料号 "; + // DataAccess.ExecuteDataTable_OleDb_Access(sql, out dt); + //} + ///// + ///// 0090 F2 分线缸盖上线工位 + ///// 1、缸盖到位后,显示该工位的操作指南,物料表和物料验证表 + ///// 2、扫描缸盖,验证缸盖物料号 + ///// 3、扫描“物料追踪号” + ///// 4、保存“物料追踪号”和缸盖号到缸盖需要验证的工位 + ///// + ///// + //static public void WorkPositionGuidOnLine_MaterialList_F2(out DataTable dt, out string engineID) + //{ + // //订单号 + // string orderForm; + // //发动机号 + // engineID = null; + // string sql; + // string whereStr = " WHERE c.ID <> 0 "; + // string order = " ORDER BY d.是否优先代码 DESC, a.执行顺序, c.发动机号 "; + // sql = "SELECT a.订单号, a.执行顺序, a.计划下达日期, a.订单完成日期, b.完成情况代码, b.完成情况, " + // + " c.ID, c.发动机号, c.发动机型号代码,c.发动机机型, c.投料日期, c.人员代码, c.班次, " + // + " c.是否优先代码, c.是否装配代码, c.装配日期, d.是否优先代码, d.是否优先, e.是否装配代码, e.是否装配" + // + " FROM (((MES_计划BOM_订单计划下达_执行顺序 AS a INNER JOIN MES_计划BOM_订单计划下达_完成情况 AS b ON a.完成情况代码 = b.完成情况代码) INNER JOIN MES_计划BOM_发动机号 AS c ON a.订单号 = c.订单号) INNER JOIN MES_计划BOM_发动机号_是否优先 AS d ON c.是否优先代码 = d.是否优先代码) INNER JOIN MES_计划BOM_发动机号_是否装配 AS e ON c.是否装配代码 = e.是否装配代码 "; + // whereStr = whereStr + " and e.是否装配代码 = 0"; + // sql = sql + whereStr + order; + // DataAccess.ExecuteDataTable_OleDb_Access(sql, out dt); + // if (dt != null) + // { + // if (dt.Rows.Count > 0) + // { + // orderForm = dt.Rows[0]["订单号"].ToString(); + // engineID = dt.Rows[0]["发动机号"].ToString(); + // WorkPositionGuidOnLine_MaterialList(orderForm, ApplicationConfig.OpName, out dt); + // } + // } + //} + ///// + ///// 根据追踪代码(挂牌号)获得物料表 + /////六:分线缸盖半自动工位流程:MachineType=“S”,ScannerType = “1”, + /////OpType=“P2”, OpNameMainLine=“OP0000”(总线缸盖上线工位) + /////1:PLC向MES发送工件到位,开始扫描信号。WorkStart=1 + /////2:扫描追踪代码(挂牌号) + /////3:通过OpNameMainLine(总线缸盖上线工位)工位数据表和本工位的装配指南, + /////获得当前工位的装配指南,订单号、缸盖号、机型、机型标志。 + /////4:显示订单号、缸盖号、机型、机型标志 + /////5:显示装配指南和被验证物料 + /////6:MES向PLC写入发动机号、机型、机型标志、追踪代码 + /////7:MES向PLC写入MES激发变量扫描完成,EngineGetOver=1 + /////8:验证物料。 + /////9:物料验证完成,MES向PLC写入MES激发变量物料验证完毕信号,MaterialVerifyOver=1。 + /////10:PLC向MES发送工件离开信号WorkStart=0, + /////保存数据发动机号、机型、机型标志、追踪代码到OpNameMainLine(总线缸盖上线工位)工位数据表中, + /////完成工件当日计数和工作开始时间和结束时间。 + ///// + ///// + //static public void WorkPositionGuidOnLine_MaterialList_P2(string opName, string orderForm, out DataTable dt) + //{ + // ////物料追踪数据库来源 + // //string OpNameOther=null; + // //////物料追踪数据库保存 + // ////string OpNameMainLine; + // ////订单号 + // //string orderForm=null; + // string sql; + // //sql = "SELECT * FROM [MES_装配数据_零部件追溯_数据主表] " + // // + " WHERE 追踪代码='" + traceCode+"'"; + // //DataAccess.ExecuteDataTable_OleDb_Access(sql,ApplicationConfig.OpNameOtherFileName, out dt); + // //if (dt == null) return; + // //if (dt.Rows.Count > 0) + // //{ + // // orderForm = dt.Rows[0]["订单号"].ToString(); + // //} + // ////物料清单 + + // sql = "SELECT [ID], [订单号], [SAP物料号], [发动机型号], [发动机型号代码], [发动机机型]," + + // "[发动机数量], [厂牌编号起始号], [客户名称], [投料日期], [文件编号], [集团名称], [通知号], " + + // "[功率], [指南文件编号], [装机状态], [适用状态], [物料描述],[计划下达日期], [计划完工日期],[实际完成日期],[实际结束日期],[操作时间], " + + // "[主配厂家],[工位号], [工位名称], [物料号], [零件图号], [零件名称], [零件数量],[是否扫描],d.扫描方式代码,d.扫描方式,[厂家代码], [生产厂家], " + + // "[操作指导],[工位基本操作指导],[工位基本指导图片],[日计划产量], [工位操作指导],[工位指导图片],b.物料来源代码, b.物料来源, a.是否禁用代码, a.是否禁用,被强制验证物料号,更改代码,更改原因 " + // + " FROM MES_计划BOM_订单计划下达_扫描方式 AS d INNER JOIN (MES_计划BOM_订单计划下达_是否禁用 AS a INNER JOIN (MES_计划BOM_订单计划下达_物料来源 AS b INNER JOIN MES_计划BOM_订单计划下达 AS c ON b.物料来源代码 = c.物料来源代码) ON a.是否禁用代码 = c.是否禁用代码) ON c.扫描方式=d.扫描方式代码 " + // + " WHERE 订单号 ='" + orderForm + "'" + // + " AND 工位号 = '" + opName + "' " + // + " ORDER BY 物料号 "; + + // DataAccess.ExecuteDataTable_OleDb_Access(sql, out dt); + //} + /// + /// 根据订单号和工位获得装配指南信息 + /// [MES_计划BOM_订单计划下达] + /// + /// 订单号 + /// 工位号 + /// 是验证物料还是全部物料 + /// + //public static DataTable GetMaterialListBak(string orderForm, string OpName, bool isVerify) + //{ + // string errorMessage; + // DataTable dt; + // string sql; + // if (isVerify) + // { + // sql = "SELECT [ID], [订单号], [SAP物料号], [发动机型号], [发动机型号代码], [发动机机型]," + + // "[发动机数量], [厂牌编号起始号], [客户名称], [投料日期], [文件编号], [集团名称], [通知号], " + + // "[功率], [指南文件编号], [装机状态], [适用状态], [物料描述],[计划下达日期], [计划完工日期]," + + // "[主配厂家],[工位号], [工位名称], [物料号], [零件图号], [零件名称], [零件数量],[是否扫描],d.扫描方式代码,d.扫描方式,[厂家代码], [生产厂家], " + + // "[操作指导],'' as 发动机号,'' as 追踪代码,0 as 物料号表索引号,0 as 零件数量验证," + // + "'' as 物料条码,'' as 物料条码物料号,'' as 物料条码批次,0 as 验证结果," + // + "'' as 操作者工号,'' as 操作者姓名,'' as 班次代码," + // + "b.物料来源代码, b.物料来源, a.是否禁用代码, a.是否禁用,被强制验证物料号,更改代码,更改原因 " + // + " FROM MES_计划BOM_订单计划下达_扫描方式 AS d INNER JOIN (MES_计划BOM_订单计划下达_是否禁用 AS a INNER JOIN (MES_计划BOM_订单计划下达_物料来源 AS b INNER JOIN MES_计划BOM_订单计划下达 AS c ON b.物料来源代码 = c.物料来源代码) ON a.是否禁用代码 = c.是否禁用代码) ON c.扫描方式=d.扫描方式代码 " + // + "where 订单号='" + orderForm + "'" + // + "and 工位号='" + OpName + "' and a.是否禁用代码 = 0 and 是否扫描 <> 0 " + // + " ORDER BY 物料号 "; + // } + // else + // { + // sql = "SELECT [ID],[订单号], [SAP物料号], [发动机型号], [发动机型号代码], [发动机机型]," + + // "[发动机数量], [厂牌编号起始号], [客户名称], [投料日期], [文件编号], [集团名称], [通知号], " + + // "[功率], [指南文件编号], [装机状态], [适用状态], [物料描述],[计划下达日期], [计划完工日期]," + + // "[主配厂家],[工位号], [工位名称], [物料号], [零件图号], [零件名称], [零件数量],[是否扫描],d.扫描方式代码,d.扫描方式,[厂家代码], [生产厂家], " + + // "[操作指导],'' as 发动机号,0 as 物料号表索引号,0 as 零件数量验证," + // + "'' as 物料条码,'' as 物料条码物料号,'' as 物料条码批次,0 as 验证结果," + // + "'' as 操作者工号,'' as 操作者姓名,'' as 班次代码," + // + "b.物料来源代码, b.物料来源, a.是否禁用代码, a.是否禁用,被强制验证物料号,更改代码,更改原因 " + // + " FROM MES_计划BOM_订单计划下达_扫描方式 AS d INNER JOIN (MES_计划BOM_订单计划下达_是否禁用 AS a INNER JOIN (MES_计划BOM_订单计划下达_物料来源 AS b INNER JOIN MES_计划BOM_订单计划下达 AS c ON b.物料来源代码 = c.物料来源代码) ON a.是否禁用代码 = c.是否禁用代码) ON c.扫描方式=d.扫描方式代码 " + // + "where 订单号='" + orderForm + "'" + // + "and 工位号='" + OpName + "' and a.是否禁用代码 = 0 " + // + " ORDER BY 物料号 "; + // } + // SQLCommon.ExecuteDataTable_OleDb(sql, ApplicationConfig.ConnectionString_Access, out dt, out errorMessage); + // return dt; + //} + } +} diff --git a/Common/07WebBusinessFacade/BusinessFacade/MES/BaseDataSystemMES.MaterialVerifyManagement.cs b/Common/07WebBusinessFacade/BusinessFacade/MES/BaseDataSystemMES.MaterialVerifyManagement.cs new file mode 100644 index 0000000..f0f4b29 --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/MES/BaseDataSystemMES.MaterialVerifyManagement.cs @@ -0,0 +1,232 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Data; +using System.Data.SqlClient; +using System.Data.OleDb; +using DataLinkMesWork; + + +//using SystemFramework; + +namespace bizFacade +{ + public partial class BaseDataSystemMES + { + /// + /// 增加,[MES_装配数据_零部件追溯_临时状态_缺省物料] + /// + /// 物料条码 + //static public void DefaultMaterialBarCodeInsert(string barCode) + //{ + // string sql; + // sql = "INSERT INTO [MES_装配数据_零部件追溯_临时状态_缺省物料] (物料条码)" + // +"VALUES('"+barCode+"')"; + // DataAccess.ExecuteSQL_OleDb_Access(sql); + //} + /// + /// 修改,[MES_装配数据_零部件追溯_临时状态_缺省物料] + /// + /// + /// + //static public void DefaultMaterialBarCodeUpdate(string ID,string barCode) + //{ + // string sql; + // sql = "UPDATE [MES_装配数据_零部件追溯_临时状态_缺省物料] " + // + "SET 物料条码 = '" + barCode + "'" + // + "WHERE ID = "+ID.ToString(); + // DataAccess.ExecuteSQL_OleDb_Access(sql); + //} + /// + /// 删除 + /// [MES_装配数据_零部件追溯_临时状态_缺省物料] + /// + /// + //static public void DefaultMaterialBarCodeDelete(string ID) + //{ + // string sql; + // sql = "DELETE FROM [MES_装配数据_零部件追溯_临时状态_缺省物料] " + // + "WHERE ID = " + ID.ToString(); + // DataAccess.ExecuteSQL_OleDb_Access(sql); + //} + /// + /// 获得 [MES_装配数据_零部件追溯_临时状态_缺省物料] + /// + /// + //static public void DefaultMaterialBarCodeSelect(out DataTable dt) + //{ + // string sql; + // sql = "SELECT * FROM [MES_装配数据_零部件追溯_临时状态_缺省物料] "; + // DataAccess.ExecuteDataTable_OleDb_Access(sql, out dt); + //} + /// + /// 强制验证物料删除,要将原物料设置为启用状态 + /// + /// + //static public void WorkPositionGuidOnLine_MaterialUpdateByMaterrial(string materialNumberVerify) + //{ + // string sql; + // sql = "UPDATE MES_计划BOM_订单计划下达 SET 是否禁用代码=0 WHERE 物料号='" + materialNumberVerify+"'"; + + // DataAccess.ExecuteSQL_OleDb_Access(sql); + //} + /// + /// 物料禁用 + /// + /// + //static public void WorkPositionGuidOnLine_MaterialNoUsing(int ID) + //{ + // string sql; + // sql = "UPDATE MES_计划BOM_订单计划下达 SET 是否禁用代码=1 WHERE ID=" + Convert.ToString(ID); + + // DataAccess.ExecuteSQL_OleDb_Access(sql); + //} + /// + /// 物料启用 + /// + /// + //static public void WorkPositionGuidOnLine_MaterialUsing(int ID) + //{ + // string sql; + // sql = "UPDATE MES_计划BOM_订单计划下达 SET 是否禁用代码=0 WHERE ID=" + Convert.ToString(ID); + + // DataAccess.ExecuteSQL_OleDb_Access(sql); + //} + + /// + /// 订单号, 发动机型号, 发动机类型, 发动机数量 + /// + /// + /// + //static public void WorkPositionGuidOnLine_OrderForm(string orderForm, out DataTable dt) + //{ + // string sql; + // sql = "SELECT distinct 订单号, 发动机型号, 发动机机型, 发动机数量, 客户名称,投料日期,计划下达日期 " + // + "FROM MES_计划BOM_订单计划下达_执行顺序 WHERE 订单号='" + // + orderForm + "'"; + + // DataAccess.ExecuteDataTable_OleDb_Access(sql, out dt); + //} + + + + /// + /// MES_计划BOM_订单计划下达_扫描方式 + /// + /// + //static public void WorkPositionGuidOnLine_MaterialVerifyID(out DataTable dt) + //{ + // string sql; + // sql = "SELECT 扫描方式代码,扫描方式 from MES_计划BOM_订单计划下达_扫描方式 "; + // DataAccess.ExecuteDataTable_OleDb_Access(sql, out dt); + //} + /// + /// MES_计划BOM_订单计划下达_物料来源 + /// + /// + //static public void WorkPositionGuidOnLine_MaterialComeFrom(out DataTable dt) + //{ + // string sql; + // sql = "SELECT 物料来源代码,物料来源 from MES_计划BOM_订单计划下达_物料来源 "; + // DataAccess.ExecuteDataTable_OleDb_Access(sql, out dt); + //} + /// + /// MES_计划BOM_订单计划下达_是否禁用 + /// + /// + //static public void WorkPositionGuidOnLine_MaterialIsUsing(out DataTable dt) + //{ + // string sql; + // sql = "SELECT 是否禁用代码,是否禁用 from MES_计划BOM_订单计划下达_是否禁用 "; + // DataAccess.ExecuteDataTable_OleDb_Access(sql, out dt); + //} + + /// + /// 物料验证 + /// 删除新物料 + /// + /// + //static public void WorkPositionGuidOnLine_NewMaterial_Delete(int ID) + //{ + // string sql; + // sql = "DELETE FROM MES_计划BOM_订单计划下达 WHERE ID=" + Convert.ToString(ID); + + // DataAccess.ExecuteSQL_OleDb_Access(sql); + //} + + /// + /// 物料验证 + /// 添加新物料 + /// + /// + //static public bool WorkPositionGuidOnLine_NewMaterial_Insert(DataTable dt) + //{ + // string sql; + // sql = + // "INSERT INTO [MES_计划BOM_订单计划下达]" + + // "([订单号], [SAP物料号], [发动机型号], [发动机型号代码], [发动机机型]," + + // "[发动机数量], [厂牌编号起始号], [客户名称], [投料日期], [文件编号], [集团名称], [通知号], " + + // "[功率], [指南文件编号], [装机状态], [适用状态], [物料描述],[计划下达日期], [计划完工日期],[实际完成日期],[实际结束日期],[操作时间], " + + // "[主配厂家],[工位号], [工位名称], [物料号], [零件图号], [零件名称], [零件数量],[是否扫描],[扫描方式],[厂家代码], [生产厂家], " + + // "[操作指导],[工位基本操作指导],[工位基本指导图片],[日计划产量], [工位操作指导],[工位指导图片],[物料来源代码],[是否禁用代码],[被强制验证物料号],更改代码,更改原因)" + + // "VALUES(@订单号,@SAP物料号,@发动机型号,@发动机型号代码,@发动机机型," + + // "@发动机数量,@厂牌编号起始号,@客户名称,@投料日期,@文件编号,@集团名称,@通知号," + + // "@功率,@指南文件编号,@装机状态,@适用状态,@物料描述,@计划下达日期,@计划完工日期,@实际完成日期,@实际结束日期,@操作时间," + + // "@主配厂家,@工位号,@工位名称,@物料号,@零件图号,@零件名称,@零件数量,@是否扫描,@扫描方式,@厂家代码,@生产厂家," + + // "@操作指导,@工位基本操作指导,@工位基本指导图片,@日计划产量,@工位操作指导,@工位指导图片,@物料来源代码,@是否禁用代码,@被强制验证物料号,@更改代码,@更改原因)"; + // OleDbParameter[] thisParms = new OleDbParameter[44]; + // thisParms[0] = new OleDbParameter("@订单号", OleDbType.VarChar, 50, "订单号"); + // thisParms[1] = new OleDbParameter("@SAP物料号", OleDbType.VarChar, 50, "SAP物料号"); + // thisParms[2] = new OleDbParameter("@发动机型号", OleDbType.VarChar, 50, "发动机型号"); + // thisParms[3] = new OleDbParameter("@发动机型号代码", OleDbType.Integer, 4, "发动机型号代码"); + // thisParms[4] = new OleDbParameter("@发动机机型", OleDbType.VarChar, 50, "发动机机型"); + + // thisParms[5] = new OleDbParameter("@发动机数量", OleDbType.Integer, 4, "发动机数量"); + // thisParms[6] = new OleDbParameter("@厂牌编号起始号", OleDbType.Integer, 4, "厂牌编号起始号"); + // thisParms[7] = new OleDbParameter("@客户名称", OleDbType.VarChar, 255, "客户名称"); + // thisParms[8] = new OleDbParameter("@投料日期", OleDbType.DBDate, 8, "投料日期"); + // thisParms[9] = new OleDbParameter("@文件编号", OleDbType.VarChar, 50, "文件编号"); + // thisParms[10] = new OleDbParameter("@集团名称", OleDbType.VarChar, 255, "集团名称"); + // thisParms[11] = new OleDbParameter("@通知号", OleDbType.VarChar, 50, "通知号"); + + // thisParms[12] = new OleDbParameter("@功率", OleDbType.VarChar, 50, "功率"); + // thisParms[13] = new OleDbParameter("@指南文件编号", OleDbType.VarChar, 50, "指南文件编号"); + // thisParms[14] = new OleDbParameter("@装机状态", OleDbType.VarChar, 50, "装机状态"); + // thisParms[15] = new OleDbParameter("@适用状态", OleDbType.VarChar, 50, "适用状态"); + // thisParms[16] = new OleDbParameter("@物料描述", OleDbType.VarChar, 255, "物料描述"); + // thisParms[17] = new OleDbParameter("@计划下达日期", OleDbType.DBDate, 8, "计划下达日期"); + // thisParms[18] = new OleDbParameter("@计划完工日期", OleDbType.DBDate, 8, "计划完工日期"); + // thisParms[19] = new OleDbParameter("@实际完成日期", OleDbType.DBDate, 8, "实际完成日期"); + // thisParms[20] = new OleDbParameter("@实际结束日期", OleDbType.DBDate, 8, "实际结束日期"); + // thisParms[21] = new OleDbParameter("@操作时间", OleDbType.DBDate, 8, "操作时间"); + + // thisParms[22] = new OleDbParameter("@主配厂家", OleDbType.VarChar, 50, "主配厂家"); + // thisParms[23] = new OleDbParameter("@工位号", OleDbType.VarChar, 50, "工位号"); + // thisParms[24] = new OleDbParameter("@工位名称", OleDbType.VarChar, 255, "工位名称"); + // thisParms[25] = new OleDbParameter("@物料号", OleDbType.VarChar, 50, "物料号"); + // thisParms[26] = new OleDbParameter("@零件图号", OleDbType.VarChar, 50, "零件图号"); + // thisParms[27] = new OleDbParameter("@零件名称", OleDbType.VarChar, 255, "零件名称"); + // thisParms[28] = new OleDbParameter("@零件数量", OleDbType.Integer, 4, "零件数量"); + // thisParms[29] = new OleDbParameter("@是否扫描", OleDbType.Integer, 4, "是否扫描"); + // thisParms[30] = new OleDbParameter("@扫描方式", OleDbType.Integer, 4, "扫描方式"); + // thisParms[31] = new OleDbParameter("@厂家代码", OleDbType.VarChar, 255, "厂家代码"); + // thisParms[32] = new OleDbParameter("@生产厂家", OleDbType.VarChar, 255, "生产厂家"); + + + // thisParms[33] = new OleDbParameter("@操作指导", OleDbType.VarChar, 255, "操作指导"); + // thisParms[34] = new OleDbParameter("@工位基本操作指导", OleDbType.VarChar, 255, "工位基本操作指导"); + // thisParms[35] = new OleDbParameter("@工位基本指导图片", OleDbType.VarBinary, 10000000, "工位基本指导图片"); + // thisParms[36] = new OleDbParameter("@日计划产量", OleDbType.Integer, 4, "日计划产量"); + // thisParms[37] = new OleDbParameter("@工位操作指导", OleDbType.VarChar, 255, "工位操作指导"); + // thisParms[38] = new OleDbParameter("@工位指导图片", OleDbType.VarBinary, 10000000, "工位指导图片"); + + // thisParms[39] = new OleDbParameter("@物料来源代码", OleDbType.Integer, 4, "物料来源代码"); + // thisParms[40] = new OleDbParameter("@是否禁用代码", OleDbType.Integer, 4, "是否禁用代码"); + // thisParms[41] = new OleDbParameter("@被强制验证物料号", OleDbType.VarChar, 255, "被强制验证物料号"); + // thisParms[42] = new OleDbParameter("@更改代码", OleDbType.VarChar, 255, "更改代码"); + // thisParms[43] = new OleDbParameter("@更改原因", OleDbType.VarChar, 255, "更改原因"); + + // return DataAccess.ExecuteDataTable_OleDb_Insert_Access(sql, dt, ref thisParms); + //} + } +} diff --git a/Common/07WebBusinessFacade/BusinessFacade/MES/BaseDataSystemMES.MesOverGo.cs b/Common/07WebBusinessFacade/BusinessFacade/MES/BaseDataSystemMES.MesOverGo.cs new file mode 100644 index 0000000..74ce578 --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/MES/BaseDataSystemMES.MesOverGo.cs @@ -0,0 +1,33 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Data; +using System.Data.SqlClient; +using DataLinkMesWork; + + +//using SystemFramework; + +namespace bizFacade +{ + public partial class BaseDataSystemMES + { + /// + /// MES放行 + /// 装配工作无法正常进行,MES填写放行原因,向PLC发送此信号,请求放行,plc接收此信号后才能安不合格流程放行 + /// DBX2.6 + /// 34 + /// + /// + //public static DataTable BaseData_tagTable_MesOverGo(string opName) + //{ + // DataTable dt; + // string sql; + // sql = "SELECT TagID,0 as TagValue,TagName,工位号,数据来源,TagTypeID,TagLong,列位置,测量位置,变量类型代码,测量项目,TagAdr,TagAdrDemo FROM [MES_基本变量_原始数据] " + // + " where 变量类型代码 = 34 and 是否启用 = 1 " + // + " and 工位号='" + opName + "'"; + // DataAccess.ExecuteDataTable_OleDb_Access(sql, out dt); + // return dt; + //} + } +} diff --git a/Common/07WebBusinessFacade/BusinessFacade/MES/BaseDataSystemMES.MesServer.cs b/Common/07WebBusinessFacade/BusinessFacade/MES/BaseDataSystemMES.MesServer.cs new file mode 100644 index 0000000..498df39 --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/MES/BaseDataSystemMES.MesServer.cs @@ -0,0 +1,56 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Data; +using System.Data.SqlClient; +using DataLinkMesWork; + + +//using SystemFramework; + +namespace bizFacade +{ + partial class BaseDataSystemMES + { + /// + /// 查询MesServerCode + /// + /// + public static DataTable GetMesServerCodeFromMIS() + { + DataTable dt; + string sql; + sql = "exec MES_计划BOM_工位与名称_查询应用程序"; + DataAccess.ExecuteDataTable(sql, out dt); + return dt; + } + + + /// + /// 查询工步属性 + /// + /// + public static DataTable GetworkStepPropertyFromMIS() + { + DataTable dt; + string sql; + sql = "SELECT distinct 工位号,工步属性 FROM [MES_计划BOM_工位与名称] where 是否监控=1"; + DataAccess.ExecuteDataTable(sql, out dt); + return dt; + } + + /// + /// 查询返修工位号 + /// + /// + public static DataTable GetOpNameRepairFromMIS() + { + DataTable dt; + string sql; + sql = "SELECT distinct 工位号,返修工位号 FROM [MES_计划BOM_工位与名称] where 是否监控=1"; + DataAccess.ExecuteDataTable(sql, out dt); + return dt; + } + + } +} diff --git a/Common/07WebBusinessFacade/BusinessFacade/MES/BaseDataSystemMES.ProduceCount.cs b/Common/07WebBusinessFacade/BusinessFacade/MES/BaseDataSystemMES.ProduceCount.cs new file mode 100644 index 0000000..f2afd7d --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/MES/BaseDataSystemMES.ProduceCount.cs @@ -0,0 +1,73 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Data; +using System.Data.SqlClient; +using DataLinkMesWork; +//using SystemFramework; + +namespace bizFacade +{ + partial class BaseDataSystemMES + { + /// + /// [MES_计划BOM_发动机号] + /// SET 是否装配代码=1 + /// + /// + //public static bool BaseData_tagTable_EngineID_UpDate(string EngineID) + //{ + // string sql; + // sql = "UPDATE MES_计划BOM_发动机号 " + // + "SET 是否装配代码=1" + // + " ,装配日期=CDATE('" + DateTime.Now.ToString("G") + // + "') " + // + " WHERE 发动机号='" + EngineID + "'"; + // return DataAccess.ExecuteSQL_OleDb_Access(sql); + //} + + /// + /// [MES_装配数据_工件到位离开时间_保留本地] + /// 计算当前日期装配的发动机数量 + /// + /// + //public static int BaseData_tagTable_EngineID_Count() + //{ + // int count; + // string sql; + // sql = "SELECT COUNT(*) FROM [MES_装配数据_工件到位离开时间_保留本地] " + // + "WHERE 计数日期=CDATE('" + DateTime.Now.ToString("d") + "')" + // + " AND 是否合格 = 1"; + // DataAccess.ExecuteOutNum_OleDb_Access(sql, out count); + // return count; + //} + + + //static public void ProduceCountInsert() + //{ + // string sql; + // sql = "INSERT INTO MES_装配数据_实际产量(实际产量) VALUES(1)"; + // DataAccess.ExecuteSQL_OleDb_Access(sql); + //} + //static public void ProduceCountDelete() + //{ + // string sql; + // sql = "DELETE FROM MES_装配数据_实际产量 WHERE 生产日期<>CDATE('" + DateTime.Now.ToString("d") + "')"; + // DataAccess.ExecuteSQL_OleDb_Access(sql); + //} + //static public void ProduceCountSelect(out DataTable dt) + //{ + // string sql; + // sql = "SELECT * FROM MES_装配数据_实际产量 WHERE 生产日期=CDATE('" + DateTime.Now.ToString("d") + "')"; + // DataAccess.ExecuteDataTable_OleDb_Access(sql, out dt); + //} + //static public void ProduceCountUpdate(int count) + //{ + // string sql; + // sql = "UPDATE MES_装配数据_实际产量 " + // + " SET 实际产量=" + count.ToString() + // + " WHERE 生产日期=CDATE('" + DateTime.Now.ToString("d") + "')"; + // DataAccess.ExecuteSQL_OleDb_Access(sql); + //} + } +} diff --git a/Common/07WebBusinessFacade/BusinessFacade/MES/BaseDataSystemMES.SubLineOpName.cs b/Common/07WebBusinessFacade/BusinessFacade/MES/BaseDataSystemMES.SubLineOpName.cs new file mode 100644 index 0000000..ff57baf --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/MES/BaseDataSystemMES.SubLineOpName.cs @@ -0,0 +1,58 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Data; +using System.Data.SqlClient; + +using System.Data.OleDb; + + +using DataLinkMesWork; + +//using SystemFramework; + +namespace bizFacade +{ + /// + /// 关键零部件追溯 + /// + public partial class BaseDataSystemMES + { + /// + /// SELECT * FROM MES_计划BOM_工位与名称 + /// + /// + //static public void GetOpNameDataForMIS(out DataTable dt) + //{ + // string sql; + // sql = "SELECT * FROM MES_计划BOM_工位与名称 "; + // DataAccess.ExecuteDataTable_OleDb_Access(sql, out dt); + //} + /// + /// 根据工位获得分线可以保存“物料追踪”的工位 + /// + /// + /// + //static public void SubLineOpName(string opName,out DataTable dt) + //{ + // string lineName; + // dt = null; + // string sql; + // sql = "SELECT 线体类型 FROM MES_计划BOM_工位与名称 " + // + "WHERE 工位号 = '" + opName+"'"; + // DataAccess.ExecuteDataTable_OleDb_Access(sql, out dt); + // if (dt != null) + // { + // if (dt.Rows.Count > 0) + // { + // lineName = dt.Rows[0]["线体类型"].ToString(); + // sql = "SELECT DISTINCT 文件名称 FROM FROM MES_计划BOM_工位与名称 " + // + "WHERE 线体类型 = '" + lineName + "'" + // +" AND PC =1 "; + // DataAccess.ExecuteDataTable_OleDb_Access(sql, out dt); + // } + // } + + //} + } +} diff --git a/Common/07WebBusinessFacade/BusinessFacade/MES/BaseDataSystemMES.WorkSheet.cs b/Common/07WebBusinessFacade/BusinessFacade/MES/BaseDataSystemMES.WorkSheet.cs new file mode 100644 index 0000000..5234d5a --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/MES/BaseDataSystemMES.WorkSheet.cs @@ -0,0 +1,75 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Data; +using System.Data.SqlClient; +using DataLinkMesWork; + + +//using SystemFramework; + +namespace bizFacade +{ + public partial class BaseDataSystemMES + { + /// + /// û룬֤¼Ϣ + /// + /// + /// + //public static bool GetWorkSheet(out DataTable dt) + //{ + // //string errorMessage; + // string sql; + // sql = "SELECT * FROM [MES__] "; + // return DataAccess.ExecuteDataTable_OleDb_Access(sql, out dt); + + //} + /// + /// + /// + /// + /// + /// + //public static bool GetOperatorCode(string operatorCode,out DataTable dt) + //{ + // //string errorMessage; + // string sql; + // sql = "SELECT * FROM [MES__û] " + // + " WHERE ߹='" + operatorCode+"'"; + // return DataAccess.ExecuteDataTable_OleDb_Access(sql, out dt); + + //} + /// + /// Ƿǣ߹ + /// + /// + /// + //public static bool GetOperatorCode(string operatorCode) + //{ + // //string errorMessage; + // DataTable dt; + // string sql; + + + // sql = "SELECT * FROM [MES__û] " + // + " WHERE ߹='" + operatorCode + "'"; + + // if (DataAccess.ExecuteDataTable_OleDb_Access(sql, out dt)) + // { + // if (dt.Rows.Count > 0) + // { + // return true; + // } + // else + // { + // return false; + // } + // } + // else + // { + // return false; + // } + //} + } +} diff --git a/Common/07WebBusinessFacade/BusinessFacade/MES/BaseDataSystemMES.cs b/Common/07WebBusinessFacade/BusinessFacade/MES/BaseDataSystemMES.cs new file mode 100644 index 0000000..a2cb19a --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/MES/BaseDataSystemMES.cs @@ -0,0 +1,224 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Data; +using System.Data.SqlClient; +using DataLinkMesWork; +//using SystemFramework; + +namespace bizFacade +{ + public partial class BaseDataSystemMES + { + /// + /// ݹλ + /// + /// + /// + public static string GetAllWorkPositionNameForMIS(string positionID) + { + string positionIDName = ""; + string errorMessage; + DataTable dt; + string sql; + sql = "SELECT top 1 λ FROM MES_ƻBOM_λ " + + "where λ='" + positionID + "'"; + //if (!SQLCommon.SqlServerConnectionStatus) + //{ + // SQLCommon.ExecuteDataTable_OleDb(sql, ApplicationConfig.ConnectionString_Access, out dt, out errorMessage); + //} + //else + { + DataAccess.ExecuteDataTable(sql, out dt); + } + if (dt == null) return positionIDName; + if (dt.Rows.Count > 0) + { + positionIDName = dt.Rows[0]["λ"].ToString(); + } + return positionIDName; + + } + /// + /// ݹλŻùλ + /// + /// + /// + public static string GetWorkPositionNameByWorkPositionID(string positionID) + { + string positionIDName = ""; + string errorMessage; + DataTable dt; + string sql; + sql = "SELECT top 1 λ FROM MES_ƻBOM_λ " + + "where λ='" + positionID + "'"; + //if (!SQLCommon.SqlServerConnectionStatus) + //{ + // SQLCommon.ExecuteDataTable_OleDb(sql, ApplicationConfig.ConnectionString_Access, out dt, out errorMessage); + //} + //else + { + DataAccess.ExecuteDataTable(sql, out dt); + } + if (dt == null) return positionIDName; + if (dt.Rows.Count > 0) + { + positionIDName = dt.Rows[0]["λ"].ToString(); + } + return positionIDName; + + } + /// + /// ݶŻöϢ + /// + /// + /// + //public static DataTable GetOrderFormPlanByOrderForm(string OrderForm) + //{ + // string errorMessage; + // DataTable dt; + // string sql; + // sql = "SELECT TOP 1 * FROM [MES_ƻBOM_ƻ´] " + // + "where ='" + OrderForm + "'"; + // SQLCommon.ExecuteDataTable_OleDb(sql, ApplicationConfig.ConnectionString_Access, out dt, out errorMessage); + // MaterialData.dt_OrderFormPlan = dt; + // return dt; + //} + /// + /// ݶŻùλָϢ + /// + /// λ + /// + /// + //public static DataTable GetWorkPositionGuidByOrderForm(string OrderForm,string OpName) + //{ + // string errorMessage; + // DataTable dt; + // string sql; + // sql = "SELECT TOP 1 λָ,λָͼƬ FROM [MES_ƻBOM_ƻ´] " + // + "where λ='" + OpName + "'" + // + " and ='" + OrderForm + "'" + // + " order by ʱ desc "; + // SQLCommon.ExecuteDataTable_OleDb(sql, ApplicationConfig.ConnectionString_Access, out dt, out errorMessage); + + // return dt; + //} + /// + /// ݷŻװָϢ + /// + /// + /// + /// + //public static DataTable GetAssemblyListByEngineNumber(string orderForm, string OpName) + //{ + // string errorMessage; + // DataTable dt; + // string sql; + // //sql = "SELECT * " + // sql = "SELECT [ID],[], [SAPϺ], [ͺ], [ͺŴ], []," + + // "[], [Ʊʼ], [ͻ], [Ͷ], [ļ], [], [֪ͨ], " + + // "[], [ָļ], [װ״̬], [״̬], [],[ƻ´], [ƻ깤]," + + // "[䳧],[λ], [λ], [Ϻ], [ͼ], [], [],[Ƿɨ],d.ɨ跽ʽ,d.ɨ跽ʽ,[Ҵ], [], " + + // "[ָ],'' as ,0 as Ϻű,0 as ֤," + // + "'' as ,'' as Ϻ,'' as ,0 as ֤," + // + "'' as ߹,'' as ,'' as δ," + // + "b.Դ, b.Դ, a.Ƿô, a.Ƿ,ǿ֤Ϻ,Ĵ,ԭ " + // + " FROM MES_ƻBOM_ƻ´_ɨ跽ʽ AS d INNER JOIN (MES_ƻBOM_ƻ´_Ƿ AS a INNER JOIN (MES_ƻBOM_ƻ´_Դ AS b INNER JOIN MES_ƻBOM_ƻ´ AS c ON b.Դ = c.Դ) ON a.Ƿô = c.Ƿô) ON c.ɨ跽ʽ=d.ɨ跽ʽ " + // + "where ='" + orderForm + "'" + // + "and λ='" + OpName + "' and a.Ƿô = 0 " + // + " ORDER BY Ϻ "; + // SQLCommon.ExecuteDataTable_OleDb(sql, ApplicationConfig.ConnectionString_Access, out dt, out errorMessage); + // return dt; + //} + /// + /// ݷŻװָϢ + /// + /// + /// + /// + //public static DataTable GetAssemblyListForVerifyByEngineNumber(string orderForm, string OpName) + //{ + // string errorMessage; + // DataTable dt; + // string sql; + // sql = "SELECT [ID], [], [SAPϺ], [ͺ], [ͺŴ], []," + + // "[], [Ʊʼ], [ͻ], [Ͷ], [ļ], [], [֪ͨ], " + + // "[], [ָļ], [װ״̬], [״̬], [],[ƻ´], [ƻ깤]," + + // "[䳧],[λ], [λ], [Ϻ], [ͼ], [], [],[Ƿɨ],d.ɨ跽ʽ,d.ɨ跽ʽ,[Ҵ], [], " + + // "[ָ],'' as ,'' as ׷ٴ,0 as Ϻű,0 as ֤," + // + "'' as ,'' as Ϻ,'' as ,0 as ֤," + // + "'' as ߹,'' as ,'' as δ," + // + "b.Դ, b.Դ, a.Ƿô, a.Ƿ,ǿ֤Ϻ,Ĵ,ԭ " + // + " FROM MES_ƻBOM_ƻ´_ɨ跽ʽ AS d INNER JOIN (MES_ƻBOM_ƻ´_Ƿ AS a INNER JOIN (MES_ƻBOM_ƻ´_Դ AS b INNER JOIN MES_ƻBOM_ƻ´ AS c ON b.Դ = c.Դ) ON a.Ƿô = c.Ƿô) ON c.ɨ跽ʽ=d.ɨ跽ʽ " + // + "where ='" + orderForm + "'" + // + "and λ='" + OpName + "' and a.Ƿô = 0 and Ƿɨ = 1 " + // + " ORDER BY Ϻ "; + // SQLCommon.ExecuteDataTable_OleDb(sql, ApplicationConfig.ConnectionString_Access, out dt, out errorMessage); + // return dt; + //} + + /// + /// ݷŻװָϢ + /// + /// + /// + /// + //public static DataTable GetAssemblyListForVerifyByEngineNumber_F3(string orderForm, string OpName) + //{ + // string errorMessage; + // DataTable dt; + // string sql; + // sql = "SELECT [ID], [], [SAPϺ], [ͺ], [ͺŴ], []," + + // "[], [Ʊʼ], [ͻ], [Ͷ], [ļ], [], [֪ͨ], " + + // "[], [ָļ], [װ״̬], [״̬], [],[ƻ´], [ƻ깤]," + + // "[䳧],[λ], [λ], [Ϻ], [ͼ], [], [],[Ƿɨ],d.ɨ跽ʽ,d.ɨ跽ʽ,[Ҵ], [], " + + // "[ָ],'' as ,'' as ׷ٴ,0 as Ϻű,0 as ֤," + // + "'' as ,'' as Ϻ,'' as ,0 as ֤," + // + "'' as ߹,'' as ,'' as δ," + // + "b.Դ, b.Դ, a.Ƿô, a.Ƿ,ǿ֤Ϻ,Ĵ,ԭ " + // + " FROM MES_ƻBOM_ƻ´_ɨ跽ʽ AS d INNER JOIN (MES_ƻBOM_ƻ´_Ƿ AS a INNER JOIN (MES_ƻBOM_ƻ´_Դ AS b INNER JOIN MES_ƻBOM_ƻ´ AS c ON b.Դ = c.Դ) ON a.Ƿô = c.Ƿô) ON c.ɨ跽ʽ=d.ɨ跽ʽ " + // + "where ='" + orderForm + "'" + // + "and λ='" + OpName + "' and a.Ƿô = 0 and Ƿɨ = 2 "// + // + " ORDER BY Ϻ "; + // SQLCommon.ExecuteDataTable_OleDb(sql, ApplicationConfig.ConnectionString_Access, out dt, out errorMessage); + // return dt; + //} + ///// + ///// =1 Accessݿ =0 SQL Server + ///// + //static int OpcServerIsAccess = 1; + /// + /// Ӽƻл÷Ϣ + /// + //public static DataTable PruducePlanGetEngineNumber() + //{ + // string errorMessage; + // DataTable dt; + // string sql; + // sql = "SELECT top 1 * FROM [MES_ƻBOM_] order by Ͷ,"; + // SQLCommon.ExecuteDataTable_OleDb(sql, ApplicationConfig.ConnectionString_Access, out dt, out errorMessage); + // MaterialData.dt_EngineNumber = dt; + + // return dt; + //} + + /// + /// λָͼƬ + /// + /// λ + /// + public static DataTable GetWorkPositionBasicGuidPictureByOpName(string OpName) + { + //string errorMessage; + DataTable dt; + string sql; + sql = "SELECT TOP 1 λָͼƬ FROM [MES_ƻBOM_λָ] " + + "where λ='" + OpName + "'"; + DataAccess.ExecuteDataTable(sql, out dt); + //BizDataAccess.DataAccess.ExecuteDataTable_OleDb_Access(sql, out dt); + + return dt; + } + + } +} diff --git a/Common/07WebBusinessFacade/BusinessFacade/MES/MES.Biz.Config.cs b/Common/07WebBusinessFacade/BusinessFacade/MES/MES.Biz.Config.cs new file mode 100644 index 0000000..5ae48f0 --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/MES/MES.Biz.Config.cs @@ -0,0 +1,196 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Data; +using System.Data.SqlClient; +using DataLinkMesWork; +using System.Data.OleDb; +using System.Collections; + +//using SystemFramework; + +namespace bizFacade +{ + public partial class BaseDataSystemMES + { + ///// + ///// 从Access配置表中读取程序配置信息 + ///// + ///// + //public static void InitConfig(string opName) + //{ + + // DataTable dt; + // string sql; + // sql = " SELECT * FROM MES_计划BOM_工位与名称 WHERE 工位号='" + opName + "'"; + // DataAccess.ExecuteDataTable_OleDb_Access(sql, out dt); + // if (dt == null) return; + // if (dt.Rows.Count < 1) return; + // try + // { + // //0032 + // ApplicationConfig.ConnectionString_Access_OpNameMainLine = dt.Rows[0]["总线上线工位数据文件连接"].ToString(); + // } + // catch { ApplicationConfig.ConnectionString_Access_OpNameMainLine = ""; } + // try + // { + // //0033 + // ApplicationConfig.ConnectionString_Access_OpNameTraceCode = dt.Rows[0]["分线物料追踪工位数据文件连接"].ToString(); + // } + // catch { ApplicationConfig.ConnectionString_Access_OpNameTraceCode = ""; } + // try + // { + // ApplicationConfig.OpNameGuid = dt.Rows[0]["指南工位号"].ToString(); + // } + // catch { ApplicationConfig.OpNameGuid = ""; } + // //try + // //{ + // // //0051 + // // ApplicationConfig.OpNameOther = dt.Rows[0]["总线被监测工位"].ToString(); + // //} + // //catch { ApplicationConfig.OpNameOther = ""; } + // try + // { + // //0052 + // ApplicationConfig.OpNameMainLine = dt.Rows[0]["总线上线工位"].ToString(); + // } + // catch { ApplicationConfig.OpNameMainLine = ""; } + // try + // { + // //0053 + // ApplicationConfig.OpNameTraceCode = dt.Rows[0]["分线物料追踪工位"].ToString(); + // } + // catch { ApplicationConfig.OpNameTraceCode = ""; } + // //try + // //{ + // // //0080 + // // ApplicationConfig.ScannerType = dt.Rows[0]["扫描枪类型"].ToString(); + // //} + // //catch { ApplicationConfig.ScannerType = "0"; } + // try + // { + // //0081 + // ApplicationConfig.MachineType = dt.Rows[0]["机床类型"].ToString(); + // } + // catch { ApplicationConfig.MachineType = "S"; } + // try + // { + // //0090 + // ApplicationConfig.OpType = dt.Rows[0]["工位类型"].ToString(); + // } + // catch { ApplicationConfig.OpType = "P1"; } + // try + // { + // //0170 + // ApplicationConfig.OpcServer = dt.Rows[0]["OpcServer"].ToString().Trim(); + // } + // catch { ApplicationConfig.OpcServer = ""; } + // try + // { + // //0170 + // ApplicationConfig.OpcServer_MIS = dt.Rows[0]["OpcServer_MIS"].ToString().Trim(); + // } + // catch { ApplicationConfig.OpcServer_MIS = ""; } + // try + // { + // //0170 + // ApplicationConfig.CycleTargetCycleTime = Convert.ToInt32(dt.Rows[0]["目标循环时间"]); + // } + // catch { ApplicationConfig.CycleTargetCycleTime = 0; } + // try + // { + // //0190 + // ApplicationConfig.PartType = dt.Rows[0]["工件类型"].ToString(); + // } + // catch { ApplicationConfig.PartType = ""; } + // try + // { + // //0190 + // ApplicationConfig.Password = dt.Rows[0]["退出密码"].ToString(); + // } + // catch { ApplicationConfig.Password = ""; } + + // try + // { + // //0190 + // ApplicationConfig.LeaderCode = dt.Rows[0]["领班工号"].ToString(); + // } + // catch { ApplicationConfig.LeaderCode = ""; } + + // if (ApplicationConfig.OpType == "F102") + // { + // sql = " SELECT * FROM MES_计划BOM_工位与名称 WHERE 工位号='" + ApplicationConfig.OpNameOther + "'"; + // DataAccess.ExecuteDataTable_OleDb_Access(sql, out dt); + // if (dt != null) + // { + // if (dt.Rows.Count > 0) + // { + // try + // { + // ApplicationConfig.OpcServerOther = dt.Rows[0]["OpcServer"].ToString(); + // } + // catch { } + // } + // } + // } + //} + + //private static void GetBarCodeCommand(out DataTable dt) + //{ + // string sql = " SELECT * FROM [MES_基本数据_条码命令] "; + // DataAccess.ExecuteDataTable_OleDb_Access(sql, out dt); + //} + + /// + /// + /// + /// + //public static void GetBarCodeCommand_RepareReason(out DataTable dt) + //{ + // string sql = " SELECT * FROM [MES_基本数据_条码命令] WHERE 命令说明='返修原因'"; + // DataAccess.ExecuteDataTable_OleDb_Access(sql, out dt); + //} + /// + /// + /// + /// + public static Hashtable Get_hashtableBarCodeCommand() + { + DataTable dt = new DataTable(); + Hashtable hashtableBarCodeCommand; + hashtableBarCodeCommand = new Hashtable(); + //GetBarCodeCommand(out dt); + for (int i = 0; i < dt.Rows.Count; i++) + { + hashtableBarCodeCommand.Add(dt.Rows[i]["命令条码"], dt.Rows[i]["命令代码"]); + + } + + return hashtableBarCodeCommand; + + + + } + /// + /// + /// + /// + public static Hashtable Get_hashtableBarCodeCommand_RepareReason() + { + DataTable dt = new DataTable (); + Hashtable hashtableBarCodeCommand; + hashtableBarCodeCommand = new Hashtable(); + //GetBarCodeCommand(out dt); + for (int i = 0; i < dt.Rows.Count; i++) + { + hashtableBarCodeCommand.Add(dt.Rows[i]["命令代码"], dt.Rows[i]["命令功能"]); + + } + + return hashtableBarCodeCommand; + + + + } + } +} diff --git a/Common/07WebBusinessFacade/BusinessFacade/MES/MES.Biz.MaterialList.cs b/Common/07WebBusinessFacade/BusinessFacade/MES/MES.Biz.MaterialList.cs new file mode 100644 index 0000000..a96b892 --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/MES/MES.Biz.MaterialList.cs @@ -0,0 +1,298 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Data; +using System.Data.SqlClient; +using System.Data.OleDb; +using DataLinkMesWork; +using System.Collections; + +//using SystemFramework; + +namespace bizFacade +{ + public partial class BaseDataSystemMES + { + + /// + /// + /// [MES_基本变量_厂家代码] + /// + /// + //public static Hashtable GetFatoryCodeHashtable() + //{ + // //厂家代码 + // string fatoryCode; + // //三位码 + // string threeCode; + // Hashtable fatoryCodeHashtable; + // fatoryCodeHashtable = new Hashtable (); + // DataTable dt; + // string sql; + // sql = "SELECT * FROM MES_基本变量_厂家代码 "; + // DataAccess.ExecuteDataTable_OleDb_Access(sql, out dt); + // for (int i = 0; i < dt.Rows.Count; i++) + // { + + // if (Convert.IsDBNull(dt.Rows[i]["厂家代码"])) + // { + // fatoryCode = ""; + // } + // else + // { + // fatoryCode = dt.Rows[i]["厂家代码"].ToString(); + // } + + // if (Convert.IsDBNull(dt.Rows[i]["三位码"])) + // { + // threeCode = ""; + // } + // else + // { + // threeCode = dt.Rows[i]["三位码"].ToString(); + // } + + // fatoryCodeHashtable.Add(fatoryCode, threeCode); + + // } + // return fatoryCodeHashtable; + //} + /// + /// 根据订单号和工位获得主物料号 + /// [MES_计划BOM_发动机装配指南] + /// + /// 订单号 + /// 工位号 + /// + public static string GetMainMaterialCode(string orderForm, string OpName) + { + string mainMaterialNumber=""; + DataTable dt; + string sql; + sql = "SELECT * FROM MES_计划BOM_发动机装配指南 " + + " WHERE 订单号 = '" + orderForm + "'" + + " AND 工位号 = '" + OpName + "'" + + " AND 是否主物料= 1"; + //if (!SQLCommon.SqlServerConnectionStatus) + //{ + // DataAccess.ExecuteDataTable_OleDb_Access(sql, out dt); + //} + //else + { + DataAccess.ExecuteDataTable(sql, out dt); + } + if (dt == null) + { + mainMaterialNumber = ""; + } + if (dt.Rows.Count > 0) + { + mainMaterialNumber = dt.Rows[0]["物料号"].ToString().Trim(); + } + return mainMaterialNumber; + } + + /// + /// 根据订单号和工位获得装配指南信息 + /// [MES_计划BOM_订单计划下达] + /// 同步通讯,从SqlServer数据库获得 + /// 异步通讯,从Access数据库获得 + /// + /// 订单号 + /// 工位号 + /// (true 是验证物料)(false 是全部物料) + /// + public static DataTable GetMaterialList(string orderForm, string OpName, bool isVerify) + { + string errorMessage; + DataTable dt; + string sql; + if (isVerify) + { + sql = "SELECT [ID], [订单号], " + + "[主配厂家],[工位号], [工位名称], [物料号], [零件图号], [零件名称], [零件数量],[是否扫描],d.扫描方式代码,d.扫描方式,[是否主物料],[厂家代码], [生产厂家], " + + "[操作指导],'' as 发动机号,'' as 追踪代码,'' as 主物料号,0 as 物料号表索引号,0 as 零件数量验证," + + "'' as 物料条码,'' as 物料条码物料号,'' as 物料条码批次,0 as 验证结果," + + "'' as 操作者工号,'' as 操作者姓名,'' as 班次代码," + + "b.物料来源代码, b.物料来源, a.是否禁用代码, a.是否禁用,被强制验证物料号,更改代码,更改原因 " + + " FROM MES_计划BOM_订单计划下达_扫描方式 AS d INNER JOIN (MES_计划BOM_订单计划下达_是否禁用 AS a INNER JOIN (MES_计划BOM_订单计划下达_物料来源 AS b INNER JOIN MES_计划BOM_发动机装配指南 AS c ON b.物料来源代码 = c.物料来源代码) ON a.是否禁用代码 = c.是否禁用代码) ON c.扫描方式=d.扫描方式代码 " + + "where 订单号='" + orderForm + "'" + + "and 工位号='" + OpName + "' and a.是否禁用代码 = 0 and 是否扫描 <> 0 " + + " ORDER BY 物料号 "; + + sql = "SELECT [ID],[订单号]," + + "[主配厂家],[工位号], [工位名称], [物料号], [零件图号], [零件名称],[零件数量]," + + "[是否扫描],扫描方式 as 扫描方式代码,'' as 扫描方式,是否主物料,[厂家代码], [生产厂家], " + + "'' as 操作指导,'' as 发动机号,'' as 追踪代码,'' as 主物料号,0 as 物料号表索引号,0 as 零件数量验证," + + "'' as 物料条码,'' as 物料条码物料号,'' as 物料条码批次,0 as 验证结果,'' as 操作者工号,'' as 操作者姓名,'' as 班次代码," + + " 物料来源代码,'' as 物料来源,是否禁用代码,'' as 是否禁用, 被强制验证物料号,更改代码,更改原因" + + " from MES_计划BOM_发动机装配指南" + + " where 是否扫描 <> 0" + + " and 订单号='" + orderForm + "'" + +"and 工位号='" + OpName + "'"; + + // + "([订单号]," + //+ "[主配厂家],[工位号], [工位名称],[物料号], [零件图号], [零件名称], [零件数量]," + //+ "[是否扫描],[扫描方式代码], [扫描方式],[是否主物料], [厂家代码],[生产厂家], " + //+ "[操作指导],[发动机号],[追踪代码],[主物料号],[物料号表索引号],[零件数量验证]," + //+ "[物料条码], [物料条码物料号], [物料条码批次],[验证结果], [操作者工号], [操作者姓名], [班次代码], " + //+ "物料来源代码,物料来源,是否禁用代码,是否禁用,被强制验证物料号,更改代码,更改原因)" +// SELECT [ID],[订单号],[主配厂家],[工位号], [工位名称], [物料号], [零件图号], [零件名称],[零件数量],[是否扫描], +//是否主物料,[厂家代码], [生产厂家], 0 as 零件数量验证,'' as 物料条码,'' +//as 物料条码物料号,'' as 物料条码批次,0 as 验证结果,被强制验证物料号,更改代码,更改原因,是否禁用代码,物料来源代码,扫描方式 +//from MES_计划BOM_发动机装配指南 +//where 订单号='100080211'and 工位号='OP3120' + } + else + { + sql = "SELECT [ID],[订单号]," + + "[主配厂家],[工位号], [工位名称], [物料号], [零件图号], [零件名称], [零件数量],[是否扫描],d.扫描方式代码,d.扫描方式,是否主物料,[厂家代码], [生产厂家], " + + "[操作指导],'' as 发动机号,'' as 主物料号,0 as 物料号表索引号,0 as 零件数量验证," + + "'' as 物料条码,'' as 物料条码物料号,'' as 物料条码批次,0 as 验证结果," + + "'' as 操作者工号,'' as 操作者姓名,'' as 班次代码," + + "b.物料来源代码, b.物料来源, a.是否禁用代码, a.是否禁用,被强制验证物料号,更改代码,更改原因 " + + " FROM MES_计划BOM_订单计划下达_扫描方式 AS d INNER JOIN (MES_计划BOM_订单计划下达_是否禁用 AS a INNER JOIN (MES_计划BOM_订单计划下达_物料来源 AS b INNER JOIN MES_计划BOM_发动机装配指南 AS c ON b.物料来源代码 = c.物料来源代码) ON a.是否禁用代码 = c.是否禁用代码) ON c.扫描方式=d.扫描方式代码 " + + "where 订单号='" + orderForm + "'" + + "and 工位号='" + OpName + "' and a.是否禁用代码 = 0 " + + " ORDER BY 物料号 "; + sql = "SELECT [ID],[订单号]," + + "[主配厂家],[工位号], [工位名称], [物料号], [零件图号], [零件名称],[零件数量]," + + "[是否扫描],扫描方式 as 扫描方式代码,'' as 扫描方式,是否主物料,[厂家代码], [生产厂家], " + + "'' as 操作指导,'' as 发动机号,'' as 追踪代码,'' as 主物料号,0 as 物料号表索引号,0 as 零件数量验证," + + "'' as 物料条码,'' as 物料条码物料号,'' as 物料条码批次,0 as 验证结果,'' as 操作者工号,'' as 操作者姓名,'' as 班次代码," + + " 物料来源代码,'' as 物料来源,是否禁用代码,'' as 是否禁用, 被强制验证物料号,更改代码,更改原因" + + " from MES_计划BOM_发动机装配指南" + + " where 订单号='" + orderForm + "'" + + "and 工位号='" + OpName + "'"; + } + //if (!SQLCommon.SqlServerConnectionStatus) + //{ + // SQLCommon.ExecuteDataTable_OleDb(sql, ApplicationConfig.ConnectionString_Access, out dt, out errorMessage); + //} + //else + { + DataAccess.ExecuteDataTable(sql, out dt); + } + return dt; + } + /// + /// MES_装配数据_零部件追溯_临时状态_增加 + /// + /// + /// + //public static void VerifyMaterialTempTableInsert(DataTable dt) + //{ + // string sql; + // sql = "INSERT INTO [MES_装配数据_零部件追溯_临时状态]" + // + "([订单号]," + // + "[主配厂家],[工位号], [工位名称],[物料号], [零件图号], [零件名称], [零件数量]," + // + "[是否扫描],[扫描方式代码], [扫描方式],[是否主物料], [厂家代码],[生产厂家], " + // + "[操作指导],[发动机号],[追踪代码],[主物料号],[物料号表索引号],[零件数量验证]," + // + "[物料条码], [物料条码物料号], [物料条码批次],[验证结果], [操作者工号], [操作者姓名], [班次代码], " + // + "物料来源代码,物料来源,是否禁用代码,是否禁用,被强制验证物料号,更改代码,更改原因)" + + // + "VALUES(@订单号," + // + "@主配厂家,@工位号,@工位名称,@物料号,@零件图号,@零件名称,@零件数量," + // + " @是否扫描,@扫描方式代码,@扫描方式,@是否主物料,@厂家代码,@生产厂家," + // + "@操作指导,@发动机号,@追踪代码,@主物料号,@物料号表索引号,@零件数量验证," + // + "@物料条码,@物料条码物料号,@物料条码批次,@验证结果,@操作者工号,@操作者姓名,@班次代码," + // + "@物料来源代码,@物料来源,@是否禁用代码,@是否禁用,@被强制验证物料号,@更改代码,@更改原因)"; + + + // OleDbParameter[] thisParms1 = new OleDbParameter[34]; + // // + "([订单号] " + // thisParms1[0] = new OleDbParameter("@订单号", OleDbType.VarChar, 50, "订单号"); + + // // + "@主配厂家,@工位号,@工位名称,@物料号,@零件图号,@零件名称,@零件数量," + + // thisParms1[1] = new OleDbParameter("@主配厂家", OleDbType.VarChar, 50, "主配厂家"); + // thisParms1[2] = new OleDbParameter("@工位号", OleDbType.VarChar, 50, "工位号"); + // thisParms1[3] = new OleDbParameter("@工位名称", OleDbType.VarChar, 50, "工位名称"); + // thisParms1[4] = new OleDbParameter("@物料号", OleDbType.VarChar, 50, "物料号"); + // thisParms1[5] = new OleDbParameter("@零件图号", OleDbType.VarChar, 50, "零件图号"); + // thisParms1[6] = new OleDbParameter("@零件名称", OleDbType.VarChar, 50, "零件名称"); + // thisParms1[7] = new OleDbParameter("@零件数量", OleDbType.Integer, 4, "零件数量"); + + // // +"[是否扫描],扫描方式代码, [扫描方式], [厂家代码],[生产厂家], " + + // thisParms1[8] = new OleDbParameter("@是否扫描", OleDbType.Integer, 4, "是否扫描"); + // thisParms1[9] = new OleDbParameter("@扫描方式代码", OleDbType.Integer, 4, "扫描方式代码"); + // thisParms1[10] = new OleDbParameter("@扫描方式", OleDbType.VarChar, 50, "扫描方式"); + // thisParms1[11] = new OleDbParameter("@是否主物料", OleDbType.Integer, 4, "是否主物料"); + // thisParms1[12] = new OleDbParameter("@厂家代码", OleDbType.VarChar, 50, "厂家代码"); + // thisParms1[13] = new OleDbParameter("@生产厂家", OleDbType.VarChar, 50, "生产厂家"); + + // //+ "@操作指导,@发动机号,@物料号表索引号,@零件数量验证," + + // thisParms1[14] = new OleDbParameter("@操作指导", OleDbType.VarChar, 255, "操作指导"); + // thisParms1[15] = new OleDbParameter("@发动机号", OleDbType.VarChar, 50, "发动机号"); + // thisParms1[16] = new OleDbParameter("@追踪代码", OleDbType.VarChar, 50, "追踪代码"); + // thisParms1[17] = new OleDbParameter("@主物料号", OleDbType.VarChar, 50, "主物料号"); + // thisParms1[18] = new OleDbParameter("@物料号表索引号", OleDbType.Integer, 4, "物料号表索引号"); + // thisParms1[19] = new OleDbParameter("@零件数量验证", OleDbType.Integer, 4, "零件数量验证"); + + // // +"[物料条码], [物料条码物料号], [物料条码批次],@验证结果, [操作者工号], [操作者姓名], [班次代码], " + // thisParms1[20] = new OleDbParameter("@物料条码", OleDbType.VarChar, 50, "物料条码"); + // thisParms1[21] = new OleDbParameter("@物料条码物料号", OleDbType.VarChar, 50, "物料条码物料号"); + // thisParms1[22] = new OleDbParameter("@物料条码批次", OleDbType.VarChar, 50, "物料条码批次"); + // thisParms1[23] = new OleDbParameter("@验证结果", OleDbType.Integer, 4, "验证结果"); + // thisParms1[24] = new OleDbParameter("@操作者工号", OleDbType.VarChar, 50, "操作者工号"); + // thisParms1[25] = new OleDbParameter("@操作者姓名", OleDbType.VarChar, 50, "操作者姓名"); + // thisParms1[26] = new OleDbParameter("@班次代码", OleDbType.VarChar, 50, "班次代码"); + + // // +"物料来源代码,物料来源,是否禁用代码,是否禁用,被强制验证物料号,更改代码,更改原因)" + + // thisParms1[27] = new OleDbParameter("@物料来源代码", OleDbType.Integer, 4, "物料来源代码"); + // thisParms1[28] = new OleDbParameter("@物料来源", OleDbType.VarChar, 50, "物料来源"); + // thisParms1[29] = new OleDbParameter("@是否禁用代码", OleDbType.Integer, 4, "是否禁用代码"); + // thisParms1[30] = new OleDbParameter("@是否禁用", OleDbType.VarChar, 50, "是否禁用"); + // thisParms1[31] = new OleDbParameter("@被强制验证物料号", OleDbType.VarChar, 50, "被强制验证物料号"); + // thisParms1[32] = new OleDbParameter("@更改代码", OleDbType.VarChar, 50, "更改代码"); + // thisParms1[33] = new OleDbParameter("@更改原因", OleDbType.VarChar, 255, "更改原因"); + + // DataAccess.ExecuteDataTable_OleDb_Insert_Access(sql, dt, ref thisParms1); + //} + + + + /// + /// 查询订单号对应的订单数据 + /// [MES_计划BOM_发动机号] + /// + /// + /// + /// + public static bool EngineSelectByOrderForm(string orderForm, out DataTable dt) + { + string sql; + sql = "SELECT TOP 1 * FROM MES_计划BOM_发动机号 WHERE 订单号='" + orderForm+"'"; + //if (!SQLCommon.SqlServerConnectionStatus) + //{ + // return DataAccess.ExecuteDataTable_OleDb_Access(sql, out dt); + //} + //else + { + return DataAccess.ExecuteDataTable(sql, out dt); + + } + } + + + /// + /// 根据追踪代码查询订单号对应的订单数据 + /// [MES_装配数据_发动机号_追踪代码] + /// + /// + /// + /// + //public static bool GetOrderFormByEngineTraceCode(string engineTraceCode, out DataTable dt) + //{ + // string sql; + // sql = "SELECT TOP 1 * FROM MES_装配数据_发动机号_追踪代码 WHERE 追踪代码='" + engineTraceCode + "'"; + // return DataAccess.ExecuteDataTable_OleDb_Access(sql, out dt); + //} + + + + } +} diff --git a/Common/07WebBusinessFacade/BusinessFacade/MES/MaterialData.cs b/Common/07WebBusinessFacade/BusinessFacade/MES/MaterialData.cs new file mode 100644 index 0000000..4aad881 --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/MES/MaterialData.cs @@ -0,0 +1,1504 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Data; +//using System.Windows.Forms; + +namespace bizFacade//MESPC +{ + /// + /// + /// + public class MaterialData + { + /// + /// ֤ȫϢϢ֤Ϣ + /// 浽ݿ[MES_װ_㲿׷] + /// + public static DataTable MaterialTableForSave=null; + /// + /// [MES_ƻBOM_ƻ] + /// + public static DataTable dt_OrderFormPlan=null; + /// + /// [MES_ƻBOM_] + /// + public static DataTable dt_EngineNumber=null; + /// + /// ԭʼϱ + /// + public static DataTable dt_Material=null; + /// + /// Ҫ֤ϱ + /// + public static DataTable dt_Material_Verify=null; + /// + /// Ҫǿ֤ϱ + /// + public static DataTable dt_MaterialUnchecked=null; + /// + /// ID + /// Ϻű + /// + public static string MaterialIndexField = "Ϻű"; + /// + /// ߹λ׷ݴ + /// + public static string FirstOpNameTraceCodeField = "߹λ׷ݴ"; + /// + /// ߹λ׷ݴ + /// + public static int firstOpNameTraceCode; + + /// + /// ׷ݴ + /// + public static int traceID ; + + /// + /// 1豸 + /// 2MES + /// + public static string RepairReasonID = "1"; + /// + /// 1豸 + /// 2MES + /// + public static string RepairReasonText = "豸"; + + + /// + /// traceID + /// + public static string OrderFormField = ""; + /// + /// + /// + public static string orderForm; + /// + /// 䳧 + /// + public static string MainPruduceFatoryField = "䳧"; + /// + /// 䳧 + /// + public static string mainPruduceFatory ; + /// + /// ƻ + /// + public static string EngineNumber_OrderPlanField = "ƻ"; + /// + /// ƻ + /// + public static string engineNumber_OrderPlan; + /// + /// + /// + public static string EngineNumberField = ""; + /// + /// + /// + public static string engineNumber; + /// + /// ׷ٴ + /// + public static string EngineTraceCodeField = "׷ٴ"; + /// + /// ׷ٴ + /// + public static string engineTraceCode; + + + /// + /// λ + /// + public static string OpNameField = "λ"; + /// + /// λ + /// + public static string opName; + /// + /// ʱ + /// + public static string CycleActualCycleTime = "ʵѭʱ"; + /// + /// ʱ + /// + public static int cycleActualCycleTime; + /// + /// ʱ + /// + public static string ArrivedTimeField = "ʱ"; + /// + /// ʱ + /// + public static DateTime arrivedTime; + /// + /// 뿪ʱ + /// + public static string LeavedTimeField = "뿪ʱ"; + /// + /// 뿪ʱ + /// + public static DateTime leavedTime; + /// + /// ߹ + /// + public static string OperatorCodeField = "߹"; + /// + /// ߹ + /// + public static string operatorCode; + /// + /// + /// + public static string OperatorNameField = ""; + /// + /// + /// + public static string operatorName; + /// + /// δ + /// + public static string OperatorShiftField = "δ"; + /// + /// δ + /// + public static string operatorShift; + /// + /// + /// + public static string OperatorShiftNameField = ""; + /// + /// + /// + public static string operatorShiftName; + /// + /// λ + /// + public static string PositionIDNameField = "λ"; + /// + /// λ + /// + public static string positionIDName; + /// + /// SAPϺ + /// + public static string SAPMaterialNumberField = "SAPϺ"; + /// + /// SAPϺ + /// + public static string sAPMaterialNumber; + /// + /// ͺ + /// + public static string EngineNumberTypeField = "ͺ"; + /// + /// ͺ + /// + public static string engineNumberType; + /// + /// ͺŴ + /// + public static string EngineNumberCodeField = "ͺŴ"; + ///// + ///// ͺŴ + ///// + //public static string EngineNumberTypeCodeField = "ͺŴ"; + /// + /// ͺŴ + /// + public static int engineNumberCode; + ///// + ///// ͺŴ + ///// + //public static int engineNumberTypeCode; + /// + /// + /// + public static string EngineNumberBasicTypeField = ""; + /// + /// + /// + public static string engineNumberBasicType; + /// + /// + /// + public static string EngineCountField = ""; + /// + /// + /// + public static string engineCount; + /// + /// Ʊʼ + /// + public static string EngineNumberFirstIDField = "Ʊʼ"; + /// + /// Ʊʼ + /// + public static string engineNumberFirstID; + /// + /// ͻ + /// + public static string CustomesNameField = "ͻ"; + /// + /// ͻ + /// + public static string customesName; + /// + /// Ͷ + /// + public static string PrepareMaterialDateTimeField = "Ͷ"; + /// + /// Ͷ + /// + public static DateTime prepareMaterialDateTime; + /// + /// ļ + /// + public static string FileCodeField = "ļ"; + /// + /// ļ + /// + public static string fileCode; + /// + /// + /// + public static string GroupNameField = ""; + /// + /// + /// + public static string groupName; + /// + /// ֪ͨ + /// + public static string NotifyCodeField = "֪ͨ"; + /// + /// ֪ͨ + /// + public static string notifyCode; + /// + /// + /// + public static string N_ForceField = ""; + /// + /// + /// + public static string n_Force; + /// + /// ָļ + /// + public static string DirectFileCodeField = "ָļ"; + /// + /// ָļ + /// + public static string directFileCode; + /// + /// װ״̬ + /// + public static string WorkEngineStatusField = "װ״̬"; + /// + /// װ״̬ + /// + public static string workEngineStatus; + /// + /// ״̬ + /// + public static string AdaptDateTimeField = "״̬"; + /// + /// ״̬ + /// + public static DateTime adaptDateTime; + /// + /// װָ + /// + public static string OrderFormDirectField = "װָ"; + /// + /// + /// + public static string MaterialDescriptField = ""; + /// + /// + /// + public static string materialDescript; + /// + /// ƻ´ + /// + public static string PlanSendedDateTimeField = "ƻ´"; + /// + /// ƻ´ + /// + public static DateTime planSendedDateTime; + /// + /// ƻ깤 + /// + public static string PlanFinishDateTimeField = "ƻ깤"; + /// + /// ƻ깤 + /// + public static DateTime planFinishDateTime; + /// + /// + /// + public static string ProduceFatoryField = ""; + /// + /// + /// + public string produceFatory; + /// + /// + /// + public static string PartTypeField = ""; + /// + /// + /// + public static int partType; + /// + /// Ƿϸ + /// + public static int isGoodQuality; + + + + + /// + /// Ϻ + /// + public static string MaterialNumberField = "Ϻ"; + /// + /// Ϻ + /// + public string materialNumber; + /// + /// Ϻ + /// + public static string MainMaterialNumberField = "Ϻ"; + /// + /// Ϻ + /// + public static string mainMaterialNumber; + /// + /// ͼ + /// + public static string PartDrawNumberField = "ͼ"; + /// + /// ͼ + /// + public string partDrawNumber; + /// + /// + /// + public static string PartDrawNameField = ""; + /// + /// + /// + public string partDrawName; + /// + /// + /// + public static string PartCountField = ""; + /// + /// + /// + public int partCount; + /// + /// ֤ + /// + public static string PartCountVerifyField = "֤"; + /// + /// ֤ + /// + public int partCountVerify; + /// + /// Ƿɨ + /// =1Ҫɨ + /// =0Ҫɨ + /// + public static string MaterialTraceField = "Ƿɨ"; + /// + /// Ƿɨ + /// =0Ҫɨ + /// =1Ҫɨ + /// + public int materialTrace; + /// + /// ɨ跽ʽ + /// =0ֻɨһ + /// =1ֻɨ輸Σֱɨ衣 + /// + public static string MaterialVerifyIDField = "ɨ跽ʽ"; + /// + /// ɨ跽ʽ + /// + public int materialVerifyID; + /// + /// Ƿ + /// =0 + /// =1 + /// + public static string IsMainMaterialField = "Ƿ"; + /// + /// Ƿ + /// + public static int isMainMaterial; + /// + /// Ҵ + /// + public static string ProduceFatoryCodeField = "Ҵ"; + /// + /// Ҵ + /// + public string produceFatoryCode; + /// + /// + /// + public static string BarCodeField = ""; + /// + /// + /// + public string barCode; + /// + /// Ϻ + /// + public static string BarCode_MaterialField = "Ϻ"; + /// + /// Ϻ + /// + public string barCode_Material; + /// + /// + /// + public static string BarCode_SerailNumberField = ""; + /// + /// + /// + public string barCode_SerailNumber; + /// + /// ֤ + /// ֤ + /// ֤ CheckState.Unchecked 0û֤ + /// ֤ CheckState.Checked 1 Ѿ֤ + /// ֤ CheckState.Indeterminate 2 Ѿǿ֤ + /// + public static string MaterialVerifyResultField = "֤"; + + + /// + /// ǿ֤ԭ + /// + public static string MaterialVerifyReasonField = "ǿ֤ԭ"; + + + /// + /// ¼ʱ + /// + public static string OperatorLoginTimeField = "¼ʱ"; + /// + /// ¼ʱ + /// + public static DateTime operatorLoginTime; + /// + /// ˳ʱ + /// + public static string OperatorLogoutTimeField = "˳ʱ"; + /// + /// ˳ʱ + /// + public static DateTime operatorLogoutTime; + + + + + + + /// + /// ֤ ѡ + /// + public static string MaterialVerifySelectField = "֤"; + /// + /// ʵʲ + /// + public static string DayActualCountField = "ʵʲ"; + /// + /// ʵʲ + /// + public static int dayActualCount; + + + /// + /// ռƻ + /// + public static string DayPlanCountField = "ռƻ"; + /// + /// ޱ־ + /// 0 װ 1 Ҫ + /// + public static int isRepairID; + /// + /// ޱ־ + /// + public static string IsRepairIDField = "ޱ־"; + /// + /// ռƻ + /// + public static int dayPlanCount; + + + + + /// + /// ID + /// + public static int ID; + ///// + ///// + ///// + //public static string engineNumberBasicType; + + /// + /// Ϻűȷ + /// + public static int materialIndexConfirm; + /// + /// Ϻȷ + /// + public static string materialNumberConfirm; + /// + /// ȷ(ǿȷ) + /// + public static string barCodeInputForConfirm; + /// + /// Ϻ(ǿȷ) + /// + public static string barCode_MaterialInputForConfirm; + /// + /// (ǿȷ) + /// + public static string barCode_SerailNumberInputForConfirm; + /// + /// ȷ + /// + public static string barCodeConfirm; + /// + /// Ϻȷ + /// + public static string barCode_MaterialConfirm; + /// + /// ȷ + /// + public static string barCode_SerailNumberConfirm; + /// + /// Ϻű + /// + public static int materialIndex; + + /// + /// ֤ + /// ֤ + /// ֤ CheckState.Unchecked 0û֤ + /// ֤ CheckState.Checked 1 Ѿ֤ + /// ֤ CheckState.Indeterminate 2 Ѿǿ֤ + /// + public int materialVerifyResult; + /// + /// ǿ֤ԭ + /// + public static string materialVerifyReason; + + /// + /// Ҫ֤ϱ + /// + /// + public static DataTable MaterialTable() + { + DataTable dt; + DataColumn dc; + dt = new DataTable(); + + // + // Ϻű + // + dc = new DataColumn(MaterialIndexField, typeof(Int32)); + dt.Columns.Add(dc); + + // + // + // + dc = new DataColumn(OrderFormField, typeof(string)); + dt.Columns.Add(dc); + // + // 䳧 + // + dc = new DataColumn(MainPruduceFatoryField, typeof(string)); + dt.Columns.Add(dc); + // + // + // + dc = new DataColumn(EngineNumberField, typeof(string)); + dt.Columns.Add(dc); + // + // ͺŴ + // + dc = new DataColumn(EngineNumberCodeField, typeof(Int32)); + dt.Columns.Add(dc); + // + // λ + // + dc = new DataColumn(OpNameField, typeof(string)); + dt.Columns.Add(dc); + // + // λ + // + dc = new DataColumn(PositionIDNameField, typeof(string)); + dt.Columns.Add(dc); + // + // SAPϺ + // + dc = new DataColumn(SAPMaterialNumberField, typeof(string)); + dt.Columns.Add(dc); + // + // ͺ + // + dc = new DataColumn(EngineNumberTypeField, typeof(string)); + dt.Columns.Add(dc); + // + // + // + dc = new DataColumn(EngineNumberBasicTypeField, typeof(string)); + dt.Columns.Add(dc); + // + // ͻ + // + dc = new DataColumn(CustomesNameField, typeof(string)); + dt.Columns.Add(dc); + // + // Ͷ + // + dc = new DataColumn(PrepareMaterialDateTimeField, typeof(DateTime)); + dt.Columns.Add(dc); + // + // ļ + // + dc = new DataColumn(FileCodeField, typeof(string)); + dt.Columns.Add(dc); + // + // + // + dc = new DataColumn(GroupNameField, typeof(string)); + dt.Columns.Add(dc); + // + // ֪ͨ + // + dc = new DataColumn(NotifyCodeField, typeof(string)); + dt.Columns.Add(dc); + // + // + // + dc = new DataColumn(N_ForceField, typeof(string)); + dt.Columns.Add(dc); + // + // ָļ + // + dc = new DataColumn(DirectFileCodeField, typeof(string)); + dt.Columns.Add(dc); + // + // װ״̬ + // + dc = new DataColumn(WorkEngineStatusField, typeof(DateTime)); + dt.Columns.Add(dc); + // + // ״̬ + // + dc = new DataColumn(AdaptDateTimeField, typeof(string)); + dt.Columns.Add(dc); + // + // װָ + // + dc = new DataColumn(OrderFormDirectField, typeof(string)); + dt.Columns.Add(dc); + // + // + // + dc = new DataColumn(MaterialDescriptField, typeof(string)); + dt.Columns.Add(dc); + // + // ƻ´ + // + dc = new DataColumn(PlanSendedDateTimeField, typeof(DateTime)); + dt.Columns.Add(dc); + // + // Ϻ + // + dc = new DataColumn(MaterialNumberField, typeof(string)); + dt.Columns.Add(dc); + // + // ͼ + // + dc = new DataColumn(PartDrawNumberField, typeof(string)); + dt.Columns.Add(dc); + // + // + // + dc = new DataColumn(PartDrawNameField, typeof(string)); + dt.Columns.Add(dc); + // + // + // + dc = new DataColumn(PartCountField, typeof(Int32)); + dt.Columns.Add(dc); + // + // ֤ + // + dc = new DataColumn(PartCountVerifyField, typeof(Int32)); + dt.Columns.Add(dc); + // + // Ƿɨ + // + dc = new DataColumn(MaterialTraceField, typeof(Int32)); + dt.Columns.Add(dc); + // + // ɨ跽ʽ + // + dc = new DataColumn(MaterialVerifyIDField, typeof(Int32)); + dt.Columns.Add(dc); + // + // Ҵ + // + dc = new DataColumn(ProduceFatoryCodeField, typeof(string)); + dt.Columns.Add(dc); + // + // + // + dc = new DataColumn(ProduceFatoryField, typeof(string)); + dt.Columns.Add(dc); + // + // + // + dc = new DataColumn(BarCodeField, typeof(string)); + dt.Columns.Add(dc); + // + // Ϻ + // + dc = new DataColumn(BarCode_MaterialField, typeof(string)); + dt.Columns.Add(dc); + // + // + // + dc = new DataColumn(BarCode_SerailNumberField, typeof(string)); + dt.Columns.Add(dc); + // + // ֤ + // ֤ + // ֤ CheckState.Unchecked 0û֤ + // ֤ CheckState.Checked 1 Ѿ֤ + // ֤ CheckState.Indeterminate 2 Ѿǿ֤ + // + dc = new DataColumn(MaterialVerifyResultField, typeof(Int32)); + dt.Columns.Add(dc); + // + // ǿ֤ԭ + // + dc = new DataColumn(MaterialVerifyReasonField, typeof(string)); + dt.Columns.Add(dc); + // + // ߹ + // + dc = new DataColumn(OperatorCodeField, typeof(string)); + dt.Columns.Add(dc); + // + // + // + dc = new DataColumn(OperatorNameField, typeof(string)); + dt.Columns.Add(dc); + // + // δ + // + dc = new DataColumn(OperatorShiftField, typeof(string)); + dt.Columns.Add(dc); + + // + // ֤ + // + dc = new DataColumn(MaterialVerifySelectField, typeof(string)); + dt.Columns.Add(dc); + // + // ޱ־ + // + dc = new DataColumn(IsRepairIDField, typeof(int)); + dt.Columns.Add(dc); + + //DataTable dt; + //DataColumn dc; + //dt = new DataTable(); + + return dt; + } + + /// + /// Ҫǿ֤ϱ"֤ = 0" + /// ֤ CheckState.Unchecked 0û֤ + /// ֤ CheckState.Checked 1 Ѿ֤ + /// ֤ CheckState.Indeterminate 2 Ѿǿ֤ + /// + /// + /// + public static DataTable GetVerifyBarCodeTableUnchecked(DataTable dt) + { + DataTable dt_MaterialUnchecked; + DataRow dr; + DataRow[] drs; + dt_MaterialUnchecked = MaterialData.MaterialTable(); + + drs = dt.Select("֤ = 0"); + for (int i = 0; i < drs.Length; i++) + { + dr = dt_MaterialUnchecked.NewRow(); + MaterialTableSetDataRowValue(drs[i], dr); + dt_MaterialUnchecked.Rows.Add(dr); + } + + return dt_MaterialUnchecked; + } + + + + /// + /// ʼϱиֵ + /// + /// + /// + /// + public static void MaterialTableSetDataRowValue(int index, DataRow dr, DataRow drOut) + { + if (dr == null) return; + try + { + // + // Ϻű + // + drOut[MaterialIndexField] = index; + // + // + // + drOut[OrderFormField] = orderForm; + + // + // + // + drOut[EngineNumberField] = engineNumber; + // + // ͺŴ + // + drOut[EngineNumberCodeField] = engineNumberCode; + // + // λ + // + drOut[OpNameField] = opName; + // + // λ + // + drOut[PositionIDNameField] = positionIDName; + // + // Ϻ + // + drOut[MaterialNumberField] = dr[MaterialNumberField]; + // + // ͼ + // + drOut[PartDrawNumberField] = dr[PartDrawNumberField]; + // + // + // + drOut[PartDrawNameField] = dr[PartDrawNameField]; + // + // + // + drOut[PartCountField] = dr[PartCountField]; + // + // + // + drOut[ProduceFatoryField] = dr[ProduceFatoryField]; + // + // Ҵ + // + drOut[ProduceFatoryCodeField] = dr[ProduceFatoryCodeField]; + // + // Ƿɨ + // + drOut[MaterialTraceField] = dr[MaterialTraceField]; + // + // ɨ跽ʽ + // + drOut[MaterialVerifyIDField] = dr[MaterialVerifyIDField]; + + // + // ߹ + // + drOut[OperatorCodeField] = operatorCode; + // + // + // + drOut[OperatorNameField] = operatorName; + // + // δ + // + drOut[OperatorShiftField] = operatorShift; + + // + // ֤ + // ֤ + // ֤ CheckState.Unchecked 0û֤ + // ֤ CheckState.Checked 1 Ѿ֤ + // ֤ CheckState.Indeterminate 2 Ѿǿ֤ + drOut[MaterialVerifyResultField] = 0; + drOut[MaterialVerifyIDField] = dr[MaterialVerifyIDField]; + // + // ǿ֤ԭ + // + drOut[MaterialVerifyReasonField] = ""; + // + drOut[MaterialVerifySelectField] = "ѡ"; + + } + catch + { + //MessageBox.Show(err.Message); + } + + } + /// + /// ϱиֵ + /// + /// + /// + public static void MaterialTableSetDataRowValue(DataRow dr, DataRow drOut) + { + if (dr == null) return; + try + { + // + // Ϻű + // + drOut[MaterialIndexField] = dr[MaterialIndexField]; + // + // + // + drOut[OrderFormField] = dr[OrderFormField]; + + // + // ͺ + // + drOut[EngineNumberField] = dr[EngineNumberField]; + // + // ͺŴ + // + drOut[EngineNumberCodeField] = dr[EngineNumberCodeField]; + // + // λ + // + drOut[OpNameField] = dr[OpNameField]; + // + // λ + // + drOut[PositionIDNameField] = dr[PositionIDNameField]; + // + // Ϻ + // + drOut[MaterialNumberField] = dr[MaterialNumberField]; + // + // ͼ + // + drOut[PartDrawNumberField] = dr[PartDrawNumberField]; + // + // + // + drOut[PartDrawNameField] = dr[PartDrawNameField]; + // + // + // + drOut[PartCountField] = dr[PartCountField]; + // + // ֤ + // + drOut[PartCountVerifyField] = dr[PartCountVerifyField]; + // + // + // + drOut[ProduceFatoryField] = dr[ProduceFatoryField]; + // + // Ҵ + // + drOut[ProduceFatoryCodeField] = dr[ProduceFatoryCodeField]; + // + // + // + drOut[BarCodeField] = dr[BarCodeField]; + // + // Ϻ + // + drOut[BarCode_MaterialField] = dr[BarCode_MaterialField]; + // + // + // + drOut[BarCode_SerailNumberField] = dr[BarCode_SerailNumberField]; + // + // Ƿɨ + // + drOut[MaterialTraceField] = dr[MaterialTraceField]; + // + // ɨ跽ʽ + // + drOut[MaterialVerifyIDField] = dr[MaterialVerifyIDField]; + + // + // ߹ + // + drOut[OperatorCodeField] = dr[OperatorCodeField]; + // + // + // + drOut[OperatorNameField] = dr[OperatorNameField]; + // + // δ + // + drOut[OperatorShiftField] = dr[OperatorShiftField]; + + // + // ֤ + // ֤ + // ֤ CheckState.Unchecked 0û֤ + // ֤ CheckState.Checked 1 Ѿ֤ + // ֤ CheckState.Indeterminate 2 Ѿǿ֤ + drOut[MaterialVerifyResultField] = dr[MaterialVerifyResultField]; + // + // ǿ֤ԭ + // + drOut[MaterialVerifyReasonField] = dr[MaterialVerifyReasonField]; + //֤ + //drOut[MaterialVerifySelectField] = dr[MaterialVerifySelectField]; + + } + catch + { + + //MessageBox.Show(err.Message); + } + + } + + /// + /// indexжӦ + /// + /// + public void MaterialTable(int index) + { + DataTable dt = dt_Material_Verify; + DataRow[] dr; + dr = dt.Select(MaterialIndexField + "= " + index.ToString()); + if (dr == null) return; + + // + // Ϻű + // + materialIndex = (int)dr[0][MaterialIndexField]; + // + // + // + orderForm = dr[0][OrderFormField].ToString(); + + // + // ͺ + // + engineNumber = dr[0][EngineNumberField].ToString(); + // + // ͺŴ + // + engineNumberCode = (int)dr[0][EngineNumberCodeField]; + // + // λ + // + opName = dr[0][OpNameField].ToString(); + // + // λ + // + positionIDName = dr[0][PositionIDNameField].ToString(); + // + // Ϻ + // + materialNumber = dr[0][MaterialNumberField].ToString(); + // + // ͼ + // + partDrawNumber = dr[0][PartDrawNumberField].ToString(); + // + // + // + partDrawName = dr[0][PartDrawNameField].ToString(); + // + // + // + partCount = (int)dr[0][PartCountField]; + // + // ֤ + // + partCountVerify = (int)dr[0][PartCountVerifyField]; + // + // + // + produceFatory = dr[0][ProduceFatoryField].ToString(); + // + // Ҵ + // + produceFatoryCode = dr[0][ProduceFatoryCodeField].ToString(); + // + // + // + barCode = dr[0][BarCodeField].ToString(); + // + // Ϻ + // + barCode_Material = dr[0][BarCode_MaterialField].ToString(); + // + // + // + barCode_SerailNumber = dr[0][BarCode_SerailNumberField].ToString(); + // + // Ƿɨ + // + materialTrace = (int)dr[0][MaterialTraceField]; + // + // ɨ跽ʽ + // + materialVerifyID = (int)dr[0][MaterialVerifyIDField]; + // + // ߹ + // + operatorCode = dr[0][OperatorCodeField].ToString(); + // + // + // + operatorName = dr[0][OperatorNameField].ToString(); + // + // δ + // + operatorShift = dr[0][OperatorShiftField].ToString(); + + // + // ֤ + // ֤ + // ֤ CheckState.Unchecked 0û֤ + // ֤ CheckState.Checked 1 Ѿ֤ + // ֤ CheckState.Indeterminate 2 Ѿǿ֤ + materialVerifyResult = (int)dr[0][MaterialVerifyResultField]; + // + // ǿ֤ԭ + // + materialVerifyReason = dr[0][MaterialVerifyReasonField].ToString(); + + } + /// + /// ֽ룬Ϻź + /// M/13009130/6800811001 + /// + /// + /// _Ϻ + /// _ + public static void SplitBarCode(string barCode, out string barCode_Material, out string barCode_SerailNumber) + { + barCode_Material = null; + barCode_SerailNumber = null; + try + { + string[] str = barCode.Split('/'); + if (str != null) + { + if (str.Length >= 2) + { + try + { + barCode_Material = str[1]; + } + catch { barCode_Material = ""; } + try + { + barCode_SerailNumber = str[2]; + } + catch { barCode_SerailNumber = ""; } + } + } + + } + catch + { + //MessageBox.Show(err.Message); + + } + } + + ///// + ///// + ///// + //public static void CreateMaterialTableForSave() + //{ + // DataTable dt; + // DataColumn dc; + // dt = new DataTable(); + + // /// + // /// + // /// + // dc = new DataColumn(OrderFormField, typeof(string)); + // dt.Columns.Add(dc); + // /// + // /// 䳧 + // /// + // dc = new DataColumn(MainPruduceFatoryField, typeof(string)); + // dt.Columns.Add(dc); + // /// + // /// + // /// + // dc = new DataColumn(EngineNumberField, typeof(string)); + // dt.Columns.Add(dc); + // /// + // /// ͺŴ + // /// + // dc = new DataColumn(EngineNumberCodeField, typeof(Int32)); + // dt.Columns.Add(dc); + // /// + // /// λ + // /// + // dc = new DataColumn(OpNameField, typeof(string)); + // dt.Columns.Add(dc); + // /// + // /// λ + // /// + // dc = new DataColumn(PositionIDNameField, typeof(string)); + // dt.Columns.Add(dc); + // /// + // /// SAPϺ + // /// + // dc = new DataColumn(SAPMaterialNumberField, typeof(string)); + // dt.Columns.Add(dc); + // /// + // /// ͺ + // /// + // dc = new DataColumn(EngineNumberTypeField, typeof(string)); + // dt.Columns.Add(dc); + // /// + // /// + // /// + // dc = new DataColumn(EngineNumberBasicTypeField, typeof(string)); + // dt.Columns.Add(dc); + // /// + // /// ͻ + // /// + // dc = new DataColumn(CustomesNameField, typeof(string)); + // dt.Columns.Add(dc); + // /// + // /// Ͷ + // /// + // dc = new DataColumn(PrepareMaterialDateTimeField, typeof(DateTime)); + // dt.Columns.Add(dc); + // /// + // /// ļ + // /// + // dc = new DataColumn(FileCodeField, typeof(string)); + // dt.Columns.Add(dc); + // /// + // /// + // /// + // dc = new DataColumn(GroupNameField, typeof(string)); + // dt.Columns.Add(dc); + // /// + // /// ֪ͨ + // /// + // dc = new DataColumn(NotifyCodeField, typeof(string)); + // dt.Columns.Add(dc); + // /// + // /// + // /// + // dc = new DataColumn(N_ForceField, typeof(string)); + // dt.Columns.Add(dc); + // /// + // /// ָļ + // /// + // dc = new DataColumn(DirectFileCodeField, typeof(string)); + // dt.Columns.Add(dc); + // /// + // /// װ״̬ + // /// + // dc = new DataColumn(WorkEngineStatusField, typeof(DateTime)); + // dt.Columns.Add(dc); + // /// + // /// ״̬ + // /// + // dc = new DataColumn(AdaptDateTimeField, typeof(string)); + // dt.Columns.Add(dc); + // /// + // /// װָ + // /// + // dc = new DataColumn(OrderFormDirectField, typeof(string)); + // dt.Columns.Add(dc); + // /// + // /// + // /// + // dc = new DataColumn(MaterialDescriptField, typeof(string)); + // dt.Columns.Add(dc); + // /// + // /// ƻ´ + // /// + // dc = new DataColumn(PlanSendedDateTimeField, typeof(DateTime)); + // dt.Columns.Add(dc); + // /// + // /// Ϻ + // /// + // dc = new DataColumn(MaterialNumberField, typeof(string)); + // dt.Columns.Add(dc); + // /// + // /// ͼ + // /// + // dc = new DataColumn(PartDrawNumberField, typeof(string)); + // dt.Columns.Add(dc); + // /// + // /// + // /// + // dc = new DataColumn(PartDrawNameField, typeof(string)); + // dt.Columns.Add(dc); + // /// + // /// + // /// + // dc = new DataColumn(PartCountField, typeof(Int32)); + // dt.Columns.Add(dc); + // /// + // /// ֤ + // /// + // dc = new DataColumn(PartCountVerifyField, typeof(Int32)); + // dt.Columns.Add(dc); + // dt.Columns.Add(dc); + // /// + // /// Ƿɨ + // /// + // dc = new DataColumn(MaterialTraceField, typeof(Int32)); + // dt.Columns.Add(dc); + // /// + // /// ɨ跽ʽ + // /// + // dc = new DataColumn(MaterialVerifyIDField, typeof(Int32)); + // dt.Columns.Add(dc); + // /// + // /// Ҵ + // /// + // dc = new DataColumn(ProduceFatoryCodeField, typeof(string)); + // dt.Columns.Add(dc); + // /// + // /// + // /// + // dc = new DataColumn(ProduceFatoryField, typeof(string)); + // dt.Columns.Add(dc); + // /// + // /// + // /// + // dc = new DataColumn(BarCodeField, typeof(string)); + // dt.Columns.Add(dc); + // /// + // /// Ϻ + // /// + // dc = new DataColumn(BarCode_MaterialField, typeof(string)); + // dt.Columns.Add(dc); + // /// + // /// + // /// + // dc = new DataColumn(BarCode_SerailNumberField, typeof(string)); + // dt.Columns.Add(dc); + // /// + // /// ֤ + // /// ֤ + // /// ֤ CheckState.Unchecked 0û֤ + // /// ֤ CheckState.Checked 1 Ѿ֤ + // /// ֤ CheckState.Indeterminate 2 Ѿǿ֤ + // /// + // dc = new DataColumn(MaterialVerifyResultField, typeof(Int32)); + // dt.Columns.Add(dc); + // /// + // /// ǿ֤ԭ + // /// + // dc = new DataColumn(MaterialVerifyReasonField, typeof(string)); + // dt.Columns.Add(dc); + // /// + // /// ߹ + // /// + // dc = new DataColumn(OperatorCodeField, typeof(string)); + // dt.Columns.Add(dc); + // /// + // /// + // /// + // dc = new DataColumn(OperatorNameField, typeof(string)); + // dt.Columns.Add(dc); + // /// + // /// δ + // /// + // dc = new DataColumn(OperatorShiftField, typeof(string)); + // dt.Columns.Add(dc); + + // MaterialTableForSave = dt; + //} + + + + /// + /// ǷҪ֤ + /// ֵ false ûȫ֤ɣҪ֤ + /// ֵ true ȫ֤ɣҪ֤ + /// ֤ CheckState.Unchecked 0û֤ + /// ֤ CheckState.Checked 1 Ѿ֤ + /// ֤ CheckState.Indeterminate 2 Ѿǿ֤ + /// + /// + public static bool CheckVeriftBarCode() + { + DataTable dt; + bool check = true; + + //dt = dt_Material_Verify; + dt = MaterialData.dt_Material_Verify;//.dt_Material_Verify; + if (dt == null) return check; + for (int i = 0; i < dt.Rows.Count; i++) + { + if ((int)dt.Rows[i]["֤"] == 0) + { + check = false; + break; + } + } + return check; + } + + /// + /// ݱ + /// TagIDλãĿֵϸ־ + /// + public static DataTable QualityTable() + { + DataTable dt; + DataColumn dc; + dt = new DataTable(); + + // Ϻű + dc = new DataColumn("TagID", typeof(string)); + dt.Columns.Add(dc); + dc = new DataColumn("λ", typeof(string)); + dt.Columns.Add(dc); + dc = new DataColumn("λ", typeof(string)); + dt.Columns.Add(dc); + + dc = new DataColumn("Ŀ", typeof(string)); + dt.Columns.Add(dc); + dc = new DataColumn("ֵ", typeof(double)); + dt.Columns.Add(dc); + dc = new DataColumn("ϸ־", typeof(Int32)); + dt.Columns.Add(dc); + return dt; + } + + } +} diff --git a/Common/07WebBusinessFacade/BusinessFacade/MES/vssver2.scc b/Common/07WebBusinessFacade/BusinessFacade/MES/vssver2.scc new file mode 100644 index 0000000..ec506c7 Binary files /dev/null and b/Common/07WebBusinessFacade/BusinessFacade/MES/vssver2.scc differ diff --git a/Common/07WebBusinessFacade/BusinessFacade/Properties/AssemblyInfo.cs b/Common/07WebBusinessFacade/BusinessFacade/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..86b7010 --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// 有关程序集的一般信息由以下 +// 控制。更改这些特性值可修改 +// 与程序集关联的信息。 +[assembly: AssemblyTitle("BusinessFacade")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("BusinessFacade")] +[assembly: AssemblyCopyright("Copyright © 2022")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// 将 ComVisible 设置为 false 会使此程序集中的类型 +//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型 +//请将此类型的 ComVisible 特性设置为 true。 +[assembly: ComVisible(false)] + +// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID +[assembly: Guid("f0a0c525-03fd-428a-9b17-7f54aa0e4475")] + +// 程序集的版本信息由下列四个值组成: +// +// 主版本 +// 次版本 +// 生成号 +// 修订号 +// +//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值 +//通过使用 "*",如下所示: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Common/07WebBusinessFacade/BusinessFacade/SyPartLoad/EngineIDCode.cs b/Common/07WebBusinessFacade/BusinessFacade/SyPartLoad/EngineIDCode.cs new file mode 100644 index 0000000..34cb183 --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/SyPartLoad/EngineIDCode.cs @@ -0,0 +1,230 @@ +using System; +using System.Data; +using System.Data.SqlClient; + +using System.Collections; +using System.Collections.Specialized; +//using SystemFramework; +using DataLinkMesWork; +namespace SystemFramework +{ + +} +namespace bizFacade +{ + /// + /// 电子看板信息系统 + /// select 重量1,重量2,重量差,允许重量差,合格标志 + /// + public partial class BaseDataSystemMES + { + + /// + /// 电子看板_发动机号_分线组件装配关系_增加 + /// + /// + /// + /// + /// + //static public void MailLineAndSubLineData_InsertAAAAA(string engineID, int engineTypeID, string engineType, string engineID_SubLine) + //{ + // string procedureName; + // procedureName = "电子看板_发动机号_分线组件装配关系_增加"; + // SqlParameter[] thisParms = new SqlParameter[4]; + // thisParms[0] = new System.Data.SqlClient.SqlParameter("@发动机号_分线", engineID_SubLine); + // thisParms[1] = new System.Data.SqlClient.SqlParameter("@发动机号", engineID); + // thisParms[2] = new System.Data.SqlClient.SqlParameter("@机型代码", engineTypeID); + // thisParms[3] = new System.Data.SqlClient.SqlParameter("@发动机型号", engineType); + // DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + //} + + /// + /// 思源库位管理_查询 + /// + /// + /// + /// + static public void GetUpLoadBarCode(string opName, out DataTable dt) + { + string procedureName; + procedureName = "思源库位管理_查询"; + SqlParameter[] thisParms = new SqlParameter[1]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out dt); + } + /// + /// [思源库位管理_下线库位_根据机型_查询] + /// + /// + /// + /// + static public void GetUpLoadWarehouseNoOpName02(string opName,string EngineIDType, out DataTable dt) + { + string procedureName; + procedureName = "思源库位管理_下线库位_根据机型_查询"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@发动机型号", EngineIDType); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out dt); + } + /// + /// 思源库位管理_下线库位查询 [思源库位管理_下线库位_根据机型_查询] + /// + /// + /// + /// + static public void GetUnLoadWarehouseNo(string opName, out DataTable dt) + { + string procedureName; + procedureName = "思源库位管理_下线库位查询"; + SqlParameter[] thisParms = new SqlParameter[1]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out dt); + } + //[思源库位管理_上线发动机号订单号查询] + static public void GetUpLoadEngineIDOrderForm(string opName,string kuweihao, out DataTable dt) + { + string procedureName; + procedureName = "[思源库位管理_上线发动机号订单号查询]"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@库位号", kuweihao); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out dt); + } + static public void UpdateKuWeiStatus(string opName, string kuweihao) + { + string procedureName; + procedureName = "[思源库位管理_上线更新状态_修改]"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@库位号", kuweihao); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } + static public void GetUpLoadBarCodeEngineID(string opName, out DataTable dt) + { + string procedureName; + procedureName = "[思源库位管理_上线发动机号查询]"; + SqlParameter[] thisParms = new SqlParameter[1]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out dt); + } + + static public void ClearOpCarData(string opName) + { + string procedureName; + procedureName = "[思源库位管理_清空所有库位数据]"; + SqlParameter[] thisParms = new SqlParameter[1]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } + // ALTER PROCEDURE[dbo].[思源库位管理_修改] + // @条码 nvarchar(50), + //@ nvarchar(50)=NULL, + //@ nvarchar(50), + //@ nvarchar(50), + + //@工位号 nvarchar(50), + //@库位号 nvarchar(50) + static public void GetUpLoadBarCode_Update(string opName,string kuweiNum ,string barCode,string orderForm, + string EngineID, string EngineIDType, int typeID) + { + string procedureName; + procedureName = "思源库位管理_修改"; + SqlParameter[] thisParms = new SqlParameter[7]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@库位号", kuweiNum); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@条码", barCode); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@订单号", orderForm); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@发动机号", EngineID); + thisParms[5] = new System.Data.SqlClient.SqlParameter("@发动机型号", EngineIDType); + thisParms[6] = new System.Data.SqlClient.SqlParameter("@机型代码", typeID); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } + + static public void GetUpLoadBarCode_0utUpdate(string opName, string kuweiNum) + { + string procedureName; + procedureName = "思源库位管理_出库修改"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@库位号", kuweiNum); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } + /// + /// 上线工位 扫面零件码 判断是否当前要加工的零件 + /// + /// + /// + static public void CheckUpLoadPart(string partCode, string scanPosition, out DataTable dt) + { + string procedureName; + procedureName = "SY_MES_计划BOM_判断工件是否匹配"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@partCode", partCode); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@抓取位置", scanPosition); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out dt); + } + /// + /// 线首工位自动查找生产订单 + /// + /// + static public void GetUpLoadPart(out DataTable dt) + { + string procedureName; + procedureName = "SY_MES_计划BOM_线首工位自动查找生产订单"; + SqlParameter[] thisParms = new SqlParameter[0]; + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out dt); + } + /// + /// 查询工位最大盆子数量 + /// + /// + /// + static public void GetMaxPartCount(string OpName, out DataTable dt) + { + string procedureName; + procedureName = "测量数据发动机在线状态_工位绑定与上线盆子数"; + SqlParameter[] thisParms = new SqlParameter[1]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", OpName); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out dt); + } + /// + /// 测量数据发动机在线状态_与订单数比对 + /// + /// + /// + static public void GetStartGoCount(out DataTable dt) + { + string procedureName; + procedureName = "测量数据发动机在线状态_与订单数比对"; + SqlParameter[] thisParms = new SqlParameter[0]; + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out dt); + } + static public void UpdateOrderStatus(string orderCode) + { + string procedureName; + procedureName = "SY_MES_计划BOM_更新订单生产状态"; + SqlParameter[] thisParms = new SqlParameter[1]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@订单号", orderCode); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } + //static public void SubLineLoadPartCountMatch_Select(string opName, out int SubLineLoadPartCountMatch) + //{ + // string procedureName; + // DataTable dt; + // procedureName = "MES_计划BOM_工位与名称_工步属性查询"; + // SqlParameter[] thisParms = new SqlParameter[1]; + // thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + // DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out dt); + // if(dt.Rows.Count>0) + // { + // SubLineLoadPartCountMatch = Convert.ToInt32(dt.Rows[0][0]); + // } + // else + // { + // SubLineLoadPartCountMatch = 0; + // } + //} + + } +} diff --git a/Common/07WebBusinessFacade/BusinessFacade/Web.New/MES1.cs b/Common/07WebBusinessFacade/BusinessFacade/Web.New/MES1.cs new file mode 100644 index 0000000..6ab69ff --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/Web.New/MES1.cs @@ -0,0 +1,120 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Data; +using System.Data.SqlClient; +using DataLinkMesWork; +using System.Security.Cryptography; +//using SystemFramework; + +namespace bizFacade +{ + public partial class MES1 + { + /// + /// 北汽福田工位状态监控MOBY_查询_订单下达用 + /// + /// + /// + /// + public static void Moby_Select_FirstOpName(string opName, out string OrderForm, + out int EngineTypeID, out string EngineType, out string EngineID, out string PartPallet_Code, + out int IsrepairBarcode, out string repairBarcode, out string EngineTypeString) + { + DataTable dt = new DataTable(); + OrderForm = ""; + EngineTypeID = 0; + EngineType = ""; + EngineID = ""; + PartPallet_Code = ""; + IsrepairBarcode = 0; + repairBarcode = ""; + EngineTypeString = ""; + try + { + string procedureName; + procedureName = "北汽福田工位状态监控MOBY_查询_订单下达用"; + SqlParameter[] thisParms = new SqlParameter[1]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out dt); + if (dt.Rows.Count > 0) + { + OrderForm = dt.Rows[0][MobyTagType.OrderForm_MES].ToString(); + EngineTypeID = Convert.ToInt32(dt.Rows[0][MobyTagType.EngineTypeID_MES]); ; + EngineType = dt.Rows[0][MobyTagType.EngineType_MES].ToString(); + EngineID = dt.Rows[0][MobyTagType.EngineID_MES].ToString(); + PartPallet_Code = dt.Rows[0][MobyTagType.PartPallet_Code].ToString(); + EngineTypeString = dt.Rows[0][MobyTagType.EngineTypeBasic].ToString(); + } + } + catch + { + OrderForm = ""; + EngineTypeID = 0; + EngineType = ""; + EngineID = ""; + PartPallet_Code = ""; + IsrepairBarcode = 0; + repairBarcode = ""; + EngineTypeString = ""; + } + } + /// + /// 普通工位,非上线工位 + /// 北汽福田工位状态监控MOBY_查询_订单下达用 + /// + /// + /// + /// + /// + /// + /// + /// + /// + public static void Moby_Select(string opName, out string OrderForm, + out int EngineTypeID, out string EngineType, out string EngineID, out string PartPallet_Code, + out int IsrepairBarcode, out string repairBarcode, out string EngineTypeString, int type = 1) + { + DataTable dt = new DataTable(); + OrderForm = ""; + EngineTypeID = 0; + EngineType = ""; + EngineID = ""; + PartPallet_Code = ""; + IsrepairBarcode = 0; + repairBarcode = ""; + EngineTypeString = ""; + try + { + string procedureName; + procedureName = "北汽福田工位状态监控MOBY_查询_订单下达用"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@计数类型", type); + + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out dt); + if (dt.Rows.Count > 0) + { + OrderForm = dt.Rows[0][MobyTagType.OrderForm].ToString(); + EngineTypeID = Convert.ToInt32(dt.Rows[0][MobyTagType.EngineTypeID]); ; + EngineType = dt.Rows[0][MobyTagType.EngineType].ToString(); + EngineID = dt.Rows[0][MobyTagType.EngineID].ToString(); + PartPallet_Code = dt.Rows[0][MobyTagType.PartPallet_Code].ToString(); + EngineTypeString = dt.Rows[0][MobyTagType.EngineTypeBasic].ToString(); + } + } + catch + { + OrderForm = ""; + EngineTypeID = 0; + EngineType = ""; + EngineID = ""; + PartPallet_Code = ""; + IsrepairBarcode = 0; + repairBarcode = ""; + EngineTypeString = ""; + } + } + } +} diff --git a/Common/07WebBusinessFacade/BusinessFacade/Web/Buttons.cs b/Common/07WebBusinessFacade/BusinessFacade/Web/Buttons.cs new file mode 100644 index 0000000..4ec33ce --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/Web/Buttons.cs @@ -0,0 +1,225 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Data; +using System.Data.SqlClient; +using DataLinkMesWork; +using System.Security.Cryptography; +//using SystemFramework; + +namespace bizFacade +{ + public class Buttons + { + /// + /// + /// + /// + /// + public static string Createbuttons(DataTable dt)//相当于在该DIV内动态画table + { + StringBuilder sb = new StringBuilder();//动态分配长度 + if (dt != null) + { + if (dt.Rows.Count > 0) + { + sb.Append(""); + for (int i = 0; i < dt.Rows.Count; i++) + { + //标签id + string id = "button_OPs" + dt.Rows[i]["工位号"].ToString(); + + //标签类型 + string type = "button"; + + //标签样式 + string style = "height:98%;width:98%;font-family:微软雅黑;font-size:15px;border-color: #99CCFF"; + + string style_td = "width:20%; height:35px"; + + //标签值 + string value = dt.Rows[i]["工位号"].ToString(); + + //标签点击事件 + string onclick = "QualityDataSelect(value)"; + + string bgc = "background-color: #CCCCCC";//默认按钮背景色 + if (dt.Rows[i]["合格标志"].ToString() == "NOK") + { + bgc = "background-color: red"; + } + else if (dt.Rows[i]["合格标志"].ToString() == "OK") + { + bgc = "background-color: green"; + } + else + { + bgc = "background-color: #CCCCCC"; + } + //对行按钮数进行处理,保证五个换行 + if (i % 4 == 3) + { + + sb.Append(""); + sb.Append("\r\n"); + } + else + { + sb.Append(""); + } + } + sb.Append("
"); + } + } + return sb.ToString(); + } + + public static string CreateNewbuttons(DataTable dt)//相当于在该DIV内动态画table + { + StringBuilder sb = new StringBuilder();//动态分配长度 + if (dt != null) + { + if (dt.Rows.Count > 0) + { + sb.Append(""); + for (int i = 0; i < dt.Rows.Count; i++) + { + //标签id + string id = "button_OPs" + dt.Rows[i]["工位号"].ToString(); + + //标签类型 + string type = "button"; + + //标签样式 + string style = "height:98%;width:98%;font-family:微软雅黑;font-size:15px;border-color: #99CCFF"; + + string style_td = "width:15%; height:30px"; + + //标签值 + string value = dt.Rows[i]["工位号"].ToString(); + + //标签点击事件 + string onclick = "QualityDataSelect(value)"; + + string bgc = "background-color: #CCCCCC";//默认按钮背景色 + if (dt.Rows[i]["合格标志"].ToString() == "NOK") + { + bgc = "background-color: red"; + } + else if (dt.Rows[i]["合格标志"].ToString() == "OK") + { + bgc = "background-color: green"; + } + else + { + bgc = "background-color: #CCCCCC"; + } + //对行按钮数进行处理,保证五个换行 + if (i % 5 == 4) + { + + sb.Append(""); + sb.Append("\r\n"); + } + else + { + sb.Append(""); + } + } + sb.Append("
"); + } + } + return sb.ToString(); + } + /// + /// 物料原因模块按钮创建 + /// + /// + /// + public static string CreateMaterialsButtons(DataTable dt) + { + StringBuilder sb = new StringBuilder(); + if (dt != null) + { + if (dt.Rows.Count > 0) + { + sb.Append(""); + for (int i = 0; i < dt.Rows.Count; i++) + { + string id = (string)dt.Rows[i]["id"]; + string type = (string)dt.Rows[i]["type"]; + string style = (string)dt.Rows[i]["style"]; + string value = (string)dt.Rows[i]["零件名称"]; + string onclick = (string)dt.Rows[i]["onclick"]; + string bgc = "";//默认按钮背景色 + sb.Append(""); + } + sb.Append("
"); + } + } + return sb.ToString(); + } + /// + /// + /// + /// + /// + public static string Createbuttons_alert(DataTable dt)//相当于在该DIV内动态画table + { + StringBuilder sb = new StringBuilder();//动态分配长度 + if (dt != null) + { + if (dt.Rows.Count > 0) + { + sb.Append(""); + for (int i = 0; i < dt.Rows.Count; i++) + { + //标签id + string id = "button_OPs" + dt.Rows[i]["工位号"].ToString(); + + //标签类型 + string type = "button"; + + //标签样式 + string style = "height:40px;line-height:35px;width:98%;font-family:'微软雅黑';font-size:15px;border-color:#99CCFF"; + + string style_td = "width:20%; height:35px"; + + //标签值 + string value = dt.Rows[i]["工位号"].ToString(); + + //标签点击事件 + string onclick = "QualityDataSelect_alert(value)"; + + string bgc = "background-color: #CCCCCC";//默认按钮背景色 + if (dt.Rows[i]["合格标志"].ToString() == "NOK") + { + bgc = "background-color: red"; + } + else if (dt.Rows[i]["合格标志"].ToString() == "OK") + { + bgc = "background-color: green"; + } + else + { + bgc = "background-color: #CCCCCC"; + } + //对行按钮数进行处理,保证五个换行 + if (i % 4 == 3) + { + + sb.Append(""); + sb.Append("\r\n"); + } + else + { + sb.Append(""); + } + } + sb.Append("
"); + } + } + return sb.ToString(); + } + } +} diff --git a/Common/07WebBusinessFacade/BusinessFacade/Web/Login.cs b/Common/07WebBusinessFacade/BusinessFacade/Web/Login.cs new file mode 100644 index 0000000..0ad092c --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/Web/Login.cs @@ -0,0 +1,237 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Data; +using System.Data.SqlClient; +using DataLinkMesWork; +using System.Security.Cryptography; +//using SystemFramework; + +namespace bizFacade +{ + public class UserLogin + { + /// + /// 登陆者查询_Easyui + /// + /// 登陆名 + /// 密码 + /// + /// + public static bool Getlogin(string opName, string message, out int IsSuccess) + { + IsSuccess = 0; + string produceName = "MES_用户管理_人员登录_扫码"; + SqlParameter[] thisParms = new SqlParameter[3]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@条码", message); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@是否符合", IsSuccess); + thisParms[2].Direction = ParameterDirection.Output; + if (DataAccess.ExecuteStoredProcedure(produceName, ref thisParms)) + { + IsSuccess = Convert.ToInt32(thisParms[2].Value); + return true; + } + return false; + } + + + public static void GetUrl(string opname, out DataTable tb) + { + string sql = "SELECT TOP 1 [WebHtml],[工位号],[工步属性],[服务器IP],[通讯端口] FROM [dbo].[MES_计划BOM_工位与名称_视图] WHERE [工位号]='" + opname + "'"; + //string connectionString = ApplicationConfig.ConnectionString; + string errorMessage; + tb = null; + DataAccess.ExecuteDataTable(sql, out tb); + } + public static bool ConfirmClass(string classes, out string confirmclass) + { + string procedureName = "AMES_物料拉动_人员班组管理_班次信息_查询"; + //string connectionString = ApplicationConfig.ConnectionString; + string errorMessage; + confirmclass = ""; + SqlParameter[] sqlParameters = new SqlParameter[1]; + sqlParameters[0] = new SqlParameter("@班次", SqlDbType.NVarChar, 50); + sqlParameters[0].Direction = ParameterDirection.Output; + if (DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters)) + { + confirmclass = sqlParameters[0].Value.ToString(); + return true; + } + return false; + } + public static void ClassName_Select(string ClassCode, out DataTable dt) + { + //string connectionString = ApplicationConfig.ConnectionString; + string errorMessage; + string sql; + sql = "SELECT top 1 班次描述 FROM [dbo].[AMES_物料拉动_人员班组管理_班次信息] WHERE [班次代码]='" + ClassCode + "'"; + dt = null; + DataAccess.ExecuteDataTable(sql, out dt); + } + /// + /// 修改新密码 + /// + /// + /// + public static void updatePassWord(string userName, string passWord, out DataTable tb) + { + string sql = "update [dbo].[MES_用户管理_人员] set 密码='" + passWord + "' WHERE [用户名]='" + userName + "'"; + //string connectionString = ApplicationConfig.ConnectionString; + string errorMessage; + tb = null; + DataAccess.ExecuteDataTable(sql, out tb); + } + /// + /// 登陆界面设置窗口提交 + /// + /// + /// + public static void InitLoginCombobox(string clientIp,out DataTable tb) + { + string sql = "SELECT [工位代码],[工位号] FROM [dbo].[MES_计划BOM_工位与名称_视图] WHERE [工控机IP]='" + clientIp + "'"; + //string connectionString = ApplicationConfig.ConnectionString; + string errorMessage; + tb = null; + DataAccess.ExecuteDataTable(sql, out tb); + } + + + /// + /// 登陆界面设置窗口提交 + /// + /// + /// + public static void submitSetOk(string opNum,string opName,string serverIp,string serverPort,string manchineIp, out DataTable tb) + { + string sql = "update [dbo].[MES_计划BOM_工位与名称] set 工位代码='" + opNum + "',工控机IP='" + manchineIp + "',工位号='" + opName + "',服务器IP='" + serverIp + "',通讯端口='" + serverPort + "' WHERE [工位号]='" + opName + "'"; + //string connectionString = ApplicationConfig.ConnectionString; + string errorMessage; + tb = null; + DataAccess.ExecuteDataTable(sql, out tb); + } + /// + /// 初始化设置串口的工位号 + /// + /// + public static void InitSetCombobox(out DataTable tb) + { + string sql = "SELECT [工位代码],[工位号] FROM [dbo].[MES_计划BOM_工位与名称_视图]"; + //string connectionString = ApplicationConfig.ConnectionString; + string errorMessage; + tb = null; + DataAccess.ExecuteDataTable(sql, out tb); + } + /// + /// 登陆者查询_Easyui + /// + /// 登陆名 + /// 密码 + /// + /// + public static bool loginUserSelect(string loginUser, string passWord, out DataTable tb) + { + string procedureName = "登陆者查询_Easyui"; + //string connectionString = ApplicationConfig.ConnectionString_MES; + DataSet ds; + string errorMessage; + bool isOK; + SqlParameter[] sqlParameters = new SqlParameter[2]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@登陆名", loginUser); + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@密码", passWord); + isOK = DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out ds); + if (isOK) + { + tb = ds.Tables[0]; + return true; + } + else + { + tb = null; + return false; + } + + } + + + + + public static void ClassCode_Select(string ClassName, out DataTable dt) + { + //string connectionString = ApplicationConfig.ConnectionString; + string errorMessage; + string sql; + sql = "SELECT top 1 班次代码 FROM AMES_物料拉动_人员班组管理_班次信息 WHERE [班次描述]='" + ClassName + "'"; + dt = null; + DataAccess.ExecuteDataTable(sql, out dt); + } + + + /// + /// 查询是否登录过 + /// + /// + /// + /// + public static void SearchUrl(string opname, out DataTable dt) + { + string procedureName; + procedureName = "测量数据工位_监控系统_操作者工号_查询"; + SqlParameter[] sqlParameters = new SqlParameter[1]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", opname); + DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + } + + + + + /// + /// [测量数据工位_监控系统_员工在线信息表_员工下线] + /// + /// + /// + /// + /// + /// + /// + /// + public static bool Getoff_WorkingHours(string Opname, string OperatorName, string OperatorManger, string Password, int Type, out string Msg) + { + string procedureName = "AMES_物料拉动_测量数据工位_监控系统_员工在线信息表_员工下线"; + //string connectionString = ApplicationConfig.ConnectionString; + string errorMessage; + Msg = ""; + SqlParameter[] sqlParameters = new SqlParameter[6]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@操作者工号", OperatorName); + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@管理者工号", OperatorManger); + sqlParameters[2] = new System.Data.SqlClient.SqlParameter("@工位号", Opname); + sqlParameters[3] = new System.Data.SqlClient.SqlParameter("@密码", Password); + sqlParameters[4] = new System.Data.SqlClient.SqlParameter("@下线类型", Type); + sqlParameters[5] = new SqlParameter("@Result", SqlDbType.NVarChar, 50); + sqlParameters[5].Direction = ParameterDirection.Output; + + if (DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters)) + { + Msg = sqlParameters[5].Value.ToString(); + return true; + } + + return false; + + + } + /// + /// 查询班次 + /// + /// + public static void Getclasses(out DataTable tb) + { + string sql = "SELECT [班次代码],[班次描述] FROM [dbo].[AMES_物料拉动_人员班组管理_班次信息] ORDER BY 班次代码 "; + //string connectionString = ApplicationConfig.ConnectionString; + string errorMessage; + tb = null; + DataAccess.ExecuteDataTable(sql, out tb); + } + + } +} diff --git a/Common/07WebBusinessFacade/BusinessFacade/Web/MES.Functions.cs b/Common/07WebBusinessFacade/BusinessFacade/Web/MES.Functions.cs new file mode 100644 index 0000000..641d883 --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/Web/MES.Functions.cs @@ -0,0 +1,619 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Data; +using System.Data.SqlClient; +using DataLinkMesWork; +using System.Security.Cryptography; +//using SystemFramework; +using System.Web; + +namespace bizFacade +{ + public partial class MES + { + /// + /// 测量数据工位_监控系统_MOBY_查询 + /// + /// + /// + /// + public static void Moby_Select(string opName, out string orderNum, + out int EngineTypeID, out string EngineType, out string EngineID, out string PartPallet_Code, + out int IsrepairBarcode, out string repairBarcode) + { + orderNum = ""; + EngineTypeID = 0; + EngineType = ""; + EngineID = ""; + PartPallet_Code = ""; + IsrepairBarcode = 0; + repairBarcode = ""; + try + { + string procedureName; + procedureName = "测量数据工位_监控系统_MOBY_查询"; + SqlParameter[] thisParms = new SqlParameter[8]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@订单号", SqlDbType.NVarChar, 50, "订单号"); + thisParms[1].Direction = ParameterDirection.Output; + thisParms[2] = new System.Data.SqlClient.SqlParameter("@产品型号代码", SqlDbType.Int, 4, "产品型号代码"); + thisParms[2].Direction = ParameterDirection.Output; + thisParms[3] = new System.Data.SqlClient.SqlParameter("@发动机型号", SqlDbType.NVarChar, 50, "发动机型号"); + thisParms[3].Direction = ParameterDirection.Output; + thisParms[4] = new System.Data.SqlClient.SqlParameter("@发动机号", SqlDbType.NVarChar, 50, "发动机号"); + thisParms[4].Direction = ParameterDirection.Output; + thisParms[5] = new System.Data.SqlClient.SqlParameter("@托盘号", SqlDbType.NVarChar, 50, "托盘号"); + thisParms[5].Direction = ParameterDirection.Output; + thisParms[6] = new System.Data.SqlClient.SqlParameter("@拆解标志", SqlDbType.Int, 4, "拆解标志"); + thisParms[6].Direction = ParameterDirection.Output; + thisParms[7] = new System.Data.SqlClient.SqlParameter("@拆解返修条码", SqlDbType.NVarChar, 50, "拆解返修条码"); + thisParms[7].Direction = ParameterDirection.Output; + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + if (thisParms[1].Value != null && thisParms[2].Value != null && thisParms[3].Value != null && thisParms[4].Value != null && thisParms[5].Value != null && thisParms[6].Value != null && thisParms[7].Value != null) + { + orderNum = thisParms[1].Value.ToString(); + EngineTypeID = Convert.ToInt32(thisParms[2].Value); ; + EngineType = thisParms[3].Value.ToString(); + EngineID = thisParms[4].Value.ToString(); + PartPallet_Code = thisParms[5].Value.ToString(); + IsrepairBarcode = Convert.ToInt32(thisParms[6].Value); ; + repairBarcode = thisParms[7].Value.ToString(); + } + } + catch + { + orderNum = ""; + EngineTypeID = 0; + EngineType = ""; + EngineID = ""; + PartPallet_Code = ""; + IsrepairBarcode = 0; + repairBarcode = ""; + } + } + + /// + /// 基本数据_工作日历_班次产量查询_Web页面显示_初始化查询 + /// + /// + /// + /// + public static void InitOpNameOuputCount(string opName, out int outputValue, out int nowOutputValue, + out int opNameBeatValue, out int NowOpNameBeatValue, out int classNumber) + { + outputValue = 0;//工位产量 + nowOutputValue = 0;//在线产量 + opNameBeatValue = 0;//工位节拍 + NowOpNameBeatValue = 0;//在线节拍 + classNumber = 0;//班次 + try + { + string procedureName; + procedureName = "Web页面显示_计划产量初始化查询"; + SqlParameter[] thisParms = new SqlParameter[6]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@工位产量", SqlDbType.Int, 4, "工位产量"); + thisParms[1].Direction = ParameterDirection.Output; + thisParms[2] = new System.Data.SqlClient.SqlParameter("@工位节拍", SqlDbType.Int, 4, "工位节拍"); + thisParms[2].Direction = ParameterDirection.Output; + thisParms[3] = new System.Data.SqlClient.SqlParameter("@在线产量", SqlDbType.Int, 4, "在线产量"); + thisParms[3].Direction = ParameterDirection.Output; + thisParms[4] = new System.Data.SqlClient.SqlParameter("@在线节拍", SqlDbType.Int, 4, "在线节拍"); + thisParms[4].Direction = ParameterDirection.Output; + thisParms[5] = new System.Data.SqlClient.SqlParameter("@班次代码", SqlDbType.Int, 4, "班次代码"); + thisParms[5].Direction = ParameterDirection.Output; + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + if (thisParms[1].Value != null && thisParms[2].Value != null && thisParms[3].Value != null && thisParms[4].Value != null && thisParms[5].Value != null) + { + outputValue = Convert.ToInt32(thisParms[1].Value); + opNameBeatValue = Convert.ToInt32(thisParms[2].Value); + nowOutputValue = Convert.ToInt32(thisParms[3].Value); + NowOpNameBeatValue = Convert.ToInt32(thisParms[4].Value); + classNumber = Convert.ToInt32(thisParms[5].Value); + } + } + catch + { + outputValue = 0; + opNameBeatValue = 0; + nowOutputValue = 0; + NowOpNameBeatValue = 0; + classNumber = 0; + } + } + + static public bool MaterialsDelete(string engineID, string engineType) + { + string procedureName = "轴系返修零件_删除"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工件编号", engineID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@产品型号", engineType); + return DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } + + /// + /// 测量数据工位_监控系统_手动转线_增加 + /// + /// + /// + /// + static public bool AskManualTransfer(string opName, int manualTransfer1, int applyOffLine, int updateOptions1) + { + string procedureName = "测量数据工位_监控系统_手动转线_增加"; + SqlParameter[] thisParms = new SqlParameter[4]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@是否启动转线", manualTransfer1); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@是否强制下线", applyOffLine); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@更新项目", updateOptions1); + + return DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } + + /// + /// 电子看板_工序内容_查询 + /// + /// 工位号 + /// 产品型号代码 + /// + static public void Process_Select(string opName, int engineTypeID, string EngineType, out DataTable dt) + { + dt = null; + string sql = "exec 电子看板_工序内容_查询 '" + opName + "'," + engineTypeID.ToString() + ",'" + EngineType + "'"; + DataAccess.ExecuteDataTable(sql, out dt); + } + + /// + /// 生产计划_派工订单_查询_工位执行 + /// + /// 工位号 + /// + static public void OrderFormList_Select(string opName, out DataTable dt) + { + dt = null; + string sql = "exec 生产计划_派工订单_查询_工位执行 '" + opName + "'"; + DataAccess.ExecuteDataTable(sql, out dt); + } + + /// + /// 电子看板_装配零件_物料验证_查询 20131231 + /// + /// 工位号 + /// 发动机号 + /// + static public bool PartMaterialVerify_Select(string opName, int engineTypeID, string engineType, out DataTable dt) + { + dt = null; + string procedureName; + procedureName = "电子看板_装配零件_临时表_查询"; + SqlParameter[] thisParms = new SqlParameter[3]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@产品型号代码", engineTypeID); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@发动机型号", engineType); + //thisParms[1] = new System.Data.SqlClient.SqlParameter("@发动机号", engineID); + return DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out dt); + } + + /// + /// 电子看板_工位机型_质量数据测量位置_查询_工作顺序 + /// + /// 工位号 + /// 产品型号代码 + /// + static public bool ShaftPositionSelect(string opNum, int EngineTypeID, out DataTable dt) + { + string procedureName = "电子看板_工位机型_质量数据测量位置_临时表_查询"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opNum); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@产品型号代码", EngineTypeID); + return DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out dt); + } + + /// + /// 电子看板_工位机型_物料检测测量位置_查询_物料检测 + /// + /// + /// + /// + static public bool MaterialCheckSelect(string opName, out DataTable dt) + { + string procedureName = "电子看板_工位机型_物料检测测量位置_查询_物料检测"; + SqlParameter[] thisParms = new SqlParameter[1]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + return DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out dt); + } + + /// + /// 测量数据合格_查询 + /// + /// + /// + /// + /// + static public bool QualitySelect(string opName, string engineID, out DataTable dt) + { + string procedureName = "测量数据合格_查询"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@发动机号", engineID); + return DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out dt); + } + + /// + /// 启用拧紧 + /// + /// + /// + /// + static public bool IsBackWork_Add(string opName, int IsBackWork) + { + string procedureName = "测量数据工位_监控系统_拧紧与返修拧紧_增加"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@是否启用备用模式", IsBackWork); + return DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } + + /// + /// 将手动转线/申请下线/返修上线更新到数据库中 + /// + /// + /// + /// + /// + /// + static public bool updataCbxFunction_add(string opName, int manualValue, int outlineValue, int repairVaule) + { + string procedureName = "测量数据工位_监控系统_上线下线转线_增加"; + SqlParameter[] thisParms = new SqlParameter[4]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@申请下线", outlineValue); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@返修上线", repairVaule); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@手动转线", manualValue); + return DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } + + /// + /// 测量数据工位_监控系统_订单号_增加 + /// + /// + /// + /// + static public bool OrderNum_Add(string opName, string orderNum) + { + string procedureName = "测量数据工位_监控系统_订单号_增加"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@订单号", orderNum); + return DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } + + /// + /// 测量数据工位_监控系统_订单号_增加 + /// + /// + /// + /// + static public bool Insert_OnlineOutline(string opName, int orderNum) + { + string procedureName = "测量数据工位_监控系统_在线离线屏蔽_增加"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@工位状态", orderNum); + return DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } + + /// + /// 功能按钮-从数据库中更新在线/离线/屏蔽 + /// + /// + /// + public static void Init_OnlineOutline(string opname, out DataTable tb) + { + string sql = "SELECT [工位状态] FROM [dbo].[测量数据工位_监控系统_在线离线屏蔽] WHERE [工位号]='" + opname + "'"; + //string connectionString = ApplicationConfig.ConnectionString; + string errorMessage; + tb = null; + DataAccess.ExecuteDataTable(sql, out tb); + } + + /// + /// 电子看板_工位机型_质量数据测量位置_查询_返修 + /// + /// + /// + /// + /// + public static void Init_TreeData1(string opName, int engineTypeId, string engineType, out DataTable tb) + { + string sql = "SELECT [序号],[说明] FROM [dbo].[电子看板_工位机型_质量数据测量位置] WHERE [工位号]='" + opName + "' and [产品型号代码]=" + engineTypeId + " and [发动机型号]='" + engineType + "'"; + //string connectionString = ApplicationConfig.ConnectionString; + string errorMessage; + tb = null; + DataAccess.ExecuteDataTable(sql, out tb); + } + + /// + /// 电子看板_工位机型_质量数据测量位置_查询_返修 + /// + /// + /// + /// + static public bool Init_TreeData(string opName, out DataTable dt) + { + string procedureName = "电子看板_工位机型_质量数据测量位置_查询_返修"; + SqlParameter[] thisParms = new SqlParameter[1]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + return DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out dt); + } + + /// + /// 测量数据工位_监控系统_发动机型号_增加 + /// + /// + /// + /// + /// + static public bool EngineNum_Add(string opName, string enginetype, int enginetypeID) + { + string procedureName = "测量数据工位_监控系统_发动机型号_增加"; + SqlParameter[] thisParms = new SqlParameter[3]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@发动机型号", enginetype); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@产品型号代码", enginetypeID); + return DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } + + /// + /// 测量数据工位_监控系统_手动打印_增加 + /// + /// + /// + /// + /// + /// + /// + public static bool OpName_MIS_Manual_Insert(string opName, int year, int month, int day, int num) + { + string produceName = "测量数据工位_监控系统_手动打印_增加"; + SqlParameter[] thisParms = new SqlParameter[5]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@年", year); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@月", month); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@日", day); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@流水号", num); + return DataAccess.ExecuteStoredProcedure(produceName, ref thisParms); + } + + /// + /// 测量数据工位_监控系统_订单号_查询 + /// + /// + /// + /// + public static bool OpName_MIS_OrderForm_Select(string opName, out DataTable dt) + { + string sql = "select top 1 订单号 from 测量数据工位_监控系统_订单号 where 工位号='" + opName + "'"; + return DataAccess.ExecuteDataTable(sql, out dt); + } + + /// + /// 测量数据工位_监控系统_发动机型号_查询 + /// + /// + /// + /// + public static bool OpName_MIS_EngineType_Select(string opName, out DataTable dt) + { + string sql = "select top 1 产品型号代码,发动机型号 from 测量数据工位_监控系统_发动机型号 where 工位号='" + opName + "'"; + return DataAccess.ExecuteDataTable(sql, out dt); + } + + /// + /// 测量数据工位_监控系统_系统初始化 + /// + /// + /// + public static bool WebLoginIn(string opName) + { + string produceName = "测量数据工位_监控系统_系统初始化"; + SqlParameter[] thisParms = new SqlParameter[1]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + return DataAccess.ExecuteStoredProcedure(produceName, ref thisParms); + } + + /// + /// 获得工位对应的返修工位号 + /// + /// + /// + public static void GetopRepairName(string opname, out DataTable tb) + { + string sql = "SELECT TOP 1 [返修工位号] FROM [dbo].[MES_计划BOM_工位与名称_视图] WHERE [工位号]='" + opname + "'"; + //string connectionString =ApplicationConfig.ConnectionString; + string errorMessage; + tb = null; + DataAccess.ExecuteDataTable(sql, out tb); + } + + /// + /// 测量数据工位_监控系统_离线返修_增加 + /// + /// + /// + /// + static public bool AskOutLineRepair(string opName, int outLineRepair1) + { + string procedureName = "测量数据工位_监控系统_离线返修_增加"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@离线返修", outLineRepair1); + return DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } + + /// + /// 电子看板_装配零件_修改_零件批号 + /// + /// + /// + /// + /// + public static bool Material_Betch_Update(string opName, string engineType, DataTable dt) + { + string produceName = "电子看板_装配零件_修改_零件批号"; + SqlParameter[] thisParms = new SqlParameter[5]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@零件图号", SqlDbType.NVarChar, 50, "零件图号"); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@零件批号", SqlDbType.NVarChar, 50, "零件批号"); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@生产厂家", SqlDbType.NVarChar, 50, "生产厂家"); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@发动机型号", engineType); + return DataAccess.ExecuteStoredProcedure(produceName, ref thisParms, dt); + } + + /// + /// 电子看板_工位机型_质量数据测量位置_临时表_修改_返修 + /// + /// + /// + public static bool Insert_selectTreeData(DataTable dt) + { + string produceName = "电子看板_工位机型_质量数据测量位置_临时表_修改_返修"; + SqlParameter[] thisParms = new SqlParameter[3]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", SqlDbType.NVarChar, 50, "工位号"); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@产品型号代码", SqlDbType.Int, 4, "产品型号代码"); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@序号", SqlDbType.Int, 4, "序号"); + return DataAccess.ExecuteStoredProcedure(produceName, ref thisParms, dt); + } + + /// + /// 返修上线插入界面选择的工位合格标志 + /// + /// + /// + public static bool Insert_RepairPartLoad_OpInfo(string opname, string zbz_parameter, string csq_parameter, string zzx_parameter, string jcx_parameter) + { + string sql = "UPDATE [电子看板_发动机号_线首工位_工位合格标志] SET [轴部装线]=" + zbz_parameter + + " ,[差速器线]=" + csq_parameter + + " ,[总装线]=" + zzx_parameter + + " ,[检测线]=" + jcx_parameter + + " WHERE [工位号]='" + opname + "'"; + //string connectionString = ApplicationConfig.ConnectionString; + string errorMessage; + return DataAccess.ExecuteSQL(sql); + } + + /// + /// 返修上线插入界面选择的工位合格标志 + /// + /// + /// + public static bool Select_RepairLoadBtn(string opname, out DataTable dt) + { + string sql = "SELECT [轴部装线],[差速器线],[总装线],[检测线] FROM [电子看板_发动机号_线首工位_工位合格标志] WHERE 工位号='" + opname + "'"; + //string connectionString = ApplicationConfig.ConnectionString; + string errorMessage; + return DataAccess.ExecuteDataTable(sql, out dt); + } + + /// + /// 获得返修数量信息 + /// + /// + /// + /// + public static bool OpName_MIS_RepiareNum_Select(string opName, out DataTable dt) + { + string sql = "select top 1 设置数量,当前数量 from 测量数据工位_监控系统_批量返修 where 工位号='" + opName + "'"; + return DataAccess.ExecuteDataTable(sql, out dt); + } + + /// + /// 插入返修数量信息 + /// + /// + /// + /// + static public bool Insert_RepiareNum(string opName, int RepiareNum) + { + string procedureName = "测量数据工位_监控系统_批量返修_增加"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@返修数量", RepiareNum); + return DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } + + /// + /// 生产计划_派工订单_查询_工位执行_完工判断 + /// + /// + /// + /// + /// + public static void Select_OrderFormList_OrderComplete(string opName, out int isCompleted, out int num_plan, out int num_complete) + { + isCompleted = 0;//订单数量是否完全上线 + num_plan = 0;//计划数量 + num_complete = 0;//上线数量 + try + { + string procedureName; + procedureName = "生产计划_派工订单_查询_工位执行_完工判断"; + SqlParameter[] thisParms = new SqlParameter[4]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@ISCOMPLETE", SqlDbType.Int, 4, "ISCOMPLETE"); + thisParms[1].Direction = ParameterDirection.Output; + thisParms[2] = new System.Data.SqlClient.SqlParameter("@NUM_PLAN", SqlDbType.Int, 4, "NUM_PLAN"); + thisParms[2].Direction = ParameterDirection.Output; + thisParms[3] = new System.Data.SqlClient.SqlParameter("@NUM_COMPLETE", SqlDbType.Int, 4, "NUM_COMPLETE"); + thisParms[3].Direction = ParameterDirection.Output; + + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + if (thisParms[1].Value != null && thisParms[2].Value != null && thisParms[3].Value != null) + { + isCompleted = Convert.ToInt32(thisParms[1].Value); + num_plan = Convert.ToInt32(thisParms[2].Value); + num_complete = Convert.ToInt32(thisParms[3].Value); + } + } + catch + { + isCompleted = 0; + num_plan = 0; + num_complete = 0; + } + } + + /// + /// WEB根据工位号和线外扫描主物料查询质量数据合格索引(包括了分线的信息、存储过程中根据工位类型区分) 20170318 corbin + /// + /// + /// + /// + /// + public static bool QualityDataButton_bgColor_alert_Select(string opname, out DataTable dt) + { + string procedureName = "显示测量数据_工位号_根据线外工位验证_查询"; + SqlParameter[] sqlParameters = new SqlParameter[1]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", opname); + //sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@发动机号", lineout_barcode); + return DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + } + + /// + /// 显示物料数据_根据_工位号_发动机型号_查询_分线数据 + /// + /// + /// + /// + /// + static public bool MaterialDataSelect_F_EnergineID(string opname, string energineID, out DataTable dt) + { + string procedureName; + procedureName = "显示物料数据_根据_工位号_发动机型号_查询_分线数据"; + SqlParameter[] sqlParameters = new SqlParameter[2]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", opname); + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@发动机号", energineID); + return DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + } + } +} \ No newline at end of file diff --git a/Common/07WebBusinessFacade/BusinessFacade/Web/MES.MaterialPull.cs b/Common/07WebBusinessFacade/BusinessFacade/Web/MES.MaterialPull.cs new file mode 100644 index 0000000..7ca3942 --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/Web/MES.MaterialPull.cs @@ -0,0 +1,684 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Data; +using System.Data.SqlClient; +using DataLinkMesWork; +using System.Security.Cryptography; +//using SystemFramework; + +namespace bizFacade +{ + public partial class MaterialPull + { + #region + //---------------------------------MES.Function中的---------------------------------- + /// + /// 物料拉动_工位物料需求单_转移_查询_单号 + /// + /// 工位号 + /// 1 + /// + static public void MaterialPush_ListNumer_Select(int orderNum_Check, string orderNum, int opName_Checked, string opName,int type_Check,string type, out DataTable dt) + { + dt = null; + string sql = "物料拉动_工位物料需求单_转移_查询_单号 " + orderNum_Check + ",'" + orderNum + "'," + opName_Checked + ",'" + opName + "'," + type_Check + ",'" + type+"'"; + DataAccess.ExecuteDataTable(sql, out dt); + } + + /// + /// 物料拉动_工位物料需求单_转移_查询 + /// + /// 工位号 + /// + static public void MaterialPush_Details_Select(string listNumber,string opName, out DataTable dt) + { + dt = null; + string sql = "物料拉动_工位物料需求单_转移_查询 '" + listNumber + "','" + opName + "'"; + DataAccess.ExecuteDataTable(sql, out dt); + } + + /// + /// 物料拉动_线边库存_接受物料_物料需求单 + /// + /// + /// + /// + /// + public static bool DistributionNum(string opName, string DistributionNum) + { + string produceName = "物料拉动_线边库存_接受物料_物料需求单"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@配送单号", DistributionNum); + return DataAccess.ExecuteStoredProcedure(produceName, ref thisParms); + } + /// + /// 配送单实时同步表数据增加 + /// + /// + /// + static public bool MaterialPull_DocumentInfo_Add(DataTable dt) + { + //string connectionString = ApplicationConfig.ConnectionString; + string produceName = "AMES_物料拉动_配送物料接收_配送物料信息_增加"; + SqlParameter[] thisParms = new SqlParameter[12]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@仓库地址", SqlDbType.NVarChar, 50, "WAREHOUSE_CODE"); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@创建时间", SqlDbType.DateTime, 50, "CREATION_DATE"); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@订单号", SqlDbType.NVarChar, 50, "ORDER_NUMBER"); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@工位号", SqlDbType.NVarChar, 50, "DISTRIBUTE_WKC_CODE"); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@供应商代码", SqlDbType.NVarChar, 50, "SUPPLIER_CODE"); + thisParms[5] = new System.Data.SqlClient.SqlParameter("@卡片条码", SqlDbType.NVarChar, 50, "BARCODE"); + thisParms[6] = new System.Data.SqlClient.SqlParameter("@类型", SqlDbType.NVarChar, 50, "IS_DOCUMENT"); + thisParms[7] = new System.Data.SqlClient.SqlParameter("@配送单号", SqlDbType.NVarChar, 50, "DOCUMENT_NUM"); + thisParms[8] = new System.Data.SqlClient.SqlParameter("@配送数量", SqlDbType.Int, 50, "QUANTITY"); + thisParms[9] = new System.Data.SqlClient.SqlParameter("@批次号", SqlDbType.NVarChar, 50, "LOT_NUMBER"); + thisParms[10] = new System.Data.SqlClient.SqlParameter("@条码数量", SqlDbType.Int, 50, "BARCODE_QTY"); + thisParms[11] = new System.Data.SqlClient.SqlParameter("@物料号", SqlDbType.NVarChar, 50, "ITEM_CODE"); + if (DataAccess.ExecuteStoredProcedure(produceName, ref thisParms, dt)) + { + return true; + } + return false; + } + + /// + /// 获取卡片一览信息查询 + /// + /// + /// + /// + public static bool getMaterialNumInfo(string opName, string itemCode, out DataTable dt) + { + string errorMessage; + string sql; + //string connectionString_MES = ApplicationConfig.ConnectionString; + sql = "SELECT 线边库存流水号,订单号,工位号,物料号,卡片条码,批次号,当前数量 AS '库存数量',卡片数量,使用标志 FROM dbo.AMES_物料拉动_线边库存 WHERE 工位号='" + opName + "' AND 物料号='" + itemCode + "' ORDER BY 使用标志 DESC"; + return DataAccess.ExecuteDataTable(sql, out dt); + } + /// + /// 物料号一览信息查询 + /// + /// + /// + public static void InitMaterial_Dialog_MaterialNum(string opcnum, out DataTable dt) + { + //string connectionString = ApplicationConfig.ConnectionString; + string errorMessage; + string sql; + dt = null; + sql = "SELECT DISTINCT 物料号 FROM dbo.AMES_物料拉动_线边库存 WHERE 工位号='" + opcnum + "' GROUP BY 物料号 ORDER BY 物料号 "; + DataAccess.ExecuteDataTable(sql, out dt); + + } + /// + /// 查询班次 + /// + /// + public static void Getclasses(out DataTable tb) + { + string sql = "SELECT [班次代码],[班次描述] FROM [dbo].[AMES_物料拉动_人员班组管理_班次信息] ORDER BY 班次代码 "; + //string connectionString = ApplicationConfig.ConnectionString; + string errorMessage; + tb = null; + DataAccess.ExecuteDataTable(sql, out tb); + } + + /// + /// 查询打卡上线人数 + /// + /// + /// + public static void Search_OnlineInfo(string opname, out DataTable dt) + { + string sql = "SELECT [工位号] ,[操作者工号],[操作者姓名] ,[班次] ,[操作时间] FROM [dbo].[AMES_物料拉动_测量数据工位_监控系统_员工在线信息表] WHERE [工位号]='" + opname + "'"; + //string connectionString = ApplicationConfig.ConnectionString; + string errorMessage; + dt = null; + DataAccess.ExecuteDataTable(sql, out dt); + } + public static void ClassName_Select(string ClassCode, out DataTable dt) + { + //string connectionString = ApplicationConfig.ConnectionString; + string errorMessage; + string sql; + sql = "SELECT top 1 班次描述 FROM AMES_物料拉动_人员班组管理_班次信息 WHERE [班次代码]='" + ClassCode + "'"; + dt = null; + DataAccess.ExecuteDataTable(sql, out dt); + } + public static bool ConfirmClass( out string confirmclass) + { + string procedureName = "AMES_物料拉动_人员班组管理_班次信息_查询"; + //string connectionString = ApplicationConfig.ConnectionString; + string errorMessage; + confirmclass = ""; + SqlParameter[] sqlParameters = new SqlParameter[1]; + sqlParameters[0] = new SqlParameter("@班次", SqlDbType.NVarChar, 50); + sqlParameters[0].Direction = ParameterDirection.Output; + if (DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters)) + { + confirmclass = sqlParameters[0].Value.ToString(); + return true; + } + return false; + } + + /// + /// [测量数据工位_监控系统_员工在线信息表_增加] + /// + /// + /// + /// + /// + /// + public static bool Insert_WorkingHours(string Opname, string OperatorName, string Password, string Classes, out string Msg) + { + string procedureName = "AMES_物料拉动_测量数据工位_监控系统_员工在线信息表_员工上线"; + //string connectionString = ApplicationConfig.ConnectionString; + string errorMessage; + Msg = ""; + SqlParameter[] sqlParameters = new SqlParameter[5]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@操作者工号", OperatorName); + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@工位号", Opname); + sqlParameters[2] = new System.Data.SqlClient.SqlParameter("@员工密码", Password); + sqlParameters[3] = new System.Data.SqlClient.SqlParameter("@班次", Classes); + sqlParameters[4] = new SqlParameter("@Result", SqlDbType.NVarChar, 50); + sqlParameters[4].Direction = ParameterDirection.Output; + + if (DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters)) + { + Msg = sqlParameters[4].Value.ToString(); + return true; + } + + return false; + + + } + #endregion + + #region + //---------------------------------login中的---------------------------------- + /// + /// 查询工作中心 + /// + /// + /// + public static DataTable DirectUpload_WorkCenterCode_Select() + { + DataTable dt = null; + string sql; + sql = "SELECT top 1 工作中心 FROM dbo.AMES_物料拉动_MES_工厂与工作中心 "; + DataAccess.ExecuteDataTable(sql, out dt); + return dt; + } + + //新增直供上线 + public static bool DirectUpload_VerifyTempTable_Delete(string opName) + { + string produceName = "AMES_物料拉动_直供上线_验证临时表_删除"; + SqlParameter[] thisParms = new SqlParameter[1]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + + return DataAccess.ExecuteStoredProcedure(produceName, ref thisParms); + } + //新增直供上线 + public static bool DirectUpload_VerifyTempTable_Add(string opName, DataTable dt) + { + string produceName = "AMES_物料拉动_直供上线_验证临时表_增加"; + SqlParameter[] thisParms = new SqlParameter[18]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@仓库地址", SqlDbType.NVarChar, 50, "WAREHOUSE_CODE"); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@是否标准", SqlDbType.NVarChar, 50, "NOTIFICATION_TYPE_MEAN"); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@允许接收", SqlDbType.NVarChar, 50, "IS_NEED_VALIDATING"); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@工厂", SqlDbType.NVarChar, 50, "PLANT_ID"); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@工作中心", SqlDbType.NVarChar, 50, "PROD_LINE_CODE"); + thisParms[5] = new System.Data.SqlClient.SqlParameter("@卡片条码", SqlDbType.NVarChar, 50, "SGL_CODE"); + thisParms[6] = new System.Data.SqlClient.SqlParameter("@物料号", SqlDbType.NVarChar, 50, "ITEM_CODE"); + thisParms[7] = new System.Data.SqlClient.SqlParameter("@物料描述", SqlDbType.NVarChar, 50, "DESCRIPTIONS"); + thisParms[8] = new System.Data.SqlClient.SqlParameter("@卡片数量", SqlDbType.NVarChar, 50, "QUANTITY"); + thisParms[9] = new System.Data.SqlClient.SqlParameter("@批次号", SqlDbType.NVarChar, 50, "LOT_NUMBER"); + thisParms[10] = new System.Data.SqlClient.SqlParameter("@供应商代码", SqlDbType.NVarChar, 50, "SUPPLIER_CODE"); + thisParms[11] = new System.Data.SqlClient.SqlParameter("@工位号", SqlDbType.NVarChar, 50, "DISTRIBUTE_WKC_CODE"); + thisParms[12] = new System.Data.SqlClient.SqlParameter("@配送单号", SqlDbType.NVarChar, 50, "ATTRIBUTE9"); + thisParms[13] = new System.Data.SqlClient.SqlParameter("@订单号", SqlDbType.NVarChar, 50, "ORDER_NUMBER"); + thisParms[14] = new System.Data.SqlClient.SqlParameter("@线边地址", SqlDbType.NVarChar, 50, "WAREHOUSE_CODE1"); + thisParms[15] = new System.Data.SqlClient.SqlParameter("@创建时间", SqlDbType.NVarChar, 50, "CREATION_DATE"); + thisParms[16] = new System.Data.SqlClient.SqlParameter("@条码状态", SqlDbType.NVarChar, 50, "STATUS"); + thisParms[17] = new System.Data.SqlClient.SqlParameter("@验证工位号", opName); + return DataAccess.ExecuteStoredProcedure(produceName, ref thisParms, dt); + } + //新增直供上线 + public static bool DirectUpload_VerifyTempTable_Select(string opName, string document_Num, out string process_Message, out DataTable dt) + { + process_Message = ""; + string procedureName = "AMES_物料拉动_直供上线_验证临时表_查询_送货单行"; + SqlParameter[] thisParms = new SqlParameter[3]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@配送单号", document_Num); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@PROCESS_MESSGE", SqlDbType.NVarChar, 200); + thisParms[2].Direction = ParameterDirection.Output; + if (DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out dt)) + { + process_Message = thisParms[2].Value.ToString(); + return true; + } + return false; + } + + public static bool DirectUpload_VerifyTempTable_Barcode_Select(string opName, string document_Num, string barcode, out string process_Message, out DataTable dt) + { + process_Message = ""; + string procedureName = "AMES_物料拉动_直供上线_验证临时表_查询_料箱标签"; + SqlParameter[] thisParms = new SqlParameter[4]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@配送单号", document_Num); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@卡片条码", barcode); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@PROCESS_MESSGE", SqlDbType.NVarChar, 200); + thisParms[3].Direction = ParameterDirection.Output; + if (DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out dt)) + { + process_Message = thisParms[3].Value.ToString(); + return true; + } + return false; + } + + public static bool DirectUpload_VerifyTempTable_VerifyOK(string opName, string document_Num, out string process_Message) + { + process_Message = ""; + string procedureName = "AMES_物料拉动_直供上线_验证临时表_验证成功"; + SqlParameter[] thisParms = new SqlParameter[3]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@配送单号", document_Num); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@PROCESS_MESSGE", SqlDbType.NVarChar, 200); + thisParms[2].Direction = ParameterDirection.Output; + if (DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms)) + { + process_Message = thisParms[2].Value.ToString(); + return true; + } + return false; + } + + public static bool DirectUpload_ReceiveRecord_Select(string opName, string document_Num, string groupId, out DataTable dt) + { + + string procedureName = "AMES_物料拉动_直供上线_接收记录_查询"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@配送单号", document_Num); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@GroupID", groupId); + return DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out dt); + } + public static bool DirectUpload_VerifyTempTable_NoticeOK(string opName, string document_Num, string groupId, int isOk, string outResult) + { + string produceName = "AMES_物料拉动_直供上线_验证临时表_调用成功"; + SqlParameter[] thisParms = new SqlParameter[5]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@配送单号", document_Num); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@GROUPID", groupId); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@是否成功", isOk); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@PROCESS_MESSGE", outResult); + return DataAccess.ExecuteStoredProcedure(produceName, ref thisParms); + } + + public static DataTable DirectUpload_OpName_Select(string opName) + { + DataTable dt = null; + string sql; + sql = "SELECT top 1 指南工位号 FROM MES_计划BOM_工位与名称 WHERE 工位号='" + opName + "'"; + DataAccess.ExecuteDataTable(sql, out dt); + return dt; + } + /// + /// 物料拉动_库存盘点_物料号查询 + /// + /// + + public static void Init_MaterialNumCombobox(string Opname, out DataTable dt_MaterialNum) + { + string sql = "SELECT DISTINCT ROW_NUMBER() OVER (ORDER BY 物料号 )AS ID,[物料号] FROM AMES_物料拉动_线边库存 WHERE 工位号='" + Opname + "' GROUP BY 物料号 ORDER BY 物料号 "; + //string connectionString = ApplicationConfig.ConnectionString; + string errorMessage; + dt_MaterialNum = null; + DataAccess.ExecuteDataTable(sql, out dt_MaterialNum); + } + + /// + /// 物料拉动_库存盘点_消耗 + /// + /// + /// + /// + public static bool Consume_StockCount(string OrderNumber, string ConsumeNum, string Opname, string CardNum) + { + string procedureName = "[AMES_物料拉动_线边库存_消耗_人工盘点]"; + //string connectionString = ApplicationConfig.ConnectionString_MES; + string errorMessage; + bool isOK; + SqlParameter[] sqlParameters = new SqlParameter[4]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@订单号", OrderNumber); + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@消耗数量", ConsumeNum); + sqlParameters[2] = new System.Data.SqlClient.SqlParameter("@盘点工位号", Opname); + sqlParameters[3] = new System.Data.SqlClient.SqlParameter("@卡片条码", CardNum); + isOK = DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters); + if (isOK) + { + return true; + } + else + { + return false; + } + } + + + static public bool MaterialPull_DocumentInfo_ReceiveRecord_Select(string document_Num, string groupId, out DataTable dt) + { + //此存储过程与直供上线通用 + string procedureName = "AMES_物料拉动_直供上线_接收记录_查询"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@配送单号", document_Num); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@GroupID", groupId); + if (DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out dt)) + { + return true; + } + return false; + } + + + //调用成功 + static public bool MaterialPull_DocumentInfo_NoticeOK(string document_Num, string groupId, int isOk, string outResult) + { + string process_Message = ""; + string produceName = "AMES_物料拉动_配送物料接收_调用成功"; + SqlParameter[] thisParms = new SqlParameter[4]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@配送单号", document_Num); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@GROUPID", groupId); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@是否成功", isOk); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@PROCESS_MESSGE", outResult); + if (DataAccess.ExecuteStoredProcedure(produceName, ref thisParms)) + { + return true; + } + return false; + } + public static bool DocumentOutLineInfo_Select(string distributionNum, out DataTable dt) + { + string sql; + sql = "SELECT * FROM AMES_物料拉动_线边库存_备份 WHERE 配送单号='" + distributionNum + "'"; + dt = null; + return DataAccess.ExecuteDataTable(sql, out dt); + } + + public static bool WorkStationInfo_Select(out DataTable dt) + { + string sql; + sql = "SELECT top 1 工作中心 FROM AMES_物料拉动_MES_工厂与工作中心 "; + return DataAccess.ExecuteDataTable(sql, out dt); + } + //物料拉动_库存盘点_初始化 DataGrid + public static void init_StockCount(string opname, string MaterialNum, out DataTable dt_StockCount) + { + string sql = "SELECT DISTINCT A.线边库存流水号,A.工位号, A.订单号,A.当前数量, A.物料号, B.物料描述, A.卡片条码 FROM AMES_物料拉动_线边库存 as A INNER JOIN dbo.AMES_物料拉动_生产计划_派工订单BOM_分配到工位 AS B ON A.物料号 = B.物料号 where A.工位号='" + opname + "'and A.物料号='" + MaterialNum + "' ORDER BY [物料号]"; + //string connectionString = ApplicationConfig.ConnectionString; + string errorMessage; + dt_StockCount = null; + DataAccess.ExecuteDataTable(sql, out dt_StockCount); + } + /// + /// 物料拉动_库存盘点_订单号查询 + /// + /// + public static void Init_FinalOrderNumberCombobox(out DataTable dt_OrderNumber) + { + string dateString = DateTime.Now.ToString("yyyy-MM-01"); + string sql = "SELECT DISTINCT ROW_NUMBER() OVER (ORDER BY 订单号 )AS ID,订单号 FROM [dbo].[AMES_物料拉动_生产计划_派工订单完工统计] WHERE 操作时间 > '" + dateString + "' GROUP BY 订单号 ORDER BY [订单号]"; + //string connectionString = ApplicationConfig.ConnectionString; + string errorMessage; + dt_OrderNumber = null; + DataAccess.ExecuteDataTable(sql, out dt_OrderNumber); + } + /// + /// FTT总成编号查询 + /// + /// + public static void Init_FinalListCombobox(string opName, out DataTable dt_EngineNum) + { + string sql; + sql = "SELECT TOP 20 ROW_NUMBER() OVER (ORDER BY 发动机号 )AS ID, 发动机号 FROM [dbo].[测量数据发动机在线状态_跟踪发动机条码状态]" + "WHERE 工位号='" + opName + "' ORDER BY 发动机号 DESC"; + //string connectionString = ApplicationConfig.ConnectionString; + string errorMessage; + dt_EngineNum = null; + DataAccess.ExecuteDataTable(sql, out dt_EngineNum); + } + /// + /// 缺陷代码查询 + /// + /// + /// + public static void Init_DefectCodeCombobox(string opName, out DataTable dt_DefectCode) + { + string sql; + sql = "SELECT [编号],[编号描述] FROM [dbo].[ANDON_类型_编号]where 工位号='" + opName + "'AND [安东类型代码]=2 "; + //string connectionString = ApplicationConfig.ConnectionString; + string errorMessage; + dt_DefectCode = null; + DataAccess.ExecuteDataTable(sql, out dt_DefectCode); + } + /// + /// 质量管理_质量FTT_不合格品补录_临时表_增加 + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + public static bool Insert_FTTInformation(string opname, string andoTypeCode, string EngineNum, string group_Number, string defect_Number, string ProblemDate, int callCount, out string Msg) + { + string procedureName = "质量管理_质量FTT_不合格品补录_临时表_增加"; + //string connectionString = ApplicationConfig.ConnectionString; + string errorMessage; + Msg = ""; + SqlParameter[] sqlParameters = new SqlParameter[8]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", opname); + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@代码组", group_Number); + sqlParameters[2] = new System.Data.SqlClient.SqlParameter("@代码", defect_Number); + sqlParameters[3] = new System.Data.SqlClient.SqlParameter("@呼叫数量", callCount); + sqlParameters[4] = new System.Data.SqlClient.SqlParameter("@安东类型代码", andoTypeCode); + sqlParameters[5] = new System.Data.SqlClient.SqlParameter("@工件编号", EngineNum); + sqlParameters[6] = new System.Data.SqlClient.SqlParameter("@问题日期", ProblemDate); + sqlParameters[7] = new SqlParameter("@Msg", SqlDbType.NVarChar, 50); + sqlParameters[7].Direction = ParameterDirection.Output; + + if (DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters)) + { + Msg = sqlParameters[7].Value.ToString(); + return true; + } + + return false; + + + } + + static public bool MaterialPull_DocumentInfo_CreateRecord(string document_Num, out string process_Message) + { + process_Message = ""; + string procedureName = "AMES_物料拉动_配送物料接收_产生接收记录"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@配送单号", document_Num); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@PROCESS_MESSGE", SqlDbType.NVarChar, 200); + thisParms[1].Direction = ParameterDirection.Output; + if (DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms)) + { + process_Message = thisParms[1].Value.ToString(); + return true; + } + return false; + } + + /// + /// 校验发动机号 + /// + /// + /// + public static void Confirm_EngineNum(string Final_EngineNum, string DefectGroup, string DefectCode, string Opname, out DataTable dt_DefectCode) + { + string sql; + sql = " SELECT COUNT(*)FROM 质量管理_质量FTT_不合格品_临时表 WHERE 产品序列号 ='" + Final_EngineNum + "' AND 代码='" + DefectCode + "' AND 代码组='" + DefectGroup + "' AND 工位号='" + Opname + "' "; + //string connectionString = ApplicationConfig.ConnectionString; + string errorMessage; + dt_DefectCode = null; + DataAccess.ExecuteDataTable(sql, out dt_DefectCode); + } + /// 查询指南工位号 + ///
+ /// + /// + public static void OpName_Convert_Select(string opname, out DataTable dt_ConvertOpname) + { + + string errorMessage; + string sql; + sql = " SELECT 指南工位号 FROM MES_计划BOM_工位与名称 WHERE 工位号='" + opname + "' "; + //string connectionString = ApplicationConfig.ConnectionString; + dt_ConvertOpname = null; + DataAccess.ExecuteDataTable(sql, out dt_ConvertOpname); + + } + #endregion + /// + /// 订单机型查询 + /// + /// + /// + /// + public static void Init_OrderNum_Query(string startTime, string endTime, out DataTable dt) + { + string sql; + sql = "SELECT [订单号] ,[产品型号] FROM dbo.AMES_物料拉动_生产计划_派工订单_订单历史 where 计划开始时间>='" + startTime + "'and 计划开始时间<='" + endTime + "' ORDER BY 计划开始时间"; + //string connectionString = ApplicationConfig.ConnectionString; + string errorMessage; + dt = null; + DataAccess.ExecuteDataTable(sql, out dt); + } + /// + /// 工位工时补报统计 + /// + /// + /// + /// + public static void Init_Worktime(string orderNum, string Opname, int Num, out DataTable dt) + { + string procedureName; + procedureName = "AMES_物料拉动_生产计划_派工订单完工统计_工时统计"; + SqlParameter[] sqlParameters = new SqlParameter[3]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@订单号", orderNum); + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@工位号", Opname); + sqlParameters[2] = new System.Data.SqlClient.SqlParameter("@Workplace", Num); + DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + } + public static void workTime_CompleteCount(string OrderNum, out DataTable dt) + { + string sql = "SELECT SUM(报工数量) FROM [dbo].[测量数据发动机在线状态_跟踪发动机条码状态] WHERE [订单号]='" + OrderNum + "'AND [工位标识]='O' AND [使用标志]='1' AND 是否禁用=0"; + //string connectionString = ApplicationConfig.ConnectionString; + string errorMessage; + dt = null; + DataAccess.ExecuteDataTable(sql, out dt); + } + public static void init_Statistics(string orderNum, string Opname, out DataTable dt) + { + string procedureName; + procedureName = "AMES_物料拉动_测量数据发动机在线状态_跟踪发动机条码状态_工时补报统计"; + SqlParameter[] sqlParameters = new SqlParameter[2]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@订单号", orderNum); + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@工位号", Opname); + + DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + } + /// + /// 校验工时补录人员[MES_用户管理_人员] + /// + /// + /// + public static void Confirm_Person(string OperatorName, out DataTable dt) + { + string sql = "SELECT COUNT(*) FROM [dbo].[MES_用户管理_人员] WHERE [用户名]='" + OperatorName + "'"; + //string connectionString = ApplicationConfig.ConnectionString; + string errorMessage; + dt = null; + DataAccess.ExecuteDataTable(sql, out dt); + } + /// + /// AMES_物料拉动_生产计划_派工订单_查询_根据订单 + /// + /// + /// + public static void Init_Ordernum_data(string orderNum, out DataTable dt) + { + string procedureName; + procedureName = "AMES_物料拉动_生产计划_派工订单_查询_根据订单"; + SqlParameter[] sqlParameters = new SqlParameter[1]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@订单号", orderNum); + DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + } + + public static void ClassCode_Select(string ClassName, out DataTable dt) + { + //string connectionString = ApplicationConfig.ConnectionString; + string errorMessage; + string sql; + sql = "SELECT top 1 班次代码 FROM AMES_物料拉动_人员班组管理_班次信息 WHERE [班次描述]='" + ClassName + "'"; + dt = null; + DataAccess.ExecuteDataTable(sql, out dt); + } + + public static bool Workinghours_Insert(string OrderNum, string EngineType, string Opname, int Count, string OperatorName, string Classes, string UploadTime) + { + string procedureName = "AMES_物料拉动_测量数据发动机在线状态_跟踪发动机条码状态_工时补报_增加"; + //string connectionString = ApplicationConfig.ConnectionString_MES; + string errorMessage; + bool isOK; + SqlParameter[] sqlParameters = new SqlParameter[7]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@订单号", OrderNum); + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@发动机型号", EngineType); + sqlParameters[2] = new System.Data.SqlClient.SqlParameter("@工位号", Opname); + sqlParameters[3] = new System.Data.SqlClient.SqlParameter("@报工数量", Count); + sqlParameters[4] = new System.Data.SqlClient.SqlParameter("@操作者工号", OperatorName); + sqlParameters[5] = new System.Data.SqlClient.SqlParameter("@班次", Classes); + sqlParameters[6] = new System.Data.SqlClient.SqlParameter("@报工时间", UploadTime); + isOK = DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters); + if (isOK) + { + return true; + } + else + { + return false; + } + } + + /// + /// 物料拉动工位库存查询 + /// + /// + /// + /// + /// + public static void getWorkStationMaterialInfo(string opName, out DataTable dt) + { + string procedureName; + procedureName = "AMES_电子看板_装配零件_库存信息_查询"; + SqlParameter[] sqlParameters = new SqlParameter[1]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + } + } + + +} diff --git a/Common/07WebBusinessFacade/BusinessFacade/Web/MES.cs b/Common/07WebBusinessFacade/BusinessFacade/Web/MES.cs new file mode 100644 index 0000000..76de495 --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/Web/MES.cs @@ -0,0 +1,748 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Data; +using System.Data.SqlClient; +using DataLinkMesWork; +using System.Security.Cryptography; +//using SystemFramework; + +namespace bizFacade +{ + public partial class MES + { + /// + ///电子看板_发动机号_合格放行_记录_增加 + /// + /// + /// + public static bool InsertRecord_ComfirmOkGO(string opName, string userName, string type) + { + string procedureName = "电子看板_发动机号_合格放行_记录_增加"; + //string connectionString = ApplicationConfig.ConnectionString; + string errorMessage; + SqlParameter[] sqlParameters = new SqlParameter[3]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + sqlParameters[0].Direction = ParameterDirection.Input; + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@放行者工号", userName); + sqlParameters[1].Direction = ParameterDirection.Input; + sqlParameters[2] = new System.Data.SqlClient.SqlParameter("@放行类别", type); + sqlParameters[2].Direction = ParameterDirection.Input; + bool isOK; + isOK = DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters); + if (isOK) + { + return true; + } + else + { + return false; + } + + } + /// + /// 操作指南-手动转线-增加 + /// + /// + /// + /// + public static bool ManualTurnLine_Insert(string opname, int Cbx_ManualTurnLine) + { + + string procedureName = "测量数据工位_监控系统_手动转线_增加"; + //string connectionString = ApplicationConfig.ConnectionString; + string errorMessage; + SqlParameter[] sqlParameters = new SqlParameter[2]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", opname); + sqlParameters[0].Direction = ParameterDirection.Input; + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@是否启用转线", Cbx_ManualTurnLine); + sqlParameters[1].Direction = ParameterDirection.Input; + bool isOK; + isOK = DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters); + if (isOK) + { + return true; + } + else + { + return false; + } + } + /// + /// 操作指南-离线返修-增加 + /// + /// + /// + /// + public static bool OutLineRepair_Insert(string opname, int Cbx_OutLineRepair) + { + + string procedureName = "测量数据工位_监控系统_离线返修_增加"; + //string connectionString = ApplicationConfig.ConnectionString; + string errorMessage; + SqlParameter[] sqlParameters = new SqlParameter[2]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", opname); + sqlParameters[0].Direction = ParameterDirection.Input; + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@离线返修", Cbx_OutLineRepair); + sqlParameters[1].Direction = ParameterDirection.Input; + bool isOK; + isOK = DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters); + if (isOK) + { + return true; + } + else + { + return false; + } + } + /// + /// 显示测量数据_工位号_根据发动机型号_查询 + /// + /// + /// + /// + /// + static public bool QualityDataSelect_engineID(string opName, string engineID, out DataTable dt) + { + string procedureName; + procedureName = "显示测量数据_工位号_根据发动机型号_查询"; + SqlParameter[] sqlParameters = new SqlParameter[2]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@发动机号", engineID); + return DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + } + /// + /// StudentSelect + /// + /// + /// + public static bool getopname(string opname, out DataTable dt) + { + string procedureName = "MES_计划BOM_工位与名称_查询_根据工位号"; + SqlParameter[] sqlParameters = new SqlParameter[1]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", opname); + return DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + } + + /// + /// 排产计划_查询计划 + /// + /// + /// + /// + /// + public static bool GetPlan(string opname,string selectDate, out DataTable tb) + { + string procedureName = "排产计划_查询计划"; + //string connectionString = ApplicationConfig.ConnectionString; + DataSet ds; + string errorMessage; + bool isOK; + tb = null; + SqlParameter[] sqlParameters = new SqlParameter[2]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@转生产订单日期", selectDate); + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@工位号", opname); + isOK = DataAccess.ExecuteStoredProcedure(procedureName,ref sqlParameters, out ds); + if (isOK) + { + if (ds.Tables.Count > 0) + { + tb = ds.Tables[0]; + return true; + } + else + { + return false; + } + } + else + { + return false; + } + + } + /// + /// [电子看板_发动机号_线首工位_分线订单主表_数据_查询] + /// + /// + /// + /// + /// + public static bool GetPlan_Cap(string opname, out DataTable tb) + { + string procedureName = "电子看板_发动机号_线首工位_分线订单主表_数据_查询"; + //string connectionString = ApplicationConfig.ConnectionString; + DataSet ds; + string errorMessage; + bool isOK; + tb = null; + SqlParameter[] sqlParameters = new SqlParameter[1]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", opname); + isOK = DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out ds); + if (isOK) + { + if (ds.Tables.Count > 0) + { + tb = ds.Tables[0]; + return true; + } + else + { + return false; + } + } + else + { + return false; + } + + } + + /// + /// 电子看板_发动机号_工位队列表_查询_根据工位号(数据源工位) 20140709 wt + /// + /// + /// + /// + public static bool GetQueue(string opname, out DataTable tb) + { + string procedureName = "电子看板_发动机号_工位队列表_查询_根据工位号"; + //string connectionString = ApplicationConfig.ConnectionString; + DataSet ds; + string errorMessage; + bool isOK; + tb = null; + SqlParameter[] sqlParameters = new SqlParameter[1]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@数据源工位", opname); + isOK = DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out ds); + if (isOK) + { + if (ds.Tables.Count > 0) + { + tb = ds.Tables[0]; + return true; + } + else + { + return false; + } + } + else + { + return false; + } + } + /// + /// 电子看板_发动机号_工位队列表_增加 20140709 wt ClearQueue + /// + /// + /// + /// + /// + public static bool InsertQueue(string opname, string engineId) + { + + string procedureName = "电子看板_发动机号_工位队列表_增加"; + //string connectionString = ApplicationConfig.ConnectionString; + string errorMessage; + SqlParameter[] sqlParameters = new SqlParameter[2]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@数据源工位", opname); + sqlParameters[0].Direction = ParameterDirection.Input; + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@发动机号", engineId); + sqlParameters[1].Direction = ParameterDirection.Input; + bool isOK; + isOK = DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters); + if (isOK) + { + return true; + } + else + { + return false; + } + } + /// + /// 电子看板_发动机号_工位队列表_清空 20140709 wt + /// + /// + /// + /// + /// + //public static bool ClearQueue() + //{ + + // string procedureName = "电子看板_发动机号_工位队列表_清空"; + // //string connectionString = ApplicationConfig.ConnectionString; + // string errorMessage; + // bool isOK; + // isOK = DataAccess.ExecuteNonQuery(procedureName); + // if (isOK) + // { + // return true; + // } + // else + // { + // return false; + // } + //} + /// + /// 测量数据合格_查询_WEB页面显示 20140622 wt + /// + /// + /// + /// + /// + public static bool GetCurrentQuality_Select(string engineID,string opname, out DataTable tb) + { + string procedureName = "测量数据合格_查询_WEB页面显示"; + //string connectionString = ApplicationConfig.ConnectionString; + DataSet ds; + string errorMessage; + bool isOK; + tb = null; + SqlParameter[] sqlParameters = new SqlParameter[2]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@发动机号", engineID); + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@工位号", opname); + isOK = DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out ds); + if (isOK) + { + if (ds.Tables.Count > 0) + { + tb = ds.Tables[0]; + return true; + } + else + { + return false; + } + } + else + { + return false; + } + + } + + ///// + ///// WEB查询按钮的信息 20140625 wt + ///// + ///// + ///// + //public static bool OpnameSelect_Buttons(out DataTable tb) + //{ + // string procedureName = "WEB_质量查询模块_按钮基础信息_查询"; + // //string connectionString = ApplicationConfig.ConnectionString; + // DataSet ds; + // string errorMessage; + // bool isOK; + + // isOK = DataAccess.ExecuteStoredProcedure(procedureName, out ds); + // if (isOK) + // { + // tb = ds.Tables[0]; + // return true; + // } + // else + // { + // tb = null; + // return false; + // } + + //} + /// + /// WEB_安东模块_物料原因按钮基础信息_查询 20140707 wt + /// + /// + /// + /// + /// + public static bool MaterialProblemButtons_Select(string opname, string engineId, out DataTable tb) + { + + string procedureName = "WEB_安东模块_物料原因按钮基础信息_查询"; + //string connectionString = ApplicationConfig.ConnectionString; + string errorMessage; + bool isOK; + SqlParameter[] sqlParameters = new SqlParameter[2]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", opname); + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@发动机号", engineId); + DataSet ds; + isOK = DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out ds); + if (isOK) + { + tb = ds.Tables[0]; + return true; + } + else + { + tb = null; + return false; + } + } + /// + /// WEB_安东模块_物料ANDON信息_插入 20140708 wt + /// + /// + /// + /// + /// + public static bool MaterialProblemButtons_Insert(string opname, string materialname) + { + + string procedureName = "WEB_安东模块_物料ANDON信息_插入"; + //string connectionString = ApplicationConfig.ConnectionString; + string errorMessage; + SqlParameter[] sqlParameters = new SqlParameter[2]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", opname); + sqlParameters[0].Direction = ParameterDirection.Input; + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@物料描述", materialname); + sqlParameters[1].Direction = ParameterDirection.Input; + bool isOK; + isOK = DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters); + if (isOK) + { + return true; + } + else + { + return false; + } + } + /// + /// WEB根据工位名称和发动机号查询质量数据 20140625 wt + /// + /// + /// + /// + /// + public static bool QualityData_Select(string opname, string engineId, out DataTable tb) + { + + string procedureName = "WEB_质量查询模块_测量数据合格_查询"; + //string connectionString = ApplicationConfig.ConnectionString; + string errorMessage; + bool isOK; + SqlParameter[] sqlParameters = new SqlParameter[2]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", opname); + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@发动机号", engineId); + DataSet ds; + isOK = DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out ds); + if (isOK) + { + tb = ds.Tables[0]; + return true; + } + else + { + tb = null; + return false; + } + } + /// + /// WEB根据工位名称和发动机号查询质量数据合格索引(包括了分线的信息、存储过程中根据工位类型区分) 20140626 wt + /// + /// + /// + /// + /// + public static bool QualityDataButton_bgColor_Select(string opname, out DataTable dt) + { + string procedureName = "显示测量数据_工位号_查询"; + SqlParameter[] sqlParameters = new SqlParameter[1]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", opname); + return DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + } + + + /// + /// MES界面显示_弹窗消息_查询 + /// + /// + /// + /// + public static bool ShowWindowNotice(string opname, out DataTable dt) + { + string procedureName = "MES界面显示_弹窗消息_查询"; + SqlParameter[] sqlParameters = new SqlParameter[1]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", opname); + return DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + } + + + /// + /// MES界面显示_消息滚动_查询 + /// + /// + /// + /// + public static bool ShowLEDNotice(string opname, out DataTable dt) + { + string procedureName = "MES界面显示_消息滚动_查询"; + SqlParameter[] sqlParameters = new SqlParameter[1]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", opname); + return DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + } + + /// + /// 上线临时表插入数据 20140609 通过页面直接插入数据库 + /// + /// 工位号 + /// 发动机号 + static public bool SubOnLoadTemp_Insert(string opName, string orderNum, string engineType, string sublineOrderID, out DataTable tb) + { + string procedureName = "电子看板_发动机号_上线临时表_增加"; + //string connectionString = ApplicationConfig.ConnectionString; + DataSet ds; + string errorMessage; + bool isOK; + tb = null; + SqlParameter[] sqlParameters = new SqlParameter[4]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@订单号", orderNum); + sqlParameters[2] = new System.Data.SqlClient.SqlParameter("@发动机型号", engineType); + sqlParameters[3] = new System.Data.SqlClient.SqlParameter("@分线主表数据ID", Convert.ToInt32(sublineOrderID)); + isOK = DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out ds); + if (isOK) + { + if (ds.Tables.Count > 0) + { + tb = ds.Tables[0]; + return true; + } + else + { + return false; + } + } + else + { + return false; + } + + } + + + /// + /// [电子看板_发动机号_线首工位_查询_根据发动机号和工位号] 20140604 王可心 + /// + /// + /// + static public bool GetEngineIDOpName_Select(string engineID, string opName, out DataTable dt) + { + string errorMessage = ""; + DataSet ds; + bool isOK; + dt = null; + //string connectionString = ApplicationConfig.ConnectionString; + string procedureName; + procedureName = "电子看板_发动机号_线首工位_查询_根据发动机号和工位号"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@发动机号", engineID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + isOK= DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out ds); + if (isOK) + { + if (ds.Tables.Count > 0) + { + dt = ds.Tables[0]; + return true; + } + else + { + return false; + } + } + else + { + return false; + } + } + + + + /// + /// 电子看板_工序内容_查询 + /// + /// 工位号 + /// 产品型号代码 + /// + static public void Process_Select(string opName, int engineTypeID, out DataTable dt) + { + dt = null; + string sql = "exec 电子看板_工序内容_查询 '" + opName + "'," + engineTypeID.ToString(); + DataAccess.ExecuteDataTable(sql, out dt); + } + + /// + /// 电子看板_装配零件_物料验证_查询 20131231 + /// + /// 工位号 + /// 发动机号 + /// + static public bool PartMaterialVerify_Select(string opName, out DataTable dt) + { + string errorMessage = ""; + DataSet ds; + dt = null; + bool isOK; + + //string connectionString = ApplicationConfig.ConnectionString; + + string procedureName; + procedureName = "电子看板_装配零件_物料验证_查询"; + SqlParameter[] thisParms = new SqlParameter[1]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + //thisParms[1] = new System.Data.SqlClient.SqlParameter("@发动机号", engineID); + + isOK= DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out ds); + if (isOK) + { + if (ds.Tables.Count > 0) + { + dt = ds.Tables[0]; + return true; + } + else + { + return false; + } + } + else + { + return false; + } + } + + /// + /// 设备管理_设备维护内容_查询 + /// + /// + /// + /// + /// ShowMaintainPic + static public bool LoadMachineType(string opName,out DataTable dt) + { + string procedureName; + procedureName = "设备管理_设备维护初始化_查询"; + SqlParameter[] sqlParameters = new SqlParameter[1]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + return DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + } + + /// + /// 设备管理_设备维护内容_查询 + /// + /// + /// + /// + /// ShowMaintainPic + static public bool ShowMaintainData(string opName, string MachineType, out DataTable dt) + { + string procedureName; + procedureName = "设备管理_设备维护内容_查询"; + SqlParameter[] sqlParameters = new SqlParameter[2]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@保养类型代码", MachineType); + return DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + } + + /// + /// 设备管理_设备维护图片_查询 + /// + /// + /// + /// + static public void GetMaintainImageFile(string opName, string MachineType, out byte[] pic) + { + string sql; + DataTable dt; + pic = null; + sql = "exec 设备管理_设备维护图片_查询 '" + opName + "'," + MachineType; + DataAccess.ExecuteDataTable(sql, out dt); + if (dt != null) + { + if (dt.Rows.Count > 0) + { + pic = (byte[])dt.Rows[0]["保养图片"]; + } + } + } + + /// + /// 显示测量数据_工位数据_查询 + /// + /// + /// + /// + /// + static public bool QualityDataSelect(string opName, string opname, out DataTable dt) + { + string procedureName; + procedureName = "显示测量数据_工位数据_查询"; + SqlParameter[] sqlParameters = new SqlParameter[2]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@查询工位号", opname); + return DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + } + + /// + /// 显示物料数据_工位数据_查询 + /// + /// + /// + /// + /// + static public bool MaterialDataSelect(string opName, string opname, out DataTable dt) + { + string procedureName; + procedureName = "显示物料数据_工位数据_查询"; + SqlParameter[] sqlParameters = new SqlParameter[2]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@查询工位号", opname); + return DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + } + + /// + /// 操作指南- + /// + /// 工位号 + /// 是否启用备用模式 + /// + public static bool Assembel_RadioNormal_Insert(string opName, int IsNormalOrRepair) + { + string produceName = "测量数据工位_监控系统_拧紧与返修拧紧_增加"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@是否启用备用模式", IsNormalOrRepair); + return DataAccess.ExecuteStoredProcedure(produceName, ref thisParms); + } + /// + /// 测量数据工位_监控系统_返修上下线_上线_增加 + /// + /// + /// + /// + public static bool AssembelRadioNormalWork_Insert(string opName, int upLine) + { + string produceName = "测量数据工位_监控系统_返修上下线_上线_增加"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@是否启用备用模式", upLine); + return DataAccess.ExecuteStoredProcedure(produceName, ref thisParms); + } + /// + /// 启用拧紧_初始化 + /// + /// + /// + public static void cbx_BakOpNameIsWorkStatus_Select(string opName, out DataTable tb) + { + string sql = "SELECT [是否启用备用模式] FROM [dbo].[测量数据工位_监控系统_拧紧与返修拧紧] WHERE [工位号]='" + opName + "'"; + //string connectionString = ApplicationConfig.ConnectionString; + string errorMessage; + tb = null; + DataAccess.ExecuteDataTable(sql, out tb); + } + } +} diff --git a/Common/07WebBusinessFacade/BusinessFacade/Web/MES_Loading.cs b/Common/07WebBusinessFacade/BusinessFacade/Web/MES_Loading.cs new file mode 100644 index 0000000..7d3034a --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/Web/MES_Loading.cs @@ -0,0 +1,99 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Data; +using System.Data.SqlClient; +using DataLinkMesWork; +using System.Security.Cryptography; +//using SystemFramework; + +namespace bizFacade +{ + public class MES_Loading + { + /// + /// + /// + /// + /// + static public void MES_LoadingOPName(string opName, out DataTable dt) + { + string sql; + sql = " select 线外工位号 as opname from [dbo].[线外工位验证] where 工位号='"+opName+"'"; + DataAccess.ExecuteDataTable(sql, out dt); + } + + + /// + /// MES_界面显示_标签语言_视图_查询 + /// + /// 主模块代码 + /// MesWebCode + /// opName + /// + public static void MES_Loading_select(string mainModule, string MesWebCode,string opName, out DataTable tb) + { + string procedureName = "MES_界面显示_标签语言_视图_查询"; + //string connectionString = ApplicationConfig.ConnectionString; + DataSet ds; + string errorMessage; + bool isOK; + SqlParameter[] sqlParameters = new SqlParameter[3]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@主模块代码", mainModule); + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@MesWebCode", MesWebCode); + sqlParameters[2] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + isOK = DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out ds); + if (isOK) + { + tb = ds.Tables[0]; + } + else + { + tb = null; + } + + } + /// + /// 测量数据工位_监控系统_操作者工号_增加 + /// + /// + /// + /// + public static bool MES_Loading_Insert(string opName,string userNum) + { + string produceName = "测量数据工位_监控系统_操作者工号_增加"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@操作者工号", userNum); + return DataAccess.ExecuteStoredProcedure(produceName, ref thisParms); + } + + /// + /// 测量数据合格_查询 + /// + /// + /// + /// + public static void initImage(string opname, string engineid, out DataTable tb) + { + string procedureName = "测量数据合格_查询"; + //string connectionString = ApplicationConfig.ConnectionString; + DataSet ds; + string errorMessage; + bool isOK; + SqlParameter[] sqlParameters = new SqlParameter[2]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", opname); + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@发动机号", engineid); + isOK = DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out ds); + if (isOK) + { + tb = ds.Tables[0]; + } + else + { + tb = null; + } + + } + } +} diff --git a/Common/07WebBusinessFacade/BusinessFacade/Web/MES_MachineManage.cs b/Common/07WebBusinessFacade/BusinessFacade/Web/MES_MachineManage.cs new file mode 100644 index 0000000..d9286b6 --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/Web/MES_MachineManage.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Data; +using System.Data.SqlClient; +using DataLinkMesWork; +using System.Security.Cryptography; +//using SystemFramework; + +namespace bizFacade +{ + public class MES_MachineManage + { + /// + /// [设备管理_设备维护记录表_增加] + /// + /// 工位号 + /// 备注 + /// + public static bool Mes_MachineTakeCare_Insert(string opName, string mark) + { + string produceName = "设备管理_设备维护记录表_增加"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@备注", mark); + return DataAccess.ExecuteStoredProcedure(produceName, ref thisParms); + } + } +} diff --git a/Common/07WebBusinessFacade/BusinessFacade/Web/ando_load.cs b/Common/07WebBusinessFacade/BusinessFacade/Web/ando_load.cs new file mode 100644 index 0000000..276ae78 --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/Web/ando_load.cs @@ -0,0 +1,67 @@ +using System.Data; +using System.Data.SqlClient; +using DataLinkMesWork; +using System.Security.Cryptography; +//using SystemFramework; +using System.Text; + +namespace bizFacade +{ + public class ando_load + { + /// + /// 查询ando类型andoTypeSelect + /// + /// + public static bool andoTypeSelect(out DataTable dt) + { + string procedureName = "ANDON_类型_查询"; + return DataAccess.ExecuteStoredProcedure(procedureName, out dt); + } + /// + /// + /// + /// + /// + public static bool andoDetailCount(out DataTable dt) + { + string procedureName = "ANDON_类型_查询"; + return DataAccess.ExecuteStoredProcedure(procedureName, out dt); + } + /// + /// 初始化ando界面 + /// + public static string ando_loading(string opname) + { + System.Data.DataTable dt; + dt=null; + andoTypeSelect(out dt); + string responsetext=""; + StringBuilder sb = new StringBuilder(); + + for(int i=0;i + /// 查询ando类型andoTypeSelect + ///
+ /// + public static bool andoTypeSelect(out DataTable dt) + { + string procedureName = "ANDON_类型_查询"; + return DataAccess.ExecuteStoredProcedure(procedureName, out dt); + } + /// + /// + /// + /// + /// + public static bool andoDetailCount(out DataTable dt) + { + string procedureName = "ANDON_类型_查询"; + return DataAccess.ExecuteStoredProcedure(procedureName, out dt); + } + /// + /// 初始化ando界面 + /// + public static string ando_loading(string opname) + { + System.Data.DataTable dt; + dt=null; + andoTypeSelect(out dt); + string responsetext=""; + StringBuilder sb = new StringBuilder(); + + for(int i=0;i + /// 创建质量ando + ///
+ /// + /// + /// + public static string CreateAndo_Machine(string opname, string AndoTypeCode) + { + System.Data.DataTable dt_list; + //查询ando明细 + ando_matertial.andoListSelect(opname, AndoTypeCode, out dt_list); + + + StringBuilder sb = new StringBuilder(); + + sb.Append("
"); + sb.Append("
"); + sb.Append("
"); + + #region 大图片的div + sb.Append("
"); + sb.Append("\"loading....\""); + sb.Append("
"); + #endregion + + #region 整个ANDON选项DIV + sb.Append("
"); + + #region 左按钮DIV + sb.Append("
"); + sb.Append(""); + sb.Append("
"); + #endregion + + + #region 中间内容DIV + sb.Append("
"); + + #region 可支持移动的div + + sb.Append("
"); + + sb.Append("
"); + + + //附加tabel + string tabelString = CreatAndo_machine_table(opname, AndoTypeCode); + sb.Append(tabelString); + + sb.Append("
"); + sb.Append("
"); + #endregion + + sb.Append("
"); + #endregion + + #region 右按钮div + + sb.Append("
"); + + sb.Append(">\" onclick=\"machine_leftMove()\" />"); + sb.Append("
"); + + #endregion + + sb.Append("
"); + #endregion + #region ando按钮div + + sb.Append("
"); + + sb.Append("
"); + + sb.Append(""); + sb.Append(""); + sb.Append(""); + sb.Append(""); + sb.Append(""); + sb.Append(""); + sb.Append(""); + sb.Append(""); + sb.Append(""); + sb.Append("
"); + sb.Append("\"loading...\""); + sb.Append(""); + sb.Append("\"loading...\""); + sb.Append("
"); + sb.Append(""); + sb.Append(""); + sb.Append(""); + sb.Append("
"); + + sb.Append("
"); + + sb.Append("
"); + + #endregion + + sb.Append("
"); + + + return sb.ToString(); + //string text = ""; + //int count = dt_list.Rows.Count/2*120; + //return text = "{\"InnerHtml\":\"" + sb.ToString() + "\",\"Count\":\"" + count + "\"}"; + } + /// + /// 创建物料ando的table + /// + /// + /// + /// + public static string CreatAndo_machine_table(string opname, string AndoTypeCode) + { + System.Data.DataTable dt_list; + //查询ando明细 + ando_matertial.andoListSelect(opname, AndoTypeCode, out dt_list); + StringBuilder sb = new StringBuilder(); + int tableCount = dt_list.Rows.Count; + int td_count = (tableCount / 2) + (tableCount % 2);//获取每个tr中应该创建多少个td + int tablewidth = 145 * td_count; + if (tablewidth == 0) + { + tablewidth = 10; + } + string tablewidth2 = Convert.ToString(tablewidth) + "px"; + + #region table + + sb.Append(""); + + //创建第一行 + sb.Append(""); + for (int i = 0; i < td_count; i++) + { + #region 第一行按钮 + sb.Append(""); + + #endregion + } + sb.Append(""); + + + //创建第二行 + sb.Append(""); + for (int i = td_count; i < tableCount; i++) + { + #region 第二行按钮 + sb.Append(""); + + #endregion + } + + //补充第二行的信息 + if ((tableCount % 2) > 0 && (tableCount > 0)) + { + sb.Append(""); + } + sb.Append(""); + + //最后组合成table + sb.Append("
"); + //标签id + string id = "button_ando_machine_" + dt_list.Rows[i]["编号"].ToString(); + + #region 颜色代码 + //标签值 + string value = dt_list.Rows[i]["编号描述2"].ToString(); + string color = dt_list.Rows[i]["颜色代码"].ToString(); + //string inputColor = "background-color:" + color + ""; + if (color == "0") + { + sb.Append(""); + } + if (color == "1") + { + sb.Append(""); + } + if (color == "2") + { + sb.Append(""); + } + #endregion + + sb.Append("
"); + //标签id + string id = "button_ando_machine_" + dt_list.Rows[i]["编号"].ToString(); + + #region 颜色代码 + //标签值 + string value = dt_list.Rows[i]["编号描述2"].ToString(); + string color = dt_list.Rows[i]["颜色代码"].ToString(); + if (color == "0") + { + sb.Append(""); + } + if (color == "1") + { + sb.Append(""); + } + if (color == "2") + { + sb.Append(""); + } + #endregion + + sb.Append(""); + sb.Append("
"); + return sb.ToString(); + #endregion + } + } +} diff --git a/Common/07WebBusinessFacade/BusinessFacade/Web/ando_machine_2.cs b/Common/07WebBusinessFacade/BusinessFacade/Web/ando_machine_2.cs new file mode 100644 index 0000000..5d957d9 --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/Web/ando_machine_2.cs @@ -0,0 +1,225 @@ +using System.Data; +using System.Data.SqlClient; +using DataLinkMesWork; +using System.Security.Cryptography; +//using SystemFramework; +using System.Text; +using System; + +namespace bizFacade +{ + public class ando_machine_2 + { + /// + /// 创建质量ando + /// + /// + /// + /// + public static string CreateAndo_Machine(string opname, string AndoTypeCode) + { + System.Data.DataTable dt_list; + //查询ando明细 + ando_matertial.andoListSelect(opname, AndoTypeCode, out dt_list); + + + StringBuilder sb = new StringBuilder(); + + sb.Append("
"); + sb.Append("
"); + sb.Append("
"); + + #region 大图片的div + sb.Append("
"); + sb.Append("\"loading....\""); + sb.Append("
"); + #endregion + + #region 整个ANDON选项DIV + sb.Append("
"); + + #region 左按钮DIV + sb.Append("
"); + sb.Append(""); + sb.Append("
"); + #endregion + + + #region 中间内容DIV + sb.Append("
"); + + #region 可支持移动的div + + sb.Append("
"); + + sb.Append("
"); + + + //附加tabel + string tabelString = CreatAndo_machine_table(opname, AndoTypeCode); + sb.Append(tabelString); + + sb.Append("
"); + sb.Append("
"); + #endregion + + sb.Append("
"); + #endregion + + #region 右按钮div + + sb.Append("
"); + + sb.Append(">\" onclick=\"machine_leftMove()\" />"); + sb.Append("
"); + + #endregion + + sb.Append("
"); + #endregion + #region ando按钮div + + sb.Append("
"); + + sb.Append("
"); + + sb.Append(""); + sb.Append(""); + sb.Append(""); + sb.Append(""); + sb.Append(""); + sb.Append(""); + sb.Append(""); + sb.Append(""); + sb.Append(""); + sb.Append("
"); + sb.Append("\"loading...\""); + sb.Append(""); + sb.Append("\"loading...\""); + sb.Append("
"); + sb.Append(""); + sb.Append(""); + sb.Append(""); + sb.Append("
"); + + sb.Append("
"); + + sb.Append("
"); + + #endregion + + sb.Append("
"); + + + return sb.ToString(); + //string text = ""; + //int count = dt_list.Rows.Count/2*120; + //return text = "{\"InnerHtml\":\"" + sb.ToString() + "\",\"Count\":\"" + count + "\"}"; + } + /// + /// 创建物料ando的table + /// + /// + /// + /// + public static string CreatAndo_machine_table(string opname, string AndoTypeCode) + { + System.Data.DataTable dt_list; + //查询ando明细 + ando_matertial.andoListSelect(opname, AndoTypeCode, out dt_list); + StringBuilder sb = new StringBuilder(); + int tableCount = dt_list.Rows.Count; + int td_count = (tableCount / 2) + (tableCount % 2);//获取每个tr中应该创建多少个td + int tablewidth = 145 * td_count; + if (tablewidth == 0) + { + tablewidth = 10; + } + string tablewidth2 = Convert.ToString(tablewidth) + "px"; + + #region table + + sb.Append(""); + + //创建第一行 + sb.Append(""); + for (int i = 0; i < td_count; i++) + { + #region 第一行按钮 + sb.Append(""); + + #endregion + } + sb.Append(""); + + + //创建第二行 + sb.Append(""); + for (int i = td_count; i < tableCount; i++) + { + #region 第二行按钮 + sb.Append(""); + + #endregion + } + + //补充第二行的信息 + if ((tableCount % 2) > 0 && (tableCount > 0)) + { + sb.Append(""); + } + sb.Append(""); + + //最后组合成table + sb.Append("
"); + //标签id + string id = "button_ando_machine_" + dt_list.Rows[i]["编号"].ToString(); + + #region 颜色代码 + //标签值 + string value = dt_list.Rows[i]["编号描述2"].ToString(); + string color = dt_list.Rows[i]["颜色代码"].ToString(); + //string inputColor = "background-color:" + color + ""; + if (color == "0") + { + sb.Append(""); + } + if (color == "1") + { + sb.Append(""); + } + if (color == "2") + { + sb.Append(""); + } + #endregion + + sb.Append("
"); + //标签id + string id = "button_ando_machine_" + dt_list.Rows[i]["编号"].ToString(); + + #region 颜色代码 + //标签值 + string value = dt_list.Rows[i]["编号描述2"].ToString(); + string color = dt_list.Rows[i]["颜色代码"].ToString(); + if (color == "0") + { + sb.Append(""); + } + if (color == "1") + { + sb.Append(""); + } + if (color == "2") + { + sb.Append(""); + } + #endregion + + sb.Append(""); + sb.Append("
"); + return sb.ToString(); + #endregion + } + } +} diff --git a/Common/07WebBusinessFacade/BusinessFacade/Web/ando_matertial.cs b/Common/07WebBusinessFacade/BusinessFacade/Web/ando_matertial.cs new file mode 100644 index 0000000..41eb9f9 --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/Web/ando_matertial.cs @@ -0,0 +1,605 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Data; +using System.Data.SqlClient; +using DataLinkMesWork; +using System.Security.Cryptography; +//using SystemFramework; + +namespace bizFacade +{ + public class ando_matertial + { + + /// + /// 物料ando明细查询 ANDON_类型_编号_查询 + /// + /// + /// + public static bool andoListSelect(string opname, string andoTypeCode, out DataTable tb) + { + string procedureName = "ANDON_类型_编号_查询"; + //string connectionString = ApplicationConfig.ConnectionString; + DataSet ds; + string errorMessage; + bool isOK; + tb = null; + SqlParameter[] sqlParameters = new SqlParameter[2]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@安东类型代码", andoTypeCode); + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@工位号", opname); + isOK = DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out ds); + if (isOK) + { + if (ds.Tables.Count > 0) + { + tb = ds.Tables[0]; + return true; + } + else + { + return false; + } + } + else + { + return false; + } + } + /// + /// ANDON_呼叫状态_解除(返回table) + /// + /// 工位号 + /// 具体button编号 + /// 安东类型代码 + /// 安东明细代码(补料,错料,不合格) + /// 呼叫内容 + /// + public static bool AndoMaterialResetOutTable(string opname, string number, string andoTypeCode, string andoListCode, string callInfo,out DataTable tb) + { + string procedureName = "ANDON_呼叫状态_解除"; + //string connectionString = ApplicationConfig.ConnectionString; + DataSet ds; + string errorMessage; + bool isOK; + tb = null; + SqlParameter[] sqlParameters = new SqlParameter[5]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", opname); + sqlParameters[0].Direction = ParameterDirection.Input; + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@编号", number); + sqlParameters[1].Direction = ParameterDirection.Input; + sqlParameters[2] = new System.Data.SqlClient.SqlParameter("@安东类型代码", andoTypeCode); + sqlParameters[2].Direction = ParameterDirection.Input; + sqlParameters[3] = new System.Data.SqlClient.SqlParameter("@安东明细代码", andoListCode); + sqlParameters[3].Direction = ParameterDirection.Input; + sqlParameters[4] = new System.Data.SqlClient.SqlParameter("@解除内容", callInfo); + sqlParameters[4].Direction = ParameterDirection.Input; + isOK = DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out ds); + if (isOK) + { + if (ds.Tables.Count > 0) + { + tb = ds.Tables[0]; + return true; + } + else + { + return false; + } + } + else + { + return false; + } + } + + /// + /// ANDON_呼叫状态_解除 + /// + /// + /// + /// + /// + /// + /// + public static bool AndoMaterialReset(string opname, string number, string andoTypeCode, string andoListCode, string callInfo) + { + + string procedureName = "ANDON_呼叫状态_解除"; + //string connectionString = ApplicationConfig.ConnectionString; + string errorMessage; + SqlParameter[] sqlParameters = new SqlParameter[5]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", opname); + sqlParameters[0].Direction = ParameterDirection.Input; + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@编号", number); + sqlParameters[1].Direction = ParameterDirection.Input; + sqlParameters[2] = new System.Data.SqlClient.SqlParameter("@安东类型代码", andoTypeCode); + sqlParameters[2].Direction = ParameterDirection.Input; + sqlParameters[3] = new System.Data.SqlClient.SqlParameter("@安东明细代码", andoListCode); + sqlParameters[3].Direction = ParameterDirection.Input; + sqlParameters[4] = new System.Data.SqlClient.SqlParameter("@解除内容", callInfo); + sqlParameters[4].Direction = ParameterDirection.Input; + bool isOK; + isOK = DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters); + if (isOK) + { + return true; + } + else + { + return false; + } + } + + + /// + /// ANDON_呼叫状态_呼叫(物料ando插入) + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + public static bool andoMaterialCall(string opname, string andoTypeCode, string andoListCode, string number, string callInfo, int callCount, string cardNumber, string noNumber) + { + + string procedureName = "ANDON_呼叫状态_呼叫"; + //string connectionString = ApplicationConfig.ConnectionString; + string errorMessage; + SqlParameter[] sqlParameters = new SqlParameter[8]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", opname); + sqlParameters[0].Direction = ParameterDirection.Input; + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@安东类型代码", andoTypeCode); + sqlParameters[1].Direction = ParameterDirection.Input; + sqlParameters[2] = new System.Data.SqlClient.SqlParameter("@安东明细代码", andoListCode); + sqlParameters[2].Direction = ParameterDirection.Input; + sqlParameters[3] = new System.Data.SqlClient.SqlParameter("@编号", number); + sqlParameters[3].Direction = ParameterDirection.Input; + sqlParameters[4] = new System.Data.SqlClient.SqlParameter("@呼叫内容", callInfo); + sqlParameters[4].Direction = ParameterDirection.Input; + sqlParameters[5] = new System.Data.SqlClient.SqlParameter("@呼叫数量", callCount); + sqlParameters[5].Direction = ParameterDirection.Input; + sqlParameters[6] = new System.Data.SqlClient.SqlParameter("@卡片条码", cardNumber); + sqlParameters[6].Direction = ParameterDirection.Input; + sqlParameters[7] = new System.Data.SqlClient.SqlParameter("@不合格代码", noNumber); + sqlParameters[7].Direction = ParameterDirection.Input; + bool isOK; + isOK = DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters); + if (isOK) + { + return true; + } + else + { + return false; + } + } + /// + /// ANDON_呼叫状态_呼叫(物料ando插入,返回table) + /// + /// 工位号 + /// 安东类型代码 + /// 安东明细代码(缺料,补料,不合格) + /// 编号(具体物料信息) + /// + /// + /// + /// + /// + /// + public static bool andoMaterialCallOutTable(string opname, string andoTypeCode,string andoListCode,string number,string callInfo,int callCount,string cardNumber,string noNumber,out DataTable tb) + { + string procedureName = "ANDON_呼叫状态_呼叫"; + //string connectionString = ApplicationConfig.ConnectionString; + DataSet ds; + string errorMessage; + bool isOK; + tb = null; + SqlParameter[] sqlParameters = new SqlParameter[8]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", opname); + sqlParameters[0].Direction = ParameterDirection.Input; + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@安东类型代码", andoTypeCode); + sqlParameters[1].Direction = ParameterDirection.Input; + sqlParameters[2] = new System.Data.SqlClient.SqlParameter("@安东明细代码", andoListCode); + sqlParameters[2].Direction = ParameterDirection.Input; + sqlParameters[3] = new System.Data.SqlClient.SqlParameter("@编号", number); + sqlParameters[3].Direction = ParameterDirection.Input; + sqlParameters[4] = new System.Data.SqlClient.SqlParameter("@呼叫内容", callInfo); + sqlParameters[4].Direction = ParameterDirection.Input; + sqlParameters[5] = new System.Data.SqlClient.SqlParameter("@呼叫数量", callCount); + sqlParameters[5].Direction = ParameterDirection.Input; + sqlParameters[6] = new System.Data.SqlClient.SqlParameter("@卡片条码", cardNumber); + sqlParameters[6].Direction = ParameterDirection.Input; + sqlParameters[7] = new System.Data.SqlClient.SqlParameter("@不合格代码", noNumber); + sqlParameters[7].Direction = ParameterDirection.Input; + isOK = DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out ds); + if (isOK) + { + if (ds.Tables.Count > 0) + { + tb = ds.Tables[0]; + return true; + } + else + { + return false; + } + } + else + { + return false; + } + } + /// + /// 创建物料andon + /// + /// + /// + public static string CreateAndo_Material(string opname,string AndoTypeCode) + { + System.Data.DataTable dt_list; + //查询ando明细 + andoListSelect(opname, AndoTypeCode, out dt_list); + + + StringBuilder sb = new StringBuilder(); + //if (dt_list != null) + //{ + // if (dt_list.Rows.Count > 0) + // { + sb.Append("
"); + sb.Append("
"); + sb.Append("
"); + + #region 大图片的div + sb.Append("
"); + sb.Append("\"loading....\""); + sb.Append("
"); + #endregion + + #region 整个ANDON选项DIV + sb.Append("
"); + + #region 左按钮DIV + sb.Append("
"); + sb.Append(""); + sb.Append("
"); + #endregion + + + #region 中间内容DIV + sb.Append("
"); + + #region 可支持移动的div + + sb.Append("
"); + + sb.Append("
"); + + + //附加tabel + string tabelString=CreatAndo_Material_table(opname,AndoTypeCode); + sb.Append(tabelString); + + sb.Append("
"); + sb.Append("
"); + #endregion + + sb.Append("
"); + #endregion + + #region 右按钮div + + sb.Append("
"); + + sb.Append(">\" onclick=\"leftMove()\" />"); + sb.Append("
"); + + #endregion + + sb.Append("
"); + #endregion + #region ando按钮div + + sb.Append("
"); + + sb.Append("
"); + + sb.Append(""); + sb.Append(""); + sb.Append(""); + sb.Append(""); + sb.Append(""); + sb.Append(""); + sb.Append(""); + sb.Append(""); + sb.Append(""); + sb.Append("
"); + sb.Append("\"loading...\""); + sb.Append(""); + sb.Append("\"loading...\""); + sb.Append("
"); + sb.Append(""); + sb.Append(""); + sb.Append(""); + sb.Append("
"); + + sb.Append("
"); + + sb.Append("
"); + + #endregion + + sb.Append("
"); + + // } + + //} + return sb.ToString(); + } + /// + /// 更新物料安东的中间的tabel + /// + /// 工位号 + /// 物料ando类型明细 + /// + public static string CreatAndo_Material_table(string opname, string AndoTypeCode) + { + System.Data.DataTable dt_list; + //查询ando明细 + andoListSelect(opname, AndoTypeCode, out dt_list); + StringBuilder sb = new StringBuilder(); + int tableCount = dt_list.Rows.Count; + int td_count = (tableCount / 2) + (tableCount % 2);//获取每个tr中应该创建多少个td + int tablewidth = 145 * td_count; + if (tablewidth == 0) + { + tablewidth = 10; + } + string tablewidth2 = Convert.ToString(tablewidth) + "px"; + + #region table + + sb.Append(""); + + //创建第一行 + sb.Append(""); + for (int i = 0; i < td_count; i++) + { + #region 第一行按钮 + sb.Append(""); + + #endregion + } + sb.Append(""); + + + //创建第二行 + sb.Append(""); + for (int i = td_count; i < tableCount; i++) + { + #region 第二行按钮 + sb.Append(""); + + #endregion + } + + //补充第二行的信息 + if ((tableCount % 2) > 0 && (tableCount > 0)) + { + sb.Append(""); + } + sb.Append(""); + + //最后组合成table + sb.Append("
"); + //标签id + string id = "button_ando_material_" + dt_list.Rows[i]["编号"].ToString(); + + #region 颜色代码 + //标签值 + string value = dt_list.Rows[i]["编号描述2"].ToString(); + string color = dt_list.Rows[i]["颜色代码"].ToString(); + //string inputColor = "background-color:" + color + ""; + if (color == "0") + { + sb.Append(""); + } + if (color == "1") + { + sb.Append(""); + } + if (color == "2") + { + sb.Append(""); + } + #endregion + + sb.Append("
"); + //标签id + string id = "button_ando_material_" + dt_list.Rows[i]["编号"].ToString(); + + #region 颜色代码 + //标签值 + string value = dt_list.Rows[i]["编号描述2"].ToString(); + string color = dt_list.Rows[i]["颜色代码"].ToString(); + //string inputColor = "background-color:" + color + ""; + if (color == "0") + { + sb.Append(""); + } + if (color == "1") + { + sb.Append(""); + } + if (color == "2") + { + sb.Append(""); + } + #endregion + + sb.Append(""); + sb.Append("
"); + return sb.ToString(); + + + // if (tableCount > 4) + // { + // sb.Append(""); + // int i = 0; + // for (i = 0; i < dt_list.Rows.Count; i++) + // { + // //总条数 + // int seecond = dt_list.Rows.Count; + // //总条数和2取余 + // int seecond1 = seecond % 2; + // if ((seecond % 2) == 1) + // { + // seecond = seecond / 2 + 1; + // } + // else + // { + // seecond = dt_list.Rows.Count / 2; + // } + // if (i <= seecond) + // { + // #region 第一行按钮 + + + // sb.Append(""); + // //标签id + // string id = "button_ando_material_" + dt_list.Rows[i]["编号"].ToString(); + + // #region 颜色代码 + // //标签值 + // string value = dt_list.Rows[i]["编号描述2"].ToString(); + // string color = dt_list.Rows[i]["颜色代码"].ToString(); + // //string inputColor = "background-color:" + color + ""; + // if (color == "0") + // { + // sb.Append(""); + // } + // if (color == "1") + // { + // sb.Append(""); + // } + // if (color == "2") + // { + // sb.Append(""); + // } + // #endregion + + // sb.Append(""); + + // #endregion + + // } + // } + // sb.Append(""); + // sb.Append(""); + // for (i = 0; i < dt_list.Rows.Count; i++) + // { + // //如果第一行超过一半的按钮就重新放一行 + // int second1 = dt_list.Rows.Count; + // if ((second1) % 2 == 1) + // { + // second1 = second1 / 2 + 1; + + // } + // else + // { + // second1 = dt_list.Rows.Count / 2; + // } + // if (i > second1) + // { + // #region 第二行按钮 + + + // sb.Append(""); + // //标签id + // string id = "button_ando_material_" + dt_list.Rows[i]["编号"].ToString(); + + // #region 颜色代码 + + // //标签值 + // string value = dt_list.Rows[i]["编号描述2"].ToString(); + // string color = dt_list.Rows[i]["颜色代码"].ToString(); + // //string inputColor = "background-color:" + color + ""; + // if (color == "0") + // { + // sb.Append(""); + // } + // if (color == "1") + // { + // sb.Append(""); + // } + // if (color == "2") + // { + // sb.Append(""); + // } + // #endregion + + // sb.Append(""); + // #endregion + + // } + // } + // sb.Append(""); + // } + // //小于4个物料ando按钮 + // else + // { + // sb.Append(""); + // int i = 0; + // for (i = 0; i < dt_list.Rows.Count; i++) + // { + // //如果按钮数小于一半,都放在第一行 + // if (i < dt_list.Rows.Count) + // { + // #region 第一行按钮 + + + // sb.Append(""); + // //标签id + // string id = "button_ando_material_" + dt_list.Rows[i]["编号"].ToString(); + + // #region 颜色代码 + + // //标签值 + // string value = dt_list.Rows[i]["编号描述2"].ToString(); + // string color = dt_list.Rows[i]["颜色代码"].ToString(); + // //string inputColor = "background-color:" + color + ""; + // if (color == "0") + // { + // sb.Append(""); + // } + // if (color == "1") + // { + // sb.Append(""); + // } + // if (color == "2") + // { + // sb.Append(""); + // } + // #endregion + + // sb.Append(""); + + // #endregion + + // } + // } + // sb.Append(""); + // } + //sb.Append(""); + + //return sb.ToString(); + + #endregion + } + } +} diff --git a/Common/07WebBusinessFacade/BusinessFacade/Web/ando_matertial_2.cs b/Common/07WebBusinessFacade/BusinessFacade/Web/ando_matertial_2.cs new file mode 100644 index 0000000..7010604 --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/Web/ando_matertial_2.cs @@ -0,0 +1,605 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Data; +using System.Data.SqlClient; +using DataLinkMesWork; +using System.Security.Cryptography; +//using SystemFramework; + +namespace bizFacade +{ + public class ando_matertial_2 + { + + /// + /// 物料ando明细查询 ANDON_类型_编号_查询 + /// + /// + /// + public static bool andoListSelect(string opname, string andoTypeCode, out DataTable tb) + { + string procedureName = "ANDON_类型_编号_查询"; + //string connectionString = ApplicationConfig.ConnectionString; + DataSet ds; + string errorMessage; + bool isOK; + tb = null; + SqlParameter[] sqlParameters = new SqlParameter[2]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@安东类型代码", andoTypeCode); + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@工位号", opname); + isOK = DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out ds); + if (isOK) + { + if (ds.Tables.Count > 0) + { + tb = ds.Tables[0]; + return true; + } + else + { + return false; + } + } + else + { + return false; + } + } + /// + /// ANDON_呼叫状态_解除(返回table) + /// + /// 工位号 + /// 具体button编号 + /// 安东类型代码 + /// 安东明细代码(补料,错料,不合格) + /// 呼叫内容 + /// + public static bool AndoMaterialResetOutTable(string opname, string number, string andoTypeCode, string andoListCode, string callInfo,out DataTable tb) + { + string procedureName = "ANDON_呼叫状态_解除"; + //string connectionString = ApplicationConfig.ConnectionString; + DataSet ds; + string errorMessage; + bool isOK; + tb = null; + SqlParameter[] sqlParameters = new SqlParameter[5]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", opname); + sqlParameters[0].Direction = ParameterDirection.Input; + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@编号", number); + sqlParameters[1].Direction = ParameterDirection.Input; + sqlParameters[2] = new System.Data.SqlClient.SqlParameter("@安东类型代码", andoTypeCode); + sqlParameters[2].Direction = ParameterDirection.Input; + sqlParameters[3] = new System.Data.SqlClient.SqlParameter("@安东明细代码", andoListCode); + sqlParameters[3].Direction = ParameterDirection.Input; + sqlParameters[4] = new System.Data.SqlClient.SqlParameter("@解除内容", callInfo); + sqlParameters[4].Direction = ParameterDirection.Input; + isOK = DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out ds); + if (isOK) + { + if (ds.Tables.Count > 0) + { + tb = ds.Tables[0]; + return true; + } + else + { + return false; + } + } + else + { + return false; + } + } + + /// + /// ANDON_呼叫状态_解除 + /// + /// + /// + /// + /// + /// + /// + public static bool AndoMaterialReset(string opname, string number, string andoTypeCode, string andoListCode, string callInfo) + { + + string procedureName = "ANDON_呼叫状态_解除"; + //string connectionString = ApplicationConfig.ConnectionString; + string errorMessage; + SqlParameter[] sqlParameters = new SqlParameter[5]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", opname); + sqlParameters[0].Direction = ParameterDirection.Input; + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@编号", number); + sqlParameters[1].Direction = ParameterDirection.Input; + sqlParameters[2] = new System.Data.SqlClient.SqlParameter("@安东类型代码", andoTypeCode); + sqlParameters[2].Direction = ParameterDirection.Input; + sqlParameters[3] = new System.Data.SqlClient.SqlParameter("@安东明细代码", andoListCode); + sqlParameters[3].Direction = ParameterDirection.Input; + sqlParameters[4] = new System.Data.SqlClient.SqlParameter("@解除内容", callInfo); + sqlParameters[4].Direction = ParameterDirection.Input; + bool isOK; + isOK = DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters); + if (isOK) + { + return true; + } + else + { + return false; + } + } + + + /// + /// ANDON_呼叫状态_呼叫(物料ando插入) + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + public static bool andoMaterialCall(string opname, string andoTypeCode, string andoListCode, string number, string callInfo, int callCount, string cardNumber, string noNumber) + { + + string procedureName = "ANDON_呼叫状态_呼叫"; + //string connectionString = ApplicationConfig.ConnectionString; + string errorMessage; + SqlParameter[] sqlParameters = new SqlParameter[8]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", opname); + sqlParameters[0].Direction = ParameterDirection.Input; + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@安东类型代码", andoTypeCode); + sqlParameters[1].Direction = ParameterDirection.Input; + sqlParameters[2] = new System.Data.SqlClient.SqlParameter("@安东明细代码", andoListCode); + sqlParameters[2].Direction = ParameterDirection.Input; + sqlParameters[3] = new System.Data.SqlClient.SqlParameter("@编号", number); + sqlParameters[3].Direction = ParameterDirection.Input; + sqlParameters[4] = new System.Data.SqlClient.SqlParameter("@呼叫内容", callInfo); + sqlParameters[4].Direction = ParameterDirection.Input; + sqlParameters[5] = new System.Data.SqlClient.SqlParameter("@呼叫数量", callCount); + sqlParameters[5].Direction = ParameterDirection.Input; + sqlParameters[6] = new System.Data.SqlClient.SqlParameter("@卡片条码", cardNumber); + sqlParameters[6].Direction = ParameterDirection.Input; + sqlParameters[7] = new System.Data.SqlClient.SqlParameter("@不合格代码", noNumber); + sqlParameters[7].Direction = ParameterDirection.Input; + bool isOK; + isOK = DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters); + if (isOK) + { + return true; + } + else + { + return false; + } + } + /// + /// ANDON_呼叫状态_呼叫(物料ando插入,返回table) + /// + /// 工位号 + /// 安东类型代码 + /// 安东明细代码(缺料,补料,不合格) + /// 编号(具体物料信息) + /// + /// + /// + /// + /// + /// + public static bool andoMaterialCallOutTable(string opname, string andoTypeCode,string andoListCode,string number,string callInfo,int callCount,string cardNumber,string noNumber,out DataTable tb) + { + string procedureName = "ANDON_呼叫状态_呼叫"; + //string connectionString = ApplicationConfig.ConnectionString; + DataSet ds; + string errorMessage; + bool isOK; + tb = null; + SqlParameter[] sqlParameters = new SqlParameter[8]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", opname); + sqlParameters[0].Direction = ParameterDirection.Input; + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@安东类型代码", andoTypeCode); + sqlParameters[1].Direction = ParameterDirection.Input; + sqlParameters[2] = new System.Data.SqlClient.SqlParameter("@安东明细代码", andoListCode); + sqlParameters[2].Direction = ParameterDirection.Input; + sqlParameters[3] = new System.Data.SqlClient.SqlParameter("@编号", number); + sqlParameters[3].Direction = ParameterDirection.Input; + sqlParameters[4] = new System.Data.SqlClient.SqlParameter("@呼叫内容", callInfo); + sqlParameters[4].Direction = ParameterDirection.Input; + sqlParameters[5] = new System.Data.SqlClient.SqlParameter("@呼叫数量", callCount); + sqlParameters[5].Direction = ParameterDirection.Input; + sqlParameters[6] = new System.Data.SqlClient.SqlParameter("@卡片条码", cardNumber); + sqlParameters[6].Direction = ParameterDirection.Input; + sqlParameters[7] = new System.Data.SqlClient.SqlParameter("@不合格代码", noNumber); + sqlParameters[7].Direction = ParameterDirection.Input; + isOK = DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out ds); + if (isOK) + { + if (ds.Tables.Count > 0) + { + tb = ds.Tables[0]; + return true; + } + else + { + return false; + } + } + else + { + return false; + } + } + /// + /// 创建物料andon + /// + /// + /// + public static string CreateAndo_Material(string opname,string AndoTypeCode) + { + System.Data.DataTable dt_list; + //查询ando明细 + andoListSelect(opname, AndoTypeCode, out dt_list); + + + StringBuilder sb = new StringBuilder(); + //if (dt_list != null) + //{ + // if (dt_list.Rows.Count > 0) + // { + sb.Append("
"); + sb.Append("
"); + sb.Append("
"); + + #region 大图片的div + sb.Append("
"); + sb.Append("\"loading....\""); + sb.Append("
"); + #endregion + + #region 整个ANDON选项DIV + sb.Append("
"); + + #region 左按钮DIV + sb.Append("
"); + sb.Append(""); + sb.Append("
"); + #endregion + + + #region 中间内容DIV + sb.Append("
"); + + #region 可支持移动的div + + sb.Append("
"); + + sb.Append("
"); + + + //附加tabel + string tabelString=CreatAndo_Material_table(opname,AndoTypeCode); + sb.Append(tabelString); + + sb.Append("
"); + sb.Append("
"); + #endregion + + sb.Append("
"); + #endregion + + #region 右按钮div + + sb.Append("
"); + + sb.Append(">\" onclick=\"leftMove()\" />"); + sb.Append("
"); + + #endregion + + sb.Append("
"); + #endregion + #region ando按钮div + + sb.Append("
"); + + sb.Append("
"); + + sb.Append(""); + sb.Append(""); + sb.Append(""); + sb.Append(""); + sb.Append(""); + sb.Append(""); + sb.Append(""); + sb.Append(""); + sb.Append(""); + sb.Append("
"); + sb.Append("\"loading...\""); + sb.Append(""); + sb.Append("\"loading...\""); + sb.Append("
"); + sb.Append(""); + sb.Append(""); + sb.Append(""); + sb.Append("
"); + + sb.Append("
"); + + sb.Append("
"); + + #endregion + + sb.Append("
"); + + // } + + //} + return sb.ToString(); + } + /// + /// 更新物料安东的中间的tabel + /// + /// 工位号 + /// 物料ando类型明细 + /// + public static string CreatAndo_Material_table(string opname, string AndoTypeCode) + { + System.Data.DataTable dt_list; + //查询ando明细 + andoListSelect(opname, AndoTypeCode, out dt_list); + StringBuilder sb = new StringBuilder(); + int tableCount = dt_list.Rows.Count; + int td_count = (tableCount / 2) + (tableCount % 2);//获取每个tr中应该创建多少个td + int tablewidth = 145 * td_count; + if (tablewidth == 0) + { + tablewidth = 10; + } + string tablewidth2 = Convert.ToString(tablewidth) + "px"; + + #region table + + sb.Append(""); + + //创建第一行 + sb.Append(""); + for (int i = 0; i < td_count; i++) + { + #region 第一行按钮 + sb.Append(""); + + #endregion + } + sb.Append(""); + + + //创建第二行 + sb.Append(""); + for (int i = td_count; i < tableCount; i++) + { + #region 第二行按钮 + sb.Append(""); + + #endregion + } + + //补充第二行的信息 + if ((tableCount % 2) > 0 && (tableCount > 0)) + { + sb.Append(""); + } + sb.Append(""); + + //最后组合成table + sb.Append("
"); + //标签id + string id = "button_ando_material_" + dt_list.Rows[i]["编号"].ToString(); + + #region 颜色代码 + //标签值 + string value = dt_list.Rows[i]["编号描述2"].ToString(); + string color = dt_list.Rows[i]["颜色代码"].ToString(); + //string inputColor = "background-color:" + color + ""; + if (color == "0") + { + sb.Append(""); + } + if (color == "1") + { + sb.Append(""); + } + if (color == "2") + { + sb.Append(""); + } + #endregion + + sb.Append("
"); + //标签id + string id = "button_ando_material_" + dt_list.Rows[i]["编号"].ToString(); + + #region 颜色代码 + //标签值 + string value = dt_list.Rows[i]["编号描述2"].ToString(); + string color = dt_list.Rows[i]["颜色代码"].ToString(); + //string inputColor = "background-color:" + color + ""; + if (color == "0") + { + sb.Append(""); + } + if (color == "1") + { + sb.Append(""); + } + if (color == "2") + { + sb.Append(""); + } + #endregion + + sb.Append(""); + sb.Append("
"); + return sb.ToString(); + + + // if (tableCount > 4) + // { + // sb.Append(""); + // int i = 0; + // for (i = 0; i < dt_list.Rows.Count; i++) + // { + // //总条数 + // int seecond = dt_list.Rows.Count; + // //总条数和2取余 + // int seecond1 = seecond % 2; + // if ((seecond % 2) == 1) + // { + // seecond = seecond / 2 + 1; + // } + // else + // { + // seecond = dt_list.Rows.Count / 2; + // } + // if (i <= seecond) + // { + // #region 第一行按钮 + + + // sb.Append(""); + // //标签id + // string id = "button_ando_material_" + dt_list.Rows[i]["编号"].ToString(); + + // #region 颜色代码 + // //标签值 + // string value = dt_list.Rows[i]["编号描述2"].ToString(); + // string color = dt_list.Rows[i]["颜色代码"].ToString(); + // //string inputColor = "background-color:" + color + ""; + // if (color == "0") + // { + // sb.Append(""); + // } + // if (color == "1") + // { + // sb.Append(""); + // } + // if (color == "2") + // { + // sb.Append(""); + // } + // #endregion + + // sb.Append(""); + + // #endregion + + // } + // } + // sb.Append(""); + // sb.Append(""); + // for (i = 0; i < dt_list.Rows.Count; i++) + // { + // //如果第一行超过一半的按钮就重新放一行 + // int second1 = dt_list.Rows.Count; + // if ((second1) % 2 == 1) + // { + // second1 = second1 / 2 + 1; + + // } + // else + // { + // second1 = dt_list.Rows.Count / 2; + // } + // if (i > second1) + // { + // #region 第二行按钮 + + + // sb.Append(""); + // //标签id + // string id = "button_ando_material_" + dt_list.Rows[i]["编号"].ToString(); + + // #region 颜色代码 + + // //标签值 + // string value = dt_list.Rows[i]["编号描述2"].ToString(); + // string color = dt_list.Rows[i]["颜色代码"].ToString(); + // //string inputColor = "background-color:" + color + ""; + // if (color == "0") + // { + // sb.Append(""); + // } + // if (color == "1") + // { + // sb.Append(""); + // } + // if (color == "2") + // { + // sb.Append(""); + // } + // #endregion + + // sb.Append(""); + // #endregion + + // } + // } + // sb.Append(""); + // } + // //小于4个物料ando按钮 + // else + // { + // sb.Append(""); + // int i = 0; + // for (i = 0; i < dt_list.Rows.Count; i++) + // { + // //如果按钮数小于一半,都放在第一行 + // if (i < dt_list.Rows.Count) + // { + // #region 第一行按钮 + + + // sb.Append(""); + // //标签id + // string id = "button_ando_material_" + dt_list.Rows[i]["编号"].ToString(); + + // #region 颜色代码 + + // //标签值 + // string value = dt_list.Rows[i]["编号描述2"].ToString(); + // string color = dt_list.Rows[i]["颜色代码"].ToString(); + // //string inputColor = "background-color:" + color + ""; + // if (color == "0") + // { + // sb.Append(""); + // } + // if (color == "1") + // { + // sb.Append(""); + // } + // if (color == "2") + // { + // sb.Append(""); + // } + // #endregion + + // sb.Append(""); + + // #endregion + + // } + // } + // sb.Append(""); + // } + //sb.Append(""); + + //return sb.ToString(); + + #endregion + } + } +} diff --git a/Common/07WebBusinessFacade/BusinessFacade/Web/ando_quality.cs b/Common/07WebBusinessFacade/BusinessFacade/Web/ando_quality.cs new file mode 100644 index 0000000..b702800 --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/Web/ando_quality.cs @@ -0,0 +1,225 @@ +using System.Data; +using System.Data.SqlClient; +using DataLinkMesWork; +using System.Security.Cryptography; +//using SystemFramework; +using System.Text; +using System; + +namespace bizFacade +{ + public class ando_quality + { + /// + /// 创建质量ando + /// + /// + /// + /// + public static string CreateAndo_quality(string opname, string AndoTypeCode) + { + System.Data.DataTable dt_list; + //查询ando明细 + ando_matertial.andoListSelect(opname, AndoTypeCode, out dt_list); + + + StringBuilder sb = new StringBuilder(); + + sb.Append("
"); + sb.Append("
"); + sb.Append("
"); + + #region 大图片的div + sb.Append("
"); + sb.Append("\"loading....\""); + sb.Append("
"); + #endregion + + #region 整个ANDON选项DIV + sb.Append("
"); + + #region 左按钮DIV + sb.Append("
"); + sb.Append(""); + sb.Append("
"); + #endregion + + + #region 中间内容DIV + sb.Append("
"); + + #region 可支持移动的div + + sb.Append("
"); + + sb.Append("
"); + + + //附加tabel + string tabelString = CreatAndo_quality_table(opname, AndoTypeCode); + sb.Append(tabelString); + + sb.Append("
"); + sb.Append("
"); + #endregion + + sb.Append("
"); + #endregion + + #region 右按钮div + + sb.Append("
"); + + sb.Append(">\" onclick=\"qualty_leftMove()\" />"); + sb.Append("
"); + + #endregion + + sb.Append("
"); + #endregion + #region ando按钮div + + sb.Append("
"); + + sb.Append("
"); + + sb.Append(""); + sb.Append(""); + sb.Append(""); + sb.Append(""); + sb.Append(""); + sb.Append(""); + sb.Append(""); + sb.Append(""); + sb.Append(""); + sb.Append("
"); + sb.Append("\"loading...\""); + sb.Append(""); + sb.Append("\"loading...\""); + sb.Append("
"); + sb.Append(""); + sb.Append(""); + sb.Append(""); + sb.Append("
"); + + sb.Append("
"); + + sb.Append("
"); + + #endregion + + sb.Append("
"); + + + return sb.ToString(); + //string text = ""; + //int count = dt_list.Rows.Count/2*120; + //return text = "{\"InnerHtml\":\"" + sb.ToString() + "\",\"Count\":\"" + count + "\"}"; + } + /// + /// 创建物料ando的table + /// + /// + /// + /// + public static string CreatAndo_quality_table(string opname, string AndoTypeCode) + { + System.Data.DataTable dt_list; + //查询ando明细 + ando_matertial.andoListSelect(opname, AndoTypeCode, out dt_list); + StringBuilder sb = new StringBuilder(); + int tableCount = dt_list.Rows.Count; + int td_count = (tableCount / 2) + (tableCount % 2);//获取每个tr中应该创建多少个td + int tablewidth = 145 * td_count; + if (tablewidth == 0) + { + tablewidth = 10; + } + string tablewidth2 = Convert.ToString(tablewidth) + "px"; + + #region table + + sb.Append(""); + + //创建第一行 + sb.Append(""); + for (int i = 0; i < td_count; i++) + { + #region 第一行按钮 + sb.Append(""); + + #endregion + } + sb.Append(""); + + + //创建第二行 + sb.Append(""); + for (int i = td_count; i < tableCount; i++) + { + #region 第二行按钮 + sb.Append(""); + + #endregion + } + + //补充第二行的信息 + if ((tableCount % 2) > 0 && (tableCount > 0)) + { + sb.Append(""); + } + sb.Append(""); + + //最后组合成table + sb.Append("
"); + //标签id + string id = "button_ando_quality_" + dt_list.Rows[i]["编号"].ToString(); + + #region 颜色代码 + //标签值 + string value = dt_list.Rows[i]["编号描述2"].ToString(); + string color = dt_list.Rows[i]["颜色代码"].ToString(); + //string inputColor = "background-color:" + color + ""; + if (color == "0") + { + sb.Append(""); + } + if (color == "1") + { + sb.Append(""); + } + if (color == "2") + { + sb.Append(""); + } + #endregion + + sb.Append("
"); + //标签id + string id = "button_ando_quality_" + dt_list.Rows[i]["编号"].ToString(); + + #region 颜色代码 + //标签值 + string value = dt_list.Rows[i]["编号描述2"].ToString(); + string color = dt_list.Rows[i]["颜色代码"].ToString(); + if (color == "0") + { + sb.Append(""); + } + if (color == "1") + { + sb.Append(""); + } + if (color == "2") + { + sb.Append(""); + } + #endregion + + sb.Append(""); + sb.Append("
"); + return sb.ToString(); + #endregion + } + } +} diff --git a/Common/07WebBusinessFacade/BusinessFacade/Web/ando_quality_2.cs b/Common/07WebBusinessFacade/BusinessFacade/Web/ando_quality_2.cs new file mode 100644 index 0000000..e745f0a --- /dev/null +++ b/Common/07WebBusinessFacade/BusinessFacade/Web/ando_quality_2.cs @@ -0,0 +1,225 @@ +using System.Data; +using System.Data.SqlClient; +using DataLinkMesWork; +using System.Security.Cryptography; +//using SystemFramework; +using System.Text; +using System; + +namespace bizFacade +{ + public class ando_quality_2 + { + /// + /// 创建质量ando + /// + /// + /// + /// + public static string CreateAndo_quality(string opname, string AndoTypeCode) + { + System.Data.DataTable dt_list; + //查询ando明细 + ando_matertial.andoListSelect(opname, AndoTypeCode, out dt_list); + + + StringBuilder sb = new StringBuilder(); + + sb.Append("
"); + sb.Append("
"); + sb.Append("
"); + + #region 大图片的div + sb.Append("
"); + sb.Append("\"loading....\""); + sb.Append("
"); + #endregion + + #region 整个ANDON选项DIV + sb.Append("
"); + + #region 左按钮DIV + sb.Append("
"); + sb.Append(""); + sb.Append("
"); + #endregion + + + #region 中间内容DIV + sb.Append("
"); + + #region 可支持移动的div + + sb.Append("
"); + + sb.Append("
"); + + + //附加tabel + string tabelString = CreatAndo_quality_table(opname, AndoTypeCode); + sb.Append(tabelString); + + sb.Append("
"); + sb.Append("
"); + #endregion + + sb.Append("
"); + #endregion + + #region 右按钮div + + sb.Append("
"); + + sb.Append(">\" onclick=\"qualty_leftMove()\" />"); + sb.Append("
"); + + #endregion + + sb.Append("
"); + #endregion + #region ando按钮div + + sb.Append("
"); + + sb.Append("
"); + + sb.Append(""); + sb.Append(""); + sb.Append(""); + sb.Append(""); + sb.Append(""); + sb.Append(""); + sb.Append(""); + sb.Append(""); + sb.Append(""); + sb.Append("
"); + sb.Append("\"loading...\""); + sb.Append(""); + sb.Append("\"loading...\""); + sb.Append("
"); + sb.Append(""); + sb.Append(""); + sb.Append(""); + sb.Append("
"); + + sb.Append("
"); + + sb.Append("
"); + + #endregion + + sb.Append("
"); + + + return sb.ToString(); + //string text = ""; + //int count = dt_list.Rows.Count/2*120; + //return text = "{\"InnerHtml\":\"" + sb.ToString() + "\",\"Count\":\"" + count + "\"}"; + } + /// + /// 创建物料ando的table + /// + /// + /// + /// + public static string CreatAndo_quality_table(string opname, string AndoTypeCode) + { + System.Data.DataTable dt_list; + //查询ando明细 + ando_matertial.andoListSelect(opname, AndoTypeCode, out dt_list); + StringBuilder sb = new StringBuilder(); + int tableCount = dt_list.Rows.Count; + int td_count = (tableCount / 2) + (tableCount % 2);//获取每个tr中应该创建多少个td + int tablewidth = 145 * td_count; + if (tablewidth == 0) + { + tablewidth = 10; + } + string tablewidth2 = Convert.ToString(tablewidth) + "px"; + + #region table + + sb.Append(""); + + //创建第一行 + sb.Append(""); + for (int i = 0; i < td_count; i++) + { + #region 第一行按钮 + sb.Append(""); + + #endregion + } + sb.Append(""); + + + //创建第二行 + sb.Append(""); + for (int i = td_count; i < tableCount; i++) + { + #region 第二行按钮 + sb.Append(""); + + #endregion + } + + //补充第二行的信息 + if ((tableCount % 2) > 0 && (tableCount > 0)) + { + sb.Append(""); + } + sb.Append(""); + + //最后组合成table + sb.Append("
"); + //标签id + string id = "button_ando_quality_" + dt_list.Rows[i]["编号"].ToString(); + + #region 颜色代码 + //标签值 + string value = dt_list.Rows[i]["编号描述2"].ToString(); + string color = dt_list.Rows[i]["颜色代码"].ToString(); + //string inputColor = "background-color:" + color + ""; + if (color == "0") + { + sb.Append(""); + } + if (color == "1") + { + sb.Append(""); + } + if (color == "2") + { + sb.Append(""); + } + #endregion + + sb.Append("
"); + //标签id + string id = "button_ando_quality_" + dt_list.Rows[i]["编号"].ToString(); + + #region 颜色代码 + //标签值 + string value = dt_list.Rows[i]["编号描述2"].ToString(); + string color = dt_list.Rows[i]["颜色代码"].ToString(); + if (color == "0") + { + sb.Append(""); + } + if (color == "1") + { + sb.Append(""); + } + if (color == "2") + { + sb.Append(""); + } + #endregion + + sb.Append(""); + sb.Append("
"); + return sb.ToString(); + #endregion + } + } +} diff --git a/Common/07WebBusinessFacade/BusinessFacade/Web/vssver2.scc b/Common/07WebBusinessFacade/BusinessFacade/Web/vssver2.scc new file mode 100644 index 0000000..34129fc Binary files /dev/null and b/Common/07WebBusinessFacade/BusinessFacade/Web/vssver2.scc differ diff --git a/Common/08WebFun_base/WebFun_base.sln b/Common/08WebFun_base/WebFun_base.sln new file mode 100644 index 0000000..558edf6 --- /dev/null +++ b/Common/08WebFun_base/WebFun_base.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.32901.82 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "08-WebFun_base", "WebFun_base\08-WebFun_base.csproj", "{D98BE764-ADEB-488D-9714-61E308AA8201}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {D98BE764-ADEB-488D-9714-61E308AA8201}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {D98BE764-ADEB-488D-9714-61E308AA8201}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D98BE764-ADEB-488D-9714-61E308AA8201}.Release|Any CPU.ActiveCfg = Release|Any CPU + {D98BE764-ADEB-488D-9714-61E308AA8201}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {8FC72F3E-D566-442A-9D59-8781383AA7C9} + EndGlobalSection +EndGlobal diff --git a/Common/08WebFun_base/WebFun_base/08-WebFun_base.csproj b/Common/08WebFun_base/WebFun_base/08-WebFun_base.csproj new file mode 100644 index 0000000..e59523d --- /dev/null +++ b/Common/08WebFun_base/WebFun_base/08-WebFun_base.csproj @@ -0,0 +1,119 @@ + + + + + Debug + AnyCPU + {D98BE764-ADEB-488D-9714-61E308AA8201} + Library + Properties + WebFun_base + 08WebFun_base + v4.8 + 512 + true + + + + true + full + false + ..\..\dll\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + ..\..\dll\MQTTnet.dll + + + ..\..\dll\MQTTnet.Extensions.ManagedClient.dll + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + {f55da1a0-a982-4479-8c47-0d9a5aaf3e18} + 00MesWorkMqtt + + + {0d1af432-439a-4920-8692-43ae139f5530} + 01_01DoWhatPlc + + + {f434e066-4c59-47c8-aa82-6f48cc84501a} + 04-DataBaseAccess + + + {f0a0c525-03fd-428a-9b17-7f54aa0e4475} + 07BusinessFacade + + + + \ No newline at end of file diff --git a/Common/08WebFun_base/WebFun_base/Class1.cs b/Common/08WebFun_base/WebFun_base/Class1.cs new file mode 100644 index 0000000..d11634b --- /dev/null +++ b/Common/08WebFun_base/WebFun_base/Class1.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace WebFun_base +{ + public class Class1 + { + } +} diff --git a/Common/08WebFun_base/WebFun_base/MesWebFun_MateriallPull.cs b/Common/08WebFun_base/WebFun_base/MesWebFun_MateriallPull.cs new file mode 100644 index 0000000..ad95946 --- /dev/null +++ b/Common/08WebFun_base/WebFun_base/MesWebFun_MateriallPull.cs @@ -0,0 +1,125 @@ +using System; +using System.Collections.Generic; +using System.Web; +using System.Text; +using bizFacade; +using System.Data; +//using SystemFramework; + + +namespace MesWebFun_MateriallPull +{ + public partial class MesWebFun_MateriallPull + { + public static string MateriallFuctionRequstBase(string cmd, string opName) + { + string responseText = ""; + switch (cmd) + { + case "AMES_getMaterialInfo": + responseText = Init_WorkStationMaterial(opName); + break; + //--------物料拉动-批次接收----- + case "AMES_InitMaterial_Dialog_MaterialNum": + responseText = InitMaterial_Dialog_MaterialNum(opName); + break; + //case "AMES_getMaterialNumInfo": + // responseText = getMaterialNumInfo(opName); + // break; + //--------物料拉动-库存盘点----- + case "AMES_Init_MaterialNum_Combobox": + responseText = Init_MaterialNum_Combobox(opName); + break; + //case "AMES_ConsumeStockCount": + // responseText = Consume_stockcount(opName); + // break; + //case "AMES_initStockCount": + // responseText = initStockCount(opName); + // break; + case "AMES_Init_Final_OrderNumber_Combobox": + responseText = Init_Final_OrderNumber_Combobox(); + break; + //--------物料拉动-FTT----- + case "AMES_Init_FinalList_Combobox": + responseText = Init_FinalList_Combobox(opName); + break; + case "AMES_Init_DefectCode_Combobox": + responseText = Init_DefectCode_Combobox(opName); + break; + //case "AMES_Insert_FTT_Informatinon": + // responseText = Insert_FTT_Informatinon(opName); + // break; + //case "AMES_Insert_FTT_Confirm": + // responseText = Insert_FTT_Confirm(opName); + // break; + case "AMES_ConvertOpname_Ftt": + responseText = ConvertOpname_Ftt(opName); + break; + //--------物料拉动-打卡上线----- + case "AMES_GetClasses": + responseText = GetClasses(); + break; + case "AMES_Confirmclasses": + responseText = Confirmclasses(); + break; + case "AMES_initOnline": + responseText = initOnline(opName); + break; + //case "AMES_WorkingHours_OnlineInfo": + // responseText = WorkingHours_OnlineInfo(opName); + // break; + ////工时补录 + //case "AMES_OrderNum_Query": + // responseText = OrderNum_Query(); + // break; + //case "AMES_init_WorkTime": + // responseText = init_WorkTime(opName); + // break; + //case "AMES_Worktime_completeCount": + // responseText = Worktime_completeCount(); + // break; + //case "AMES_init_Statistics": + // responseText = init_Statistics(opName); + // break; + //case "AMES_Confirm_Person": + // responseText = Confirm_Person(); + // break; + //case "AMES_Init_OrderNum_data": + // responseText = Init_OrderNum_data(); + // break; + ////班次名称查询 + //case "AMES_SelectClassCode": + // responseText = ClassesCodeSelect(); + // break; + ////工时补录增加 + //case "AMES_Insert_WorkTime": + // responseText = Insert_WorkTime(opName); + // break; + ////--------物料拉动-配送单接收----- + //case "AMES_receiveDistributionOrder": + // responseText = ReceiveDistributionOrder(); + // break; + //--------物料拉动-直供上线----- + //case "AMES_initDirectUpload": + // responseText = initDirectUpload(opName,); + // break; + //case "AMES_directUpload_Verify": + // responseText = DirectUpload_Verify(opName,,); + // break; + //case "AMES_directUpload_Barcode_Verify_OK": + // responseText = DirectUpload_Barcode_Verify_OK(opName,); + // break; + } + return responseText; + } + + public bool IsReusable + { + get + { + return false; + } + } + + } +} diff --git a/Common/08WebFun_base/WebFun_base/MesWebFun_MateriallPullFun.cs b/Common/08WebFun_base/WebFun_base/MesWebFun_MateriallPullFun.cs new file mode 100644 index 0000000..76429b0 --- /dev/null +++ b/Common/08WebFun_base/WebFun_base/MesWebFun_MateriallPullFun.cs @@ -0,0 +1,870 @@ +using System; +using System.Collections.Generic; +using System.Web; +using System.Text; +using bizFacade; +using System.Data; +//using SystemFramework; +using MesWebFun_MateriallPull.BarCodeServer_Pro; + +namespace MesWebFun_MateriallPull +{ + public partial class MesWebFun_MateriallPull + { + private static string Init_WorkStationMaterial(string OpName) + { + DataTable dt; + MaterialPull.getWorkStationMaterialInfo(OpName, out dt); + if (dt != null) + { + return JsonHelper.CreateJsonParameters(dt, true, dt.Rows.Count); + } + else + { + return ""; + } + } + + #region 批次接收 + + /// + /// 物料号获取 + /// + /// 1) + { + for (int i = 0; i < dt.Rows.Count; i++) + { + if (i == 0) + { + sb.Append("\"id\":" + i + ",\"text\":\"" + dt.Rows[0][0] + "\",\"selected\":true},{"); + } + if (i != dt.Rows.Count - 1 & i != 0) + { + sb.Append("\"id\":" + i + ",\"text\":\"" + dt.Rows[i][0] + "\"},{"); + } + else if (i == dt.Rows.Count - 1) + { + sb.Append("\"id\":" + i + ",\"text\":\"" + dt.Rows[i][0] + "\"}]"); + } + } + } + } + return sb.ToString(); + } + + /// + /// 获取卡片一览信息 + /// + /// + /// 物料拉动_库存盘点 + ///
+ /// + private static string initStockCount(string OpName, string MaterialNum) + { + string text = ""; + System.Data.DataTable dt = null; + + //string MaterialNum = HttpContext.Current.Request["MaterialNum"]; + MaterialPull.init_StockCount(OpName, MaterialNum, out dt); + if (dt.Rows.Count > 0) + { + text = JsonHelper.DataTableToJson(dt); + } + return text; + } + + private static string Init_MaterialNum_Combobox(string OpName) + { + string text = ""; + System.Data.DataTable dt = null; + + MaterialPull.Init_MaterialNumCombobox(OpName, out dt); + text = JsonHelper.DataTableToJson(dt); + return text; + } + + private static string Init_Final_OrderNumber_Combobox() + { + string text = ""; + System.Data.DataTable dt = null; + MaterialPull.Init_FinalOrderNumberCombobox(out dt); + text = JsonHelper.DataTableToJson(dt); + return text; + } + + private static string Consume_stockcount(string OpName, string ConsumeNum, string OrderNumber,string CardNum) + { + //string ConsumeNum = HttpContext.Current.Request["ConsumeNum"]; + //string OrderNumber = HttpContext.Current.Request["OrderNumber"]; + + //string CardNum = HttpContext.Current.Request["CardNum"]; + MaterialPull.Consume_StockCount(OrderNumber, ConsumeNum, OpName, CardNum); + return ""; + } + + #endregion 库存盘点 + + #region FTT模块 + + /// + /// 物料拉动_FTT + /// + /// + private static string ConvertOpname_Ftt(string Opname) + { + string text = ""; + System.Data.DataTable dt = null; + MaterialPull.OpName_Convert_Select(Opname, out dt); + if (dt.Rows.Count > 0) + { + text = JsonHelper.DataTableToJson(dt); + } + return text; + } + + private static string Insert_FTT_Confirm(string Opname, string Final_EngineNum, string DefectGroup, string DefectCode) + { + string text = ""; + System.Data.DataTable dt = null; + //string Final_EngineNum = HttpContext.Current.Request["Final_EngineNum"]; + //string DefectGroup = HttpContext.Current.Request["DefectGroup"]; + //string DefectCode = HttpContext.Current.Request["DefectCode"]; + MaterialPull.Confirm_EngineNum(Final_EngineNum, DefectGroup, DefectCode, Opname, out dt); + if (dt.Rows.Count > 0) + { + text = dt.Rows[0][0].ToString(); + } + return text; + } + + private static string Insert_FTT_Informatinon(string Opname, string EngineNum, string DefectGroup, string DefectCode, string ProblemDate, int callCount) + { + string Msg = ""; + //string EngineNum = HttpContext.Current.Request["Final_EngineNum"]; + //string DefectGroup = HttpContext.Current.Request["DefectGroup"]; + //string DefectCode = HttpContext.Current.Request["DefectCode"]; + //string ProblemDate = HttpContext.Current.Request["ProblemDate"]; + //int callCount = Convert.ToInt32(HttpContext.Current.Request["callCount"]); + MaterialPull.Insert_FTTInformation(Opname, "2", EngineNum, DefectGroup, DefectCode, ProblemDate, callCount, out Msg); + + return Msg; + } + + private static string Init_FinalList_Combobox(string Opname) + { + string text = ""; + System.Data.DataTable dt = null; + MaterialPull.Init_FinalListCombobox(Opname, out dt); + if (dt.Rows.Count > 0) + { + text = JsonHelper.DataTableToJson(dt); + } + return text; + } + + private static string Init_DefectCode_Combobox(string Opname) + { + string text = ""; + System.Data.DataTable dt = null; + MaterialPull.Init_DefectCodeCombobox(Opname, out dt); + if (dt.Rows.Count > 0) + { + text = JsonHelper.DataTableToJson(dt); + } + return text; + } + + #endregion FTT模块 + + #region 打卡上线模块 + + /// + /// 物料拉动_打卡上线 + /// + /// + private static string GetClasses() + { + string text = null; + System.Data.DataTable dt = null; + MaterialPull.Getclasses(out dt); + text = JsonHelper.DataTableToJson(dt); + return text; + } + + private static string initOnline(string opName) + { + StringBuilder sb = new StringBuilder(); + System.Data.DataTable dt = null; + string classes = ""; + string operatorName = ""; + string loginTime = ""; + string operatorCode = ""; + string opname = ""; + MaterialPull.Search_OnlineInfo(opName, out dt); + if (dt != null) + { + sb.Append("["); + if (dt.Rows.Count > 0) + { + for (int i = 0; i < dt.Rows.Count; i++) + { + classes = dt.Rows[i]["班次"].ToString(); + System.Data.DataTable dt_output = null; + MaterialPull.ClassName_Select(classes, out dt_output); + if (dt_output != null) + { + if (dt_output.Rows.Count > 0) + { + classes = dt_output.Rows[0]["班次描述"].ToString(); + } + } + opname = dt.Rows[i]["工位号"].ToString(); + operatorCode = dt.Rows[i]["操作者工号"].ToString(); + operatorName = dt.Rows[i]["操作者姓名"].ToString(); + loginTime = dt.Rows[i]["操作时间"].ToString(); + sb.Append("{\"工位号\":\"" + opname + "\",\"操作者工号\":\"" + operatorCode + "\",\"操作者姓名\":\"" + operatorName + "\",\"班次\":\"" + classes + "\",\"操作时间\":\"" + loginTime + "\"},"); + } + sb.Remove(sb.Length - 1, 1); + } + } + sb.Append("]"); + return sb.ToString(); + } + + private static string Confirmclasses() + { + string Confirmclass = ""; + System.Data.DataTable dt_output = null; + MaterialPull.ConfirmClass(out Confirmclass); + string ConfirmclassName = ""; + MaterialPull.ClassName_Select(Confirmclass, out dt_output); + if (dt_output != null) + { + if (dt_output.Rows.Count > 0) + { + ConfirmclassName = dt_output.Rows[0]["班次描述"].ToString(); + } + } + + return ConfirmclassName; + } + + private static string WorkingHours_OnlineInfo(string Opname, string Password, string Classes, string OperatorName) + { + //string Password = ""; + //string Classes = ""; + //string OperatorName = ""; + string Msg = ""; + //Password = HttpContext.Current.Request["Password"]; + //Classes = HttpContext.Current.Request["Classes"]; + //OperatorName = HttpContext.Current.Request["OperatorName"]; + MaterialPull.Insert_WorkingHours(Opname, OperatorName, Password, Classes, out Msg); + + return Msg; + } + + #endregion 打卡上线模块 + + #region 工时 + + private static string OrderNum_Query(string start_time, string end_time) + { + string text = ""; + // string end_time = ""; + // string start_time = ""; + System.Data.DataTable dt = null; + + // start_time = HttpContext.Current.Request["Plan_start_time"]; + + // end_time = HttpContext.Current.Request["Plan_end_time"]; + + start_time = start_time + " 00:00:00"; + end_time = end_time + " 23:59:59"; + + MaterialPull.Init_OrderNum_Query(start_time, end_time, out dt); + if (dt.Rows.Count > 0) + { + text = JsonHelper.DataTableToJson(dt); + } + return text; + } + + //工时补录初始化 + private static string init_WorkTime(string Opname, string Ordernum) + { + StringBuilder sb = new StringBuilder(); + + string text = ""; + int Num = 1; + string classes = ""; + string opname = ""; + string operatorCode = ""; + string operatorName = ""; + string compeleteCount = ""; + string OrderNum = ""; + string UploadTime = ""; + System.Data.DataTable dt = null; + // string Ordernum = HttpContext.Current.Request["OrderNum"]; + MaterialPull.Init_Worktime(Ordernum, Opname, Num, out dt); + if (dt != null) + { + sb.Append("["); + if (dt.Rows.Count > 0) + { + for (int i = 0; i < dt.Rows.Count; i++) + { + System.Data.DataTable dt_output = null; + classes = dt.Rows[i]["班次"].ToString(); + MaterialPull.ClassName_Select(classes, out dt_output); + if (dt_output != null) + { + if (dt_output.Rows.Count > 0) + { + classes = dt_output.Rows[0]["班次描述"].ToString(); + } + } + OrderNum = dt.Rows[i]["订单号"].ToString(); + opname = dt.Rows[i]["工位号"].ToString(); + operatorCode = dt.Rows[i]["操作者工号"].ToString(); + operatorName = dt.Rows[i]["员工姓名"].ToString(); + compeleteCount = dt.Rows[i]["报工数量"].ToString(); + UploadTime = dt.Rows[i]["报工时间"].ToString(); + sb.Append("{\"订单号\":\"" + OrderNum + "\",\"工位号\":\"" + opname + "\",\"员工姓名\":\"" + operatorName + "\",\"操作者工号\":\"" + operatorCode + "\",\"报工数量\":\"" + compeleteCount + "\",\"班次\":\"" + classes + "\",\"报工时间\":\"" + UploadTime + "\"},"); + } + sb.Remove(sb.Length - 1, 1); + } + } + sb.Append("]"); + return sb.ToString(); + } + + private static string Worktime_completeCount(string OrderNum) + { + string text = "0"; + System.Data.DataTable dt = null; + // string OrderNum = HttpContext.Current.Request["OrderNum"]; + MaterialPull.workTime_CompleteCount(OrderNum, out dt); + if (dt != null) + { + if (dt.Rows.Count > 0) + { + text = dt.Rows[0][0].ToString(); + } + } + return text; + } + + private static string init_Statistics(string Opname, string Ordernum) + { + string text = ""; + System.Data.DataTable dt = null; + // string Ordernum = HttpContext.Current.Request["OrderNum"]; + MaterialPull.init_Statistics(Ordernum, Opname, out dt); + if (dt.Rows.Count > 0) + { + text = JsonHelper.DataTableToJson(dt); + } + return text; + } + + /// + /// 校验工时补录人员 + /// + /// + private static string Confirm_Person(string OperatorName) + { + string text = "0"; + System.Data.DataTable dt = null; + // string OperatorName = HttpContext.Current.Request["OperatorName"]; + MaterialPull.Confirm_Person(OperatorName, out dt); + if (dt != null) + { + if (dt.Rows.Count > 0) + { + text = dt.Rows[0][0].ToString(); + } + } + return text; + } + + //查询产品型号 + private static string Init_OrderNum_data(string Ordernum) + { + string text = ""; + System.Data.DataTable dt = null; + // string Ordernum = HttpContext.Current.Request["OrderNum"]; + MaterialPull.Init_Ordernum_data(Ordernum, out dt); + if (dt.Rows.Count > 0) + { + text = JsonHelper.DataTableToJson(dt); + } + return text; + } + + private static string ClassesCodeSelect(string ClassesName) + { + string ClassCode = ""; + System.Data.DataTable dt_output = null; + // string ClassesName = HttpContext.Current.Request["ClassesName"]; + MaterialPull.ClassCode_Select(ClassesName, out dt_output); + if (dt_output != null) + { + if (dt_output.Rows.Count > 0) + { + ClassCode = dt_output.Rows[0]["班次代码"].ToString(); + } + } + return ClassCode; + } + + //工时补录增加 + private static string Insert_WorkTime(string Opname, string Ordernum, string OperatorName, string Classes, string EngineType, int Count, string UploadTime) + { + string text = ""; + //string Ordernum = HttpContext.Current.Request["OrderNum"]; + //string OperatorName = HttpContext.Current.Request["OperatorName"]; + //string Classes = HttpContext.Current.Request["Classes"]; + //string EngineType = HttpContext.Current.Request["EngineType"]; + //int Count = Convert.ToInt32(HttpContext.Current.Request["Count"]); + //string UploadTime = HttpContext.Current.Request["UploadTime"]; + + MaterialPull.Workinghours_Insert(Ordernum, EngineType, Opname, Count, OperatorName, Classes, UploadTime); + return text; + } + + #endregion 工时 + + #region 配送单接收模块 + + /// + /// 物料拉动-配送单接收 + /// + /// 0) + { + text = "配送单号: " + distributionNum + " 已经接收!"; + return text; + } + else + { + if (distributionNum == "") + { + text = "请扫描配送单号!"; + return text; + } + text = MaterialPull_Document_Exec(distributionNum); + } + } + } + catch + { } + return text; + } + + private static bool isExec = false;//防止多次接收 + + private static string MaterialPull_Document_Exec(string distributionNum) + { + string text = ""; + if (!isExec)//为false才允许接收 + { + //string distributionNum = HttpContext.Current.Request["distributionNum"]; + isExec = true; + text = MaterialPull_Document_Select(distributionNum); + } + else + { + text = "不允许接收!"; + } + return text; + } + + private static string MaterialPull_Document_Select(string distributionNum) + { + //string distributionNum = HttpContext.Current.Request["distributionNum"]; + string process_Message; + try + { + string wkc = ""; + System.Data.DataTable dt_wkc; + MaterialPull.WorkStationInfo_Select(out dt_wkc); + if (dt_wkc != null) + { + if (dt_wkc.Rows.Count > 0) + { + wkc = dt_wkc.Rows[0]["工作中心"].ToString(); + } + } + if (wkc == "") + { + process_Message = "工作中心为空!"; + return process_Message; + } + string document_Num = distributionNum.ToString(); + System.Data.DataTable dt_Document; + //调试、先屏蔽 + var BarCodeServer_Document = new BarCodeServer_Pro.BarCodeSever(); + //sql版本需要用dataset承接 + DataSet ds_Document; + ds_Document = BarCodeServer_Document.Web_MaterialPull_DocumentNum_Select(document_Num, wkc); + dt_Document = ds_Document.Tables[0]; + //Orucal版本需要用dataset承接 + //dt_Document = BarCodeServer_Document.Web_MaterialPull_DocumentNum_Select(document_Num, wkc); + if (dt_Document != null) + { + if (dt_Document.Rows.Count > 0) + { + //将条码信息插入到"配送单"表,状态标识为0,暂时不做处理 + if (MaterialPull.MaterialPull_DocumentInfo_Add(dt_Document)) + { + //执行接收处理 + process_Message = MaterialPull_Document_Receive(document_Num, BarCodeServer_Document); + } + else + { + process_Message = "-1@失败,[" + document_Num + "]不能重复接收!"; + } + } + else + { + process_Message = "-1@失败,[" + document_Num + "]无此配送单信息!"; + } + } + else + { + process_Message = "-1@失败,[" + document_Num + "]无此配送单信息!"; + } + } + catch (Exception ex) + { + process_Message = "-1@未知错误,联系管理员!"; + } + isExec = false; + return process_Message; + } + + //执行接收,传入webservice + private static string MaterialPull_Document_Receive(string document_Num, BarCodeSever BarCodeServer_Document) + { + string process_Message = ""; + try + { + string r_source_id = "", r_orderNum = "", r_plant_id = "", r_wkc = "", + r_workNum = "", r_delivery_num = "", r_item_code = "", r_recept_flag = "", r_type = ""; + string p_GroupId = ""; + string documentInfo = ""; + + //产生接收记录,获得GROUPID,还有一个作用就是防止重复接收 + MaterialPull.MaterialPull_DocumentInfo_CreateRecord(document_Num, out documentInfo); + if (documentInfo.Length > 2) + { + //产生接收记录成功 + if (documentInfo.Substring(0, 2) == "0@") + { + p_GroupId = documentInfo.Substring(2, documentInfo.Length - 2); + if (p_GroupId == "") + return "-1@失败,[" + document_Num + "]产生接收记录失败"; + System.Data.DataTable dt_record; + MaterialPull.MaterialPull_DocumentInfo_ReceiveRecord_Select(document_Num, p_GroupId, out dt_record); + if (dt_record != null) + { + if (dt_record.Rows.Count > 0) + { + r_source_id = dt_record.Rows[0]["ID"].ToString(); + r_orderNum = dt_record.Rows[0]["订单号"].ToString(); + r_plant_id = dt_record.Rows[0]["工厂"].ToString(); + r_wkc = dt_record.Rows[0]["工作中心"].ToString(); + r_workNum = dt_record.Rows[0]["工位号"].ToString(); + r_delivery_num = dt_record.Rows[0]["配送单号"].ToString(); + r_item_code = dt_record.Rows[0]["物料号"].ToString(); + r_recept_flag = dt_record.Rows[0]["是否接收"].ToString(); + r_type = dt_record.Rows[0]["类型"].ToString(); + + string outResult; + + outResult = BarCodeServer_Document.Web_MaterialPull_DocumentNum_VerifyOK(r_source_id, r_orderNum, r_plant_id, r_wkc, + r_workNum, r_delivery_num, r_item_code, r_recept_flag, r_type, p_GroupId); + if (outResult.Length > 2) + { + //调用成功的话 返回“0@成功0@” + //将调用信息更新到接收记录表中 + //执行调用成功存储过程,将临时表中数据加到库存中 + if (outResult.Substring(0, 2) == "0@") + { + System.Data.DataSet Select_AndonCallInfo_DS = BarCodeServer_Document.Select_DocumentReceptCord_Result(document_Num, p_GroupId); + System.Data.DataTable Select_AndonCallInfo = Select_AndonCallInfo_DS.Tables[0]; + if (Select_AndonCallInfo != null) + { + if (Select_AndonCallInfo.Rows.Count > 0) + { + string PROCESS_STATUS = Select_AndonCallInfo.Rows[0]["PROCESS_STATUS"].ToString(); + if (PROCESS_STATUS != "SUCCESS") + { + MaterialPull.MaterialPull_DocumentInfo_NoticeOK(document_Num, p_GroupId, 0, outResult); + } + else + { + MaterialPull.MaterialPull_DocumentInfo_NoticeOK(document_Num, p_GroupId, 1, outResult); + } + } + else + { + MaterialPull.MaterialPull_DocumentInfo_NoticeOK(document_Num, p_GroupId, 0, outResult); + } + } + else + { + MaterialPull.MaterialPull_DocumentInfo_NoticeOK(document_Num, p_GroupId, 0, outResult); + } + } + else + { + MaterialPull.MaterialPull_DocumentInfo_NoticeOK(document_Num, p_GroupId, 0, outResult); + } + } + process_Message = outResult + "[" + document_Num + "]"; + } + else + { + process_Message = "-1@失败,[" + document_Num + "]产生接收记录失败"; + } + } + else + { + process_Message = "-1@失败,[" + document_Num + "]产生接收记录失败"; + } + } + else + { + process_Message = documentInfo; + } + } + } + catch + { + process_Message = "-1@未知错误,[" + document_Num + "]联系管理员!"; + } + return process_Message; + } + + #endregion 配送单接收模块 + + #region 直供上线模块 + + /// + /// 物料拉动-直供上线 + /// + /// + private static string initDirectUpload(string OpName,string document_Num) + { + string text = "[{}]"; + try + { + DataTable dt_VarifyTemp = new DataTable(); + string process_Message; + + + string wkc = DirectUpload_Ini_WKC(); + // string document_Num = HttpContext.Current.Request["Barcode"]; + if (document_Num == null) + return text; + System.Data.DataTable dt_Document; + System.Data.DataSet ds_Document; + var direct = new BarCodeServer_Pro.BarCodeSever(); + ds_Document = direct.Web_DirectUpload_Document_Select(document_Num, wkc); + dt_Document = ds_Document.Tables[0]; + MaterialPull.DirectUpload_VerifyTempTable_Delete(OpName); + MaterialPull.DirectUpload_VerifyTempTable_Add(OpName, dt_Document); + MaterialPull.DirectUpload_VerifyTempTable_Select(OpName, document_Num, out process_Message, out dt_VarifyTemp); + if (dt_VarifyTemp == null) + { + process_Message = "条码查询失败!请重新扫描"; + return text = "{\"result\":\"1\"}"; ; + } + + if (dt_VarifyTemp.Rows.Count == 0) + { + process_Message = "条码查询失败!请重新扫描"; + } + + text = JsonHelper.DataTableToJson(dt_VarifyTemp); + } + catch (Exception ex) + { } + return text; + } + + private static string DirectUpload_Ini_WKC() + { + string work_center_code = ""; + System.Data.DataTable dt_wkc; + dt_wkc = MaterialPull.DirectUpload_WorkCenterCode_Select(); + if (dt_wkc != null) + { + if (dt_wkc.Rows.Count > 0) + { + work_center_code = dt_wkc.Rows[0]["工作中心"].ToString(); + } + } + return work_center_code; + } + + private static string DirectUpload_Verify(string OpName, string document_Num, string barcode) + { + string text = ""; + try + { + string process_Message = ""; + //string document_Num = HttpContext.Current.Request["documentNum"];//送货单行条码 + //string barcode = HttpContext.Current.Request["barcode"];//卡片条码 + System.Data.DataTable dt_VarifyTemp; + MaterialPull.DirectUpload_VerifyTempTable_Barcode_Select(OpName, document_Num, barcode, out process_Message, out dt_VarifyTemp); + text = JsonHelper.DataTableToJson(dt_VarifyTemp); + } + catch + { } + return text; + } + + private static string DirectUpload_Barcode_Verify_OK(string OpName, string document_Num) + { + string text = ""; + try + { + // string document_Num = HttpContext.Current.Request["documentNum"];//送货单行条码 + if (document_Num == null) + return text; + string process_Message_verify = ""; + string p_GroupId = ""; + + string r_source_id = "", r_orderNum = "", r_plant_id = "", r_wkc = "", + r_workNum = "", r_delivery_num = "", r_item_code = "", r_recept_flag = ""; + + System.Data.DataTable dt_ReceiveRecord; + + MaterialPull.DirectUpload_VerifyTempTable_VerifyOK(OpName, document_Num, out process_Message_verify); + if (process_Message_verify.Length > 2) + { + //产生接收记录成功 + if (process_Message_verify.Substring(0, 2) == "0@") + { + p_GroupId = process_Message_verify.Substring(2, process_Message_verify.Length - 2); + if (p_GroupId == "") + return text; + MaterialPull.DirectUpload_ReceiveRecord_Select(OpName, document_Num, p_GroupId, out dt_ReceiveRecord); + if (dt_ReceiveRecord != null) + { + if (dt_ReceiveRecord.Rows.Count > 0) + { + r_source_id = dt_ReceiveRecord.Rows[0]["ID"].ToString(); + r_orderNum = dt_ReceiveRecord.Rows[0]["订单号"].ToString(); + r_plant_id = dt_ReceiveRecord.Rows[0]["工厂"].ToString(); + r_wkc = dt_ReceiveRecord.Rows[0]["工作中心"].ToString(); + r_workNum = dt_ReceiveRecord.Rows[0]["工位号"].ToString(); + r_delivery_num = dt_ReceiveRecord.Rows[0]["配送单号"].ToString(); + r_item_code = dt_ReceiveRecord.Rows[0]["物料号"].ToString(); + r_recept_flag = dt_ReceiveRecord.Rows[0]["是否接收"].ToString(); + + r_workNum = DirectUpload_Ini_Opname(r_workNum);//产生接收记录工位号与SAP一致 + + string outResult; + var direct = new BarCodeServer_Pro.BarCodeSever(); + outResult = direct.Web_DirectUpload_Document_VerifyOK(r_source_id, r_orderNum, r_plant_id, r_wkc, + r_workNum, r_delivery_num, r_item_code, r_recept_flag, p_GroupId); + if (outResult.Length > 2) + { + //调用成功的话 返回“0@成功0@” + //将调用信息更新到接收记录表中 + //执行调用成功存储过程,将临时表中数据加到库存中 + if (outResult.Substring(0, 2) == "0@") + { + MaterialPull.DirectUpload_VerifyTempTable_NoticeOK(OpName, document_Num, p_GroupId, 1, outResult); + } + else + { + MaterialPull.DirectUpload_VerifyTempTable_NoticeOK(OpName, document_Num, p_GroupId, 0, outResult); + } + text = JsonHelper.ObjectToJson(outResult); + } + } + } + } + //已经接收,不允许重复接收 + else + { + text = JsonHelper.ObjectToJson(process_Message_verify); + } + } + } + catch + { } + return text; + } + + private static string DirectUpload_Ini_Opname(string opName_Ori) + { + string opName_Convert = ""; + System.Data.DataTable dt_opName_Convert; + dt_opName_Convert = MaterialPull.DirectUpload_OpName_Select(opName_Ori); + if (dt_opName_Convert != null) + { + if (dt_opName_Convert.Rows.Count > 0) + { + opName_Convert = dt_opName_Convert.Rows[0]["指南工位号"].ToString(); + } + } + return opName_Convert; + } + + #endregion 直供上线模块 + } +} \ No newline at end of file diff --git a/Common/08WebFun_base/WebFun_base/MesWebFun_Special.cs b/Common/08WebFun_base/WebFun_base/MesWebFun_Special.cs new file mode 100644 index 0000000..90b7362 --- /dev/null +++ b/Common/08WebFun_base/WebFun_base/MesWebFun_Special.cs @@ -0,0 +1,104 @@ +using System; +using System.Collections.Generic; +using System.Web; +using System.Text; +using bizFacade; +using System.Data; +////using SystemFramework; +using DataLinkMesWork; + +namespace MesWebFun +{ + public class MesWebFun_Special + { + /// + /// 提供调用特殊工位类型方法的调用入口 + /// + /// + /// + public static string SpecialFuctionRequstBase( string cmd,string opName) + { + // string filepath = context.Request.UrlReferrer.ToString(); + // string[] fileItem = filepath.Split('/'); + // string item = fileItem[fileItem.Length - 1]; + // string[] itemUrl = item.Split('?'); + // string destUrl = itemUrl[0];//取得页面值 + // string mesWebFun = ApplicationConfig.MesWebFun[destUrl].ToString(); + // string type = HttpContext.Current.Request["type"]; + string responseText = ""; + // switch (mesWebFun) + { + //case "01": + //WebFunction01 fun01 = new WebFunction01(); + // responseText = fun01.ProcessRequest(context); + // break; + //case "02": + // WebFunction02 fun02 = new WebFunction02(); + // responseText = fun02.ProcessRequest(context); + // break; + //case "04": + // WebFunction04 fun04 = new WebFunction04(); + // responseText = fun04.ProcessRequest(context); + // break; + //case "05": + // WebFunction05 fun05 = new WebFunction05(); + // responseText = fun05.ProcessRequest(context); + // break; + //case "06": + // WebFunction06 fun06 = new WebFunction06(); + // responseText = fun06.ProcessRequest(context); + // break; + //case "07": + // WebFunction07 fun07 = new WebFunction07(); + // responseText = fun07.ProcessRequest(context); + // break; + //case "08": + // WebFunction08 fun08 = new WebFunction08(); + // responseText = fun08.ProcessRequest(context); + // break; + //case "10": + // WebFunction10 fun10 = new WebFunction10(); + // responseText = fun10.ProcessRequest(context); + // break; + //case "11": + // WebFunction11 fun11 = new WebFunction11(); + // responseText = fun11.ProcessRequest(context); + // break; + //case "12": + // WebFunction12 fun12 = new WebFunction12(); + // responseText = fun12.ProcessRequest(context); + // break; + //case "13": + // WebFunction13 fun13 = new WebFunction13(); + // responseText = fun13.ProcessRequest(context); + // break; + //case "14": + // WebFunction14 fun14 = new WebFunction14(); + // responseText = fun14.ProcessRequest(context); + // break; + //case "15": + // WebFunction15 fun15 = new WebFunction15(); + // responseText = fun15.ProcessRequest(context); + // break; + //case "16": + // WebFunction16 fun16 = new WebFunction16(); + // responseText = fun16.ProcessRequest(context); + // break; + //case "17": + // WebFunction17 fun17 = new WebFunction17(); + // responseText = fun17.ProcessRequest(context); + // break; + } + return responseText; + } + + public bool IsReusable + { + get + { + return false; + } + } + + } +} diff --git a/Common/08WebFun_base/WebFun_base/MesWebFun_base.cs b/Common/08WebFun_base/WebFun_base/MesWebFun_base.cs new file mode 100644 index 0000000..eaaeed9 --- /dev/null +++ b/Common/08WebFun_base/WebFun_base/MesWebFun_base.cs @@ -0,0 +1,231 @@ +using System; +using System.Collections.Generic; +using System.Web; +using System.Text; +using bizFacade; +using System.Data; +//using SystemFramework; +namespace MesWebFun_base +{ + public partial class MesWebFun_base + { + public string ProcessRequest(string cmd,string opName/*,string engineID*/) + { + string responseText = ""; + switch (cmd) + { + //托盘信息 + case "MobySelect": + responseText = MobySelect(opName); + break; + //操作图片 + case "PictureShow": + responseText = PictureShow(opName); + break; + //物料信息 + case "MaterialList": + responseText = MaterialList(opName); + break; + //操作指南 + case "ProcessList": + responseText = ProcessList(opName); + break; + case "ShaftPosition": + responseText = ShaftPotion_Select(opName); + break; + //选择订单_增加订单号 + //case "InsertOrderNum": + // responseText = InsertOrderNum(,opName); + // break; + //选择订单_增加发动机型号 + //case "InsertEngineNum": + // responseText = InsertEngineNum(opName,,); + // break; + //订单完工_选择机型 + case "Orderenginetypeselect": + responseText = Orderenginetypeselect(); + break; + //物料拉动_确认接受 + //case "AffirmReceive": + // responseText = AffirmReceive(opName,); + // break; + case "ShowTimelyQuality": + responseText = Quality_Select(opName); + break; + //case "MesloadingSelect": + // responseText = MesloadingSelect(opName); + // break; + //工步属性 + case "StepProperty": + responseText = StepProperty(opName); + break; + //订单信息 + case "OrderFormList": + responseText = OrderFormList(opName); + break; + //查询单号 + case "MaterialPush_ListNumer": + responseText = MaterialPush_ListNumer(opName); + break; + //根据单号查询详细信息 + //case "MaterialPush_Details": + // responseText = MaterialPush_Details(opName); + // break; + case "QualityDataButton_bgColor_Select": + responseText = QualityDataButton_bgColor_Select(opName); + break; + //查询具体ando类型明细 + case "InitComboboxAndoDetail": + responseText = InitComboboxAndoDetail(); + break;//InitMaterailAndo + case "InitMaterailAndo": + responseText = InitMaterailAndo(opName); + break; + //case "InitMaterailAndoCount": + // responseText = InitMaterailAndoCount(opName); + // break; + //物料ando_呼叫 + //case "submitAndoMaterialCall": + // responseText = submitAndoMaterialCall(opName); + // break; + //ando界面_物料ando_更新物料安东table + //case "updataAndoMaterialTabel": + // responseText = updataAndoMaterialTabel(opName); + // break; + //ando界面_质量ando_更新质量安东table + //case "updataAndoQualityTabel": + // responseText = updataAndoQualityTabel(opName); + // break; + ////ando界面_物料ando_物料ando复位 + //case "submitAndoMaterialReset": + // responseText = submitAndoMaterialReset(opName); + // break; + ////ando界面_复位 + //case "submitAndoQualityReset": + // responseText = submitAndoQualityReset(opName); + // break; + //////////////////////设备管理 + case "LoadMachineType": //初始化设备维护类型 + responseText = LoadMachineType(opName); + break; + //case "ShowMaintainData": + // responseText = ShowMaintainData(opName); + // break; + //case "ShowMaintainPic": + // responseText = ShowMaintainPic(opName); + // break; + //case "equipmentmanagementSubmit": + // responseText = equipmentmanagementSubmit(opName); + // break;//equipmentmanagementSubmit + /////////////////////////质量查询 + //case "QualityDataSelect": + // responseText = QualityDataSelect(opName); + // break; + //弹窗消息 + case "ShowWindowNotice": + responseText = ShowWindowNotice(opName); + break; + //消息滚动 + case "ShowLEDNotice": + responseText = ShowLEDNotice(opName); + break; + case "GetOrderForm"://获取生产订单 + responseText = GetOrderForm(opName); + break; + case "GetEngineType"://获取发动机型号 + responseText = GetEngineType(opName); + break; + case "ShowOpNameMessage"://显示工位名称、操作工编号 + responseText = ShowOpNameMessage(opName); + break; + case "WebLoginIn"://系统初始化时,复位一些信息 + responseText = WebLoginIn(opName); + break; + case "MaterialCheckPosition"://物料检测指导 + responseText = MaterialCheckPosition(opName); + break; + //case "functionButtonConfirmOk"://合格放行 + // responseText = functionButtonConfirmOk(opName); + // break; + ////物料追溯数据查询 + //case "MaterialDataSelect": + // responseText = MaterialDataSelect(opName); + // break; + //case "MaterialSelect"://电子看板_装配零件_查询 + // responseText = MaterialSelect(opName); + // break; + //case "MaterialManualUpdateBetch"://手动修改批次信息以及生产厂家 + // responseText = MaterialManualUpdateBetch(opName); + // break; + //case "Insert_OnlineOutline"://将在线,离线,屏蔽更新到数据库中 + // responseText = Insert_OnlineOutline(opName); + // break; + case "Init_OnlineOutline"://功能按钮 - 从数据库中初始化在线 / 离线 / 屏蔽的combobox + responseText = Init_OnlineOutline(opName); + break; + case "InitOpNameOuputCount"://初始化节拍数据 + responseText = InitOpNameOuputCount(opName); + break; + //case "Insert_ConfirmOk"://电子看板_发动机号_合格放行_记录_增加 + // responseText = Insert_ConfirmOk(opName); + // break; + case "OrderFormList_OrderComplete"://订单完工,上线数量大于计划数量,界面提示 + responseText = OrderFormList_OrderComplete(opName); + break; + case "GetLoginUrl": + responseText = GetLoginOutUrl(); + break; + //case "SetRepaireNum": + // responseText = Insert_RepiareNum(opName); + // break; + case "GetRepaireNum": + responseText = GetRepaireNum(opName); + break; + case "Init_TreeData"://返修上线 + responseText = Init_TreeData(opName); + break; + //case "Quality_Select_Repair"://返修上线选择质量数据 + // responseText = Quality_Select_Repair(opName, engineID); + // break; + //case "Insert_selectTreeData"://返修上线-将选择的根节点数据更新到数据库中 + // responseText = Insert_selectTreeData(opName); + // break; + case "QualityDataButton_bgColor_alert_Select": + responseText = QualityDataButton_bgColor_alert_Select(opName); + break; + ////物料追溯数据查询_根据发动机号 20170319 + //case "MaterialDataSelect_F_EnergineID": + // responseText = MaterialDataSelect_F_EnergineID(opName); + // break; + case "GetPdfSrc": + responseText = GetPdfSrc(opName); //获取操作指南的PDF路径 + break; + default: + string[] sArray = cmd.Split('_'); + string Funtype = sArray[0]; + if (Funtype == "AMES") + { + responseText = MesWebFun_MateriallPull.MesWebFun_MateriallPull.MateriallFuctionRequstBase(cmd, opName); + } + else + { + responseText = MesWebFun.MesWebFun_Special.SpecialFuctionRequstBase(cmd, opName); + } + break; + } + return responseText; + } + + + public bool IsReusable + { + get + { + return false; + } + } + + + + } +} \ No newline at end of file diff --git a/Common/08WebFun_base/WebFun_base/MesWebFun_baseFun.cs b/Common/08WebFun_base/WebFun_base/MesWebFun_baseFun.cs new file mode 100644 index 0000000..6adbc0b --- /dev/null +++ b/Common/08WebFun_base/WebFun_base/MesWebFun_baseFun.cs @@ -0,0 +1,1787 @@ +using System; +using System.Collections.Generic; +using System.Web; +using System.Text; +using bizFacade; +using System.Data; +//using SystemFramework; + +namespace MesWebFun_base +{ + public partial class MesWebFun_base + { + /// + /// 电子看板_发动机号_合格放行_记录_增加 + /// + /// + private string Insert_ConfirmOk(string opName, string operatorNum, string type) + { + string text = ""; + try + { + // string operatorNum = HttpContext.Current.Request["userName"];//放行者工号 + // string type = HttpContext.Current.Request["recordType"];//放行类型 + MES.InsertRecord_ComfirmOkGO(opName, operatorNum, type); + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "MesWebFun_baseFun:Insert_ConfirmOk"); + } + return text; + } + + /// + /// 订单完工,上线数量大于计划数量,界面提示 + /// + /// + private string OrderFormList_OrderComplete(string opName) + { + string text = ""; + try + { + int isCompleted;//订单数量是否完全上线 + int num_plan;//计划数量 + int num_complete;//上线数量 + MES.Select_OrderFormList_OrderComplete(opName, out isCompleted, out num_plan, out num_complete); + text = "{\"isCompleted\":\"" + isCompleted + "\",\"num_plan\":\"" + num_plan + "\",\"num_complete\":\"" + num_complete + "\"}"; + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "MesWebFun_baseFun:OrderFormList_OrderComplete"); + } + return text; + } + + /// + /// 初始化节拍数据 + /// + /// + private string InitOpNameOuputCount(string opnameValue) + { + string text = ""; + try + { + int outputValue = 0; //工位产量 + int nowOutputValue = 0; //在线产量 + int opNameBeatValue = 0; //工位节拍 + int NowOpNameBeatValue = 0; //在线节拍 + int classNumber = 0;//班次代码 + MES.InitOpNameOuputCount(opnameValue, out outputValue, out nowOutputValue, out opNameBeatValue, out NowOpNameBeatValue, out classNumber); + text = "{\"outputValue\":\"" + outputValue + "\",\"nowOutputValue\":\"" + nowOutputValue + "\",\"opNameBeatValue\":\"" + opNameBeatValue + "\",\"NowOpNameBeatValue\":\"" + NowOpNameBeatValue + "\",\"classNumber\":\"" + classNumber + "\"}"; + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "MesWebFun_baseFun:InitOpNameOuputCount"); + } + return text; + } + + /// + /// 功能按钮 - 从数据库中初始化在线 / 离线 / 屏蔽的combobox + /// + /// + private string Init_OnlineOutline(string opnameValue) + { + string text = ""; + try + { + System.Data.DataTable dt = null; + MES.Init_OnlineOutline(opnameValue, out dt); + string value = ""; + if (dt != null) + { + if (dt.Rows.Count > 0) + { + value = dt.Rows[0]["工位状态"].ToString(); + } + } + text = "{\"value\":\"" + value + "\"}"; + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "MesWebFun_baseFun:Init_OnlineOutline"); + } + return text; + } + + /// + /// 功能按钮---将在线,离线,屏蔽更新到数据库中 + /// + /// + private string Insert_OnlineOutline(string opnameValue, string selectValue) + { + string text = ""; + try + { + //string opnameValue = HttpContext.Current.Request["opnameValue"];//工位号 + //string selectValue = HttpContext.Current.Request["selectValue"];//选择的值 + if (selectValue == "") + { + selectValue = "0"; + } + int selectValueint = Convert.ToInt32(selectValue); + bool falg = MES.Insert_OnlineOutline(opnameValue, selectValueint); + if (falg) + { + text = "{\"falg\":\"1\"}"; + } + else + { + text = "{\"falg\":\"0\"}"; + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "MesWebFun_baseFun:Insert_OnlineOutline"); + } + return text; + } + + /// + /// 合格放行 + /// + /// + private string functionButtonConfirmOk(string userName, string passWord) + { + string text = ""; + try + { + string roleFlag = ""; + string loginFlag = ""; + System.Data.DataTable dt_User = null; + //string userName = HttpContext.Current.Request["function_button_confirmOkGo_userName"]; + //string passWord = HttpContext.Current.Request["function_button_confirmOkGo_passWord"]; + + BaseDataSystemMES.UserInfo_Login(userName, passWord, out dt_User); + if (dt_User != null) + { + if (dt_User.Rows.Count == 1) + { + int roleCodSum = Convert.ToInt32(dt_User.Rows[0][0].ToString()); + bool IsOK = false; + RoleDistribution(roleCodSum, out IsOK); + if (IsOK == true) + { + roleFlag = "1"; + loginFlag = "1"; + } + else + { + roleFlag = "0"; + } + } + else + { + loginFlag = "0"; + } + } + else + { + loginFlag = "0"; + } + text = "{\"roleFlag\":\"" + roleFlag + "\",\"loginFlag\":\"" + loginFlag + "\"}"; + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "MesWebFun_baseFun:functionButtonConfirmOk"); + } + return text; + } + + /// + /// 看用户是否有权限访问该页面 + /// + /// + /// + private void RoleDistribution(int roleCodSum, out bool IsOK) + { + IsOK = false; + //登录工位MES的权限是256 如果role&256>0则有权限登录MES软件 + int roleCode = 64; + //ArrayList aList = new ArrayList(); + if ((roleCodSum & roleCode) > 0) + { + ////加了没用上 + //aList.Add(roleCode); + + switch (roleCode) + { + case 64: + { + //一级用户管理 + IsOK = true; + } + break; + + default: + break; + } + } + } + + /// + /// 选择订单_增加订单号 + /// + /// + private string InsertOrderNum(string orderlist, string opName) + { + //string orderlist = HttpContext.Current.Request["orderNum"]; + MES.OrderNum_Add(opName, orderlist); + return orderlist; + } + + /// + /// 选择订单_增加发动机型号 + /// + /// + private string InsertEngineNum(string opName, string enginetype, string enginetypecode) + { + string orderlist = ""; + //string enginetype = HttpContext.Current.Request["enginetype"]; + //string enginetypecode = HttpContext.Current.Request["enginetypecode"]; + int enginetypeID = Convert.ToInt32(enginetypecode); + MES.EngineNum_Add(opName, enginetype, enginetypeID); + return orderlist; + } + + /// + /// 物料拉动_确认接受 + /// + /// + private string AffirmReceive(string opName, string DistributionNums) + { + string text = ""; + try + { + bool falg = false; + //string DistributionNums = HttpContext.Current.Request["DistributionNums"]; + string[] array = DistributionNums.Split(','); + string DistributionNum = ""; + for (int i = 0; i < array.Length; i++) + { + DistributionNum = array[i]; + falg = MaterialPull.DistributionNum(opName, DistributionNum); + } + if (falg) + { + text = "{\"falg\":\"1\"}"; + } + else + { + text = "{\"falg\":\"0\"}"; + } + } + catch (Exception err) + { + //////ApplicationLog.WriteLog(err, "MesWebFun_baseFun:AffirmReceive"); + } + return text; + } + + /// + /// 设备管理_设备保养记录增加 + /// + /// + private string equipmentmanagementSubmit(string opname, string mark) + { + string text = ""; + try + { + bool flag; + // string mark = HttpContext.Current.Request["mark"]; + flag = bizFacade.MES_MachineManage.Mes_MachineTakeCare_Insert(opname, mark); + if (flag) + { + text = "{\"flag\":\"1\"}"; + } + else + { + text = "{\"flag\":\"0\"}"; + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "MesWebFun_baseFun:equipmentmanagementSubmit"); + } + return text; + } + + /// + /// 获取对应工位的质量数据 + /// + /// + private string QualityDataSelect(string opName, string opname) + { + string qualitydata = ""; + try + { + System.Data.DataTable dt = null; + //string opName = HttpContext.Current.Request["value"]; + //string opname = HttpContext.Current.Request["opname"]; + MES.QualityDataSelect(opName, opname, out dt); + if (dt != null) + { + if (dt.Rows.Count > 0) + { + qualitydata = JsonHelper.CreateJsonParameters(dt); + } + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "MesWebFun_baseFun:QualityDataSelect"); + } + return qualitydata; + } + + + + /// 获取设备保养类型 + ///
+ /// + private string LoadMachineType(string opName) + { + string Maintain = ""; + try + { + System.Data.DataTable dt = null; + //string opName = HttpContext.Current.Request["value"]; + MES.LoadMachineType(opName, out dt); + if (dt.Rows.Count > 0) + { + Maintain = JsonHelper.DataTableToJson(dt); + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "MesWebFun_baseFun:LoadMachineType"); + } + return Maintain; + } + + + /// 获取设备保养内容 + /// + /// + private string ShowMaintainData(string opName, string MachineType) + { + string Maintain = ""; + try + { + System.Data.DataTable dt = null; + //string opName = HttpContext.Current.Request["value"]; + //string MachineType = HttpContext.Current.Request["machinetype"]; + MES.ShowMaintainData(opName, MachineType, out dt); + if (dt.Rows.Count > 0) + { + Maintain = JsonHelper.CreateJsonParameters(dt); + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "MesWebFun_baseFun:ShowMaintainData"); + } + return Maintain; + } + + /// + /// 获取设备保养图片 + /// + /// + private string ShowMaintainPic(string opName, string MachineType) + { + string Maintain = ""; + try + { + //string opName = HttpContext.Current.Request["value"]; + //string MachineType = HttpContext.Current.Request["machinetype"]; + byte[] imgBytesIn; + MES.GetMaintainImageFile(opName, MachineType, out imgBytesIn); + if (imgBytesIn == null) + { + return Maintain; + } + Maintain = Convert.ToBase64String(imgBytesIn); + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "MesWebFun_baseFun:ShowMaintainPic"); + } + return Maintain; + } + + /// + /// 物料ando复位 + /// + /// + private string submitAndoMaterialReset(string opname, string andoTypeCode, string andoListCode, string number) + { + string text = ""; + try + { + string number1 = ""; + //string andoTypeCode = HttpContext.Current.Request["andoTypeCode"]; + //string andoListCode = HttpContext.Current.Request["andoListCode"]; + //string number = HttpContext.Current.Request["number"]; + + string[] number_array = number.Split(','); + string number_value = ""; + string callInfo = "复位信息"; + + for (int i = 0; i < number_array.Length - 1; i++) + { + number_value = number_array[i].ToString(); + string[] valuelist = number_value.Split('_'); + if (valuelist.Length >= 4) + { + number1 = valuelist[3]; + bizFacade.ando_matertial.AndoMaterialReset(opname, number1, andoTypeCode, andoListCode, callInfo); + } + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "MesWebFun_baseFun:submitAndoMaterialReset"); + } + + return text; + } + + /// + /// ando界面_质量ando复位 + /// + /// + private string submitAndoQualityReset(string opname, string andoTypeCode, string andoListCode, string number) + { + string text = ""; + try + { + string number1 = ""; + //string andoTypeCode = HttpContext.Current.Request["andoTypeCode"]; + //string andoListCode = HttpContext.Current.Request["andoListCode"]; + //string number = HttpContext.Current.Request["number"]; + string[] valuelist = number.Split('_'); + if (valuelist.Length >= 4) + { + number1 = valuelist[3]; + } + + //呼叫内容 + string callInfo = "复位信息"; + bool flag = bizFacade.ando_matertial.AndoMaterialReset(opname, number1, andoTypeCode, andoListCode, callInfo); + if (flag) + { + text = "{\"flag\":\"1\"}"; + } + else + { + text = "{\"flag\":\"0\"}"; + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "MesWebFun_baseFun:submitAndoQualityReset"); + } + return text; + } + + /// + /// 物料ando_更新ando的具体的tabel + /// + /// + private string updataAndoMaterialTabel(string opname, string andoTypeCode) + { + string text = ""; + try + { + //string andoTypeCode = HttpContext.Current.Request["andoTypeCode"]; + text = bizFacade.ando_matertial.CreatAndo_Material_table(opname, andoTypeCode); + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "MesWebFun_baseFun:updataAndoMaterialTabel"); + } + return text; + } + + /// + /// 质量ando_更新ando的具体的tabel + /// + /// + private string updataAndoQualityTabel(string opname, string andoTypeCode) + { + string text = ""; + try + { + // string andoTypeCode = HttpContext.Current.Request["andoTypeCode"]; + text = bizFacade.ando_quality.CreatAndo_quality_table(opname, andoTypeCode); + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "MesWebFun_baseFun:updataAndoQualityTabel"); + } + return text; + } + + /// + /// ando界面_提交物料ando信息(插入呼叫信息) + /// + /// + private string submitAndoMaterialCall(string opname, string andoTypeCode, string andoListCode, string number) + { + string text = ""; + try + { + string number1 = ""; + //System.Data.DataTable tb; + //string andoTypeCode = HttpContext.Current.Request["andoTypeCode"]; + //string andoListCode = HttpContext.Current.Request["andoListCode"]; + //string number = HttpContext.Current.Request["number"]; + string[] number_array = number.Split(','); + string number_value = ""; + string callInfo = "0"; + int callCount = 0; + string cardNumber = "0"; + string noNumber = "0"; + + for (int i = 0; i < number_array.Length - 1; i++) + { + number_value = number_array[i].ToString(); + string[] valuelist = number_value.Split('_'); + if (valuelist.Length >= 4) + { + number1 = valuelist[3]; + bizFacade.ando_matertial.andoMaterialCall(opname, andoTypeCode, andoListCode, number1, callInfo, callCount, cardNumber, noNumber); + } + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "MesWebFun_baseFun:submitAndoMaterialCall"); + } + return text; + } + + /// + /// 安东界面_质量ando_呼叫提交 + /// + /// + private string submitAndoQualityCall() + { + string text = ""; + //string number1 = ""; + //string opname = HttpContext.Current.Request["opname"]; + //string andoTypeCode = HttpContext.Current.Request["andoTypeCode"]; + //string andoListCode = HttpContext.Current.Request["andoListCode"]; + //string number = HttpContext.Current.Request["number"]; + //string[] valuelist = number.Split('_'); + //if (valuelist.Length >= 4) + //{ + // number1 = valuelist[3]; + //} + //string callInfo = "0"; + //int callCount = 5; + //string cardNumber = "0"; + //string noNumber = "0"; + //bool flag = bizFacade.ando_matertial.andoMaterialCall(opname, andoTypeCode, andoListCode, number1, callInfo, callCount, cardNumber, noNumber); + //if (flag) + //{ + // text = "{\"flag\":\"1\"}"; + //} + //else + //{ + // text = "{\"flag\":\"0\"}"; + //} + return text; + } + + /// + /// 查询物料ando条数,为了左移动的 + /// + /// + private string InitMaterailAndoCount(string opname, string andoTypeCode) + { + string text = ""; + try + { + System.Data.DataTable dt_material; + System.Data.DataTable dt_quality; + System.Data.DataTable dt_machine; + //string andoTypeCode = HttpContext.Current.Request["andoTypeCode"]; + //查询物料ando具体的button个数 + bizFacade.ando_matertial.andoListSelect(opname, "1", out dt_material); + int count_material = 0; + + //不为空 + if (dt_material != null) + { + if (dt_material.Rows.Count == 0) + { + count_material = 0; + } + else + { + count_material = dt_material.Rows.Count; + } + } + //查询质量ando具体的button个数 + bizFacade.ando_matertial.andoListSelect(opname, "2", out dt_quality); + int count_quality = 0; + if (dt_quality != null) + { + if (dt_quality.Rows.Count == 0) + { + count_quality = 0; + } + else + { + count_quality = dt_quality.Rows.Count; + } + } + //查询设备ando具体的button个数 + bizFacade.ando_matertial.andoListSelect(opname, "3", out dt_machine); + + int count_machine = 0; + if (dt_machine != null) + { + if (dt_machine.Rows.Count == 0) + { + count_machine = 0; + } + else + { + count_machine = dt_machine.Rows.Count; + } + } + text = "{\"material_count\":\"" + count_material + "\",\"machine_count\":\"" + count_machine + "\",\"quality_count\":\"" + count_quality + "\"}"; + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "MesWebFun_baseFun:InitMaterailAndoCount"); + } + return text; + } + + /// + /// 初始化ando + /// + /// + private string InitMaterailAndo(string opname) + { + string text = ""; + try + { + text = bizFacade.ando_load.ando_loading(opname); + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "MesWebFun_baseFun:InitMaterailAndo"); + } + return text; + } + + /// + /// ando_查询具体ando类型明细 + /// + /// + private string InitComboboxAndoDetail() + { + string text = ""; + //System.Data.DataTable dt = null; + //string andoType="1"; + //bizFacade.ando.select_ando_detail(andoType, out dt); + //text = JsonHelper.DataTableToJson(dt); + return text; + } + + /// + /// 初始化装配线MES + /// + /// + private string MesloadingSelect(string opname, string languageType, string mainModule) + { + string text = ""; + try + { + System.Data.DataTable dt = null; + + //string languageType = HttpContext.Current.Request["mainModule"]; + //string mainModule = HttpContext.Current.Request["MesWebCode"]; + bizFacade.MES_Loading.MES_Loading_select(languageType, mainModule, opname, out dt); + if (dt != null) + { + if (dt.Rows.Count > 0) + { + text = JsonHelper.DataTableToJson(dt); + } + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "MesWebFun_baseFun:MesloadingSelect"); + } + return text; + } + + /// + /// 查询托盘信息 + /// + /// + private string MobySelect(string OpName) + { + string data = ""; + try + { + string orderNum = ""; + int EngineTypeID = 0; + string EngineType = ""; + string EngineID = ""; + string PartPallet_Code = ""; + int IsrepairBarcode = 0; + string repairBarcode = ""; + MES.Moby_Select(OpName, out orderNum, out EngineTypeID, out EngineType, out EngineID, out PartPallet_Code, out IsrepairBarcode, out repairBarcode); + data = orderNum + "&" + EngineTypeID + "&" + EngineType + "&" + EngineID + "&" + PartPallet_Code + "&" + IsrepairBarcode + "&" + repairBarcode; + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "MesWebFun_baseFun:MobySelect"); + } + return data; + } + + /// + /// 查询操作图片 + /// + /// + private string PictureShow(string OpName) + { + string data = ""; + try + { + string orderNum = ""; + int EngineTypeID = 0; + string EngineType = ""; + string EngineID = ""; + string PartPallet_Code = ""; + int IsrepairBarcode = 0; + string repairBarcode = ""; + byte[] imgBytesIn; + MES.Moby_Select(OpName, out orderNum, out EngineTypeID, out EngineType, out EngineID, out PartPallet_Code, out IsrepairBarcode, out repairBarcode); + BaseDataSystemMES.GetImageFile(OpName, EngineTypeID.ToString(), out imgBytesIn); + if (imgBytesIn == null) + { + return data; + } + data = Convert.ToBase64String(imgBytesIn); + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "MesWebFun_baseFun:PictureShow"); + } + return data; + } + + /// + /// 查询物料 + /// + /// + private string MaterialList(string OpName) + { + string jsonStr_Materail = ""; + try + { + string orderNum = ""; + int EngineTypeID = 0; + string EngineType = ""; + string EngineID = ""; + string PartPallet_Code = ""; + int IsrepairBarcode = 0; + string repairBarcode = ""; + + MES.Moby_Select(OpName, out orderNum, out EngineTypeID, out EngineType, out EngineID, out PartPallet_Code, out IsrepairBarcode, out repairBarcode); + DataTable dt_Material; + + MES.PartMaterialVerify_Select(OpName, EngineTypeID, EngineType, out dt_Material); + if (dt_Material != null) + { + if (dt_Material.Rows.Count > 0) + { + jsonStr_Materail = JsonHelper.CreateJsonParameters(dt_Material); + } + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "MesWebFun_baseFun:MaterialList"); + } + return jsonStr_Materail; + } + + /// + /// 查询物料库存信息 + /// + /// + private string MaterialListStock(string OpName) + { + string jsonStr_Materail = ""; + try + { + string orderNum = ""; + int EngineTypeID = 0; + string EngineType = ""; + string EngineID = ""; + string PartPallet_Code = ""; + int IsrepairBarcode = 0; + string repairBarcode = ""; + + MES.Moby_Select(OpName, out orderNum, out EngineTypeID, out EngineType, out EngineID, out PartPallet_Code, out IsrepairBarcode, out repairBarcode); + DataTable dt_Material; + + MES.PartMaterialVerify_Select(OpName, EngineTypeID, EngineType, out dt_Material); + if (dt_Material != null) + { + if (dt_Material.Rows.Count > 0) + { + jsonStr_Materail = JsonHelper.CreateJsonParameters(dt_Material); + } + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "MesWebFun_baseFun:MaterialList"); + } + return jsonStr_Materail; + } + + /// + /// 查询操作指南 + /// + /// + private string ProcessList(string OpName) + { + string jsonStr_Process = ""; + try + { + string orderNum = ""; + int EngineTypeID = 0; + string EngineType = ""; + string EngineID = ""; + string PartPallet_Code = ""; + int IsrepairBarcode = 0; + string repairBarcode = ""; + DataTable dt_Proccess; + + MES.Moby_Select(OpName, out orderNum, out EngineTypeID, out EngineType, out EngineID, out PartPallet_Code, out IsrepairBarcode, out repairBarcode); + + MES.Process_Select(OpName, EngineTypeID, EngineType, out dt_Proccess); + if (dt_Proccess != null) + { + if (dt_Proccess.Rows.Count > 0) + { + jsonStr_Process = JsonHelper.CreateJsonParameters(dt_Proccess); + } + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "MesWebFun_baseFun:ProcessList"); + } + return jsonStr_Process; + } + + /// + /// 创建动态div + /// + /// + private string ShaftPotion_Select(string OpName) + { + string text = ""; + try + { + string orderNum = ""; + int EngineTypeID = 0; + string EngineType = ""; + string EngineID = ""; + string PartPallet_Code = ""; + int IsrepairBarcode = 0; + string repairBarcode = ""; + DataTable dt; + + MES.Moby_Select(OpName, out orderNum, out EngineTypeID, out EngineType, out EngineID, out PartPallet_Code, out IsrepairBarcode, out repairBarcode); + MES.ShaftPositionSelect(OpName, EngineTypeID, out dt); + if (dt != null) + { + if (dt.Rows.Count > 0) + { + text = JsonHelper.DataTableToJson(dt); + } + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "MesWebFun_baseFun:ShaftPotion_Select"); + } + return text; + } + + /// + /// 实时显示质量数据 + /// + /// + private string Quality_Select(string OpName) + { + string text = ""; + try + { + string orderNum = ""; + int EngineTypeID = 0; + string EngineType = ""; + string EngineID = ""; + string PartPallet_Code = ""; + int IsrepairBarcode = 0; + string repairBarcode = ""; + DataTable dt; + + MES.Moby_Select(OpName, out orderNum, out EngineTypeID, out EngineType, out EngineID, out PartPallet_Code, out IsrepairBarcode, out repairBarcode); + MES.QualitySelect(OpName, EngineID, out dt); + if (dt != null) + { + if (dt.Rows.Count > 0) + { + text = JsonHelper.CreateJsonParameters(dt); + } + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "MesWebFun_baseFun:Quality_Select"); + } + return text; + } + + /// + /// 获得工步属性 + /// + /// + private string StepProperty(string opName) + { + string stepProperty = "512"; + System.Data.DataTable dt = null; + bizFacade.UserLogin.GetUrl(opName, out dt); + if (dt != null) + { + if (dt.Rows.Count > 0) + { + stepProperty = dt.Rows[0]["工步属性"].ToString(); + } + } + return stepProperty; + } + + /// + /// 获得订单信息 + /// + /// + private string OrderFormList(string opName) + { + string orderlist = ""; + try + { + System.Data.DataTable dt = null; + MES.OrderFormList_Select(opName, out dt); + //对其进行判断 + if (dt != null) + { + if (dt.Rows.Count > 0) + { + int planCount;//计划数量 + int finishCount;//完成数量 + int isOverCount;//是否超标,0表示未完成,1表示正好完成,2表示超过预期 + int isSelect;//选择标志 + int isCanSelect;//是否有订单选择权限 + string status;//状态 + for (int i = 0; i < dt.Rows.Count; i++) + { + planCount = 0; + finishCount = 0; + isOverCount = 0; + isSelect = 0; + isCanSelect = 0; + status = ""; + + if (dt.Rows[i]["计划数量"].ToString() != "") + { + planCount = Convert.ToInt32(dt.Rows[i]["计划数量"]); + } + if (dt.Rows[i]["完成数量"].ToString() != "") + { + finishCount = Convert.ToInt32(dt.Rows[i]["完成数量"]); + } + if (dt.Rows[i]["选择标志"].ToString() != "") + { + isSelect = Convert.ToInt32(dt.Rows[i]["选择标志"]); + } + if (dt.Rows[i]["订单选择权限"].ToString() != "") + { + isCanSelect = Convert.ToInt32(dt.Rows[i]["订单选择权限"]); + } + if (isSelect == 1)//表示选择当前订单,显示"√" + { + status = "√"; + } + if (finishCount == planCount)//完成数量>计划数量则表示超标 + { + isOverCount = 1; + } + if (finishCount > planCount)//完成数量>计划数量则表示超标 + { + isOverCount = 2; + } + //重新赋值 + dt.Rows[i]["状态"] = status; + dt.Rows[i]["是否超标"] = isOverCount;//0表示未完成,1表示正好完成,2表示超过预期 + dt.Rows[i]["选择标志"] = isSelect; + dt.Rows[i]["订单选择权限"] = isCanSelect; + } + } + } + + orderlist = JsonHelper.CreateJsonParameters(dt); + //orderlist = CreateJsonParameters(dt); + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "MesWebFun_baseFun:OrderFormList"); + } + return orderlist; + } + + private static string CreateJsonParameters(DataTable dt) + { + StringBuilder JsonString = new StringBuilder(); + //Exception Handling + if (dt != null) + { + JsonString.Append("{ "); + JsonString.Append("\"total\":"); + JsonString.Append(dt.Rows.Count); + JsonString.Append(","); + JsonString.Append("\"rows\":[ "); + for (int i = 0; i < dt.Rows.Count; i++) + { + JsonString.Append("{ "); + for (int j = 0; j < dt.Columns.Count; j++) + { + if (j < dt.Columns.Count - 1) + { + //if (dt.Rows[i][j] == DBNull.Value) continue; + if (dt.Columns[j].DataType == typeof(bool)) + { + JsonString.Append("\"JSON_" + dt.Columns[j].ColumnName.ToLower() + "\":" + + dt.Rows[i][j].ToString().ToLower() + ","); + } + else if (dt.Columns[j].DataType == typeof(string)) + { + JsonString.Append("\"JSON_" + dt.Columns[j].ColumnName.ToLower() + "\":" + "\"" + + dt.Rows[i][j].ToString().Replace("\"", "\\\"") + "\","); + } + else + { + JsonString.Append("\"JSON_" + dt.Columns[j].ColumnName.ToLower() + "\":" + "\"" + dt.Rows[i][j] + "\","); + } + } + else if (j == dt.Columns.Count - 1) + { + //if (dt.Rows[i][j] == DBNull.Value) continue; + if (dt.Columns[j].DataType == typeof(bool)) + { + JsonString.Append("\"JSON_" + dt.Columns[j].ColumnName.ToLower() + "\":" + + dt.Rows[i][j].ToString().ToLower()); + } + else if (dt.Columns[j].DataType == typeof(string)) + { + JsonString.Append("\"JSON_" + dt.Columns[j].ColumnName.ToLower() + "\":" + "\"" + + dt.Rows[i][j].ToString().Replace("\"", "\\\"") + "\""); + } + else + { + JsonString.Append("\"JSON_" + dt.Columns[j].ColumnName.ToLower() + "\":" + "\"" + dt.Rows[i][j] + "\""); + } + } + } + /*end Of String*/ + if (i == dt.Rows.Count - 1) + { + JsonString.Append("} "); + } + else + { + JsonString.Append("}, "); + } + } + JsonString.Append("]"); + JsonString.Append("}"); + return JsonString.ToString().Replace("\n", ""); + } + else + { + return null; + } + } + + /// + /// 获得机型 + /// + /// + private string Orderenginetypeselect() + { + string enginetypelist = ""; + try + { + System.Data.DataTable dt = null; + ShaftPosition.EngineType_Select(out dt); + if (dt != null) + { + if (dt.Rows.Count > 0) + { + enginetypelist = JsonHelper.DataTableToJson(dt); + } + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "MesWebFun_baseFun:Orderenginetypeselect"); + } + return enginetypelist; + } + + /// + /// 物料拉动_获取单号 + /// + /// + private string MaterialPush_ListNumer(string opName) + { + string listNumber = ""; + try + { + System.Data.DataTable dt = null; + MaterialPull.MaterialPush_ListNumer_Select(0, "", 1, opName, 0, "", out dt); + if (dt != null) + { + if (dt.Rows.Count > 0) + { + listNumber = JsonHelper.CreateJsonParameters(dt); + } + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "MesWebFun_baseFun:MaterialPush_ListNumer"); + } + return listNumber; + } + + /// + /// 物料拉动_根据单号获取详细信息 + /// + /// + private string MaterialPush_Details(string opname, string listNumer) + { + string listDetails = ""; + try + { + System.Data.DataTable dt = null; + //单号 + //string listNumer = HttpContext.Current.Request["listNumber"]; + MaterialPull.MaterialPush_Details_Select(listNumer, opname, out dt); + if (dt != null) + { + if (dt.Rows.Count > 0) + { + listDetails = JsonHelper.CreateJsonParameters(dt); + } + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "MesWebFun_baseFun:MaterialPush_Details"); + } + return listDetails; + } + + /// + /// 物料拉动_根据单号获取详细信息 + /// + /// + private string QualityDataButton_bgColor_Select(string opname) + { + string text = ""; + try + { + System.Data.DataTable dt = null; + //单号 + MES.QualityDataButton_bgColor_Select(opname, out dt); + if (dt != null) + { + if (dt.Rows.Count >= 0) + { + text = Buttons.Createbuttons(dt); + } + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "MesWebFun_baseFun:QualityDataButton_bgColor_Select"); + } + return text; + } + + /// + /// 消息提醒 + /// + /// + private string ShowWindowNotice(string opname) + { + string text = ""; + try + { + System.Data.DataTable dt = null; + MES.ShowWindowNotice(opname, out dt); + if (dt != null) + { + if (dt.Rows.Count > 0) + { + text = JsonHelper.DataTableToJson(dt); + } + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "MesWebFun_baseFun:ShowWindowNotice"); + } + return text; + } + + /// + /// 消息滚动 + /// + /// + private string ShowLEDNotice(string opname) + { + string text = ""; + try + { + System.Data.DataTable dt = null; + MES.ShowLEDNotice(opname, out dt); + if (dt != null) + { + if (dt.Rows.Count > 0) + { + text = JsonHelper.DataTableToJson(dt); + } + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "MesWebFun_baseFun:ShowLEDNotice"); + } + return text; + } + + /// + /// 获取生产订单 + /// + /// + private string GetOrderForm(string opname) + { + string text = ""; + try + { + System.Data.DataTable dt = null; + MES.OpName_MIS_OrderForm_Select(opname, out dt); + if (dt != null) + { + if (dt.Rows.Count > 0) + { + text = dt.Rows[0]["订单号"].ToString(); + return text; + } + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "MesWebFun_baseFun:GetOrderForm"); + } + return text; + } + + /// + /// 获取发动机型号 + /// + /// + private string GetEngineType(string opname) + { + string text = ""; + try + { + System.Data.DataTable dt = null; + MES.OpName_MIS_EngineType_Select(opname, out dt); + if (dt != null) + { + if (dt.Rows.Count > 0) + { + text = dt.Rows[0]["产品型号代码"].ToString() + "&" + dt.Rows[0]["发动机型号"].ToString(); + return text; + } + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "MesWebFun_baseFun:GetEngineType"); + } + return ("" + "&" + ""); + } + + /// + /// + /// + /// + private string ShowOpNameMessage(string opname) + { + string text = ""; + try + { + System.Data.DataTable dt = null; + BaseDataSystemMES.GetOpNameByOpName(opname, out dt); + if (dt != null) + { + if (dt.Rows.Count > 0) + { + text = dt.Rows[0]["工序名称"].ToString() + "&" + dt.Rows[0]["操作者工号"].ToString() + "&" + dt.Rows[0]["是否启用物料拉动"].ToString(); + return text; + } + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "MesWebFun_baseFun:ShowOpNameMessage"); + } + return ("" + "&" + "" + "&" + "0"); + } + + /// + /// 系统初始化时 + /// + /// + private string WebLoginIn(string opname) + { + string text = ""; + MES.WebLoginIn(opname); + return text; + } + + /// + /// 物料检测 + /// + /// + private string MaterialCheckPosition(string OpName) + { + string text = ""; + try + { + DataTable dt; + + MES.MaterialCheckSelect(OpName, out dt); + if (dt != null) + { + if (dt.Rows.Count > 0) + { + text = JsonHelper.DataTableToJson(dt); + } + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "MesWebFun_baseFun:MaterialCheckPosition"); + } + return text; + } + + /// + /// 获取对应工位的物料数据 + /// + /// + private string MaterialDataSelect(string opName, string opname) + { + string qualitydata = ""; + try + { + System.Data.DataTable dt = null; + //string opName = HttpContext.Current.Request["value"]; + //string opname = HttpContext.Current.Request["opname"]; + MES.MaterialDataSelect(opName, opname, out dt); + if (dt != null) + { + //if (dt.Rows.Count > 0) + { + qualitydata = JsonHelper.CreateJsonParameters(dt); + } + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "MesWebFun_baseFun:MaterialDataSelect"); + } + return qualitydata; + } + + /// + /// 电子看板_装配零件_查询 + /// + /// + private string MaterialSelect(string opName, string enginetypeid, string enginetype) + { + string text = ""; + try + { + System.Data.DataTable dt = null; + //string enginetypeid = HttpContext.Current.Request["enginetypeid"]; + //string enginetype = HttpContext.Current.Request["enginetype"]; + ShaftPosition.Material_Select(opName, enginetypeid, enginetype, out dt); + + if (dt != null) + { + if (dt.Rows.Count > 0) + { + text = JsonHelper.CreateJsonParameters(dt); + } + } + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, "MesWebFun_baseFun:MaterialSelect"); + } + return text; + } + + public string GetLoginOutUrl() + { + string url = System.Configuration.ConfigurationManager.AppSettings["Linklogin"].ToString(); + return url; + } + + /// + /// 手动修改批次信息 + /// + /// + private string MaterialManualUpdateBetch(string opName,string arrays, string enginetype) + { + string text = ""; + try + { + //string arrays = HttpContext.Current.Request["arrays"];//组合 + //string enginetype = HttpContext.Current.Request["enginetype"];//产品型号 + + //创建datatable + DataRow row; + DataTable dt = new DataTable(); + dt.Columns.AddRange(new DataColumn[] { + new DataColumn("零件图号"), + new DataColumn("零件批号"), + new DataColumn("生产厂家") }); + + string[] collection = arrays.Split('^');//获取 + if (collection.Length > 0) + { + for (int i = 0; i < collection.Length; i++) + { + string a = collection[i]; + string[] a_array = a.Split('&'); + if (a_array.Length > 2) + { + row = dt.NewRow(); + string materialid = a_array[0].ToString(); + string betch = a_array[1].ToString(); + string factory = a_array[2].ToString(); + row["零件图号"] = materialid; + row["零件批号"] = betch; + row["生产厂家"] = factory; + dt.Rows.Add(row); + } + } + + //修改到数据库 + if (dt != null) + { + if (dt.Rows.Count > 0) + { + MES.Material_Betch_Update(opName, enginetype, dt); + } + } + } + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, "MesWebFun_baseFun:MaterialManualUpdateBetch"); + } + return text; + } + + /// + /// 获得返修数量信息 + /// + /// + private string GetRepaireNum(string opname) + { + string text = ""; + try + { + System.Data.DataTable dt = null; + MES.OpName_MIS_RepiareNum_Select(opname, out dt); + if (dt != null) + { + if (dt.Rows.Count > 0) + { + text = dt.Rows[0]["当前数量"].ToString() + "&" + dt.Rows[0]["设置数量"].ToString(); + return text; + } + else + { + return text = "0&0"; + } + } + else + { + return text = "0&0"; + } + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, "MesWebFun_baseFun:GetEngineType"); + } + return ("" + "&" + ""); + } + + /// + /// 插入返修数量 + /// + /// + private string Insert_RepiareNum(string opnameValue, string selectValue) + { + string text = ""; + try + { + //string selectValue = HttpContext.Current.Request["CurrentNum"];//选择值 + if (selectValue == "") + { + selectValue = "0"; + } + int selectValueint = Convert.ToInt32(selectValue); + bool falg = MES.Insert_RepiareNum(opnameValue, selectValueint); + if (falg) + { + text = "{\"falg\":\"1\"}"; + } + else + { + text = "{\"falg\":\"0\"}"; + } + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, "MesWebFun_baseFun:Insert_RepiareNum"); + } + return text; + } + + /// + /// 初始化返修选择tree数据 + /// + /// + private string Init_TreeData(string opnameValue) + { + string text = ""; + try + { + System.Data.DataTable dt; + //string opnameValue = HttpContext.Current.Request["Opname"];//工位号 + MES.Init_TreeData(opnameValue, out dt); + if (dt != null) + { + if (dt.Rows.Count > 0) + { + text = JsonHelper.CreateJsonParameters(dt); + } + } + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, "MesWebFun_baseFun:Init_TreeData"); + } + return text; + } + + /// + /// 返修上线--初始化质量数据 + /// + /// + private string Quality_Select_Repair(string OpName, string EngineID) + { + string text = ""; + try + { + DataTable dt; + MES.QualitySelect(OpName, EngineID, out dt); + if (dt != null) + { + if (dt.Rows.Count > 0) + { + text = JsonHelper.CreateJsonParameters(dt); + } + } + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, "MesWebFun_baseFun:Quality_Select_Repair"); + } + return text; + } + + /// + /// 返修上线-将选择的根节点数据更新到数据库中 + /// + /// + private string Insert_selectTreeData(string opName, string engineTypeId, string selectIdsArray) + { + string text = ""; + try + { + //string engineTypeId = HttpContext.Current.Request["engineTypeId"];//产品型号代码 + //string selectIdsArray = HttpContext.Current.Request["selectId"];//选中的节点数据数据 + //创建datatable + DataRow row; + DataTable dt = new DataTable(); + dt.Columns.AddRange(new DataColumn[] { + new DataColumn("工位号"), + new DataColumn("产品型号代码"), + new DataColumn("序号") }); + string[] collection = selectIdsArray.Split(',');//获取 + if (collection.Length > 0) + { + for (int i = 0; i < collection.Length - 1; i++) + { + string idValue = collection[i]; + row = dt.NewRow(); + string opNameValue = opName; + int engineTypeIdValue = Convert.ToInt32(engineTypeId); + int selectId = Convert.ToInt32(idValue); + row["工位号"] = opNameValue; + row["产品型号代码"] = engineTypeIdValue; + row["序号"] = selectId; + dt.Rows.Add(row); + } + //修改到数据库 + if (dt != null) + { + if (dt.Rows.Count > 0) + { + MES.Insert_selectTreeData(dt); + } + } + } + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, "MesWebFun_baseFun:Insert_selectTreeData"); + } + + return text; + } + + /// + /// 质量报警_根据按钮获取详细信息 20170318 + /// + /// + private string QualityDataButton_bgColor_alert_Select(string opname) + { + string text = ""; + try + { + System.Data.DataTable dt = null; + //单号 + //string opname = HttpContext.Current.Request["value"]; + //string lineout_barcode = HttpContext.Current.Request["lineout_barcode"]; + MES.QualityDataButton_bgColor_alert_Select(opname, out dt); + if (dt != null) + { + if (dt.Rows.Count >= 0) + { + text = Buttons.Createbuttons_alert(dt); + } + } + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, "MesWebFun_baseFun:QualityDataButton_bgColor_alert_Select"); + } + return text; + } + + /// + /// 获取对应工位的物料数据_根据发动机 20170319 + /// + /// + private string MaterialDataSelect_F_EnergineID(string opname, string energineID) + { + string qualitydata = ""; + try + { + System.Data.DataTable dt = null; + //string energineID = HttpContext.Current.Request["value"]; + MES.MaterialDataSelect_F_EnergineID(opname, energineID, out dt); + if (dt != null) + { + if (dt.Rows.Count > 0) + { + qualitydata = JsonHelper.CreateJsonParameters(dt); + } + } + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, "MesWebFun_baseFun:MaterialDataSelect"); + } + return qualitydata; + } + + /// + /// 获取操作指南的PDF路径 + /// + /// + private string GetPdfSrc(string opName) + { + string PdfSrc = ""; + try + { + System.Data.DataTable dt = null; + + string orderNum = ""; + int EngineTypeID = 0; + string EngineType = ""; + string EngineID = ""; + string PartPallet_Code = ""; + int IsrepairBarcode = 0; + string repairBarcode = ""; + + MES.Moby_Select(opName, out orderNum, out EngineTypeID, out EngineType, out EngineID, out PartPallet_Code, out IsrepairBarcode, out repairBarcode); + BaseDataSystemMES.GetPdfSrc(opName, EngineTypeID.ToString(), out PdfSrc); + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, "MesWebFun_baseFun:GetPdfSrc"); + } + return PdfSrc; + } + + } +} \ No newline at end of file diff --git a/Common/08WebFun_base/WebFun_base/MisWebInterfaceFunc/Tab_OperateGuid.cs b/Common/08WebFun_base/WebFun_base/MisWebInterfaceFunc/Tab_OperateGuid.cs new file mode 100644 index 0000000..e2dcfd6 --- /dev/null +++ b/Common/08WebFun_base/WebFun_base/MisWebInterfaceFunc/Tab_OperateGuid.cs @@ -0,0 +1,232 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +//using SystemFramework; + +namespace MesWebFun_base +{ + public partial class MisWebInterface + { + + // /*该js文件用于处理"操作指南"业务逻辑处理*/ + + // bool IsShow = false; + // //是否显示绿脸_全局变量 + // bool IsShowGreenSmile = false; + // //是否显示红脸_全局变量 + // bool IsShowRedSmile = false; + // //显示绿色笑脸 + + // //显示红色笑脸 + + + // //显示绿色笑脸 + // void ShowGreenSmile_match() + // { + // $('#RedAndGreenSmile_match').attr("src", ""); + // if (IsShowGreenSmile_match == true) + // { + // $('#RedAndGreenSmile_match').attr("src", "../images/img_MatchSuccess.png"); + // $('#RedAndGreenDiv_match').css({ + // "display": "block" + // }); + // IsShowGreenSmile_match = false; + // } + // else + // { + // $('#RedAndGreenDiv_match').css({ + // "display": "none" + // }); //设置不显示 + // } + // } + // //显示红色笑脸 + // void ShowRedSmile_match() + // { + // $('#RedAndGreenSmile_match').attr("src", ""); + // if (IsShowRedSmile_match == true) + // { + // $('#RedAndGreenSmile_match').attr("src", "../images/img_MatchFail.png"); + // $('#RedAndGreenDiv_match').css({ + // "display": "block" + // }); //设置显示 + // IsShowRedSmile_match = false; + // } + // else + // { + // $('#RedAndGreenDiv_match').css({ + // "display": "none" + // }); //设置不显示 + // } + // } + + // //初始化工艺卡 + // void initoperationcard() + // { + // var cardwidth = $("#div_tab_operationcard").width(); + // var cardheight = $("#div_tab_operationcard").height(); + // $("#pdf_operationcard").media({ width: cardwidth, height: cardheight }); + // } + + // //初始化操作指南 + // void initProcessData() + // { + // var serialNumWidth = $("#div_tab_assembly_craft").width() * 0.1; + // var processWidth = $("#div_tab_assembly_craft").width() * 0.4; + // var technologyRequestWidth = $("#div_tab_assembly_craft").width() * 0.3; + // var processPropetyWidth = $("#div_tab_assembly_craft").width() * 0.2; + // $('#datagrid_processinfo').datagrid({ + // url: '', + // title: '', + // sortOrder: 'desc', //升序降序 //2017-01-03 + // idField: 'JSON_工步号', + // fit: true, + // fitColumns: true, + // rownumbers: true, + // columns: + // [[ + // { title: "序号", field: 'JSON_工步号', width: 70, align: 'left', hidden: true }, + // { title: '工序内容', field: 'JSON_操作内容', width: 264, align: 'left', resizable: false }, + // { title: '工步属性', field: 'JSON_工步属性名称', width: 180, align: 'left', resizable: false } + // ]], + // nowrap: false, + // fit: true, + // singleSelect: true, + // rowStyler: function(rowIndex, rowData) { + // if (rowIndex % 2 == 0) + // { + // return 'background-color:#D0D8E8; height:45px'; + // } + // else + // { + // return 'background-color:#E9EDF4; height:45px'; + // } + // } + // }); + // } + + + + + // //初始化物料(物料拉动模块) + // void initAssembleDataMaterrial() + // { + // var serialNumWidth = $("#div_tab_assembly_material").width() * 0.1; + // var materialNumWidth = $("#div_tab_assembly_material").width() * 0.2; + // var materialNameWidth = $("#div_tab_assembly_material").width() * 0.2; + // var demandCountWidth = $("#div_tab_assembly_material").width() * 0.1; + // var reserveCountWidth = $("#div_tab_assembly_material").width() * 0.2; + // var batchNumWidth = $("#div_tab_assembly_material").width() * 0.2; + // $('#datagridview_div_tab_distributematerrial').datagrid({ + // url: '', + // title: '', + // idField: 'JSON_标号', + // columns: + // [[ + // { title: '序号', field: 'JSON_标号', width: 60, align: 'left', hidden: true }, + // { title: '零件图号', field: 'JSON_零件图号', width: 150, align: 'left', resizable: false }, + // { title: '零件名称', field: 'JSON_零件名称', width: 150, align: 'left', resizable: false }, + // { title: '零件数量', field: 'JSON_零件数量', width: 60, align: 'left', resizable: false }, + // { title: '库存数量', field: 'JSON_库存数量', width: 60, align: 'left', hidden: false }, + // { title: '卡片条码', field: 'JSON_卡片条码', width: 150, align: 'left', hidden: false }, + // ]], + // nowrap: false, + // fit: true,fitColumns: true, + // singleSelect: true, + // rownumbers: true + // }); + // } + + //显示操作指南 + string ReceivedSignal_ProcessList(string opName) + { + + //url: '../submit/OpName.ashx?type=ProcessList&value=' + opName, + var responseStr = _MesWebFun_base.ProcessRequest("ProcessList", opName); + return responseStr; + + } + + //显示物料 + string ReceivedSignal_MaterialList(string opName) + { + // initAssembleData(); + // url: '../submit/OpName.ashx?type=MaterialList&value=' + opName, + var responseStr = _MesWebFun_base.ProcessRequest("MaterialList", opName); + return responseStr; + + } + + //显示操作图片√ + string ReceivedSignal_PictureShow(string opName) + { + //url: '../submit/OpName.ashx?type=PictureShow&value=' + opName, + var responseStr = _MesWebFun_base.ProcessRequest("PictureShow", opName); + return responseStr; + + } + + // void pdf_operationcardshowORhidden(title) + // { + // $("#div_tab_operationcard").toggle(); + // var tab = $('#div_tab').tabs('getSelected'); + // var launageType = $("#Hidden_language").val(); + // if (launageType == 1) + // { + // if (tab.title == "操作指南") + // { + // $('#div_tab').tabs('update', { + // tab: tab, + // options: + // { + // title: "工艺卡" // 新tab的title + // } + // }); + // } + // else + // { + // $('#div_tab').tabs('update', { + // tab: tab, + // options: + // { + // title: "操作指南" // 新tab的title + // } + // }); + // } + // } + // if (launageType == 2) + // { + // if (tab.title == "OperageGuid") + // { + // $('#div_tab').tabs('update', { + // tab: tab, + // options: + // { + // title: "ProcessCard" // 新tab的title + // } + // }); + // } + // else + // { + // $('#div_tab').tabs('update', { + // tab: tab, + // options: + // { + // title: "OperageGuid" // 新tab的title + // } + // }); + // } + // } + // } + + + + + + + + + + } +} diff --git a/Common/08WebFun_base/WebFun_base/MisWebInterfaceFunc/WWW - 复制 - 复制(2).cs b/Common/08WebFun_base/WebFun_base/MisWebInterfaceFunc/WWW - 复制 - 复制(2).cs new file mode 100644 index 0000000..d848117 --- /dev/null +++ b/Common/08WebFun_base/WebFun_base/MisWebInterfaceFunc/WWW - 复制 - 复制(2).cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +//using SystemFramework; + +namespace MesWebFun_base +{ + public partial class MisWebInterface + { + + + + + + + + + + + + } +} diff --git a/Common/08WebFun_base/WebFun_base/MisWebInterfaceFunc/WWW - 复制 - 复制(3).cs b/Common/08WebFun_base/WebFun_base/MisWebInterfaceFunc/WWW - 复制 - 复制(3).cs new file mode 100644 index 0000000..748cad9 --- /dev/null +++ b/Common/08WebFun_base/WebFun_base/MisWebInterfaceFunc/WWW - 复制 - 复制(3).cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +////using SystemFramework; + +namespace MesWebFun_base +{ + public partial class MisWebInterface + { + + + + + + + + + + + + } +} diff --git a/Common/08WebFun_base/WebFun_base/MisWebInterfaceFunc/WWW - 复制 - 复制(4).cs b/Common/08WebFun_base/WebFun_base/MisWebInterfaceFunc/WWW - 复制 - 复制(4).cs new file mode 100644 index 0000000..d848117 --- /dev/null +++ b/Common/08WebFun_base/WebFun_base/MisWebInterfaceFunc/WWW - 复制 - 复制(4).cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +//using SystemFramework; + +namespace MesWebFun_base +{ + public partial class MisWebInterface + { + + + + + + + + + + + + } +} diff --git a/Common/08WebFun_base/WebFun_base/MisWebInterfaceFunc/WWW - 复制 - 复制(5).cs b/Common/08WebFun_base/WebFun_base/MisWebInterfaceFunc/WWW - 复制 - 复制(5).cs new file mode 100644 index 0000000..d848117 --- /dev/null +++ b/Common/08WebFun_base/WebFun_base/MisWebInterfaceFunc/WWW - 复制 - 复制(5).cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +//using SystemFramework; + +namespace MesWebFun_base +{ + public partial class MisWebInterface + { + + + + + + + + + + + + } +} diff --git a/Common/08WebFun_base/WebFun_base/MisWebInterfaceFunc/WWW - 复制 - 复制(6).cs b/Common/08WebFun_base/WebFun_base/MisWebInterfaceFunc/WWW - 复制 - 复制(6).cs new file mode 100644 index 0000000..d848117 --- /dev/null +++ b/Common/08WebFun_base/WebFun_base/MisWebInterfaceFunc/WWW - 复制 - 复制(6).cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +//using SystemFramework; + +namespace MesWebFun_base +{ + public partial class MisWebInterface + { + + + + + + + + + + + + } +} diff --git a/Common/08WebFun_base/WebFun_base/MisWebInterfaceFunc/WWW - 复制 - 复制(7).cs b/Common/08WebFun_base/WebFun_base/MisWebInterfaceFunc/WWW - 复制 - 复制(7).cs new file mode 100644 index 0000000..d848117 --- /dev/null +++ b/Common/08WebFun_base/WebFun_base/MisWebInterfaceFunc/WWW - 复制 - 复制(7).cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +//using SystemFramework; + +namespace MesWebFun_base +{ + public partial class MisWebInterface + { + + + + + + + + + + + + } +} diff --git a/Common/08WebFun_base/WebFun_base/MisWebInterfaceFunc/WWW - 复制 - 复制(8).cs b/Common/08WebFun_base/WebFun_base/MisWebInterfaceFunc/WWW - 复制 - 复制(8).cs new file mode 100644 index 0000000..d848117 --- /dev/null +++ b/Common/08WebFun_base/WebFun_base/MisWebInterfaceFunc/WWW - 复制 - 复制(8).cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +//using SystemFramework; + +namespace MesWebFun_base +{ + public partial class MisWebInterface + { + + + + + + + + + + + + } +} diff --git a/Common/08WebFun_base/WebFun_base/MisWebInterfaceFunc/WWW - 复制 - 复制(9).cs b/Common/08WebFun_base/WebFun_base/MisWebInterfaceFunc/WWW - 复制 - 复制(9).cs new file mode 100644 index 0000000..ddde9bb --- /dev/null +++ b/Common/08WebFun_base/WebFun_base/MisWebInterfaceFunc/WWW - 复制 - 复制(9).cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +//////using SystemFramework; + +namespace MesWebFun_base +{ + public partial class MisWebInterface + { + + + + + + + + + + + + } +} diff --git a/Common/08WebFun_base/WebFun_base/MisWebInterfaceFunc/WWW - 复制 - 复制.cs b/Common/08WebFun_base/WebFun_base/MisWebInterfaceFunc/WWW - 复制 - 复制.cs new file mode 100644 index 0000000..748cad9 --- /dev/null +++ b/Common/08WebFun_base/WebFun_base/MisWebInterfaceFunc/WWW - 复制 - 复制.cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +////using SystemFramework; + +namespace MesWebFun_base +{ + public partial class MisWebInterface + { + + + + + + + + + + + + } +} diff --git a/Common/08WebFun_base/WebFun_base/MisWebInterfaceFunc/WWW - 复制.cs b/Common/08WebFun_base/WebFun_base/MisWebInterfaceFunc/WWW - 复制.cs new file mode 100644 index 0000000..d848117 --- /dev/null +++ b/Common/08WebFun_base/WebFun_base/MisWebInterfaceFunc/WWW - 复制.cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +//using SystemFramework; + +namespace MesWebFun_base +{ + public partial class MisWebInterface + { + + + + + + + + + + + + } +} diff --git a/Common/08WebFun_base/WebFun_base/MisWebInterfaceFunc/Web_Common_Barcode.cs b/Common/08WebFun_base/WebFun_base/MisWebInterfaceFunc/Web_Common_Barcode.cs new file mode 100644 index 0000000..4553b12 --- /dev/null +++ b/Common/08WebFun_base/WebFun_base/MisWebInterfaceFunc/Web_Common_Barcode.cs @@ -0,0 +1,40 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +//using SystemFramework; + +namespace MesWebFun_base +{ + public partial class MisWebInterface + { + + + + /*该js文件用于处理显示"条码"业务逻辑处理*/ + + //MES主界面_扫描条码_点击扫描条码事件 + void scanbarcodesubmit() + { + // var opName = $("#tbx_opname").val(); + // var value = $("#tbx_scanbarcode").val(); + // var sendmessage = "MSG,Barcode|" + opName + "|" + value; + // sendMessage(sendmessage); + //$.messager.show({ + // title: '提示', + // msg: '条码扫描成功!', + // timeout: 2000, + // showType: 'slide' + //}); + + } + + + + + + + + } +} diff --git a/Common/08WebFun_base/WebFun_base/MisWebInterfaceFunc/Web_Common_ShowEngineID.cs b/Common/08WebFun_base/WebFun_base/MisWebInterfaceFunc/Web_Common_ShowEngineID.cs new file mode 100644 index 0000000..448c558 --- /dev/null +++ b/Common/08WebFun_base/WebFun_base/MisWebInterfaceFunc/Web_Common_ShowEngineID.cs @@ -0,0 +1,175 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +//using SystemFramework; + +namespace MesWebFun_base +{ + public partial class MisWebInterface + { + + // /*该js文件用于处理显示"工件信息"业务逻辑处理*/ + // string isOpenMaterialPush = "0"; //是否启用物料拉动 + + // //显示托盘信息 + // void ShowPalletInfo(string m_Value) + // { + // var s_valueArrays = m_Value.Split('&'); + // if (s_valueArrays.Length > 0) + // { + // var s_palletinfo = s_valueArrays[0]; //托盘状态 + // switch (s_palletinfo) + // { + // case "0": //托盘错误 + // //$('#txt_status').val('托盘错误'); + // //$('#txt_status').css({ 'background-color': 'red' }); + // break; + // case "1": //合格 + // //$('#txt_status').val('合格'); + // //$('#txt_status').css({ 'background-color': 'green' }); + // break; + // case "2": //不合格 + // //$('#txt_status').val('不合格'); + // //$('#txt_status').css({ 'background-color': 'red' }); + // break; + // case "3": //返修 + // //$('#txt_status').val('返修'); + // //$('#txt_status').css({ 'background-color': 'yellow' }); + // break; + // case "4": //空托盘 + // //$('#txt_status').val('空托盘'); + // //$('#txt_status').css({ 'background-color': 'white' }); + // break; + // default: + // //$('#txt_status').val('系统错误'); + // //$('#txt_status').css({ 'background-color': 'red' }); + // break; + // } + // } + // } + + // //显示分线托盘信息 + // void ShowPalletInfo_Subline(m_Value) + // { //2017-1-3 + // var s_valueArrays = m_Value.split('&'); + // if (s_valueArrays.length > 0) + // { + // var s_palletinfo = s_valueArrays[0]; //托盘状态 + // switch (s_palletinfo) + // { + // case "0": //托盘错误 + // $('#txt_status_subline').val('托盘错误'); + // $('#txt_status_subline').css({ 'background-color': 'red' }); + // document.getElementById("img_ForceMatch_SubLine").src = "../images/red.png"; + // break; + // case "1": //合格 + // $('#txt_status_subline').val('合格'); + // $('#txt_status_subline').css({ 'background-color': 'green' }); + // document.getElementById("img_ForceMatch_SubLine").src = "../images/green.png"; + // break; + // case "2": //不合格 + // $('#txt_status_subline').val('不合格'); + // $('#txt_status_subline').css({ 'background-color': 'red' }); + // document.getElementById("img_ForceMatch_SubLine").src = "../images/red.png"; + // break; + // case "3": //返修 + // $('#txt_status_subline').val('返修'); + // $('#txt_status_subline').css({ 'background-color': 'yellow' }); + // document.getElementById("img_ForceMatch_SubLine").src = "../images/green.png"; + // break; + // case "4": //空托盘 + // $('#txt_status_subline').val('空托盘'); + // $('#txt_status_subline').css({ 'background-color': 'white' }); + // document.getElementById("img_ForceMatch_SubLine").src = "../images/red.png"; + // break; + // default: + // $('#txt_status_subline').val('系统错误'); + // $('#txt_status_subline').css({ 'background-color': 'red' }); + // document.getElementById("img_ForceMatch_SubLine").src = "../images/red.png"; + // break; + // } + // } + // } + + //显示托盘信息√ + string ReceivedSignal_MobySelect(string opName) + { + //url: '../submit/OpName.ashx?type=MobySelect&value=' + opName + '', + var responseStr = _MesWebFun_base.ProcessRequest("MobySelect", opName); + return responseStr; + } + + // //初始化时,显示当前工位、工件信息 + // void Init_ReceivedSignal_MobySelect() + // { + // var opName = $("#tbx_opname").val(); + // $.ajax({ + // type: "POST", + // url: '../submit/OpName.ashx?type=ShowOpNameMessage&value=' + opName + '', + // success: function(data) { + // if (data != "" && data != null) + // { + // var dataArrays = data.split('&'); //返回多参数,拆分 + // var craftname = dataArrays[0]; //工序名称 + // var operator = dataArrays[1]; //操作者工号 + // isOpenMaterialPush = dataArrays[2]; //是否启动物料拉动 + // $("#tbx_opnamediscription").val(craftname); + // $("#tbt_operator").val(operator); + // } + // } + // }); + // ReceivedSignal_MobySelect();//显示工件信息 + // } + // //显示分线托盘信息√ + // void ReceivedSignal_MobySelect_Subline(m_Value) + // { + // var opName = m_Value; + // $.ajax({ + // type: "POST", + // url: '../submit/OpName.ashx?type=MobySelect&value=' + opName + '', + // success: function(data) { + // if (data != "" && data != null) + // { + // var dataArrays = data.split('&'); //返回多参数,拆分 + // var orderNum = dataArrays[0]; + // var EngineTypeID = dataArrays[1]; + // var EngineType = dataArrays[2]; + // var EngineID = dataArrays[3]; + // var PartPallet_Code = dataArrays[4]; + // var IsrepairBarcode = dataArrays[5]; + // var repairBarcode = dataArrays[6]; + // $("#txt_enginetype_subline").val(EngineType); + // $("#txt_num_subline").val(EngineID); + // $("#txt_num_subline_Pallet").val(PartPallet_Code); + // } + // } + // }) + //} + + + + + + + + + + + + + + + + + + + + + + + + + } +} diff --git a/Common/08WebFun_base/WebFun_base/MisWebInterfaceFunc/Web_Common_ShowQuality.cs b/Common/08WebFun_base/WebFun_base/MisWebInterfaceFunc/Web_Common_ShowQuality.cs new file mode 100644 index 0000000..fac43b6 --- /dev/null +++ b/Common/08WebFun_base/WebFun_base/MisWebInterfaceFunc/Web_Common_ShowQuality.cs @@ -0,0 +1,65 @@ +//using System; +//using System.Collections.Generic; +//using System.Linq; +//using System.Text; +//using System.Threading.Tasks; +//using SystemFramework; + +//namespace MesWebFun_base +//{ +// public partial class MisWebInterface +// { + +// /*该js文件用于处理显示"质量数据"业务逻辑处理*/ + + +// //初始化质量状态数据--主界面 +// void initQualityData() +// { +// var opName = $("#tbx_opname").val(); +// var serialnumWidth = $("#div_quality").width() * 0.2; +// var twistWidth = $("#div_quality").width() * 0.37; +// var cornerWidth = $("#div_quality").width() * 0.37; +// datagrid_Quality = $('#datagrid_quality').datagrid({ +// url: '', +// title: '', +// sortName: '', //按哪个字段排序,将把这个提交给服务器 +// sortOrder: 'desc', //升序降序 +// idField: '', +// //columns: [[ +// // { title: "名称", field: 'JSON_名称', width: 60, align: 'center' }, +// // { title: '项目1', field: 'JSON_测量项目1', width: 50, align: 'center' }, +// // { title: '项目2', field: 'JSON_测量项目2', width: 50, align: 'center' }, +// // { title: '合格标志', field: 'JSON_合格标志', align: 'center', hidden: true } +// // ]], +// nowrap: false, +// fit: true,fitColumns: true, +// singleSelect: true, +// rowStyler: function(index, row) { +// if (row.JSON_合格标志 == "1") +// { +// return 'background-color:green'; +// } +// else +// { + +// return 'background-color:red'; +// } +// } +// }); +// } + + + + + + + + + + + + + +// } +//} diff --git a/Common/08WebFun_base/WebFun_base/MisWebInterfaceFunc/Web_Common_ShowTime.cs b/Common/08WebFun_base/WebFun_base/MisWebInterfaceFunc/Web_Common_ShowTime.cs new file mode 100644 index 0000000..3c952d4 --- /dev/null +++ b/Common/08WebFun_base/WebFun_base/MisWebInterfaceFunc/Web_Common_ShowTime.cs @@ -0,0 +1,187 @@ +//using System; +//using System.Collections.Generic; +//using System.Linq; +//using System.Text; +//using System.Threading.Tasks; +//using SystemFramework; + +//namespace MesWebFun_base +//{ +// public partial class MisWebInterface +// { + + + +// /*该js文件用于处理显示"当前时间"业务逻辑处理*/ + +// //js实时显示日期 +// void showtime_data() +// { +// var today, hour, second, minute, year, month, date; +// var strDate; +// today = new Date(); +// var n_day = today.getDay(); +// switch (n_day) +// { +// case 0: +// { +// strDate = "星期日" +// } +// break; +// case 1: +// { +// strDate = "星期一" +// } +// break; +// case 2: +// { +// strDate = "星期二" +// } +// break; +// case 3: +// { +// strDate = "星期三" +// } +// break; +// case 4: +// { +// strDate = "星期四" +// } +// break; +// case 5: +// { +// strDate = "星期五" +// } +// break; +// case 6: +// { +// strDate = "星期六" +// } +// break; +// case 7: +// { +// strDate = "星期日" +// } +// break; +// } +// year = today.getFullYear(); +// month = today.getMonth() + 1; +// date = today.getDate(); +// hour = today.getHours(); +// minute = today.getMinutes(); +// second = today.getSeconds(); + +// if (month < 10) +// { +// month_New = "0" + month; +// } +// else +// { +// month_New = month; +// } + +// if (date < 10) +// { +// date_New = "0" + date; +// } +// else +// { +// date_New = date; +// } +// document.getElementById('time').innerHTML = year + "-" + month_New + "-" + date_New; //显示时间 +// setTimeout("showtime_data();", 1000000); //设定函数自动执行时间为 1000 ms(1 s) +// } + +// //实时显示时间 +// void showtime_time() +// { +// var today, hour, second, minute, year, month, date; +// var strDate; +// today = new Date(); +// var n_day = today.getDay(); +// switch (n_day) +// { +// case 0: +// { +// strDate = "星期日" +// } +// break; +// case 1: +// { +// strDate = "星期一" +// } +// break; +// case 2: +// { +// strDate = "星期二" +// } +// break; +// case 3: +// { +// strDate = "星期三" +// } +// break; +// case 4: +// { +// strDate = "星期四" +// } +// break; +// case 5: +// { +// strDate = "星期五" +// } +// break; +// case 6: +// { +// strDate = "星期六" +// } +// break; +// case 7: +// { +// strDate = "星期日" +// } +// break; +// } +// year = today.getFullYear(); +// month = today.getMonth() + 1; +// date = today.getDate(); +// hour = today.getHours(); +// if (hour < 10) +// { +// hour_New = "0" + hour; +// } +// else +// { +// hour_New = hour; +// } +// minute = today.getMinutes(); +// if (minute < 10) +// { +// minute_New = "0" + minute; +// } +// else +// { +// minute_New = minute; +// } +// second = today.getSeconds(); +// if (second < 10) +// { +// second_New = "0" + second; +// } +// else +// { +// second_New = second; +// } +// document.getElementById('Span_time').innerHTML = hour_New + ":" + minute_New + ":" + second_New + "  " + strDate; ; //显示时间 +// setTimeout("showtime_time();", 1000); //设定函数自动执行时间为 1000 ms(1 s) +// } + + + + + + + + +// } +//} diff --git a/Common/08WebFun_base/WebFun_base/MisWebInterfaceFunc/Web_FixGuiad.cs b/Common/08WebFun_base/WebFun_base/MisWebInterfaceFunc/Web_FixGuiad.cs new file mode 100644 index 0000000..682366f --- /dev/null +++ b/Common/08WebFun_base/WebFun_base/MisWebInterfaceFunc/Web_FixGuiad.cs @@ -0,0 +1,327 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +//using SystemFramework; + +namespace MesWebFun_base +{ + public partial class MisWebInterface + { + + // /*该js文件用于处理"详细具体指导(拧紧、检测、称重等业务指导)"业务逻辑处理*/ + + // ////////////////////////////////////////////////////////4 + + // var jsonArrayStatic; //全局json + // var CircleDivList; //全局记录包含image的div + // var CircleDivListCount = 0; + // var CircleImageList; //全局记录全部的拧紧或者压装小圆圈图片 + // var CircleImageListCount = 0; + + + //动态创建拧紧指导div + string InitShowGuidCircle(string opName) + { + // url: '../submit/OpName.ashx?type=ShaftPosition&value=' + opName, + var responseStr = _MesWebFun_base.ProcessRequest("ShaftPosition", opName); + return responseStr; + } + // //创建div + // void SetUpCircleDiv(data) + // { + // CircleDivList = { }; + // CircleImageList = { }; + // CircleImageListCount = 0; + // CircleImageListCount = 0; + + // var CircleImage = "
"; //默认 + // var CricleColor = "ni_png_0910"; //默认 + // var CricleColor_1 = "ni_png_0910"; //拧紧类型 + // var CricleColor_2 = "bluerectangle"; //其它类型 + // var height = $(window).height(); + // var width = $(window).width(); + // if (data != "" && data != null) + // { + + // for (var i = 0; i < data.length; i++) + // { + // var divImgWidth = $("#div_tab_assembly_craft_main").width(); + // var CircleDivID = "CircleDivID" + i; + // var CircleImageID = "CircleImageID" + i; + // var CircleLabelID = "CircleLabelID" + i; + // var LocationX_data = (data[i].测量位置X / 1000) * width; + // //var LocationX = divImgWidth + LocationX_data + 8; + // var LocationX = divImgWidth + LocationX_data; + // //var LocationY = data[i].测量位置Y + 115; + // var LocationY = (data[i].测量位置Y / 760) * height; + // var contrlosWidth = data[i].控件宽度; + // var contrlosHeight = data[i].控件高度; + // var instruction = data[i].说明; + // var controlcode = data[i].控件类型; + // var isrepaire = data[i].是否返修; + + // var number = data[i].序号; + + // if (controlcode == "1") + // {//其它类型 + // CricleColor = CricleColor_1; + // } + + // else + // {//其它类型 + // CricleColor = CricleColor_2; + // } + + // switch (data[i].拧紧完成) + // { + // case 1: + // CricleColor = "green"; + // break; + // default: + // CricleColor = "ni_png_0910"; + // break; + + // } + + // //普通拧紧 + // if (isrepaire == 0) + // { + + // if (controlcode == "1") + // {//拧紧类型 + // CircleImage = "
" + // + "" + // + "
" + // } + + // else + // {//其它类型 + // CircleImage = "
" + // + "" + instruction + "" + // + "" + // + "
" + // } + // } + // //返修拧紧 + // else + // { + // if (data[i].拧紧完成 == "2") + // { + // CricleColor = "red"; + // } + + // if (controlcode == "1") + // {//拧紧类型 + // CircleImage = "
" + // + "" + // + "
" + // } + + // } + + + // $('#div_tab_assembly_craft').append(CircleImage); + // $('#' + CircleDivID).css( + // { + // "top": LocationY + "px", + // "left": LocationX + "px", + // "z-index": "4", + // "width": contrlosWidth, + // "height": contrlosHeight, + // "position": "absolute" + // }); + + // $('#' + CircleImageID).css( + // { + // "width": contrlosWidth, + // "height": contrlosHeight + // } + // ); + + // if (controlcode != "1") + // {//其它类型 + // $('#' + CircleLabelID).css( + // { + // "top": 7 + "px", + // "left": 17 + "px", + // "z-index": "4", + // "position": "absolute" + // } + // ); + // } + + // CircleDivList[i] = CircleDivID; + // CircleImageList[number] = CircleImageID; //改过[i] + // CircleDivListCount++; + // CircleImageListCount++; + // } + // } + // } + + // //移除控件 + // void ClearCircle() + // { + // //console.info(CircleDivListCount); + // if (CircleDivListCount > 0) + // { + // for (var i = CircleDivListCount - 1; i >= 0; i--) + // { + // var id = CircleDivList[i]; + // $('#' + id).remove(); + // } + // } + // } + + // //获取第一次拧紧的组号和套筒号 + // void GetFirstGroupNumAndBoltCode(data) + // { + // var groupindex = 0; + // var boltcode = 0; + // var isfinish = 0; //拧紧完成 + + // var isOK = 0;//是否存在未拧紧轴 + // if (data != "" && data != null) + // { + // for (var j = 0; j < data.length; j++) + // { + // if (data[j].拧紧完成 == 0) + // { + // isOK = 1; + // } + // } + + + // for (var i = 0; i < data.length; i++) + // { + // isfinish = data[i].拧紧完成; + // groupindex = data[i].组号; + // boltcode = data[i].套筒号; + + // if (isOK == 1) + // { + // if (isfinish == 0) + // { + // return groupindex; + // } + // } + // else + // { + // if (isfinish == 2) + // { + // return groupindex; + // } + // } + // } + // } + // } + + // //根据序列号,显示对应的状态(status为0表示不合格,status为1为合格,status为2为还未开始,status为4为开始拧紧) + // void ShowStep(GroupNum, status, jsonArray) + // { + + // //先判断是否还有未完成拧紧或者的位置 + // var imageid; + // var imagesrc; + // var Num; + // var ReadGroupNum; + // var boltCode; //套筒号 + // var controlcode; //控件类型 + + // // ShowAndHideFixAgainButton(false); //默认隐藏 + // if (CircleImageListCount > 0) + // { + // for (var i = 0; i < jsonArray.length; i++) + // { + // ReadGroupNum = jsonArray[i].组号; + // if (GroupNum == ReadGroupNum) + // { + // Num = jsonArray[i].序号; + // controlcode = jsonArray[i].控件类型; + // imageid = CircleImageList[Num]; //改过-1 + + + // if (status == 0) + // { + // if (controlcode == "1") + // { + // imagesrc = "../images/red.png"; + // } + // else + // { + // imagesrc = "../images/redrectangle.png"; + // //清空套筒号 + // ClearBoltCode(); + // } + // } + // if (status == 1) + // { + // if (controlcode == "1") + // { + // imagesrc = "../images/green.png"; + // } + // else + // { + // imagesrc = "../images/greenrectangle.png"; + // //清空套筒号 + // ClearBoltCode(); + // } + // //开始拧紧下一个 + // } + // if (status == 2) + // { + // if (controlcode == "1") + // { + // imagesrc = "../images/ni_png_0910.png"; + // } + // else + // { + // imagesrc = "../images/bluerectangle.png"; + // //清空套筒号 + // ClearBoltCode(); + // } + // } + // if (status == 4) + // { + // if (controlcode == "1") + // { + // imagesrc = "../images/StartWorkCircle.gif"; + // } + // else + // { + // imagesrc = "../images/blinkrectangle.gif"; + // //清空套筒号 + // ClearBoltCode(); + // } + // } + + + // $('#' + imageid).attr("src", imagesrc); + // } + // } + // } + // } + + + + + + + + + } +} diff --git a/Common/08WebFun_base/WebFun_base/MisWebInterfaceFunc/Web_Init.cs b/Common/08WebFun_base/WebFun_base/MisWebInterfaceFunc/Web_Init.cs new file mode 100644 index 0000000..2309ad7 --- /dev/null +++ b/Common/08WebFun_base/WebFun_base/MisWebInterfaceFunc/Web_Init.cs @@ -0,0 +1,816 @@ +//using System; +//using System.Collections.Generic; +//using System.Linq; +//using System.Text; +//using System.Threading.Tasks; +//using SystemFramework; + +//namespace MesWebFun_base +//{ +// public partial class MisWebInterface +// { + + +// /*该js文件用于处理"页面初始化"业务逻辑处理*/ + +// //记录TabSelect时的Tab顺序 +// var Tab_Index = '操作指南'; +// //记录操作指南区域的先后顺序:1显示操作指南,0显示工艺卡 +// var Index = 1; +// var btnconfig = +// { +// btn: { +// close:' 重新工作', +// comfrie:' 继续工作' +// } +// } +//var dditConfig = { +// btn: { +// close:' 重新工作', +// comfrie:' 继续工作' +// }, +// hintLayer: { +// icon: 7, +// title: ["涂胶-拧紧超时报警","background-color:#4476A7"], +// area: ['600px', '320px'], +// skin: 'layui-layer-molv', +// offset: '240px', +// btn: [btnconfig.btn.comfrie, btnconfig.btn.close] +// }, +// hintLayer1: { +// icon: 1, +// area: ['360px', '250px'], +// title: "提示信息", +// skin: 'layerStyle', +// offset: '350px', +// btn: ["确定登录", "取消登录"] +//} +//} +////初始化MES界面 +//void loadingMes() +//{ +// var opName = $("#tbx_opname").val(); +// //初始化Mes界面_更新上面的数据 +// loadingMesData(); +// $.ajax({ +// url: '../submit/OpName.ashx?type=MesloadingSelect&value=' + opName, +// data: +// { +// mainModule: 1, //主模块代码 +// MesWebCode: 2//页面代码 +// }, +// dataType: 'json', +// success: function(data) { +// if (data != null && data != "") +// { +// for (i = 0; i < data.length; i++) +// { +// switch (data[i].标签属性) +// { +// case "lbl": +// { +// updataLbl(data[i]); +// } +// break; +// case "tab": +// { +// updataTab(data[i]); +// } +// break; +// case "btn": +// { +// updataBtn(data[i]); +// } +// break; +// } +// } +// } +// else +// { +// return; +// } +// } +// }) +// //更新lbl +// void updataLbl(data) +//{ +// try +// { +// var key = data.标签ID; +// var value = data.标签文字; +// $('#' + key).text(value); +// } +// catch (Error) +// { +// } +//} +////更新btn +//void updataBtn(data) +//{ +// var key = data.标签ID; +// var value = data.标签文字; +// $('#' + key).val(value); +//} +////更新tab +//void updataTab(data) +//{ +// //第一步取到tab的控件 +// var tab_key = data.所属父级ID; +// var launageType = data.语言编号; +// $("#Hidden_language").val(launageType); +// var value = data.模块描述; +// //console.info(value); +// var tab_index = data.模块编号; + +// if (data.是否禁用 == 0 && data.是否禁用 != undefined) +// { +// var tab_child = $('#' + tab_key).tabs('getTab', value); +// if (tab_child != null) +// { +// $('#' + tab_key).tabs('update', { +// tab: tab_child, +// options: +// { +// title: value // 新tab的title +// } +// }); +// } +// } else +//{ +// $('#' + tab_key).tabs('close', value); +// $('#' + tab_key).tabs('select', 0); +//} +// } +//} +////初始化Mes界面_更新上面的input +//void loadingMesData() +//{ +//} + +////打开功能按钮对话框 +//void OpenPanel() +//{ +// $("#div_btnfunction_main").toggle(); +//} + +////根据对象以及百分比获取实际absolutely长度大小 +//void FixWidth(sender, percent) +//{ +// alert('0'); +// return $('#' + sender).width() * percent; +//} + +////获取html页面参数 +//void getvalue(name) +//{ +// var str = window.location.search; +// if (str.indexOf(name) != -1) +// { +// var pos_start = str.indexOf(name) + name.length + 1; +// var pos_end = str.indexOf("&", pos_start); +// if (pos_end == -1) +// { +// return str.substring(pos_start); +// } +// else +// { +// return str.substring(pos_start, pos_end) +// } +// } +// else +// { +// return "没有这个name值"; +// } +//} + +////初始化工步属性 +//void IniStepProperty() +//{ +// var opName = $("#tbx_opname").val(); +// $.ajax({ +// type: "POST", +// url: '../submit/OpName.ashx?type=StepProperty&value=' + opName + '', +// success: function(data) { +// if (data != null && data != "") +// { +// var stepProperty = data.toString(); +// $("#Hidden_stepProperty").val(stepProperty); +// } +// } +// }) +//} + +////在线,离线,启用点击事件 +//void show_Pannel_status1() +//{ +// $('#combobox_btnfunction_status').combobox('showPanel'); +//} +////功能按钮-从数据库中初始化在线/离线/屏蔽的combobox +//void initOnlineOutlineCombobox() +//{ +// var opName = $("#tbx_opname").val(); +// $.ajax({ +// type: "POST", +// url: "../submit/OpName.ashx?type=Init_OnlineOutline", +// data: +// { +// opnameValue: opName +// }, +// dataType: 'json', +// success: function(data) { +// if (data != null && data != "") +// { +// if (data.value == "2") +// { +// $("#btn_function").css("background-color", "red"); +// $("#combobox_btnfunction_status").combobox("setValue", "2"); +// } +// else +// { +// $("#btn_function").css("background-color", "green"); +// $("#combobox_btnfunction_status").combobox("setValue", "0"); +// } +// } +// } +// }); +//} +////初始化combox--功能按钮 +//void initCombobox() +//{ +// var opName = $("#tbx_opname").val(); +// var headwidth = $("#div_btnfunction_status").width(); +// var headheight = $("#div_btnfunction_status").height(); +// $("#combobox_btnfunction_status").combobox({ +// width: 130, +// height: 35, +// //panelHeight: headheight, +// panelHeight: 80, +// valueField: "id", +// textField: "line", +// value: "在线", +// data: +// [{ +// id: "0", +// line: "在线" +// }, { +// id: "2", +// line: "屏蔽" +// }], +// editable: false, +// onSelect: function(record) { +// var opName = $("#tbx_opname").val(); +// var text = $("#combobox_btnfunction_status").combobox("getText"); +// var value = $("#combobox_btnfunction_status").combobox("getValue"); +// if (value == 2) +// { +// $("#btn_function").css("background-color", "red"); +// } +// else +// { +// $("#btn_function").css("background-color", "green"); +// } +// //插入到数据库 +// $.ajax({ +// type: "POST", +// url: "../submit/OpName.ashx?type=Insert_OnlineOutline", +// data: +// { +// opnameValue: opName, +// selectValue: value +// }, +// dataType: 'json', +// success: function(data) { +// if (data != null && data != "") +// { +// if (data.falg == "1") +// { +// //发送信号 +// var sendmessage = "MSG,OnLineState|" + opName + "|" + value; +// sendMessage(sendmessage); +// } +// else +// { +// } +// } +// } +// }); +// } +// }); +//} //初始化tab + +//var slectTabFlag = 1; + +////初始化tab +//void initTab() +//{ +// var meswidth = $("#div_mes_main").width(); +// var timewidth = $("#div_time_main").width(); +// // var tabWidth = (meswidth - timewidth) * 0.975; +// var tabWidth = (meswidth - timewidth) * 0.83; +// var tabHeight = $("#div_time_main").height(); +// $('#div_tab').tabs({ +// border: false, +// tabWidth: tabWidth / 6, +// tabHeight: tabHeight, +// onSelect: function(title, index) { +// switch (title) +// { +// case '操作指南': +// SettingIndex(title); +// initProcessData(); +// initAssembleData(); +// ShowCraft(); +// break; +// case '工艺卡': +// SettingIndex(title); +// ShowCraft(); +// break; +// case '订单完工': +// SettingIndex(title); +// initOrderInfoData(); +// ReloadOrderInfoData(); +// break; +// case '物料拉动': +// SettingIndex(title); +// initOrderInfoData(); +// ReloadOrderInfoData(); +// break; +// case '质量查询': +// SettingIndex(title); +// IniQualityButtons_bgColor(); +// initStationdata(); +// repairMark = 0; +// break; +// case '设备管理': +// SettingIndex(title); +// initMaintainInfodata(); +// var tab = $('#div_tab').tabs('getSelected'); +// tab.panel('refresh'); +// break; +// case 'ANDON': +// SettingIndex(title); +// ///测试 +// init_Combobox_ando_call(); +// init_combobox_ando_reset(); +// InitMaterailAndo(); +// //alert($("#tbx_opname").val()); +// $('#div_andon_table_material').css({ +// "left": "0px" +// }); +////初始化物料ando弹出的div +//Init_ando_popup(); +////初始化质量ando弹出的div +//Init_ando_quality_popup(); +////初始化设备ando弹出的div +//Init_ando_machine_popup(); +//break; +// case '返修管理': +// SettingIndex(title); +//initStationdataRepair(); +//IniQualityButtons_bgColorRepair(); +//repairMark = 1; +//break; +// } +// } +// }); +//} + +////点击Tab设置Index +//void SettingIndex(index) +//{ +// switch (index) +// { +// case '操作指南': //操作指南 +// if (Tab_Index != '操作指南') +// { +// Index = 0; +// Tab_Index = '操作指南'; +// return; +// } +// else +// { +// if (Index == 1) +// { +// Index = 0; +// return; +// } +// if (Index == 0) +// { +// Index = 1; +// return; +// } +// } +// break; +// case '工艺卡': //工艺卡 +// if (Tab_Index != '工艺卡') +// { +// Index = 0; +// Tab_Index = '操作指南'; +// return; +// } +// else +// { +// if (Index == 1) +// { +// Index = 0; +// return; +// } +// if (Index == 0) +// { +// Index = 1; +// return; +// } +// } +// break; +// case '订单完工': //订单完工 +// Tab_Index = index; +// Index = 0; +// return; +// break; +// case '物料拉动': //物料拉动 +// Tab_Index = index; +// Index = 0; +// return; +// break; +// case '质量查询': //质量查询 +// Tab_Index = index; +// Index = 0; +// return; +// break; +// case '设备管理': //设备管理 +// Tab_Index = index; +// Index = 0; +// return; +// break; +// case 'ANDON': //Andon +// Tab_Index = index; +// Index = 0; +// return; +// break; +// case '返修管理': //返修管理 +// Tab_Index = index; +// Index = 0; +// return; +// break; +// default: +// Tab_Index = 0; +// Index = 0; +// return; +// break; +// } +//} + +////显示工序卡和操作指南头 +//void ShowCraft() +//{ +// if (Index == 0) +// { +// var tab = $('#div_tab').tabs('getSelected'); +// var launageType = $("#Hidden_language").val(); +// if (launageType == 1) +// { +// $('#div_tab').tabs('update', { +// tab: tab, +// options: +// { +// title: "操作指南" // 新tab的title +// } +// }); +// } +// if (launageType == 2) +//{ +// $('#div_tab').tabs('update', { +// tab: tab, +// options: +// { +// title: "OperageGuid" // 新tab的title +// } +// }); +//} +// $("#div_tab_operationcard").css({ +// "display": "none" +// }); +// } +// else +//{ +// //20170331 CORBIN +// var opName = $('#tbx_opname').val(); + +// $.ajax({ +// type: "POST", +// url: '../submit/OpName.ashx?type=GetPdfSrc&value=' + opName, +// success: function(data) { +// if (data != "" || data == null) +// { +// if (document.getElementById('pdf_operationcard') != null) +// { +// $('#pdf_operationcard').attr("src", data); +// initoperationcard(); +// } +// } +// else +// { +// $('#pdf_operationcard').attr("src", "../pdf/确认是否上传PDF.pdf"); +// initoperationcard(); +// } +// } +// }) + +// //20170331 CORBIN + +// $("#div_tab_operationcard").css({ +// "display": "block" +// }); +// var tab = $('#div_tab').tabs('getSelected'); +// var launageType = $("#Hidden_language").val(); +// if (launageType == 1) +// { +// $('#div_tab').tabs('update', { +// tab: tab, +// options: +// { +// title: "工艺卡" // 新tab的title +// } +// }); +// } +// if (launageType == 2) +// { +// $('#div_tab').tabs('update', { +// tab: tab, +// options: +// { +// title: "ProcessCard" // 新tab的title +// } +// }); +// } +//} +//} + +////测试虚拟键盘 +//void test_tbx_scanbarcode() +//{ +// VirtualKeyboard.toggle('', 'softkey'); +// $("#kb_langselector,#kb_mappingselector,#copyrights").css("display", "none"); +//} + +////工位刚登入时,将一些信息复位掉 +//void Web_Login() +//{ +// var opName = $("#tbx_opname").val(); +// $.ajax({ +// type: "POST", +// url: '../submit/OpName.ashx?type=WebLoginIn&value=' + opName + '', +// success: function(data) { +// if (data != null && data != "") +// { +// } +// } +// }); +////初始化界面 +////显示操作指南 ph- 2014年11月18日 +//ReceivedSignal_ProcessList(); //显示操作指南 +//ReceivedSignal_MaterialList(); //显示物料 +//ReceivedSignal_PictureShow(); //显示操作图片 +//ShowLEDNotice(); //初始化LED +//} + +//void InitMaterialLeave_dialog() +//{ +// //open方法 +// layer.open({ +// icon: 7, +// closeBtn: 1, +// skin: 'layui-layer-lan', +// area:['600px', '350px'], +// content: $("#MaterialLeave_dialog").html(), +// btn:["确定" ], +// yes: function(index, layero) { +// layer.close(index); +// } +// }); +//} +////质量门 +//void MaterailQuality_dialoga() +//{ +// //open方法 +// layer.open({ +// icon: 7, +// closeBtn: 1, +// skin: 'layui-layer-lan', +// area:['600px', '350px'], +// content: $("#MaterailQuality_dialog").html(), +// btn:["确定"], +// yes: function(index, layero) { +// layer.close(index); +// } +// }); +//} +////涂胶延时提醒 +//void InitdelayTime_dialog() +//{ +// //open方法 +// layer.open({ +// icon: 7, +// title:["延时提醒提示"], +// closeBtn: 1, +// skin: 'layui-layer-lan', +// area:['600px', '350px'], +// content: $("#delayTime_dialog").html(), +// btn:["继续工作", "重新工作", ], +// yes: function(index, layero) { +// var opName = $("#tbx_opname").val(); +// var sendmessage = "MSG,ContinueFixAllow|" + opName + "|1"; +// sendMessage(sendmessage); +// layer.close(index); +// }, +// btn2: function(index, layero) { +// layer.close(index); +// }, +// }); +//} +////打印条码提醒 +//void InitPrintConfirm_dialog() +//{ +// $('#PrintConfirm_dialog').dialog({ +// title: '打印条码扫描验证错误', +// width: 600, +// height: 270, +// modal: true, +// closed: true, +// buttons: +// [{ +// text: '继续工作', +// iconCls: 'icon-ok', +// handler: function() { +// var opName = $("#tbx_opname").val(); +// var sendmessage = "MSG,PrinterrorAlter|" + opName + "|1"; +// sendMessage(sendmessage); +// $('#PrintConfirm_dialog').dialog('close'); +// } +// }, { +// text: '重新工作', +// iconCls: 'icon-cancel', +// handler: function() { +// $('#PrintConfirm_dialog').dialog('close'); +// } +// }] +// }); +//} +////OP2150涂胶延时提醒 +//void InitTightdelayTime_dialog() +//{ +// //open方法 +// layer.open({ +// icon: 7, +// title:["涂胶延时提醒"], +// closeBtn: 1, +// skin: 'layui-layer-lan', +// area:['600px', '350px'], +// content: $("#tightTime_dialog").html(), +// btn:["继续工作", "重新工作",], +// yes: function(index, layero) { +// var opName = $("#tbx_opname").val(); +// var sendmessage = "MSG,ContinueFixAllow|" + opName + "|1"; +// sendMessage(sendmessage); +// layer.close(index); +// }, +// btn2: function(index, layero) { +// layer.close(index); +// }, +// }); +//} +////涂胶时间不足提醒 +//void InitNotenough_dialog() +//{ +// //open方法 +// layer.open({ +// icon: 7, +// title:["涂胶-测试台架时间不足"], +// closeBtn: 1, +// skin: 'layui-layer-lan', +// area:['600px', '350px'], +// content: $("#Notenough_dialog").html(), +// btn:["继续工作", "重新工作", ], +// yes: function(index, layero) { +// var opName = $("#tbx_opname").val(); +// var sendmessage = "MSG,ContinueFixAllow|" + opName + "|1"; +// sendMessage(sendmessage); +// layer.close(index); +// }, +// btn2: function(index, layero) { +// layer.close(index); +// }, +// }); +//} +////OP4150打标重复报警 +//void InitMarking_dialog() +//{ +// //open方法 +// layer.open({ +// icon: 7, +// title:["打标工件编号重复"], +// closeBtn: 1, +// skin: 'layui-layer-lan', +// area:['600px', '350px'], +// content: $("#Marking_dialog").html(), +// btn:["继续工作", "重新工作", ], +// yes: function(index, layero) { +// var opName = $("#tbx_opname").val(); +// var sendmessage = "MSG,ContinueFixAllow|" + opName + "|1"; +// sendMessage(sendmessage); +// layer.close(index); +// }, +// btn2: function(index, layero) { +// layer.close(index); +// }, +// }); +//} +////二维码零件未扫描 +//void InitNoScan_dialog() +//{ +// $('#NoScanMats_dialog').dialog({ +// title: '物料未扫描完全', +// width: 600, +// height: 270, +// modal: true, +// closed: true, +// buttons: +// [{ +// text: '确定', +// iconCls: 'icon-ok', +// handler: function() { +// $('#NoScanMats_dialog').dialog('close'); +// } +// }] +// }); +//} +////删除排队 +//void button_Orderdele() +//{ +// var opName = $("#tbx_opname").val(); +// var orderengine_num = $("#txt_orderengine_num").val(); +// $.ajax({ +// type: 'post', +// url: '../submit/OpName.ashx?type=OrderlistDelete&value=' + opName + '&orderengine_num=' + orderengine_num, +// dataType: 'json', +// success: function(data) { +// $("#txt_orderengine_num").val(''); +// } +// }); +//sendMessage(sendmessage); +// $.messager.show({ +//title: '提示', +// msg: '删除成功!', +// timeout: 2000, +// showType: 'slide' +// }); +//} + +////线外工位质量数据、物料数据 +//void InitLineout_dialog() +//{ +// $('#Lineout_dialog').dialog({ +// title: '线外工装数据显示', +// width: 860, +// height: 610, +// closed: false, +// cache: false, +// modal: true +// }); +//IniQualityButtons_bgColor_alert(); +//initStationdata_alert(); + +//} + +//void btn_Lineout_dialog_Cancel() +//{ +// $('#Lineout_dialog').dialog({ +// closed: true, +// }); +//} + +//void btn_Lineout_dialog_Continue() +//{ +// var opName = $("#tbx_opname").val(); +// var barcode = $("#Lineout_barcode").val(); +// var sendmessage = "MSG,ContinueFixAllow|" + opName + "|" + barcode; +// sendMessage(sendmessage); +// $('#Lineout_dialog').dialog({ +// closed: true, +// }); +//} + + + + + + + + + + + + + +// } +//} diff --git a/Common/08WebFun_base/WebFun_base/MisWebInterfaceFunc/Web_MaterialCheck.cs b/Common/08WebFun_base/WebFun_base/MisWebInterfaceFunc/Web_MaterialCheck.cs new file mode 100644 index 0000000..00bada9 --- /dev/null +++ b/Common/08WebFun_base/WebFun_base/MisWebInterfaceFunc/Web_MaterialCheck.cs @@ -0,0 +1,155 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +//using SystemFramework; + +namespace MesWebFun_base +{ + public partial class MisWebInterface + { + + + // /*该js文件用于处理"物料检测"业务逻辑处理*/ + + // var jsonArrayStatic_MaterialCheck; //全局json_物料检测 + // var CircleDivList_MaterialCheck; //全局记录包含image的div + // var CircleDivListCount_MaterialCheck = 0; + // var CircleImageList_MaterialCheck; //全局记录全部的物料检测小圆圈图片 + // var CircleImageListCount_MaterialCheck = 0; + + //初始化物料检测指导 + string InitMaterialCheck(string opName) + { + //url: '../submit/OpName.ashx?type=MaterialCheckPosition&value=' + opName, + var responseStr = _MesWebFun_base.ProcessRequest("MaterialCheckPosition", opName); + return responseStr; + + } + + + // //创建div(MaterialCheck) + // void SetUpCircleDiv_MaterialCheck(data) + // { + // CircleDivList_MaterialCheck = { }; + // CircleImageList_MaterialCheck = { }; + // CircleImageListCount_MaterialCheck = 0; + // CircleImageListCount_MaterialCheck = 0; + + // var CircleImage = "
"; //默认 + // var CricleColor = "checkred"; //默认 + + // for (var i = 0; i < data.length; i++) + // { + // var divImgWidth = $("#div_tab_assembly_craft_main").width(); + // var CircleDivID = "CheckMaterialDivID" + i; + // var CircleImageID = "CheckMaterialImageID" + i; + // var LocationX_data = data[i].测量位置X; + // var LocationX = divImgWidth + LocationX_data; + // var LocationY = data[i].测量位置Y; + // var contrlosWidth = data[i].控件宽度; + // var contrlosHeight = data[i].控件高度; + + // CircleImage = "
" + // + "" + // + "
" + + // $('#div_tab_assembly_craft').append(CircleImage); + // $('#' + CircleDivID).css( + // { + // "top": LocationY + "px", + // "left": LocationX + "px", + // "z-index": "4", + // "width": contrlosWidth, + // "height": contrlosHeight, + // "position": "absolute" + // }); + + // $('#' + CircleImageID).css( + // { + // "width": contrlosWidth, + // "height": contrlosHeight + // } + // ); + + // //赋值变量 + // CircleDivList_MaterialCheck[i] = CircleDivID; + // CircleImageList_MaterialCheck[i] = CircleImageID; + // CircleDivListCount_MaterialCheck++; + // CircleImageListCount_MaterialCheck++; + // } + // } + + // //移除控件 + // void ClearCircle_MaterialCheck() + // { + // if (CircleDivListCount_MaterialCheck > 0) + // { + // for (var i = CircleDivListCount_MaterialCheck - 1; i >= 0; i--) + // { + // var id = CircleDivList_MaterialCheck[i]; + // $('#' + id).remove(); + // } + // } + // } + + + // //根据传递的物料检测信息 + // void ShowMaterialCheck(m_Value) + // { + + // //先判断是否还有未完成拧紧或者的位置 + // var imageid; + // var imagesrc; + // var Num; + // var check; + + // var s_valueArrays = m_Value.split('&'); //将接收到的检测信息split + // if (CircleImageListCount_MaterialCheck > 0) + // { + // if (s_valueArrays.length > 0) + // { + // for (var i = 0; i < jsonArrayStatic_MaterialCheck.length; i++) + // { + // Num = jsonArrayStatic_MaterialCheck[i].物料检测; //检测序号 + // imageid = CircleImageList_MaterialCheck[Num]; + // if (Num <= (s_valueArrays.length - 1)) + // { + // check = s_valueArrays[Num]; + // if (check == 0) + // {//未能检测到显示红色动画 + // imagesrc = "../images/checkred.gif"; + // } + // if (check == 1) + // {//检测到显示绿色动画 + // imagesrc = "../images/checkgreen.gif"; + // } + // else + // { + // imagesrc = "../images/checkred.gif"; + // } + // $('#' + imageid).attr("src", imagesrc); + // } + // } + // } + // } + // } + + + + + + + + + + + + + } +} diff --git a/Common/08WebFun_base/WebFun_base/MisWebInterfaceFunc/Web_Notice.cs b/Common/08WebFun_base/WebFun_base/MisWebInterfaceFunc/Web_Notice.cs new file mode 100644 index 0000000..37d567e --- /dev/null +++ b/Common/08WebFun_base/WebFun_base/MisWebInterfaceFunc/Web_Notice.cs @@ -0,0 +1,38 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +//using SystemFramework; + +namespace MesWebFun_base +{ + public partial class MisWebInterface + { + + + /*该js文件用于处理"弹窗消息"业务逻辑处理*/ + string ShowWindowNotice(string opName) + { + //url: '../submit/OpName.ashx?type=ShowWindowNotice&value=' + opName, + var responseStr = _MesWebFun_base.ProcessRequest("ShowWindowNotice", opName); + return responseStr; + } + + //LED消息提醒 + string ShowLEDNotice(string opName) + { + // url: '../submit/OpName.ashx?type=ShowLEDNotice&value=' + opName, + var responseStr = _MesWebFun_base.ProcessRequest("ShowLEDNotice", opName); + return responseStr; + } + + + + + + + + + } +} diff --git a/Common/08WebFun_base/WebFun_base/MisWebInterfaceFunc/Web_OutLineRepair.cs b/Common/08WebFun_base/WebFun_base/MisWebInterfaceFunc/Web_OutLineRepair.cs new file mode 100644 index 0000000..f110882 --- /dev/null +++ b/Common/08WebFun_base/WebFun_base/MisWebInterfaceFunc/Web_OutLineRepair.cs @@ -0,0 +1,420 @@ +//using System; +//using System.Collections.Generic; +//using System.Linq; +//using System.Text; +//using System.Threading.Tasks; +//using SystemFramework; + +//namespace MesWebFun_base +//{ +// public partial class MisWebInterface +// { + + + + + +// //初始化返修上线dialog +// void Initdiv_RepairPartLoad_dialg() +// { +// $('#div_RepairPartLoad_dialg').dialog({ +// title: '返修上线', +// width: 600, +// height: 350, +// closed: true +// }); +// } +// //获取日期字符串 +// void RepairPartLoad_GetDate() +// { +// var today, hour, second, minute, year, month, date; +// var strDate; +// today = new Date(); +// year = today.getFullYear(); +// month = today.getMonth() + 1; +// date = today.getDate(); +// hour = today.getHours(); +// minute = today.getMinutes(); +// second = today.getSeconds(); + +// if (month < 10) +// { +// month_New = "0" + month; +// } +// else +// { +// month_New = month; +// } + +// if (date < 10) +// { +// date_New = "0" + date; +// } +// else +// { +// date_New = date; +// } +// // var date3 = document.getElementById('input_RepairPartLoad_EngineID_date').value = year + "-" + month_New + "-" + date_New; //显示时间 +// } + + +// //更新返修状态 +// void update_RepairStatus(data) +// { +// var opName = $("#tbx_opname").val(); //工位号 +// var str0 = data; +// var str1 = new Array(); +// str1 = str0.split("_"); +// var opname = str1[1] +// var btnColor = document.getElementById("" + data + "").style.backgroundColor; +// var status = 0; + +// if (btnColor == "lime") +// { +// status = 1; + +// } +// if (btnColor == "") +// { +// status = 0; +// } + +// //更新到数据库中 +// $.ajax({ +// url: '../submit/OpName.ashx?type=updateRepairStatus&value=' + opName +// + '&opname=' + opname +// + '&status=' + status, +// success: function(data) { + + +// } +// }); +// } + + + +// //全选 +// void SelectAllBtn() +// { +// var btn_Str = ""; +// var repairtags = document.getElementsByName("RepairBtn"); +// var str_value = ""; +// for (var i = 0; i < repairtags.length; i++) +// { +// repairtags[i].style.backgroundColor = "green"; +// } + +// } + +// //清空 +// void RemoveAllBtn() +// { +// var btn_Str = ""; +// var repairtags = document.getElementsByName("RepairBtn"); +// var str_value = ""; +// for (var i = 0; i < repairtags.length; i++) +// { +// repairtags[i].style.backgroundColor = "gray"; +// } +// } + +// //反选 +// void ReverseSelectBtn() +// { +// var btn_Str = ""; +// var repairtags = document.getElementsByName("RepairBtn"); +// var str_value = ""; +// for (var i = 0; i < repairtags.length; i++) +// { +// var btnColor = repairtags[i].style.backgroundColor; +// if (btnColor == "green")//判断按钮背景色 +// { +// repairtags[i].style.backgroundColor = "gray"; +// } +// else +// { +// repairtags[i].style.backgroundColor = "green"; +// } +// } +// } + +// //保存返修数据 +// void RepairPartLoad_Confirm() +// { +// var btn_Str = ""; +// var repairtags = document.getElementsByName("RepairBtn"); +// var str_value = ""; +// for (var i = 0; i < repairtags.length; i++) +// { +// var btnColor = repairtags[i].style.backgroundColor; +// if (btnColor == "green")//判断按钮背景色 +// { +// str_value = repairtags[i].value + "^" + "1" + "|" + str_value; +// } +// else +// { +// str_value = repairtags[i].value + "^" + "0" + "|" + str_value; +// } +// } +// var RepairMethod = $("input[name='RepairMethod']:checked").val(); +// var engineID = $("#text_selectByID").val(); +// var OpNanme_Str = btn_Str.split("|"); +// var engineType = $("#text_engingeType").val(); +// var OpName = $("#tbx_opname").val(); //工位号 +// $.ajax({ +// url: '../submit/OpName.ashx?type=SaveRepairStatus&str_value=' + str_value + '&engineID=' + engineID + '&RepairMethod=' + RepairMethod + '&engineType=' + engineType + '&OpName=' + OpName, +// success: function(data) { + +// if (data == "True") +// { +// $.messager.show({ +// title: '提示', +// msg: "返修上线数据保存成功!", +// timeout: 5000, +// showType: 'slide' +// }); +// $('#div_RepairPartLoad_dialg').dialog({ + +// closed: true +// }); +// var opName = $("#tbx_opname").val(); +// var value = $("#text_selectByID").val(); +// var m_value = value + "/" + RepairMethod; +// var sendmessage = "MSG,RepairMarks|" + opName + "|" + m_value; +// sendMessage(sendmessage); +// } +// else +// { +// $.messager.show({ +// title: '提示', +// msg: "返修上线数据保存失败!", +// timeout: 5000, +// showType: 'slide' +// }); + +// } +// } +// }); +// } + +// //初始化返修上线弹出框的动态按钮 +// void Initdiv_RepairPartLoadBtn() +// { +// var opName = $("#tbx_opname").val(); //工位号 +// var text_selectByID = $("#text_selectByID").val(); //工件编号 +// if (text_selectByID == "") +// { +// return; +// } +// $.ajax({ +// url: '../submit/OpName.ashx?type=RepairStatusInit&value=' + opName + '&text_selectByID=' + text_selectByID, +// success: function(data) +// { +// if (data != null && data != "") +// { +// document.getElementById("div_RepairPartLoad_zbz").innerHTML = '' + data + ''; +// } +// } +// }); + +// } +// //关闭弹窗 +// void RepairPartLoad_Cancel() +// { + +// $('#div_RepairPartLoad_dialg').dialog({ + +// closed: true +// }); + +// } + +// //点击返修上线按钮 +// void btn_outlinerepair() +// { +// /////////////////////返修上线//////////////////// +// //弹出返修上线dialog + +// $("#div_RepairPartLoad_dialg").dialog("open"); + +// } + + +// void RepairBtnClick(data) +// { + +// var opname = data.value; +// var btnColor = document.getElementById("Btn_" + opname + "").style.backgroundColor; +// if (btnColor == "green")//判断按钮背景色 +// { +// $('#Btn_' + opname).css({ +// "background-color": "gray"//设置背景色为空 +// }); +// } +// else +// { +// $('#Btn_' + opname).css({ +// "background-color": "green" +// }); +// } +// } + + + +// //初始化质量查询返修 +// void initStationdataRepair() +// { +// //console.info("质量查询的tab"); +// var opNumWidth = $("#div_tab_stationdata").width() * 0.3; +// var measureDataWidth = $("#div_tab_stationdata").width() * 0.2; +// var measureNameWidth = $("#div_tab_stationdata").width() * 0.3; +// var qualifiedMarkWidth = $("#div_tab_stationdata").width() * 0.19; +// $('#datagridview_stationdata_repair').datagrid({ +// url: '', +// title: '', +// sortName: '', //按哪个字段排序,把这个提交给服务器 +// sortOrder: 'desc', //升序降序 +// idField: '', +// fit: true, +// fitColumns: true, +// columns: +// [[ +// { title: '工位号', field: 'JSON_工位号', width: 70, align: 'center' }, +// { title: '测量位置', field: 'JSON_测量位置', width: 110, align: 'center' }, +// { title: '测量数据', field: 'JSON_测量值', width: 80, align: 'center' }, +// { title: '测量名称', field: 'JSON_测量项目', width: 75, align: 'center' }, +// { title: '是否合格', field: 'JSON_合格标志', width: 70, align: 'center' } +// ]], + +// rowStyler: function(index, row) { +// if (index % 2 == 0 && row.JSON_合格标志 == "OK") +// { +// return 'background-color:#D0D8E8'; +// } +// else if (index % 2 != 0 && row.JSON_合格标志 == "OK") +// { +// return 'background-color:#E9EDF4'; +// } +// else +// { +// return 'background-color:red'; +// } +// } + +// }) +//} +// //更新质量查询模块按钮颜色返修界面 +// void IniQualityButtons_bgColorRepair() +// { +// var opName = $("#tbx_opname").val(); +// $.ajax({ +// url: '../submit/OpName.ashx?type=QualityDataButton_bgColor_Select&value=' + opName + '&v=' + new Date().getTime(), +// success: function(data) { +// if (data != null && data != "") +// { +// document.getElementById("div_tab_station_Repair").innerHTML = data; +// } +// } +// }); +// } +// //更新质量查询模块按钮颜色返修 +// void IniQualityButtons_bgColor_byenergineID_Repair() +// { +// var opName = $("#tbx_opname").val(); +// var energineID = $("#text_selectByID").val(); +// $.ajax({ +// type: 'post', +// url: '../submit/OpName.ashx?type=QualityDataButton_bgColor_Select_ByEnergineID&value=' + opName + '&energineID=' + energineID + '&v=' + new Date().getTime(), +// success: function(data) { +// if (data != null && data != "") +// { +// //document.getElementById("div_tab_station_Repair").innerHTML = data; +// $("#div_tab_station_Repair").html(data); +// } +// } +// }); +// //显示 机型 +// $.ajax({ +// type: 'post', +// url: '../submit/OpName.ashx?type=Select_engineType_ByEnergineID&value=' + opName + '&energineID=' + energineID + '&v=' + new Date().getTime(), +// success: function(data) { +// if (data != null && data != "") +// { +// var engineType = data.engineType; //机型 +// $("#text_engingeType").val(engineType); +// } +// } +// }); +// } + +// //对应返修质量数据查询 +// void QualityDataSelectRepair(opname) +// { +// var opName = $("#tbx_opname").val(); //当前工位号 +// var opname = opname; //选择工位号 +// $.ajax({ +// type: 'post', +// url: '../submit/OpName.ashx?type=QualityDataSelect&value=' + opName + '&opname=' + opname, +// dataType: 'json', +// success: function(data) { +// if (data != null && data != "") +// { +// $("#datagridview_stationdata_repair").datagrid("loadData", data); +// } +// } +// }) +//} + + +// var time = 0; +// //根据发动机号查询质量数据 +// void qualityDataSelect() +// { + +// if (time == 0) +// { +// document.getElementById('button_select').style.background = 'green'; +// QualityDataSelectRepair('0000'); //用于清空缓存数据 +// IniQualityButtons_bgColor_byenergineID_Repair(); +// time = 2; +// } +// if (time == 1) +// { + +// document.getElementById('button_select').style.background = 'gray'; +// QualityDataSelectRepair('0000'); +// document.getElementById('text_selectByID').value = ""; +// document.getElementById('text_engingeType').value = ""; +// IniQualityButtons_bgColorRepair(); +// time = 0; +// } +// if (time == 2) +// { +// time = 1; +// } + +// } + +// //更新质量查询模块按钮颜色返修用 +// void IniQualityButtons_bgColorRepair() +// { +// var opName = $("#tbx_opname").val(); +// $.ajax({ +// url: '../submit/OpName.ashx?type=QualityDataButton_bgColor_Select&value=' + opName + '&v=' + new Date().getTime(), +// success: function(data) { +// if (data != null && data != "") +// { +// document.getElementById("div_tab_station_Repair").innerHTML = data; +// } +// } +// }); +// } + + + + + + + +// } +//} diff --git a/Common/08WebFun_base/WebFun_base/MisWebInterfaceFunc/Web_Socket.cs b/Common/08WebFun_base/WebFun_base/MisWebInterfaceFunc/Web_Socket.cs new file mode 100644 index 0000000..b41a388 --- /dev/null +++ b/Common/08WebFun_base/WebFun_base/MisWebInterfaceFunc/Web_Socket.cs @@ -0,0 +1,189 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +//using SystemFramework; + +namespace MesWebFun_base +{ + public partial class MisWebInterface + { + + /// + /// + /// + public static MesWebFun_base _MesWebFun_base = new MesWebFun_base(); + + + public string WebSocket_Function(string msg) + { + var responseStr = ""; + try + { + //返回的数据msg.data,包含了协议中的4部分9 + var arrays_signal = msg.Split('|'); + var m_Source = arrays_signal[0]; + var m_Command = arrays_signal[1]; + var m_Opname = arrays_signal[2]; + var m_Value = arrays_signal[3]; + // var opName = $("#tbx_opname").val(); + switch (m_Source) + { + case "MES": + + switch (m_Command) + { + //显示托盘信息 √ + case "ShowMoby": + try + { + responseStr = ReceivedSignal_MobySelect( m_Opname); + } + catch (Exception exception) + { + //ApplicationLog.WriteLog("信息提示" + "|" + "错误断点:ShowMoby" + "|" + "info"); + } + break; + //显示操作指南√ + case "ProcessList": + try + { + responseStr = ReceivedSignal_ProcessList(m_Opname); + } + catch (Exception exception) + { + //ApplicationLog.WriteLog("信息提示" + "|" + "错误断点:ProcessList" + "|" + "info"); + } + break; + //显示物料√ + case "MaterialList": + try + { + responseStr = ReceivedSignal_MaterialList(m_Opname); + } + catch (Exception exception) + { + //ApplicationLog.WriteLog("信息提示" + "|" + "错误断点:MaterialList" + "|" + "info"); + } + break; + //显示操作图片√ + case "PicShow": + try + { + responseStr = ReceivedSignal_PictureShow(m_Opname); + } + catch (Exception exception) + { + //ApplicationLog.WriteLog("信息提示" + "|" + "错误断点:PicShow" + "|" + "info"); + } + break; + //显示拧紧位置√ + case "ShaftPosition": + try + { + responseStr = InitShowGuidCircle(m_Opname); + } + catch (Exception exception) + { + //ApplicationLog.WriteLog("信息提示" + "|" + "错误断点:ShaftPosition" + "|" + "info"); + } + break; + //实时显示质量数据√ + case "ShowTimelyQuality": + try + { + // url: '../submit/OpName.ashx?type=ShowTimelyQuality&value=' + opName, + responseStr = _MesWebFun_base.ProcessRequest("ShowTimelyQuality", m_Opname); + } + catch (Exception exception) + { + //ApplicationLog.WriteLog("信息提示" + "|" + "错误断点:ShowTimelyQuality" + "|" + "info"); + } + break; + //手动拧紧实时显示质量数据√ + case "ShowTimelyQuality_Tight": + try + { + // url: '../submit/OpName.ashx?type=ShowTimelyQuality&value=' + opName, + responseStr = _MesWebFun_base.ProcessRequest("ShowTimelyQuality", m_Opname); + } + catch (Exception exception) + { + //ApplicationLog.WriteLog("信息提示" + "|" + "错误断点:ShowTimelyQuality_Tight" + "|" + "info"); + } + break; + + //√ + case "OrderFormList": + try + { + // ReloadOrderInfoData(); + //url: '../submit/OpName.ashx?type=OrderFormList&value=' + opName, + responseStr = _MesWebFun_base.ProcessRequest("OrderFormList", m_Opname); + } + catch (Exception exception) + { + //ApplicationLog.WriteLog("信息提示" + "|" + "错误断点:OrderFormList" + "|" + "info"); + } + break; + //弹窗消息√ + case "Notice": + try + { + responseStr = ShowWindowNotice(m_Opname); + } + catch (Exception exception) + { + //ApplicationLog.WriteLog("信息提示" + "|" + "错误断点:Notice" + "|" + "info"); + } + break; + //LED消息提醒√ + case "ScrollNotice": + try + { + responseStr = ShowLEDNotice(m_Opname); + } + catch (Exception exception) + { + //ApplicationLog.WriteLog("信息提示" + "|" + "错误断点:ScrollNotice" + "|" + "info"); + } + break; + //物料检测初始化√ + case "MaterialCheckPosition": + responseStr = InitMaterialCheck(m_Opname); + break; + //返修质量数据显示√ + case "RepairQuality": + try + { + // IniQualityButtons_bgColor_byenergineID_socket(m_Value); + //url: '../submit/OpName.ashx?type=QualityDataButton_bgColor_Select_ByEnergineID&value=' + opName + '&energineID=' + energineID + '&v=' + new Date().getTime(), + responseStr = _MesWebFun_base.ProcessRequest("QualityDataButton_bgColor_Select_ByEnergineID", m_Opname); + } + catch (Exception exception) + { + //ApplicationLog.WriteLog("信息提示" + "|" + "错误断点:RepairQuality" + "|" + "info"); + } + break; + + default: + // Web_Socket_Interface(m_Opname, msg); + break; + } + break; + } + } + catch (Exception exception) + { + var error = exception.ToString(); + //ApplicationLog.WriteLog("信息提示" + "|" + "系统出现错误,接受onmessage:" + "|" + error + "|" + "info"); + responseStr = ""; + } + return responseStr; + } + + + + } +} diff --git a/Common/08WebFun_base/WebFun_base/MisWebInterfaceFunc/Web_Socket_Interface.cs b/Common/08WebFun_base/WebFun_base/MisWebInterfaceFunc/Web_Socket_Interface.cs new file mode 100644 index 0000000..65424a0 --- /dev/null +++ b/Common/08WebFun_base/WebFun_base/MisWebInterfaceFunc/Web_Socket_Interface.cs @@ -0,0 +1,170 @@ +//using System; +//using System.Collections.Generic; +//using System.Linq; +//using System.Text; +//using System.Threading.Tasks; +//using SystemFramework; + +//namespace MesWebFun_base +//{ +// public partial class MisWebInterface +// { + + +// /*该js文件用于处理"弹窗消息"业务逻辑处理*/ + +// //接口函数 +// void Web_Socket_Interface(opName, msg) +// { +// //获取工位号对应Fun类型 +// $.ajax({ +// type: "POST", +// url: '../submit/OpName.ashx?type=' + opName + '&value=' + opName, +// success: function(data) { +// if (data != null && data != "") +// { +// switch (data) +// { +// case "01": +// Web_Socket_Fun01(opName, msg); +// break; +// case "02": +// Web_Socket_Fun02(opName, msg); +// break; +// case "03": +// Web_Socket_Fun03(opName, msg); +// break; +// case "04": +// Web_Socket_Fun04(opName, msg); +// break; +// case "05": +// Web_Socket_Fun05(opName, msg); +// break; +// case "06": +// Web_Socket_Fun06(opName, msg); +// break; +// case "07": +// Web_Socket_Fun07(opName, msg); +// break; +// case "08": +// Web_Socket_Fun08(opName, msg); +// break; +// case "09": +// Web_Socket_Fun09(opName, msg); +// break; +// case "10": +// Web_Socket_Fun10(opName, msg); +// break; +// case "11": +// Web_Socket_Fun11(opName, msg); +// break; +// case "12": +// Web_Socket_Fun12(opName, msg); +// break; +// case "13": +// Web_Socket_Fun13(opName, msg); +// break; +// case "14": +// Web_Socket_Fun14(opName, msg); +// break; +// case "15": +// Web_Socket_Fun15(opName, msg); +// break +// case "16": +// Web_Socket_Fun16(opName, msg); +// break; +// case "17": +// Web_Socket_Fun17(opName, msg); +// break; +// default: +// break; +// } +// } +// } +// }) + +//} + +// //特殊functionjs处理 +// void Web_Socket_MesWebFun_Interface(opName, msg) +// { + +// //获取工位号对应Fun类型 +// $.ajax({ +// type: "POST", +// url: '../submit/OpName.ashx?type=' + opName + '&value=' + opName, +// success: function(data) { +// if (data != null && data != "") +// { +// switch (data) +// { +// case "01": +// Web_Socket_MesWebFun01(opName, msg); +// break; +// case "02": +// Web_Socket_MesWebFun02(opName, msg); +// break; +// case "03": +// Web_Socket_MesWebFun03(opName, msg); +// break; +// case "04": +// Web_Socket_MesWebFun04(opName, msg); +// break; +// case "05": +// Web_Socket_MesWebFun05(opName, msg); +// break; +// case "06": +// Web_Socket_MesWebFun06(opName, msg); +// break; +// case "07": +// Web_Socket_MesWebFun07(opName, msg); +// break; +// case "08": +// Web_Socket_MesWebFun08(opName, msg); +// break; +// case "09": +// Web_Socket_MesWebFun09(opName, msg); +// break; +// case "10": +// Web_Socket_MesWebFun10(opName, msg); +// break; +// case "11": +// Web_Socket_MesWebFun11(opName, msg); +// break; +// case "12": +// Web_Socket_MesWebFun12(opName, msg); +// break; +// case "13": +// Web_Socket_MesWebFun13(opName, msg); +// break; +// case "14": +// Web_Socket_MesWebFun14(opName, msg); +// break; +// case "15": +// Web_Socket_MesWebFun15(opName, msg); +// break; +// case "16": +// Web_Socket_MesWebFun16(opName, msg); +// break; +// case "17": +// Web_Socket_MesWebFun17(opName, msg); +// break; +// default: +// break; +// } +// } +// } +// }) +//} + + + + + + + + + + +// } +//} diff --git a/Common/08WebFun_base/WebFun_base/Properties/AssemblyInfo.cs b/Common/08WebFun_base/WebFun_base/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..bd9fa62 --- /dev/null +++ b/Common/08WebFun_base/WebFun_base/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// 有关程序集的一般信息由以下 +// 控制。更改这些特性值可修改 +// 与程序集关联的信息。 +[assembly: AssemblyTitle("WebFun_base")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("WebFun_base")] +[assembly: AssemblyCopyright("Copyright © 2022")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// 将 ComVisible 设置为 false 会使此程序集中的类型 +//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型 +//请将此类型的 ComVisible 特性设置为 true。 +[assembly: ComVisible(false)] + +// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID +[assembly: Guid("d98be764-adeb-488d-9714-61e308aa8201")] + +// 程序集的版本信息由下列四个值组成: +// +// 主版本 +// 次版本 +// 生成号 +// 修订号 +// +//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值 +//通过使用 "*",如下所示: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Common/08WebFun_base/WebFun_base/Reference.cs b/Common/08WebFun_base/WebFun_base/Reference.cs new file mode 100644 index 0000000..02907fa --- /dev/null +++ b/Common/08WebFun_base/WebFun_base/Reference.cs @@ -0,0 +1,1224 @@ +//------------------------------------------------------------------------------ +// +// 此代码由工具生成。 +// 运行时版本:4.0.30319.42000 +// +// 对此文件的更改可能会导致不正确的行为,并且如果 +// 重新生成代码,这些更改将会丢失。 +// +//------------------------------------------------------------------------------ + +// +// 此源代码是由 Microsoft.VSDesigner 4.0.30319.42000 版自动生成。 +// +#pragma warning disable 1591 + +namespace MesWebFun_MateriallPull.BarCodeServer_Pro { + using System; + using System.Web.Services; + using System.Diagnostics; + using System.Web.Services.Protocols; + using System.Xml.Serialization; + using System.ComponentModel; + using System.Data; + + + /// + [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.6.81.0")] + [System.Diagnostics.DebuggerStepThroughAttribute()] + [System.ComponentModel.DesignerCategoryAttribute("code")] + [System.Web.Services.WebServiceBindingAttribute(Name="BarCodeSeverSoap", Namespace="http://tempuri.org/")] + public partial class BarCodeSever : System.Web.Services.Protocols.SoapHttpClientProtocol { + + private System.Threading.SendOrPostCallback HelloWorldOperationCompleted; + + private System.Threading.SendOrPostCallback Web_BarcodeReturn_Split_ExecOperationCompleted; + + private System.Threading.SendOrPostCallback Web_BarcodeReturn_Return_ExecOperationCompleted; + + private System.Threading.SendOrPostCallback Web_Barcode_Return_ReturnCancel_OracleOperationCompleted; + + private System.Threading.SendOrPostCallback Web_DirectUpload_Document_SelectOperationCompleted; + + private System.Threading.SendOrPostCallback Web_DirectUpload_Document_VerifyOKOperationCompleted; + + private System.Threading.SendOrPostCallback CrrentOrderStateSelectOperationCompleted; + + private System.Threading.SendOrPostCallback Web_MaterialPull_AndonCall_VerifyOKOperationCompleted; + + private System.Threading.SendOrPostCallback Select_AndonCall_ResultOperationCompleted; + + private System.Threading.SendOrPostCallback Web_AndonPlanStop_Return_ExecOperationCompleted; + + private System.Threading.SendOrPostCallback Web_AndonPlanStopTypeOperationCompleted; + + private System.Threading.SendOrPostCallback Web_MaterialPull_DocumentNum_SelectOperationCompleted; + + private System.Threading.SendOrPostCallback Web_MaterialPull_DocumentNum_VerifyOKOperationCompleted; + + private System.Threading.SendOrPostCallback Select_DocumentReceptCord_ResultOperationCompleted; + + private System.Threading.SendOrPostCallback Web_OnePieceFlowModle_JudgeOperationCompleted; + + private System.Threading.SendOrPostCallback Web_OnePieceFlowModle_DetaileInfoOperationCompleted; + + private bool useDefaultCredentialsSetExplicitly; + + /// + public BarCodeSever() { + //this.Url = global::MesWebFun_base.Properties.Settings.Default.MesWebFun_MateriallPull_BarCodeServer_Pro_BarCodeSever; + //if ((this.IsLocalFileSystemWebService(this.Url) == true)) { + // this.UseDefaultCredentials = true; + // this.useDefaultCredentialsSetExplicitly = false; + //} + //else { + // this.useDefaultCredentialsSetExplicitly = true; + //} + } + + public new string Url { + get { + return base.Url; + } + set { + if ((((this.IsLocalFileSystemWebService(base.Url) == true) + && (this.useDefaultCredentialsSetExplicitly == false)) + && (this.IsLocalFileSystemWebService(value) == false))) { + base.UseDefaultCredentials = false; + } + base.Url = value; + } + } + + public new bool UseDefaultCredentials { + get { + return base.UseDefaultCredentials; + } + set { + base.UseDefaultCredentials = value; + this.useDefaultCredentialsSetExplicitly = true; + } + } + + /// + public event HelloWorldCompletedEventHandler HelloWorldCompleted; + + /// + public event Web_BarcodeReturn_Split_ExecCompletedEventHandler Web_BarcodeReturn_Split_ExecCompleted; + + /// + public event Web_BarcodeReturn_Return_ExecCompletedEventHandler Web_BarcodeReturn_Return_ExecCompleted; + + /// + public event Web_Barcode_Return_ReturnCancel_OracleCompletedEventHandler Web_Barcode_Return_ReturnCancel_OracleCompleted; + + /// + public event Web_DirectUpload_Document_SelectCompletedEventHandler Web_DirectUpload_Document_SelectCompleted; + + /// + public event Web_DirectUpload_Document_VerifyOKCompletedEventHandler Web_DirectUpload_Document_VerifyOKCompleted; + + /// + public event CrrentOrderStateSelectCompletedEventHandler CrrentOrderStateSelectCompleted; + + /// + public event Web_MaterialPull_AndonCall_VerifyOKCompletedEventHandler Web_MaterialPull_AndonCall_VerifyOKCompleted; + + /// + public event Select_AndonCall_ResultCompletedEventHandler Select_AndonCall_ResultCompleted; + + /// + public event Web_AndonPlanStop_Return_ExecCompletedEventHandler Web_AndonPlanStop_Return_ExecCompleted; + + /// + public event Web_AndonPlanStopTypeCompletedEventHandler Web_AndonPlanStopTypeCompleted; + + /// + public event Web_MaterialPull_DocumentNum_SelectCompletedEventHandler Web_MaterialPull_DocumentNum_SelectCompleted; + + /// + public event Web_MaterialPull_DocumentNum_VerifyOKCompletedEventHandler Web_MaterialPull_DocumentNum_VerifyOKCompleted; + + /// + public event Select_DocumentReceptCord_ResultCompletedEventHandler Select_DocumentReceptCord_ResultCompleted; + + /// + public event Web_OnePieceFlowModle_JudgeCompletedEventHandler Web_OnePieceFlowModle_JudgeCompleted; + + /// + public event Web_OnePieceFlowModle_DetaileInfoCompletedEventHandler Web_OnePieceFlowModle_DetaileInfoCompleted; + + /// + [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/HelloWorld", RequestNamespace="http://tempuri.org/", ResponseNamespace="http://tempuri.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] + public string HelloWorld() { + object[] results = this.Invoke("HelloWorld", new object[0]); + return ((string)(results[0])); + } + + /// + public void HelloWorldAsync() { + this.HelloWorldAsync(null); + } + + /// + public void HelloWorldAsync(object userState) { + if ((this.HelloWorldOperationCompleted == null)) { + this.HelloWorldOperationCompleted = new System.Threading.SendOrPostCallback(this.OnHelloWorldOperationCompleted); + } + this.InvokeAsync("HelloWorld", new object[0], this.HelloWorldOperationCompleted, userState); + } + + private void OnHelloWorldOperationCompleted(object arg) { + if ((this.HelloWorldCompleted != null)) { + System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); + this.HelloWorldCompleted(this, new HelloWorldCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); + } + } + + /// + [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/Web_BarcodeReturn_Split_Exec", RequestNamespace="http://tempuri.org/", ResponseNamespace="http://tempuri.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] + public string Web_BarcodeReturn_Split_Exec(string barcode, string barcode_new, string splitCount) { + object[] results = this.Invoke("Web_BarcodeReturn_Split_Exec", new object[] { + barcode, + barcode_new, + splitCount}); + return ((string)(results[0])); + } + + /// + public void Web_BarcodeReturn_Split_ExecAsync(string barcode, string barcode_new, string splitCount) { + this.Web_BarcodeReturn_Split_ExecAsync(barcode, barcode_new, splitCount, null); + } + + /// + public void Web_BarcodeReturn_Split_ExecAsync(string barcode, string barcode_new, string splitCount, object userState) { + if ((this.Web_BarcodeReturn_Split_ExecOperationCompleted == null)) { + this.Web_BarcodeReturn_Split_ExecOperationCompleted = new System.Threading.SendOrPostCallback(this.OnWeb_BarcodeReturn_Split_ExecOperationCompleted); + } + this.InvokeAsync("Web_BarcodeReturn_Split_Exec", new object[] { + barcode, + barcode_new, + splitCount}, this.Web_BarcodeReturn_Split_ExecOperationCompleted, userState); + } + + private void OnWeb_BarcodeReturn_Split_ExecOperationCompleted(object arg) { + if ((this.Web_BarcodeReturn_Split_ExecCompleted != null)) { + System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); + this.Web_BarcodeReturn_Split_ExecCompleted(this, new Web_BarcodeReturn_Split_ExecCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); + } + } + + /// + [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/Web_BarcodeReturn_Return_Exec", RequestNamespace="http://tempuri.org/", ResponseNamespace="http://tempuri.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] + public string Web_BarcodeReturn_Return_Exec(string send_warehouse, string receive_warehouse, string app_user, string app_department, string header_text, string assemble_code, string plant_id, string item_code, string quantitys, string supplier_code, string remarks, string storage_flag, string p_owner_type) { + object[] results = this.Invoke("Web_BarcodeReturn_Return_Exec", new object[] { + send_warehouse, + receive_warehouse, + app_user, + app_department, + header_text, + assemble_code, + plant_id, + item_code, + quantitys, + supplier_code, + remarks, + storage_flag, + p_owner_type}); + return ((string)(results[0])); + } + + /// + public void Web_BarcodeReturn_Return_ExecAsync(string send_warehouse, string receive_warehouse, string app_user, string app_department, string header_text, string assemble_code, string plant_id, string item_code, string quantitys, string supplier_code, string remarks, string storage_flag, string p_owner_type) { + this.Web_BarcodeReturn_Return_ExecAsync(send_warehouse, receive_warehouse, app_user, app_department, header_text, assemble_code, plant_id, item_code, quantitys, supplier_code, remarks, storage_flag, p_owner_type, null); + } + + /// + public void Web_BarcodeReturn_Return_ExecAsync(string send_warehouse, string receive_warehouse, string app_user, string app_department, string header_text, string assemble_code, string plant_id, string item_code, string quantitys, string supplier_code, string remarks, string storage_flag, string p_owner_type, object userState) { + if ((this.Web_BarcodeReturn_Return_ExecOperationCompleted == null)) { + this.Web_BarcodeReturn_Return_ExecOperationCompleted = new System.Threading.SendOrPostCallback(this.OnWeb_BarcodeReturn_Return_ExecOperationCompleted); + } + this.InvokeAsync("Web_BarcodeReturn_Return_Exec", new object[] { + send_warehouse, + receive_warehouse, + app_user, + app_department, + header_text, + assemble_code, + plant_id, + item_code, + quantitys, + supplier_code, + remarks, + storage_flag, + p_owner_type}, this.Web_BarcodeReturn_Return_ExecOperationCompleted, userState); + } + + private void OnWeb_BarcodeReturn_Return_ExecOperationCompleted(object arg) { + if ((this.Web_BarcodeReturn_Return_ExecCompleted != null)) { + System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); + this.Web_BarcodeReturn_Return_ExecCompleted(this, new Web_BarcodeReturn_Return_ExecCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); + } + } + + /// + [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/Web_Barcode_Return_ReturnCancel_Oracle", RequestNamespace="http://tempuri.org/", ResponseNamespace="http://tempuri.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] + public string Web_Barcode_Return_ReturnCancel_Oracle(string pb_Num, string plant_id) { + object[] results = this.Invoke("Web_Barcode_Return_ReturnCancel_Oracle", new object[] { + pb_Num, + plant_id}); + return ((string)(results[0])); + } + + /// + public void Web_Barcode_Return_ReturnCancel_OracleAsync(string pb_Num, string plant_id) { + this.Web_Barcode_Return_ReturnCancel_OracleAsync(pb_Num, plant_id, null); + } + + /// + public void Web_Barcode_Return_ReturnCancel_OracleAsync(string pb_Num, string plant_id, object userState) { + if ((this.Web_Barcode_Return_ReturnCancel_OracleOperationCompleted == null)) { + this.Web_Barcode_Return_ReturnCancel_OracleOperationCompleted = new System.Threading.SendOrPostCallback(this.OnWeb_Barcode_Return_ReturnCancel_OracleOperationCompleted); + } + this.InvokeAsync("Web_Barcode_Return_ReturnCancel_Oracle", new object[] { + pb_Num, + plant_id}, this.Web_Barcode_Return_ReturnCancel_OracleOperationCompleted, userState); + } + + private void OnWeb_Barcode_Return_ReturnCancel_OracleOperationCompleted(object arg) { + if ((this.Web_Barcode_Return_ReturnCancel_OracleCompleted != null)) { + System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); + this.Web_Barcode_Return_ReturnCancel_OracleCompleted(this, new Web_Barcode_Return_ReturnCancel_OracleCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); + } + } + + /// + [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/Web_DirectUpload_Document_Select", RequestNamespace="http://tempuri.org/", ResponseNamespace="http://tempuri.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] + public System.Data.DataSet Web_DirectUpload_Document_Select(string document_num, string wkc) { + object[] results = this.Invoke("Web_DirectUpload_Document_Select", new object[] { + document_num, + wkc}); + return ((System.Data.DataSet)(results[0])); + } + + /// + public void Web_DirectUpload_Document_SelectAsync(string document_num, string wkc) { + this.Web_DirectUpload_Document_SelectAsync(document_num, wkc, null); + } + + /// + public void Web_DirectUpload_Document_SelectAsync(string document_num, string wkc, object userState) { + if ((this.Web_DirectUpload_Document_SelectOperationCompleted == null)) { + this.Web_DirectUpload_Document_SelectOperationCompleted = new System.Threading.SendOrPostCallback(this.OnWeb_DirectUpload_Document_SelectOperationCompleted); + } + this.InvokeAsync("Web_DirectUpload_Document_Select", new object[] { + document_num, + wkc}, this.Web_DirectUpload_Document_SelectOperationCompleted, userState); + } + + private void OnWeb_DirectUpload_Document_SelectOperationCompleted(object arg) { + if ((this.Web_DirectUpload_Document_SelectCompleted != null)) { + System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); + this.Web_DirectUpload_Document_SelectCompleted(this, new Web_DirectUpload_Document_SelectCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); + } + } + + /// + [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/Web_DirectUpload_Document_VerifyOK", RequestNamespace="http://tempuri.org/", ResponseNamespace="http://tempuri.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] + public string Web_DirectUpload_Document_VerifyOK(string source_id, string orderNum, string plant_id, string wkc, string workNum, string delivery_num, string item_code, string recept_flag, string GroupID) { + object[] results = this.Invoke("Web_DirectUpload_Document_VerifyOK", new object[] { + source_id, + orderNum, + plant_id, + wkc, + workNum, + delivery_num, + item_code, + recept_flag, + GroupID}); + return ((string)(results[0])); + } + + /// + public void Web_DirectUpload_Document_VerifyOKAsync(string source_id, string orderNum, string plant_id, string wkc, string workNum, string delivery_num, string item_code, string recept_flag, string GroupID) { + this.Web_DirectUpload_Document_VerifyOKAsync(source_id, orderNum, plant_id, wkc, workNum, delivery_num, item_code, recept_flag, GroupID, null); + } + + /// + public void Web_DirectUpload_Document_VerifyOKAsync(string source_id, string orderNum, string plant_id, string wkc, string workNum, string delivery_num, string item_code, string recept_flag, string GroupID, object userState) { + if ((this.Web_DirectUpload_Document_VerifyOKOperationCompleted == null)) { + this.Web_DirectUpload_Document_VerifyOKOperationCompleted = new System.Threading.SendOrPostCallback(this.OnWeb_DirectUpload_Document_VerifyOKOperationCompleted); + } + this.InvokeAsync("Web_DirectUpload_Document_VerifyOK", new object[] { + source_id, + orderNum, + plant_id, + wkc, + workNum, + delivery_num, + item_code, + recept_flag, + GroupID}, this.Web_DirectUpload_Document_VerifyOKOperationCompleted, userState); + } + + private void OnWeb_DirectUpload_Document_VerifyOKOperationCompleted(object arg) { + if ((this.Web_DirectUpload_Document_VerifyOKCompleted != null)) { + System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); + this.Web_DirectUpload_Document_VerifyOKCompleted(this, new Web_DirectUpload_Document_VerifyOKCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); + } + } + + /// + [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/CrrentOrderStateSelect", RequestNamespace="http://tempuri.org/", ResponseNamespace="http://tempuri.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] + public System.Data.DataTable CrrentOrderStateSelect(string plant_code, string wkc, string StartTime, string EndTime) { + object[] results = this.Invoke("CrrentOrderStateSelect", new object[] { + plant_code, + wkc, + StartTime, + EndTime}); + return ((System.Data.DataTable)(results[0])); + } + + /// + public void CrrentOrderStateSelectAsync(string plant_code, string wkc, string StartTime, string EndTime) { + this.CrrentOrderStateSelectAsync(plant_code, wkc, StartTime, EndTime, null); + } + + /// + public void CrrentOrderStateSelectAsync(string plant_code, string wkc, string StartTime, string EndTime, object userState) { + if ((this.CrrentOrderStateSelectOperationCompleted == null)) { + this.CrrentOrderStateSelectOperationCompleted = new System.Threading.SendOrPostCallback(this.OnCrrentOrderStateSelectOperationCompleted); + } + this.InvokeAsync("CrrentOrderStateSelect", new object[] { + plant_code, + wkc, + StartTime, + EndTime}, this.CrrentOrderStateSelectOperationCompleted, userState); + } + + private void OnCrrentOrderStateSelectOperationCompleted(object arg) { + if ((this.CrrentOrderStateSelectCompleted != null)) { + System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); + this.CrrentOrderStateSelectCompleted(this, new CrrentOrderStateSelectCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); + } + } + + /// + [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/Web_MaterialPull_AndonCall_VerifyOK", RequestNamespace="http://tempuri.org/", ResponseNamespace="http://tempuri.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] + public string Web_MaterialPull_AndonCall_VerifyOK( + string PLANT_ID, + string WORK_CENTER_CODE, + string ANDON_TYPE, + string PROCESS_GROUP_ID, + string SOURCE_ID, + string ANDON_NUMBER, + string WORK_NUMBER, + string EMPLOYEE_NUMBER, + string ITEM_CODE, + string ITEM_DESCRIPTIONS, + string QUANTITY, + string ANDON_TIME, + string process_status, + string FLAG, + string REMARK, + string stot_flag) { + object[] results = this.Invoke("Web_MaterialPull_AndonCall_VerifyOK", new object[] { + PLANT_ID, + WORK_CENTER_CODE, + ANDON_TYPE, + PROCESS_GROUP_ID, + SOURCE_ID, + ANDON_NUMBER, + WORK_NUMBER, + EMPLOYEE_NUMBER, + ITEM_CODE, + ITEM_DESCRIPTIONS, + QUANTITY, + ANDON_TIME, + process_status, + FLAG, + REMARK, + stot_flag}); + return ((string)(results[0])); + } + + /// + public void Web_MaterialPull_AndonCall_VerifyOKAsync( + string PLANT_ID, + string WORK_CENTER_CODE, + string ANDON_TYPE, + string PROCESS_GROUP_ID, + string SOURCE_ID, + string ANDON_NUMBER, + string WORK_NUMBER, + string EMPLOYEE_NUMBER, + string ITEM_CODE, + string ITEM_DESCRIPTIONS, + string QUANTITY, + string ANDON_TIME, + string process_status, + string FLAG, + string REMARK, + string stot_flag) { + this.Web_MaterialPull_AndonCall_VerifyOKAsync(PLANT_ID, WORK_CENTER_CODE, ANDON_TYPE, PROCESS_GROUP_ID, SOURCE_ID, ANDON_NUMBER, WORK_NUMBER, EMPLOYEE_NUMBER, ITEM_CODE, ITEM_DESCRIPTIONS, QUANTITY, ANDON_TIME, process_status, FLAG, REMARK, stot_flag, null); + } + + /// + public void Web_MaterialPull_AndonCall_VerifyOKAsync( + string PLANT_ID, + string WORK_CENTER_CODE, + string ANDON_TYPE, + string PROCESS_GROUP_ID, + string SOURCE_ID, + string ANDON_NUMBER, + string WORK_NUMBER, + string EMPLOYEE_NUMBER, + string ITEM_CODE, + string ITEM_DESCRIPTIONS, + string QUANTITY, + string ANDON_TIME, + string process_status, + string FLAG, + string REMARK, + string stot_flag, + object userState) { + if ((this.Web_MaterialPull_AndonCall_VerifyOKOperationCompleted == null)) { + this.Web_MaterialPull_AndonCall_VerifyOKOperationCompleted = new System.Threading.SendOrPostCallback(this.OnWeb_MaterialPull_AndonCall_VerifyOKOperationCompleted); + } + this.InvokeAsync("Web_MaterialPull_AndonCall_VerifyOK", new object[] { + PLANT_ID, + WORK_CENTER_CODE, + ANDON_TYPE, + PROCESS_GROUP_ID, + SOURCE_ID, + ANDON_NUMBER, + WORK_NUMBER, + EMPLOYEE_NUMBER, + ITEM_CODE, + ITEM_DESCRIPTIONS, + QUANTITY, + ANDON_TIME, + process_status, + FLAG, + REMARK, + stot_flag}, this.Web_MaterialPull_AndonCall_VerifyOKOperationCompleted, userState); + } + + private void OnWeb_MaterialPull_AndonCall_VerifyOKOperationCompleted(object arg) { + if ((this.Web_MaterialPull_AndonCall_VerifyOKCompleted != null)) { + System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); + this.Web_MaterialPull_AndonCall_VerifyOKCompleted(this, new Web_MaterialPull_AndonCall_VerifyOKCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); + } + } + + /// + [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/Select_AndonCall_Result", RequestNamespace="http://tempuri.org/", ResponseNamespace="http://tempuri.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] + public System.Data.DataTable Select_AndonCall_Result(string PROCESS_GROUP_ID) { + object[] results = this.Invoke("Select_AndonCall_Result", new object[] { + PROCESS_GROUP_ID}); + return ((System.Data.DataTable)(results[0])); + } + + /// + public void Select_AndonCall_ResultAsync(string PROCESS_GROUP_ID) { + this.Select_AndonCall_ResultAsync(PROCESS_GROUP_ID, null); + } + + /// + public void Select_AndonCall_ResultAsync(string PROCESS_GROUP_ID, object userState) { + if ((this.Select_AndonCall_ResultOperationCompleted == null)) { + this.Select_AndonCall_ResultOperationCompleted = new System.Threading.SendOrPostCallback(this.OnSelect_AndonCall_ResultOperationCompleted); + } + this.InvokeAsync("Select_AndonCall_Result", new object[] { + PROCESS_GROUP_ID}, this.Select_AndonCall_ResultOperationCompleted, userState); + } + + private void OnSelect_AndonCall_ResultOperationCompleted(object arg) { + if ((this.Select_AndonCall_ResultCompleted != null)) { + System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); + this.Select_AndonCall_ResultCompleted(this, new Select_AndonCall_ResultCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); + } + } + + /// + [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/Web_AndonPlanStop_Return_Exec", RequestNamespace="http://tempuri.org/", ResponseNamespace="http://tempuri.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] + public string Web_AndonPlanStop_Return_Exec(string Plan_ID, string p_user_code, string StopMachine_style, string MachineCode, string p_andon_date_s, string p_andon_date_e, string p_enable_flag, string p_ClassCode, string StopMachine_diff) { + object[] results = this.Invoke("Web_AndonPlanStop_Return_Exec", new object[] { + Plan_ID, + p_user_code, + StopMachine_style, + MachineCode, + p_andon_date_s, + p_andon_date_e, + p_enable_flag, + p_ClassCode, + StopMachine_diff}); + return ((string)(results[0])); + } + + /// + public void Web_AndonPlanStop_Return_ExecAsync(string Plan_ID, string p_user_code, string StopMachine_style, string MachineCode, string p_andon_date_s, string p_andon_date_e, string p_enable_flag, string p_ClassCode, string StopMachine_diff) { + this.Web_AndonPlanStop_Return_ExecAsync(Plan_ID, p_user_code, StopMachine_style, MachineCode, p_andon_date_s, p_andon_date_e, p_enable_flag, p_ClassCode, StopMachine_diff, null); + } + + /// + public void Web_AndonPlanStop_Return_ExecAsync(string Plan_ID, string p_user_code, string StopMachine_style, string MachineCode, string p_andon_date_s, string p_andon_date_e, string p_enable_flag, string p_ClassCode, string StopMachine_diff, object userState) { + if ((this.Web_AndonPlanStop_Return_ExecOperationCompleted == null)) { + this.Web_AndonPlanStop_Return_ExecOperationCompleted = new System.Threading.SendOrPostCallback(this.OnWeb_AndonPlanStop_Return_ExecOperationCompleted); + } + this.InvokeAsync("Web_AndonPlanStop_Return_Exec", new object[] { + Plan_ID, + p_user_code, + StopMachine_style, + MachineCode, + p_andon_date_s, + p_andon_date_e, + p_enable_flag, + p_ClassCode, + StopMachine_diff}, this.Web_AndonPlanStop_Return_ExecOperationCompleted, userState); + } + + private void OnWeb_AndonPlanStop_Return_ExecOperationCompleted(object arg) { + if ((this.Web_AndonPlanStop_Return_ExecCompleted != null)) { + System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); + this.Web_AndonPlanStop_Return_ExecCompleted(this, new Web_AndonPlanStop_Return_ExecCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); + } + } + + /// + [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/Web_AndonPlanStopType", RequestNamespace="http://tempuri.org/", ResponseNamespace="http://tempuri.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] + public System.Data.DataTable Web_AndonPlanStopType(string Result) { + object[] results = this.Invoke("Web_AndonPlanStopType", new object[] { + Result}); + return ((System.Data.DataTable)(results[0])); + } + + /// + public void Web_AndonPlanStopTypeAsync(string Result) { + this.Web_AndonPlanStopTypeAsync(Result, null); + } + + /// + public void Web_AndonPlanStopTypeAsync(string Result, object userState) { + if ((this.Web_AndonPlanStopTypeOperationCompleted == null)) { + this.Web_AndonPlanStopTypeOperationCompleted = new System.Threading.SendOrPostCallback(this.OnWeb_AndonPlanStopTypeOperationCompleted); + } + this.InvokeAsync("Web_AndonPlanStopType", new object[] { + Result}, this.Web_AndonPlanStopTypeOperationCompleted, userState); + } + + private void OnWeb_AndonPlanStopTypeOperationCompleted(object arg) { + if ((this.Web_AndonPlanStopTypeCompleted != null)) { + System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); + this.Web_AndonPlanStopTypeCompleted(this, new Web_AndonPlanStopTypeCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); + } + } + + /// + [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/Web_MaterialPull_DocumentNum_Select", RequestNamespace="http://tempuri.org/", ResponseNamespace="http://tempuri.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] + public System.Data.DataSet Web_MaterialPull_DocumentNum_Select(string document_num, string wkc) { + object[] results = this.Invoke("Web_MaterialPull_DocumentNum_Select", new object[] { + document_num, + wkc}); + return ((System.Data.DataSet)(results[0])); + } + + /// + public void Web_MaterialPull_DocumentNum_SelectAsync(string document_num, string wkc) { + this.Web_MaterialPull_DocumentNum_SelectAsync(document_num, wkc, null); + } + + /// + public void Web_MaterialPull_DocumentNum_SelectAsync(string document_num, string wkc, object userState) { + if ((this.Web_MaterialPull_DocumentNum_SelectOperationCompleted == null)) { + this.Web_MaterialPull_DocumentNum_SelectOperationCompleted = new System.Threading.SendOrPostCallback(this.OnWeb_MaterialPull_DocumentNum_SelectOperationCompleted); + } + this.InvokeAsync("Web_MaterialPull_DocumentNum_Select", new object[] { + document_num, + wkc}, this.Web_MaterialPull_DocumentNum_SelectOperationCompleted, userState); + } + + private void OnWeb_MaterialPull_DocumentNum_SelectOperationCompleted(object arg) { + if ((this.Web_MaterialPull_DocumentNum_SelectCompleted != null)) { + System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); + this.Web_MaterialPull_DocumentNum_SelectCompleted(this, new Web_MaterialPull_DocumentNum_SelectCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); + } + } + + /// + [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/Web_MaterialPull_DocumentNum_VerifyOK", RequestNamespace="http://tempuri.org/", ResponseNamespace="http://tempuri.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] + public string Web_MaterialPull_DocumentNum_VerifyOK(string source_id, string orderNum, string plant_id, string wkc, string workNum, string delivery_num, string item_code, string recept_flag, string type, string GroupID) { + object[] results = this.Invoke("Web_MaterialPull_DocumentNum_VerifyOK", new object[] { + source_id, + orderNum, + plant_id, + wkc, + workNum, + delivery_num, + item_code, + recept_flag, + type, + GroupID}); + return ((string)(results[0])); + } + + /// + public void Web_MaterialPull_DocumentNum_VerifyOKAsync(string source_id, string orderNum, string plant_id, string wkc, string workNum, string delivery_num, string item_code, string recept_flag, string type, string GroupID) { + this.Web_MaterialPull_DocumentNum_VerifyOKAsync(source_id, orderNum, plant_id, wkc, workNum, delivery_num, item_code, recept_flag, type, GroupID, null); + } + + /// + public void Web_MaterialPull_DocumentNum_VerifyOKAsync(string source_id, string orderNum, string plant_id, string wkc, string workNum, string delivery_num, string item_code, string recept_flag, string type, string GroupID, object userState) { + if ((this.Web_MaterialPull_DocumentNum_VerifyOKOperationCompleted == null)) { + this.Web_MaterialPull_DocumentNum_VerifyOKOperationCompleted = new System.Threading.SendOrPostCallback(this.OnWeb_MaterialPull_DocumentNum_VerifyOKOperationCompleted); + } + this.InvokeAsync("Web_MaterialPull_DocumentNum_VerifyOK", new object[] { + source_id, + orderNum, + plant_id, + wkc, + workNum, + delivery_num, + item_code, + recept_flag, + type, + GroupID}, this.Web_MaterialPull_DocumentNum_VerifyOKOperationCompleted, userState); + } + + private void OnWeb_MaterialPull_DocumentNum_VerifyOKOperationCompleted(object arg) { + if ((this.Web_MaterialPull_DocumentNum_VerifyOKCompleted != null)) { + System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); + this.Web_MaterialPull_DocumentNum_VerifyOKCompleted(this, new Web_MaterialPull_DocumentNum_VerifyOKCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); + } + } + + /// + [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/Select_DocumentReceptCord_Result", RequestNamespace="http://tempuri.org/", ResponseNamespace="http://tempuri.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] + public System.Data.DataSet Select_DocumentReceptCord_Result(string DocumentNum, string PROCESS_GROUP_ID) { + object[] results = this.Invoke("Select_DocumentReceptCord_Result", new object[] { + DocumentNum, + PROCESS_GROUP_ID}); + return ((System.Data.DataSet)(results[0])); + } + + /// + public void Select_DocumentReceptCord_ResultAsync(string DocumentNum, string PROCESS_GROUP_ID) { + this.Select_DocumentReceptCord_ResultAsync(DocumentNum, PROCESS_GROUP_ID, null); + } + + /// + public void Select_DocumentReceptCord_ResultAsync(string DocumentNum, string PROCESS_GROUP_ID, object userState) { + if ((this.Select_DocumentReceptCord_ResultOperationCompleted == null)) { + this.Select_DocumentReceptCord_ResultOperationCompleted = new System.Threading.SendOrPostCallback(this.OnSelect_DocumentReceptCord_ResultOperationCompleted); + } + this.InvokeAsync("Select_DocumentReceptCord_Result", new object[] { + DocumentNum, + PROCESS_GROUP_ID}, this.Select_DocumentReceptCord_ResultOperationCompleted, userState); + } + + private void OnSelect_DocumentReceptCord_ResultOperationCompleted(object arg) { + if ((this.Select_DocumentReceptCord_ResultCompleted != null)) { + System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); + this.Select_DocumentReceptCord_ResultCompleted(this, new Select_DocumentReceptCord_ResultCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); + } + } + + /// + [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/Web_OnePieceFlowModle_Judge", RequestNamespace="http://tempuri.org/", ResponseNamespace="http://tempuri.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] + public System.Data.DataTable Web_OnePieceFlowModle_Judge(string BarCode, string wkc) { + object[] results = this.Invoke("Web_OnePieceFlowModle_Judge", new object[] { + BarCode, + wkc}); + return ((System.Data.DataTable)(results[0])); + } + + /// + public void Web_OnePieceFlowModle_JudgeAsync(string BarCode, string wkc) { + this.Web_OnePieceFlowModle_JudgeAsync(BarCode, wkc, null); + } + + /// + public void Web_OnePieceFlowModle_JudgeAsync(string BarCode, string wkc, object userState) { + if ((this.Web_OnePieceFlowModle_JudgeOperationCompleted == null)) { + this.Web_OnePieceFlowModle_JudgeOperationCompleted = new System.Threading.SendOrPostCallback(this.OnWeb_OnePieceFlowModle_JudgeOperationCompleted); + } + this.InvokeAsync("Web_OnePieceFlowModle_Judge", new object[] { + BarCode, + wkc}, this.Web_OnePieceFlowModle_JudgeOperationCompleted, userState); + } + + private void OnWeb_OnePieceFlowModle_JudgeOperationCompleted(object arg) { + if ((this.Web_OnePieceFlowModle_JudgeCompleted != null)) { + System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); + this.Web_OnePieceFlowModle_JudgeCompleted(this, new Web_OnePieceFlowModle_JudgeCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); + } + } + + /// + [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/Web_OnePieceFlowModle_DetaileInfo", RequestNamespace="http://tempuri.org/", ResponseNamespace="http://tempuri.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] + public System.Data.DataTable Web_OnePieceFlowModle_DetaileInfo(string BarCode, string wkc) { + object[] results = this.Invoke("Web_OnePieceFlowModle_DetaileInfo", new object[] { + BarCode, + wkc}); + return ((System.Data.DataTable)(results[0])); + } + + /// + public void Web_OnePieceFlowModle_DetaileInfoAsync(string BarCode, string wkc) { + this.Web_OnePieceFlowModle_DetaileInfoAsync(BarCode, wkc, null); + } + + /// + public void Web_OnePieceFlowModle_DetaileInfoAsync(string BarCode, string wkc, object userState) { + if ((this.Web_OnePieceFlowModle_DetaileInfoOperationCompleted == null)) { + this.Web_OnePieceFlowModle_DetaileInfoOperationCompleted = new System.Threading.SendOrPostCallback(this.OnWeb_OnePieceFlowModle_DetaileInfoOperationCompleted); + } + this.InvokeAsync("Web_OnePieceFlowModle_DetaileInfo", new object[] { + BarCode, + wkc}, this.Web_OnePieceFlowModle_DetaileInfoOperationCompleted, userState); + } + + private void OnWeb_OnePieceFlowModle_DetaileInfoOperationCompleted(object arg) { + if ((this.Web_OnePieceFlowModle_DetaileInfoCompleted != null)) { + System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); + this.Web_OnePieceFlowModle_DetaileInfoCompleted(this, new Web_OnePieceFlowModle_DetaileInfoCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); + } + } + + /// + public new void CancelAsync(object userState) { + base.CancelAsync(userState); + } + + private bool IsLocalFileSystemWebService(string url) { + if (((url == null) + || (url == string.Empty))) { + return false; + } + System.Uri wsUri = new System.Uri(url); + if (((wsUri.Port >= 1024) + && (string.Compare(wsUri.Host, "localHost", System.StringComparison.OrdinalIgnoreCase) == 0))) { + return true; + } + return false; + } + } + + /// + [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.6.81.0")] + public delegate void HelloWorldCompletedEventHandler(object sender, HelloWorldCompletedEventArgs e); + + /// + [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.6.81.0")] + [System.Diagnostics.DebuggerStepThroughAttribute()] + [System.ComponentModel.DesignerCategoryAttribute("code")] + public partial class HelloWorldCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { + + private object[] results; + + internal HelloWorldCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : + base(exception, cancelled, userState) { + this.results = results; + } + + /// + public string Result { + get { + this.RaiseExceptionIfNecessary(); + return ((string)(this.results[0])); + } + } + } + + /// + [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.6.81.0")] + public delegate void Web_BarcodeReturn_Split_ExecCompletedEventHandler(object sender, Web_BarcodeReturn_Split_ExecCompletedEventArgs e); + + /// + [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.6.81.0")] + [System.Diagnostics.DebuggerStepThroughAttribute()] + [System.ComponentModel.DesignerCategoryAttribute("code")] + public partial class Web_BarcodeReturn_Split_ExecCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { + + private object[] results; + + internal Web_BarcodeReturn_Split_ExecCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : + base(exception, cancelled, userState) { + this.results = results; + } + + /// + public string Result { + get { + this.RaiseExceptionIfNecessary(); + return ((string)(this.results[0])); + } + } + } + + /// + [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.6.81.0")] + public delegate void Web_BarcodeReturn_Return_ExecCompletedEventHandler(object sender, Web_BarcodeReturn_Return_ExecCompletedEventArgs e); + + /// + [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.6.81.0")] + [System.Diagnostics.DebuggerStepThroughAttribute()] + [System.ComponentModel.DesignerCategoryAttribute("code")] + public partial class Web_BarcodeReturn_Return_ExecCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { + + private object[] results; + + internal Web_BarcodeReturn_Return_ExecCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : + base(exception, cancelled, userState) { + this.results = results; + } + + /// + public string Result { + get { + this.RaiseExceptionIfNecessary(); + return ((string)(this.results[0])); + } + } + } + + /// + [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.6.81.0")] + public delegate void Web_Barcode_Return_ReturnCancel_OracleCompletedEventHandler(object sender, Web_Barcode_Return_ReturnCancel_OracleCompletedEventArgs e); + + /// + [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.6.81.0")] + [System.Diagnostics.DebuggerStepThroughAttribute()] + [System.ComponentModel.DesignerCategoryAttribute("code")] + public partial class Web_Barcode_Return_ReturnCancel_OracleCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { + + private object[] results; + + internal Web_Barcode_Return_ReturnCancel_OracleCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : + base(exception, cancelled, userState) { + this.results = results; + } + + /// + public string Result { + get { + this.RaiseExceptionIfNecessary(); + return ((string)(this.results[0])); + } + } + } + + /// + [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.6.81.0")] + public delegate void Web_DirectUpload_Document_SelectCompletedEventHandler(object sender, Web_DirectUpload_Document_SelectCompletedEventArgs e); + + /// + [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.6.81.0")] + [System.Diagnostics.DebuggerStepThroughAttribute()] + [System.ComponentModel.DesignerCategoryAttribute("code")] + public partial class Web_DirectUpload_Document_SelectCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { + + private object[] results; + + internal Web_DirectUpload_Document_SelectCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : + base(exception, cancelled, userState) { + this.results = results; + } + + /// + public System.Data.DataSet Result { + get { + this.RaiseExceptionIfNecessary(); + return ((System.Data.DataSet)(this.results[0])); + } + } + } + + /// + [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.6.81.0")] + public delegate void Web_DirectUpload_Document_VerifyOKCompletedEventHandler(object sender, Web_DirectUpload_Document_VerifyOKCompletedEventArgs e); + + /// + [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.6.81.0")] + [System.Diagnostics.DebuggerStepThroughAttribute()] + [System.ComponentModel.DesignerCategoryAttribute("code")] + public partial class Web_DirectUpload_Document_VerifyOKCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { + + private object[] results; + + internal Web_DirectUpload_Document_VerifyOKCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : + base(exception, cancelled, userState) { + this.results = results; + } + + /// + public string Result { + get { + this.RaiseExceptionIfNecessary(); + return ((string)(this.results[0])); + } + } + } + + /// + [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.6.81.0")] + public delegate void CrrentOrderStateSelectCompletedEventHandler(object sender, CrrentOrderStateSelectCompletedEventArgs e); + + /// + [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.6.81.0")] + [System.Diagnostics.DebuggerStepThroughAttribute()] + [System.ComponentModel.DesignerCategoryAttribute("code")] + public partial class CrrentOrderStateSelectCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { + + private object[] results; + + internal CrrentOrderStateSelectCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : + base(exception, cancelled, userState) { + this.results = results; + } + + /// + public System.Data.DataTable Result { + get { + this.RaiseExceptionIfNecessary(); + return ((System.Data.DataTable)(this.results[0])); + } + } + } + + /// + [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.6.81.0")] + public delegate void Web_MaterialPull_AndonCall_VerifyOKCompletedEventHandler(object sender, Web_MaterialPull_AndonCall_VerifyOKCompletedEventArgs e); + + /// + [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.6.81.0")] + [System.Diagnostics.DebuggerStepThroughAttribute()] + [System.ComponentModel.DesignerCategoryAttribute("code")] + public partial class Web_MaterialPull_AndonCall_VerifyOKCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { + + private object[] results; + + internal Web_MaterialPull_AndonCall_VerifyOKCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : + base(exception, cancelled, userState) { + this.results = results; + } + + /// + public string Result { + get { + this.RaiseExceptionIfNecessary(); + return ((string)(this.results[0])); + } + } + } + + /// + [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.6.81.0")] + public delegate void Select_AndonCall_ResultCompletedEventHandler(object sender, Select_AndonCall_ResultCompletedEventArgs e); + + /// + [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.6.81.0")] + [System.Diagnostics.DebuggerStepThroughAttribute()] + [System.ComponentModel.DesignerCategoryAttribute("code")] + public partial class Select_AndonCall_ResultCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { + + private object[] results; + + internal Select_AndonCall_ResultCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : + base(exception, cancelled, userState) { + this.results = results; + } + + /// + public System.Data.DataTable Result { + get { + this.RaiseExceptionIfNecessary(); + return ((System.Data.DataTable)(this.results[0])); + } + } + } + + /// + [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.6.81.0")] + public delegate void Web_AndonPlanStop_Return_ExecCompletedEventHandler(object sender, Web_AndonPlanStop_Return_ExecCompletedEventArgs e); + + /// + [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.6.81.0")] + [System.Diagnostics.DebuggerStepThroughAttribute()] + [System.ComponentModel.DesignerCategoryAttribute("code")] + public partial class Web_AndonPlanStop_Return_ExecCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { + + private object[] results; + + internal Web_AndonPlanStop_Return_ExecCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : + base(exception, cancelled, userState) { + this.results = results; + } + + /// + public string Result { + get { + this.RaiseExceptionIfNecessary(); + return ((string)(this.results[0])); + } + } + } + + /// + [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.6.81.0")] + public delegate void Web_AndonPlanStopTypeCompletedEventHandler(object sender, Web_AndonPlanStopTypeCompletedEventArgs e); + + /// + [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.6.81.0")] + [System.Diagnostics.DebuggerStepThroughAttribute()] + [System.ComponentModel.DesignerCategoryAttribute("code")] + public partial class Web_AndonPlanStopTypeCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { + + private object[] results; + + internal Web_AndonPlanStopTypeCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : + base(exception, cancelled, userState) { + this.results = results; + } + + /// + public System.Data.DataTable Result { + get { + this.RaiseExceptionIfNecessary(); + return ((System.Data.DataTable)(this.results[0])); + } + } + } + + /// + [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.6.81.0")] + public delegate void Web_MaterialPull_DocumentNum_SelectCompletedEventHandler(object sender, Web_MaterialPull_DocumentNum_SelectCompletedEventArgs e); + + /// + [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.6.81.0")] + [System.Diagnostics.DebuggerStepThroughAttribute()] + [System.ComponentModel.DesignerCategoryAttribute("code")] + public partial class Web_MaterialPull_DocumentNum_SelectCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { + + private object[] results; + + internal Web_MaterialPull_DocumentNum_SelectCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : + base(exception, cancelled, userState) { + this.results = results; + } + + /// + public System.Data.DataSet Result { + get { + this.RaiseExceptionIfNecessary(); + return ((System.Data.DataSet)(this.results[0])); + } + } + } + + /// + [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.6.81.0")] + public delegate void Web_MaterialPull_DocumentNum_VerifyOKCompletedEventHandler(object sender, Web_MaterialPull_DocumentNum_VerifyOKCompletedEventArgs e); + + /// + [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.6.81.0")] + [System.Diagnostics.DebuggerStepThroughAttribute()] + [System.ComponentModel.DesignerCategoryAttribute("code")] + public partial class Web_MaterialPull_DocumentNum_VerifyOKCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { + + private object[] results; + + internal Web_MaterialPull_DocumentNum_VerifyOKCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : + base(exception, cancelled, userState) { + this.results = results; + } + + /// + public string Result { + get { + this.RaiseExceptionIfNecessary(); + return ((string)(this.results[0])); + } + } + } + + /// + [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.6.81.0")] + public delegate void Select_DocumentReceptCord_ResultCompletedEventHandler(object sender, Select_DocumentReceptCord_ResultCompletedEventArgs e); + + /// + [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.6.81.0")] + [System.Diagnostics.DebuggerStepThroughAttribute()] + [System.ComponentModel.DesignerCategoryAttribute("code")] + public partial class Select_DocumentReceptCord_ResultCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { + + private object[] results; + + internal Select_DocumentReceptCord_ResultCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : + base(exception, cancelled, userState) { + this.results = results; + } + + /// + public System.Data.DataSet Result { + get { + this.RaiseExceptionIfNecessary(); + return ((System.Data.DataSet)(this.results[0])); + } + } + } + + /// + [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.6.81.0")] + public delegate void Web_OnePieceFlowModle_JudgeCompletedEventHandler(object sender, Web_OnePieceFlowModle_JudgeCompletedEventArgs e); + + /// + [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.6.81.0")] + [System.Diagnostics.DebuggerStepThroughAttribute()] + [System.ComponentModel.DesignerCategoryAttribute("code")] + public partial class Web_OnePieceFlowModle_JudgeCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { + + private object[] results; + + internal Web_OnePieceFlowModle_JudgeCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : + base(exception, cancelled, userState) { + this.results = results; + } + + /// + public System.Data.DataTable Result { + get { + this.RaiseExceptionIfNecessary(); + return ((System.Data.DataTable)(this.results[0])); + } + } + } + + /// + [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.6.81.0")] + public delegate void Web_OnePieceFlowModle_DetaileInfoCompletedEventHandler(object sender, Web_OnePieceFlowModle_DetaileInfoCompletedEventArgs e); + + /// + [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.6.81.0")] + [System.Diagnostics.DebuggerStepThroughAttribute()] + [System.ComponentModel.DesignerCategoryAttribute("code")] + public partial class Web_OnePieceFlowModle_DetaileInfoCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { + + private object[] results; + + internal Web_OnePieceFlowModle_DetaileInfoCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : + base(exception, cancelled, userState) { + this.results = results; + } + + /// + public System.Data.DataTable Result { + get { + this.RaiseExceptionIfNecessary(); + return ((System.Data.DataTable)(this.results[0])); + } + } + } +} + +#pragma warning restore 1591 \ No newline at end of file diff --git a/Common/08WebFun_base/WebFun_base/SpecialFun/WebFunction01.cs b/Common/08WebFun_base/WebFun_base/SpecialFun/WebFunction01.cs new file mode 100644 index 0000000..a07d4d1 --- /dev/null +++ b/Common/08WebFun_base/WebFun_base/SpecialFun/WebFunction01.cs @@ -0,0 +1,475 @@ +using bizFacade; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Web; +//using SystemFramework; +using System.Data; +using System.Data.SqlClient; +using DataLinkMesWork; +namespace MesWebFun +{ + public class WebFunction01 + { + // HttpContext contextMesWebFun; + public string ProcessRequest(string cmd) + { + string responseText = ""; + switch (cmd) + { + ////保存手动生成条码 + //case "SavingEngineIDShift": + // responseText = SavingEngineIDShift(); + // break; + //case "SaveRepairStatus"://将返修路径及返修数据保存到数据库 + // responseText = SaveRepairStatus(); + // break; + //case "RepairStatusInit"://将返修路径及返修数据保存到数据库 + // responseText = RepairStatusInit(); + // break; + //case "Select_engineType_ByEnergineID": //根据发动机号显示机型 + // responseText = Select_engineType_ByEnergineID(); + // break; + //case "QualityDataButton_bgColor_Select_ByEnergineID": + // responseText = QualityDataButton_bgColor_Select_energineSelect(); + // break; + /////////////////////////质量查询根据发动机号 + //case "QualityDataSelectByEnergineID": + // responseText = QualityDataSelectByEnergineID(); + // break; + default: + responseText = "01"; + break; + } + return responseText; + } + /// + /// //根据发动机号显示机型,界面提示 + /// + /// + private string Select_engineType_ByEnergineID(string opName, string energineID) + { + string text = ""; + try + { + System.Data.DataTable dt = null; + //string energineID = HttpContext.Current.Request["energineID"];//发动机号 + GetEngineID_Select(energineID, opName, out dt); + + string engineType = ""; + if (dt != null) + { + if (dt.Rows.Count > 0) + { + engineType = dt.Rows[0]["发动机型号"].ToString(); + } + } + text = "{\"engineType\":\"" + engineType + "\"}"; + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, "MesWebFun08:Select_engineType_ByEnergineID"); + } + return text; + } + /// + /// 保存手动要求的条码 + /// + /// + private string SavingEngineIDShift(string opname, string date, string num) + { + string text = ""; + bool flag = false; + System.Data.DataTable dt = null; + try + { + //string date = HttpContext.Current.Request["date"];//日期 + //string num = HttpContext.Current.Request["num"];//流水号 + string[] dates = date.Split('-'); + if (dates.Length > 2) + { + int year = Convert.ToInt32(dates[0]); + int month = Convert.ToInt32(dates[1]); + int day = Convert.ToInt32(dates[2]); + int single = Convert.ToInt32(num); + MES.OpName_MIS_Manual_Insert(opname, year, month, day, single); + flag = true; + } + if (flag) + { + text = "{\"flag\":\"1\"}"; + } + else + { + text = "{\"flag\":\"0\"}"; + } + return text; + } + catch (Exception err) + { + text = "{\"flag\":\"0\"}"; + //ApplicationLog.WriteLog(err, "MesWebFun01:SavingEngineIDShift"); + return text; + } + } + + private static string RepairStatusInit(string Opname, string selectID) + { + //string selectID = HttpContext.Current.Request["text_selectByID"];//工位号 text_selectByID + string outtext = CreateRepairUpLine(Opname, selectID); + return outtext; + } + + + /// + /// 动态创建返修上线工位按钮 + /// + /// + /// + public static string CreateRepairUpLine(string OpName, string selectID) + { + StringBuilder HtmlStr = new StringBuilder();//可修改字符串 + + string BtnData = ""; + int RouteNum = 0; + bool HaveDataOrNot = false; + DataTable dt; + + string StationDataStr;//最近一条返修工位数据 + //查询返修上线字符串及路径数目 + RepairBtnDataSelect(OpName, out BtnData, out RouteNum); + string[] RepairSta = BtnData.Split('^');//目标工位数组 + string TargetStationData = "";//目标工位数据 + //查询之前的返修上线数据 + HaveDataOrNot = selectRepairStrSelect(OpName, selectID, out dt); + //合成界面显示按钮字符串 + if (HaveDataOrNot) + { + StationDataStr = dt.Rows[0]["返修字符串"].ToString(); + if (StationDataStr == "") + { + for (int i = 0; i < RepairSta.Length; i++) + { + if (i < (RepairSta.Length - 1)) + { + TargetStationData = TargetStationData + "1^"; + } + else + { + TargetStationData = TargetStationData + "1"; + } + } + } + else + { + TargetStationData = StationDataStr; + } + } + else + { + + for (int i = 0; i < RepairSta.Length; i++) + { + if (i < (RepairSta.Length - 1)) + { + TargetStationData = TargetStationData + "1^"; + } + else + { + TargetStationData = TargetStationData + "1"; + } + } + } + //页面定义 + HtmlStr.Append("\r\n"); + for (int i = 0; i < RepairSta.Length; i++) + { + //动态生成标签 + //样式定义 + string td_style = "width:20%;height:35px";//td样式 + string btn_style = "width:98%;height:98%;font-family:微软雅黑;font-size:15px;border-color: #99CCFF";//标签样式 + string type = "button"; + string tagID = "Btn_" + RepairSta[i]; + string value = RepairSta[i]; + string onclick = "RepairBtnClick(Btn_" + value + ")"; + string[] StationDataArray = TargetStationData.Split('^'); + string bgColor; + + if (StationDataArray[i] == "1") + { + bgColor = "background-color: green"; + } + else + { + bgColor = "background-color: gray"; + } + //保证每行5个按钮 + if (i < RepairSta.Length - 1) + { + if (i % 5 < 4) + { + HtmlStr.Append(""); + } + else + { + HtmlStr.Append(""); + HtmlStr.Append("\r\n"); + } + } + else + { + HtmlStr.Append(""); + HtmlStr.Append(""); + } + + } + HtmlStr.Append("
"); + //上线路径大于1条则显示上线路径 + if (RouteNum > 1) + { + + } + return HtmlStr.ToString(); + } + + + /// + /// 向数据库写入返修数据 + /// + /// + /// + /// + public static bool updateRepairStatusTo_SQL(string opname, string status) + { + string produceName = "测量数据_返修工位_工位状态_修改"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opname); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@返修状态", status); + + return DataAccess.ExecuteStoredProcedure(produceName, ref thisParms); + } + private static string SaveRepairStatus(string RepairStatus, string engineID, int RepairMethod, string engineType, string RepairOpName) + { + + try + { + //string RepairStatus = HttpContext.Current.Request["str_value"];//返修工位状态 + //string engineID = HttpContext.Current.Request["engineID"];//返修零件总成号 + //int RepairMethod = Convert.ToInt32(HttpContext.Current.Request["RepairMethod"]);//返修路径 + //string engineType = HttpContext.Current.Request["engineType"];//返修零件总成号 + //string RepairOpName = HttpContext.Current.Request["OpName"];//返修上线点 + string[] RepairStatusSplit = RepairStatus.Split('|'); + for (int i = 0; i < RepairStatusSplit.Length - 1; i++) + { + updateRepairStatusTo_SQL(RepairStatusSplit[i].Split('^')[0], RepairStatusSplit[i].Split('^')[1]); + } + + string produceName = "返修上线_返修工位及返修路径_增加"; + SqlParameter[] thisParms = new SqlParameter[5]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@总成编号", engineID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@返修状态", RepairStatus); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@返修路径", RepairMethod); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@发动机型号", engineType); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@返修上线点", RepairOpName); + string result = Convert.ToString(DataAccess.ExecuteStoredProcedure(produceName, ref thisParms)); + return result; + } + catch (Exception err) + { + return "0"; + } + + } + /// [电子看板_发动机号_线首工位_查询_根据发动机号] 20160728 majian + /// + /// + /// + static public bool GetEngineID_Select(string engineID, string opName, out DataTable dt) + { + string errorMessage = ""; + DataSet ds; + bool isOK; + dt = null; + //string connectionString = ApplicationConfig.ConnectionString; + string procedureName; + procedureName = "电子看板_发动机号_线首工位_查询_根据发动机号"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@发动机号", engineID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + isOK = DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out ds); + if (isOK) + { + if (ds.Tables.Count > 0) + { + dt = ds.Tables[0]; + return true; + } + else + { + return false; + } + } + else + { + return false; + } + } + private string QualityDataButton_bgColor_Select_energineSelect(string energineID, string opname) + { + string text = ""; + try + { + System.Data.DataTable dt = null; + //单号 + //string energineID = HttpContext.Current.Request["energineID"]; + QualityDataButton_bgColor_Select(opname, energineID, out dt);//此处重新写函数 + if (dt != null) + { + if (dt.Rows.Count >= 0) + { + text = Buttons.Createbuttons(dt); + } + } + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, "MesWebFun02:QualityDataButton_bgColor_Select"); + } + return text; + + } + /// WEB根据工位名称和发动机号查询质量数据合格索引(包括了分线的信息、存储过程中根据工位类型区分) 20140626 wt + /// + /// + /// + /// + /// + public static bool QualityDataButton_bgColor_Select(string opname, string energineID, out DataTable dt) + { + string procedureName = "显示测量数据_工位号_根据发动机型号_查询"; + SqlParameter[] sqlParameters = new SqlParameter[2]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", opname); + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@发动机号", energineID); + return DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + } + + + /// + /// 获取对应工位的质量数据 + /// + /// + private string QualityDataSelectByEnergineID(string energineID, string opname) + { + string qualitydata = ""; + try + { + System.Data.DataTable dt = null; + //string energineID = HttpContext.Current.Request["value"]; + QualityDataSelect(opname, energineID, out dt); + if (dt != null) + { + //if (dt.Rows.Count > 0) + { + qualitydata = JsonHelper.CreateJsonParameters(dt); + } + } + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, "MesWebFun10:QualityDataSelect"); + } + return qualitydata; + + } + + static public bool QualityDataSelect(string opname, string energineID, out DataTable dt) + { + string procedureName; + procedureName = "显示测量数据_根据_工位号_发动机型号_查询"; + SqlParameter[] sqlParameters = new SqlParameter[2]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", opname); + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@发动机号", energineID); + return DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + } + + /// + /// 查询返修上线工位及返修路径数目 + /// + /// + /// + /// + public static void RepairBtnDataSelect(string OpName, out string BtnData, out int RouteNum) + { + + DataTable dt; + string procedureName; + BtnData = ""; + RouteNum = 0; + procedureName = "返修上线_返修工位_返修上线点及返修路径_基础配置_查询"; + SqlParameter[] sqlParameters = new SqlParameter[1]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", OpName); + DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + if (dt != null) + { + if (dt.Rows.Count > 0) + { + BtnData = dt.Rows[0]["待返修工位"].ToString(); + RouteNum = Convert.ToInt32(dt.Rows[0]["返修路径数目"]); + } + } + } + + + /// + /// 查询当前上线点上次选择的返修工位,用于界面按钮颜色原始数据 + /// + /// + /// + /// + public static bool selectRepairData(string OpName, out DataTable dt) + { + + string procedureName; + procedureName = "返修上线_返修工位及返修路径_最近数据_查询"; + SqlParameter[] sqlParameters = new SqlParameter[1]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@返修上线点", OpName); + DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + if (dt.Rows.Count > 0) + { + return true; + } + else + { + + return false; + } + } + /// + /// + /// + /// + /// + /// + public static bool selectRepairStrSelect(string OpName, string selectID, out DataTable dt) + { + string procedureName; + procedureName = "返修上线_返修工位及返修路径_是否工作判断"; + SqlParameter[] sqlParameters = new SqlParameter[2]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@返修上线点", OpName); + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@发动机号", selectID); + DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + if (dt.Rows.Count > 0) + { + return true; + } + else + { + + return false; + } + + } + } +} diff --git a/Common/08WebFun_base/WebFun_base/SpecialFun/WebFunction02.cs b/Common/08WebFun_base/WebFun_base/SpecialFun/WebFunction02.cs new file mode 100644 index 0000000..45ac8bf --- /dev/null +++ b/Common/08WebFun_base/WebFun_base/SpecialFun/WebFunction02.cs @@ -0,0 +1,489 @@ +using DataLinkMesWork; +using bizFacade; +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.SqlClient; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Web; +//using SystemFramework; + +namespace MesWebFun +{ + public class WebFunction02 + { + HttpContext contextMesWebFun; + public string ProcessRequest(HttpContext context) + { + contextMesWebFun = context; ; + context.Response.ContentType = "text/plain"; + string type = contextMesWebFun.Request["type"]; + string responseText = ""; + switch (type) + { + //托盘信息 + case "MobySelect": + // responseText = MobySelect(); + break; + //保存手动生成条码 + case "SavingEngineIDShift": + responseText = SavingEngineIDShift(); + break; + case "SaveRepairStatus"://将返修路径及返修数据保存到数据库 + responseText = SaveRepairStatus(); + break; + case "RepairStatusInit"://将返修路径及返修数据保存到数据库 + responseText = RepairStatusInit(); + break; + case "Select_engineType_ByEnergineID": //根据发动机号显示机型 + responseText = Select_engineType_ByEnergineID(); + break; + case "QualityDataButton_bgColor_Select_ByEnergineID": + responseText = QualityDataButton_bgColor_Select_energineSelect(); + break; + ///////////////////////质量查询根据发动机号 + case "QualityDataSelectByEnergineID": + responseText = QualityDataSelectByEnergineID(); + break; + default: + responseText = "02"; + break; + } + return responseText; + } + /// + /// //根据发动机号显示机型,界面提示 + /// + /// + private string Select_engineType_ByEnergineID() + { + string text = ""; + try + { + System.Data.DataTable dt = null; + string opName = HttpContext.Current.Request["value"];//发动机号 + string energineID = HttpContext.Current.Request["energineID"];//发动机号 + GetEngineID_Select(energineID, opName, out dt); + + string engineType = ""; + if (dt != null) + { + if (dt.Rows.Count > 0) + { + engineType = dt.Rows[0]["发动机型号"].ToString(); + } + } + text = "{\"engineType\":\"" + engineType + "\"}"; + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, "MesWebFun08:Select_engineType_ByEnergineID"); + } + return text; + } + /// + /// 保存手动要求的条码 + /// + /// + private string SavingEngineIDShift() + { + string text = ""; + bool flag = false; + System.Data.DataTable dt = null; + try + { + string opname = HttpContext.Current.Request["value"];//工位号 + string date = HttpContext.Current.Request["date"];//日期 + string num = HttpContext.Current.Request["num"];//流水号 + string[] dates = date.Split('-'); + if (dates.Length > 2) + { + int year = Convert.ToInt32(dates[0]); + int month = Convert.ToInt32(dates[1]); + int day = Convert.ToInt32(dates[2]); + int single = Convert.ToInt32(num); + MES.OpName_MIS_Manual_Insert(opname, year, month, day, single); + flag = true; + } + if (flag) + { + text = "{\"flag\":\"1\"}"; + } + else + { + text = "{\"flag\":\"0\"}"; + } + return text; + } + catch (Exception err) + { + text = "{\"flag\":\"0\"}"; + //ApplicationLog.WriteLog(err, "MesWebFun01:SavingEngineIDShift"); + return text; + } + } + + private static string RepairStatusInit() + { + string Opname = HttpContext.Current.Request["value"];//工位号 + string selectID = HttpContext.Current.Request["text_selectByID"];//工位号 text_selectByID + string outtext = CreateRepairUpLine(Opname, selectID); + return outtext; + } + + + /// + /// 动态创建返修上线工位按钮 + /// + /// + /// + public static string CreateRepairUpLine(string OpName, string selectID) + { + StringBuilder HtmlStr = new StringBuilder();//可修改字符串 + + string BtnData = ""; + int RouteNum = 0; + bool HaveDataOrNot = false; + DataTable dt; + + string StationDataStr;//最近一条返修工位数据 + //查询返修上线字符串及路径数目 + RepairBtnDataSelect(OpName, out BtnData, out RouteNum); + string[] RepairSta = BtnData.Split('^');//目标工位数组 + string TargetStationData = "";//目标工位数据 + //查询之前的返修上线数据 + HaveDataOrNot = selectRepairStrSelect(OpName, selectID, out dt); + //合成界面显示按钮字符串 + if (HaveDataOrNot) + { + StationDataStr = dt.Rows[0]["返修字符串"].ToString(); + if (StationDataStr == "") + { + for (int i = 0; i < RepairSta.Length; i++) + { + if (i < (RepairSta.Length - 1)) + { + TargetStationData = TargetStationData + "1^"; + } + else + { + TargetStationData = TargetStationData + "1"; + } + } + } + else + { + TargetStationData = StationDataStr; + } + } + else + { + + for (int i = 0; i < RepairSta.Length; i++) + { + if (i < (RepairSta.Length - 1)) + { + TargetStationData = TargetStationData + "1^"; + } + else + { + TargetStationData = TargetStationData + "1"; + } + } + } + //页面定义 + HtmlStr.Append("\r\n"); + for (int i = 0; i < RepairSta.Length; i++) + { + //动态生成标签 + //样式定义 + string td_style = "width:20%;height:35px";//td样式 + string btn_style = "width:98%;height:98%;font-family:微软雅黑;font-size:15px;border-color: #99CCFF";//标签样式 + string type = "button"; + string tagID = "Btn_" + RepairSta[i]; + string value = RepairSta[i]; + string onclick = "RepairBtnClick(Btn_" + value + ")"; + string[] StationDataArray = TargetStationData.Split('^'); + string bgColor; + + if (StationDataArray[i] == "1") + { + bgColor = "background-color: green"; + } + else + { + bgColor = "background-color: gray"; + } + //保证每行5个按钮 + if (i < RepairSta.Length - 1) + { + if (i % 5 < 4) + { + HtmlStr.Append(""); + } + else + { + HtmlStr.Append(""); + HtmlStr.Append("\r\n"); + } + } + else + { + HtmlStr.Append(""); + HtmlStr.Append(""); + } + + } + HtmlStr.Append("
"); + //上线路径大于1条则显示上线路径 + if (RouteNum > 1) + { + + } + return HtmlStr.ToString(); + } + + + /// + /// 向数据库写入返修数据 + /// + /// + /// + /// + public static bool updateRepairStatusTo_SQL(string opname, string status) + { + string produceName = "测量数据_返修工位_工位状态_修改"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opname); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@返修状态", status); + + return DataAccess.ExecuteStoredProcedure(produceName, ref thisParms); + } + private static string SaveRepairStatus() + { + + try + { + string RepairStatus = HttpContext.Current.Request["str_value"];//返修工位状态 + string engineID = HttpContext.Current.Request["engineID"];//返修零件总成号 + int RepairMethod = Convert.ToInt32(HttpContext.Current.Request["RepairMethod"]);//返修路径 + string engineType = HttpContext.Current.Request["engineType"];//返修零件总成号 + string RepairOpName = HttpContext.Current.Request["OpName"];//返修上线点 + string[] RepairStatusSplit = RepairStatus.Split('|'); + for (int i = 0; i < RepairStatusSplit.Length - 1; i++) + { + updateRepairStatusTo_SQL(RepairStatusSplit[i].Split('^')[0], RepairStatusSplit[i].Split('^')[1]); + } + + string produceName = "返修上线_返修工位及返修路径_增加"; + SqlParameter[] thisParms = new SqlParameter[5]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@总成编号", engineID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@返修状态", RepairStatus); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@返修路径", RepairMethod); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@发动机型号", engineType); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@返修上线点", RepairOpName); + string result = Convert.ToString(DataAccess.ExecuteStoredProcedure(produceName, ref thisParms)); + return result; + } + catch (Exception err) + { + return "0"; + } + + } + /// [电子看板_发动机号_线首工位_查询_根据发动机号] 20160728 majian + /// + /// + /// + static public bool GetEngineID_Select(string engineID, string opName, out DataTable dt) + { + string errorMessage = ""; + DataSet ds; + bool isOK; + dt = null; + //string connectionString = ApplicationConfig.ConnectionString; + string procedureName; + procedureName = "电子看板_发动机号_线首工位_查询_根据发动机号"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@发动机号", engineID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + isOK = DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out ds); + if (isOK) + { + if (ds.Tables.Count > 0) + { + dt = ds.Tables[0]; + return true; + } + else + { + return false; + } + } + else + { + return false; + } + } + private string QualityDataButton_bgColor_Select_energineSelect() + { + string text = ""; + try + { + System.Data.DataTable dt = null; + //单号 + string energineID = HttpContext.Current.Request["energineID"]; + string opname = HttpContext.Current.Request["value"]; + QualityDataButton_bgColor_Select(opname, energineID, out dt);//此处重新写函数 + if (dt != null) + { + if (dt.Rows.Count >= 0) + { + text = Buttons.Createbuttons(dt); + } + } + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, "MesWebFun02:QualityDataButton_bgColor_Select"); + } + return text; + + } + /// WEB根据工位名称和发动机号查询质量数据合格索引(包括了分线的信息、存储过程中根据工位类型区分) 20140626 wt + /// + /// + /// + /// + /// + public static bool QualityDataButton_bgColor_Select(string opname, string energineID, out DataTable dt) + { + string procedureName = "显示测量数据_工位号_根据发动机型号_查询"; + SqlParameter[] sqlParameters = new SqlParameter[2]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", opname); + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@发动机号", energineID); + return DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + } + + + /// + /// 获取对应工位的质量数据 + /// + /// + private string QualityDataSelectByEnergineID() + { + string qualitydata = ""; + try + { + System.Data.DataTable dt = null; + string energineID = HttpContext.Current.Request["value"]; + string opname = HttpContext.Current.Request["opname"]; + QualityDataSelect(opname, energineID, out dt); + if (dt != null) + { + //if (dt.Rows.Count > 0) + { + qualitydata = JsonHelper.CreateJsonParameters(dt); + } + } + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, "MesWebFun10:QualityDataSelect"); + } + return qualitydata; + + } + + static public bool QualityDataSelect(string opname, string energineID, out DataTable dt) + { + string procedureName; + procedureName = "显示测量数据_根据_工位号_发动机型号_查询"; + SqlParameter[] sqlParameters = new SqlParameter[2]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", opname); + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@发动机号", energineID); + return DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + } + + /// + /// 查询返修上线工位及返修路径数目 + /// + /// + /// + /// + public static void RepairBtnDataSelect(string OpName, out string BtnData, out int RouteNum) + { + + DataTable dt; + string procedureName; + BtnData = ""; + RouteNum = 0; + procedureName = "返修上线_返修工位_返修上线点及返修路径_基础配置_查询"; + SqlParameter[] sqlParameters = new SqlParameter[1]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", OpName); + DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + if (dt != null) + { + if (dt.Rows.Count > 0) + { + BtnData = dt.Rows[0]["待返修工位"].ToString(); + RouteNum = Convert.ToInt32(dt.Rows[0]["返修路径数目"]); + } + } + } + + + /// + /// 查询当前上线点上次选择的返修工位,用于界面按钮颜色原始数据 + /// + /// + /// + /// + public static bool selectRepairData(string OpName, out DataTable dt) + { + + string procedureName; + procedureName = "返修上线_返修工位及返修路径_最近数据_查询"; + SqlParameter[] sqlParameters = new SqlParameter[1]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@返修上线点", OpName); + DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + if (dt.Rows.Count > 0) + { + return true; + } + else + { + + return false; + } + } + /// + /// + /// + /// + /// + /// + public static bool selectRepairStrSelect(string OpName, string selectID, out DataTable dt) + { + string procedureName; + procedureName = "返修上线_返修工位及返修路径_是否工作判断"; + SqlParameter[] sqlParameters = new SqlParameter[2]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@返修上线点", OpName); + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@发动机号", selectID); + DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + if (dt.Rows.Count > 0) + { + return true; + } + else + { + + return false; + } + + } + + } +} diff --git a/Common/08WebFun_base/WebFun_base/SpecialFun/WebFunction04.cs b/Common/08WebFun_base/WebFun_base/SpecialFun/WebFunction04.cs new file mode 100644 index 0000000..b9f3728 --- /dev/null +++ b/Common/08WebFun_base/WebFun_base/SpecialFun/WebFunction04.cs @@ -0,0 +1,491 @@ +using DataLinkMesWork; +using bizFacade; +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.SqlClient; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Web; +//using SystemFramework; + +namespace MesWebFun +{ + public class WebFunction04 + { + HttpContext contextMesWebFun; + public string ProcessRequest(HttpContext context) + { + contextMesWebFun = context; ; + context.Response.ContentType = "text/plain"; + string type = contextMesWebFun.Request["type"]; + string responseText = ""; + switch (type) + { + //托盘信息 + case "MobySelect": + // responseText = MobySelect(); + break; + //保存手动生成条码 + case "SavingEngineIDShift": + responseText = SavingEngineIDShift(); + break; + case "SaveRepairStatus"://将返修路径及返修数据保存到数据库 + responseText = SaveRepairStatus(); + break; + case "RepairStatusInit"://将返修路径及返修数据保存到数据库 + responseText = RepairStatusInit(); + break; + case "Select_engineType_ByEnergineID": //根据发动机号显示机型 + responseText = Select_engineType_ByEnergineID(); + break; + case "QualityDataButton_bgColor_Select_ByEnergineID": + responseText = QualityDataButton_bgColor_Select_energineSelect(); + break; + ///////////////////////质量查询根据发动机号 + case "QualityDataSelectByEnergineID": + responseText = QualityDataSelectByEnergineID(); + break; + default: + responseText = "04"; + break; + + + } + return responseText; + } + /// + /// //根据发动机号显示机型,界面提示 + /// + /// + private string Select_engineType_ByEnergineID() + { + string text = ""; + try + { + System.Data.DataTable dt = null; + string opName = HttpContext.Current.Request["value"];//发动机号 + string energineID = HttpContext.Current.Request["energineID"];//发动机号 + GetEngineID_Select(energineID, opName, out dt); + + string engineType = ""; + if (dt != null) + { + if (dt.Rows.Count > 0) + { + engineType = dt.Rows[0]["发动机型号"].ToString(); + } + } + text = "{\"engineType\":\"" + engineType + "\"}"; + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, "MesWebFun08:Select_engineType_ByEnergineID"); + } + return text; + } + /// + /// 保存手动要求的条码 + /// + /// + private string SavingEngineIDShift() + { + string text = ""; + bool flag = false; + System.Data.DataTable dt = null; + try + { + string opname = HttpContext.Current.Request["value"];//工位号 + string date = HttpContext.Current.Request["date"];//日期 + string num = HttpContext.Current.Request["num"];//流水号 + string[] dates = date.Split('-'); + if (dates.Length > 2) + { + int year = Convert.ToInt32(dates[0]); + int month = Convert.ToInt32(dates[1]); + int day = Convert.ToInt32(dates[2]); + int single = Convert.ToInt32(num); + MES.OpName_MIS_Manual_Insert(opname, year, month, day, single); + flag = true; + } + if (flag) + { + text = "{\"flag\":\"1\"}"; + } + else + { + text = "{\"flag\":\"0\"}"; + } + return text; + } + catch (Exception err) + { + text = "{\"flag\":\"0\"}"; + //ApplicationLog.WriteLog(err, "MesWebFun01:SavingEngineIDShift"); + return text; + } + } + + private static string RepairStatusInit() + { + string Opname = HttpContext.Current.Request["value"];//工位号 + string selectID = HttpContext.Current.Request["text_selectByID"];//工位号 text_selectByID + string outtext = CreateRepairUpLine(Opname, selectID); + return outtext; + } + + + /// + /// 动态创建返修上线工位按钮 + /// + /// + /// + public static string CreateRepairUpLine(string OpName, string selectID) + { + StringBuilder HtmlStr = new StringBuilder();//可修改字符串 + + string BtnData = ""; + int RouteNum = 0; + bool HaveDataOrNot = false; + DataTable dt; + + string StationDataStr;//最近一条返修工位数据 + //查询返修上线字符串及路径数目 + RepairBtnDataSelect(OpName, out BtnData, out RouteNum); + string[] RepairSta = BtnData.Split('^');//目标工位数组 + string TargetStationData = "";//目标工位数据 + //查询之前的返修上线数据 + HaveDataOrNot = selectRepairStrSelect(OpName, selectID, out dt); + //合成界面显示按钮字符串 + if (HaveDataOrNot) + { + StationDataStr = dt.Rows[0]["返修字符串"].ToString(); + if (StationDataStr == "") + { + for (int i = 0; i < RepairSta.Length; i++) + { + if (i < (RepairSta.Length - 1)) + { + TargetStationData = TargetStationData + "1^"; + } + else + { + TargetStationData = TargetStationData + "1"; + } + } + } + else + { + TargetStationData = StationDataStr; + } + } + else + { + + for (int i = 0; i < RepairSta.Length; i++) + { + if (i < (RepairSta.Length - 1)) + { + TargetStationData = TargetStationData + "1^"; + } + else + { + TargetStationData = TargetStationData + "1"; + } + } + } + //页面定义 + HtmlStr.Append("\r\n"); + for (int i = 0; i < RepairSta.Length; i++) + { + //动态生成标签 + //样式定义 + string td_style = "width:20%;height:35px";//td样式 + string btn_style = "width:98%;height:98%;font-family:微软雅黑;font-size:15px;border-color: #99CCFF";//标签样式 + string type = "button"; + string tagID = "Btn_" + RepairSta[i]; + string value = RepairSta[i]; + string onclick = "RepairBtnClick(Btn_" + value + ")"; + string[] StationDataArray = TargetStationData.Split('^'); + string bgColor; + + if (StationDataArray[i] == "1") + { + bgColor = "background-color: green"; + } + else + { + bgColor = "background-color: gray"; + } + //保证每行5个按钮 + if (i < RepairSta.Length - 1) + { + if (i % 5 < 4) + { + HtmlStr.Append(""); + } + else + { + HtmlStr.Append(""); + HtmlStr.Append("\r\n"); + } + } + else + { + HtmlStr.Append(""); + HtmlStr.Append(""); + } + + } + HtmlStr.Append("
"); + //上线路径大于1条则显示上线路径 + if (RouteNum > 1) + { + + } + return HtmlStr.ToString(); + } + + + /// + /// 向数据库写入返修数据 + /// + /// + /// + /// + public static bool updateRepairStatusTo_SQL(string opname, string status) + { + string produceName = "测量数据_返修工位_工位状态_修改"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opname); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@返修状态", status); + + return DataAccess.ExecuteStoredProcedure(produceName, ref thisParms); + } + private static string SaveRepairStatus() + { + + try + { + string RepairStatus = HttpContext.Current.Request["str_value"];//返修工位状态 + string engineID = HttpContext.Current.Request["engineID"];//返修零件总成号 + int RepairMethod = Convert.ToInt32(HttpContext.Current.Request["RepairMethod"]);//返修路径 + string engineType = HttpContext.Current.Request["engineType"];//返修零件总成号 + string RepairOpName = HttpContext.Current.Request["OpName"];//返修上线点 + string[] RepairStatusSplit = RepairStatus.Split('|'); + for (int i = 0; i < RepairStatusSplit.Length - 1; i++) + { + updateRepairStatusTo_SQL(RepairStatusSplit[i].Split('^')[0], RepairStatusSplit[i].Split('^')[1]); + } + + string produceName = "返修上线_返修工位及返修路径_增加"; + SqlParameter[] thisParms = new SqlParameter[5]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@总成编号", engineID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@返修状态", RepairStatus); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@返修路径", RepairMethod); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@发动机型号", engineType); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@返修上线点", RepairOpName); + string result = Convert.ToString(DataAccess.ExecuteStoredProcedure(produceName, ref thisParms)); + return result; + } + catch (Exception err) + { + return "0"; + } + + } + /// [电子看板_发动机号_线首工位_查询_根据发动机号] 20160728 majian + /// + /// + /// + static public bool GetEngineID_Select(string engineID, string opName, out DataTable dt) + { + string errorMessage = ""; + DataSet ds; + bool isOK; + dt = null; + //string connectionString = ApplicationConfig.ConnectionString; + string procedureName; + procedureName = "电子看板_发动机号_线首工位_查询_根据发动机号"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@发动机号", engineID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + isOK = DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out ds); + if (isOK) + { + if (ds.Tables.Count > 0) + { + dt = ds.Tables[0]; + return true; + } + else + { + return false; + } + } + else + { + return false; + } + } + private string QualityDataButton_bgColor_Select_energineSelect() + { + string text = ""; + try + { + System.Data.DataTable dt = null; + //单号 + string energineID = HttpContext.Current.Request["energineID"]; + string opname = HttpContext.Current.Request["value"]; + QualityDataButton_bgColor_Select(opname, energineID, out dt);//此处重新写函数 + if (dt != null) + { + if (dt.Rows.Count >= 0) + { + text = Buttons.Createbuttons(dt); + } + } + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, "MesWebFun02:QualityDataButton_bgColor_Select"); + } + return text; + + } + /// WEB根据工位名称和发动机号查询质量数据合格索引(包括了分线的信息、存储过程中根据工位类型区分) 20140626 wt + /// + /// + /// + /// + /// + public static bool QualityDataButton_bgColor_Select(string opname, string energineID, out DataTable dt) + { + string procedureName = "显示测量数据_工位号_根据发动机型号_查询"; + SqlParameter[] sqlParameters = new SqlParameter[2]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", opname); + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@发动机号", energineID); + return DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + } + + + /// + /// 获取对应工位的质量数据 + /// + /// + private string QualityDataSelectByEnergineID() + { + string qualitydata = ""; + try + { + System.Data.DataTable dt = null; + string energineID = HttpContext.Current.Request["value"]; + string opname = HttpContext.Current.Request["opname"]; + QualityDataSelect(opname, energineID, out dt); + if (dt != null) + { + //if (dt.Rows.Count > 0) + { + qualitydata = JsonHelper.CreateJsonParameters(dt); + } + } + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, "MesWebFun10:QualityDataSelect"); + } + return qualitydata; + + } + + static public bool QualityDataSelect(string opname, string energineID, out DataTable dt) + { + string procedureName; + procedureName = "显示测量数据_根据_工位号_发动机型号_查询"; + SqlParameter[] sqlParameters = new SqlParameter[2]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", opname); + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@发动机号", energineID); + return DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + } + + /// + /// 查询返修上线工位及返修路径数目 + /// + /// + /// + /// + public static void RepairBtnDataSelect(string OpName, out string BtnData, out int RouteNum) + { + + DataTable dt; + string procedureName; + BtnData = ""; + RouteNum = 0; + procedureName = "返修上线_返修工位_返修上线点及返修路径_基础配置_查询"; + SqlParameter[] sqlParameters = new SqlParameter[1]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", OpName); + DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + if (dt != null) + { + if (dt.Rows.Count > 0) + { + BtnData = dt.Rows[0]["待返修工位"].ToString(); + RouteNum = Convert.ToInt32(dt.Rows[0]["返修路径数目"]); + } + } + } + + + /// + /// 查询当前上线点上次选择的返修工位,用于界面按钮颜色原始数据 + /// + /// + /// + /// + public static bool selectRepairData(string OpName, out DataTable dt) + { + + string procedureName; + procedureName = "返修上线_返修工位及返修路径_最近数据_查询"; + SqlParameter[] sqlParameters = new SqlParameter[1]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@返修上线点", OpName); + DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + if (dt.Rows.Count > 0) + { + return true; + } + else + { + + return false; + } + } + /// + /// + /// + /// + /// + /// + public static bool selectRepairStrSelect(string OpName, string selectID, out DataTable dt) + { + string procedureName; + procedureName = "返修上线_返修工位及返修路径_是否工作判断"; + SqlParameter[] sqlParameters = new SqlParameter[2]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@返修上线点", OpName); + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@发动机号", selectID); + DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + if (dt.Rows.Count > 0) + { + return true; + } + else + { + + return false; + } + + } + + } +} diff --git a/Common/08WebFun_base/WebFun_base/SpecialFun/WebFunction05.cs b/Common/08WebFun_base/WebFun_base/SpecialFun/WebFunction05.cs new file mode 100644 index 0000000..c9d972c --- /dev/null +++ b/Common/08WebFun_base/WebFun_base/SpecialFun/WebFunction05.cs @@ -0,0 +1,491 @@ +using DataLinkMesWork; +using bizFacade; +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.SqlClient; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Web; +//using SystemFramework; + +namespace MesWebFun +{ + public class WebFunction05 + { + HttpContext contextMesWebFun; + public string ProcessRequest(HttpContext context) + { + contextMesWebFun = context; ; + context.Response.ContentType = "text/plain"; + string type = contextMesWebFun.Request["type"]; + string responseText = ""; + switch (type) + { + //托盘信息 + case "MobySelect": + // responseText = MobySelect(); + break; + //保存手动生成条码 + case "SavingEngineIDShift": + responseText = SavingEngineIDShift(); + break; + case "SaveRepairStatus"://将返修路径及返修数据保存到数据库 + responseText = SaveRepairStatus(); + break; + case "RepairStatusInit"://将返修路径及返修数据保存到数据库 + responseText = RepairStatusInit(); + break; + case "Select_engineType_ByEnergineID": //根据发动机号显示机型 + responseText = Select_engineType_ByEnergineID(); + break; + case "QualityDataButton_bgColor_Select_ByEnergineID": + responseText = QualityDataButton_bgColor_Select_energineSelect(); + break; + ///////////////////////质量查询根据发动机号 + case "QualityDataSelectByEnergineID": + responseText = QualityDataSelectByEnergineID(); + break; + default: + responseText = "05"; + break; + + + } + return responseText; + } + /// + /// //根据发动机号显示机型,界面提示 + /// + /// + private string Select_engineType_ByEnergineID() + { + string text = ""; + try + { + System.Data.DataTable dt = null; + string opName = HttpContext.Current.Request["value"];//发动机号 + string energineID = HttpContext.Current.Request["energineID"];//发动机号 + GetEngineID_Select(energineID, opName, out dt); + + string engineType = ""; + if (dt != null) + { + if (dt.Rows.Count > 0) + { + engineType = dt.Rows[0]["发动机型号"].ToString(); + } + } + text = "{\"engineType\":\"" + engineType + "\"}"; + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, "MesWebFun08:Select_engineType_ByEnergineID"); + } + return text; + } + /// + /// 保存手动要求的条码 + /// + /// + private string SavingEngineIDShift() + { + string text = ""; + bool flag = false; + System.Data.DataTable dt = null; + try + { + string opname = HttpContext.Current.Request["value"];//工位号 + string date = HttpContext.Current.Request["date"];//日期 + string num = HttpContext.Current.Request["num"];//流水号 + string[] dates = date.Split('-'); + if (dates.Length > 2) + { + int year = Convert.ToInt32(dates[0]); + int month = Convert.ToInt32(dates[1]); + int day = Convert.ToInt32(dates[2]); + int single = Convert.ToInt32(num); + MES.OpName_MIS_Manual_Insert(opname, year, month, day, single); + flag = true; + } + if (flag) + { + text = "{\"flag\":\"1\"}"; + } + else + { + text = "{\"flag\":\"0\"}"; + } + return text; + } + catch (Exception err) + { + text = "{\"flag\":\"0\"}"; + //ApplicationLog.WriteLog(err, "MesWebFun01:SavingEngineIDShift"); + return text; + } + } + + private static string RepairStatusInit() + { + string Opname = HttpContext.Current.Request["value"];//工位号 + string selectID = HttpContext.Current.Request["text_selectByID"];//工位号 text_selectByID + string outtext = CreateRepairUpLine(Opname, selectID); + return outtext; + } + + + /// + /// 动态创建返修上线工位按钮 + /// + /// + /// + public static string CreateRepairUpLine(string OpName, string selectID) + { + StringBuilder HtmlStr = new StringBuilder();//可修改字符串 + + string BtnData = ""; + int RouteNum = 0; + bool HaveDataOrNot = false; + DataTable dt; + + string StationDataStr;//最近一条返修工位数据 + //查询返修上线字符串及路径数目 + RepairBtnDataSelect(OpName, out BtnData, out RouteNum); + string[] RepairSta = BtnData.Split('^');//目标工位数组 + string TargetStationData = "";//目标工位数据 + //查询之前的返修上线数据 + HaveDataOrNot = selectRepairStrSelect(OpName, selectID, out dt); + //合成界面显示按钮字符串 + if (HaveDataOrNot) + { + StationDataStr = dt.Rows[0]["返修字符串"].ToString(); + if (StationDataStr == "") + { + for (int i = 0; i < RepairSta.Length; i++) + { + if (i < (RepairSta.Length - 1)) + { + TargetStationData = TargetStationData + "1^"; + } + else + { + TargetStationData = TargetStationData + "1"; + } + } + } + else + { + TargetStationData = StationDataStr; + } + } + else + { + + for (int i = 0; i < RepairSta.Length; i++) + { + if (i < (RepairSta.Length - 1)) + { + TargetStationData = TargetStationData + "1^"; + } + else + { + TargetStationData = TargetStationData + "1"; + } + } + } + //页面定义 + HtmlStr.Append("\r\n"); + for (int i = 0; i < RepairSta.Length; i++) + { + //动态生成标签 + //样式定义 + string td_style = "width:20%;height:35px";//td样式 + string btn_style = "width:98%;height:98%;font-family:微软雅黑;font-size:15px;border-color: #99CCFF";//标签样式 + string type = "button"; + string tagID = "Btn_" + RepairSta[i]; + string value = RepairSta[i]; + string onclick = "RepairBtnClick(Btn_" + value + ")"; + string[] StationDataArray = TargetStationData.Split('^'); + string bgColor; + + if (StationDataArray[i] == "1") + { + bgColor = "background-color: green"; + } + else + { + bgColor = "background-color: gray"; + } + //保证每行5个按钮 + if (i < RepairSta.Length - 1) + { + if (i % 5 < 4) + { + HtmlStr.Append(""); + } + else + { + HtmlStr.Append(""); + HtmlStr.Append("\r\n"); + } + } + else + { + HtmlStr.Append(""); + HtmlStr.Append(""); + } + + } + HtmlStr.Append("
"); + //上线路径大于1条则显示上线路径 + if (RouteNum > 1) + { + + } + return HtmlStr.ToString(); + } + + + /// + /// 向数据库写入返修数据 + /// + /// + /// + /// + public static bool updateRepairStatusTo_SQL(string opname, string status) + { + string produceName = "测量数据_返修工位_工位状态_修改"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opname); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@返修状态", status); + + return DataAccess.ExecuteStoredProcedure(produceName, ref thisParms); + } + private static string SaveRepairStatus() + { + + try + { + string RepairStatus = HttpContext.Current.Request["str_value"];//返修工位状态 + string engineID = HttpContext.Current.Request["engineID"];//返修零件总成号 + int RepairMethod = Convert.ToInt32(HttpContext.Current.Request["RepairMethod"]);//返修路径 + string engineType = HttpContext.Current.Request["engineType"];//返修零件总成号 + string RepairOpName = HttpContext.Current.Request["OpName"];//返修上线点 + string[] RepairStatusSplit = RepairStatus.Split('|'); + for (int i = 0; i < RepairStatusSplit.Length - 1; i++) + { + updateRepairStatusTo_SQL(RepairStatusSplit[i].Split('^')[0], RepairStatusSplit[i].Split('^')[1]); + } + + string produceName = "返修上线_返修工位及返修路径_增加"; + SqlParameter[] thisParms = new SqlParameter[5]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@总成编号", engineID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@返修状态", RepairStatus); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@返修路径", RepairMethod); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@发动机型号", engineType); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@返修上线点", RepairOpName); + string result = Convert.ToString(DataAccess.ExecuteStoredProcedure(produceName, ref thisParms)); + return result; + } + catch (Exception err) + { + return "0"; + } + + } + /// [电子看板_发动机号_线首工位_查询_根据发动机号] 20160728 majian + /// + /// + /// + static public bool GetEngineID_Select(string engineID, string opName, out DataTable dt) + { + string errorMessage = ""; + DataSet ds; + bool isOK; + dt = null; + //string connectionString = ApplicationConfig.ConnectionString; + string procedureName; + procedureName = "电子看板_发动机号_线首工位_查询_根据发动机号"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@发动机号", engineID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + isOK = DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out ds); + if (isOK) + { + if (ds.Tables.Count > 0) + { + dt = ds.Tables[0]; + return true; + } + else + { + return false; + } + } + else + { + return false; + } + } + private string QualityDataButton_bgColor_Select_energineSelect() + { + string text = ""; + try + { + System.Data.DataTable dt = null; + //单号 + string energineID = HttpContext.Current.Request["energineID"]; + string opname = HttpContext.Current.Request["value"]; + QualityDataButton_bgColor_Select(opname, energineID, out dt);//此处重新写函数 + if (dt != null) + { + if (dt.Rows.Count >= 0) + { + text = Buttons.Createbuttons(dt); + } + } + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, "MesWebFun02:QualityDataButton_bgColor_Select"); + } + return text; + + } + /// WEB根据工位名称和发动机号查询质量数据合格索引(包括了分线的信息、存储过程中根据工位类型区分) 20140626 wt + /// + /// + /// + /// + /// + public static bool QualityDataButton_bgColor_Select(string opname, string energineID, out DataTable dt) + { + string procedureName = "显示测量数据_工位号_根据发动机型号_查询"; + SqlParameter[] sqlParameters = new SqlParameter[2]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", opname); + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@发动机号", energineID); + return DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + } + + + /// + /// 获取对应工位的质量数据 + /// + /// + private string QualityDataSelectByEnergineID() + { + string qualitydata = ""; + try + { + System.Data.DataTable dt = null; + string energineID = HttpContext.Current.Request["value"]; + string opname = HttpContext.Current.Request["opname"]; + QualityDataSelect(opname, energineID, out dt); + if (dt != null) + { + //if (dt.Rows.Count > 0) + { + qualitydata = JsonHelper.CreateJsonParameters(dt); + } + } + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, "MesWebFun10:QualityDataSelect"); + } + return qualitydata; + + } + + static public bool QualityDataSelect(string opname, string energineID, out DataTable dt) + { + string procedureName; + procedureName = "显示测量数据_根据_工位号_发动机型号_查询"; + SqlParameter[] sqlParameters = new SqlParameter[2]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", opname); + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@发动机号", energineID); + return DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + } + + /// + /// 查询返修上线工位及返修路径数目 + /// + /// + /// + /// + public static void RepairBtnDataSelect(string OpName, out string BtnData, out int RouteNum) + { + + DataTable dt; + string procedureName; + BtnData = ""; + RouteNum = 0; + procedureName = "返修上线_返修工位_返修上线点及返修路径_基础配置_查询"; + SqlParameter[] sqlParameters = new SqlParameter[1]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", OpName); + DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + if (dt != null) + { + if (dt.Rows.Count > 0) + { + BtnData = dt.Rows[0]["待返修工位"].ToString(); + RouteNum = Convert.ToInt32(dt.Rows[0]["返修路径数目"]); + } + } + } + + + /// + /// 查询当前上线点上次选择的返修工位,用于界面按钮颜色原始数据 + /// + /// + /// + /// + public static bool selectRepairData(string OpName, out DataTable dt) + { + + string procedureName; + procedureName = "返修上线_返修工位及返修路径_最近数据_查询"; + SqlParameter[] sqlParameters = new SqlParameter[1]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@返修上线点", OpName); + DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + if (dt.Rows.Count > 0) + { + return true; + } + else + { + + return false; + } + } + /// + /// + /// + /// + /// + /// + public static bool selectRepairStrSelect(string OpName, string selectID, out DataTable dt) + { + string procedureName; + procedureName = "返修上线_返修工位及返修路径_是否工作判断"; + SqlParameter[] sqlParameters = new SqlParameter[2]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@返修上线点", OpName); + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@发动机号", selectID); + DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + if (dt.Rows.Count > 0) + { + return true; + } + else + { + + return false; + } + + } + + } +} diff --git a/Common/08WebFun_base/WebFun_base/SpecialFun/WebFunction06.cs b/Common/08WebFun_base/WebFun_base/SpecialFun/WebFunction06.cs new file mode 100644 index 0000000..bff44dc --- /dev/null +++ b/Common/08WebFun_base/WebFun_base/SpecialFun/WebFunction06.cs @@ -0,0 +1,491 @@ +using DataLinkMesWork; +using bizFacade; +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.SqlClient; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Web; +//using SystemFramework; + +namespace MesWebFun +{ + public class WebFunction06 + { + HttpContext contextMesWebFun; + public string ProcessRequest(HttpContext context) + { + contextMesWebFun = context; ; + context.Response.ContentType = "text/plain"; + string type = contextMesWebFun.Request["type"]; + string responseText = ""; + switch (type) + { + //托盘信息 + case "MobySelect": + // responseText = MobySelect(); + break; + //保存手动生成条码 + case "SavingEngineIDShift": + responseText = SavingEngineIDShift(); + break; + case "SaveRepairStatus"://将返修路径及返修数据保存到数据库 + responseText = SaveRepairStatus(); + break; + case "RepairStatusInit"://将返修路径及返修数据保存到数据库 + responseText = RepairStatusInit(); + break; + case "Select_engineType_ByEnergineID": //根据发动机号显示机型 + responseText = Select_engineType_ByEnergineID(); + break; + case "QualityDataButton_bgColor_Select_ByEnergineID": + responseText = QualityDataButton_bgColor_Select_energineSelect(); + break; + ///////////////////////质量查询根据发动机号 + case "QualityDataSelectByEnergineID": + responseText = QualityDataSelectByEnergineID(); + break; + default: + responseText = "06"; + break; + + + } + return responseText; + } + /// + /// //根据发动机号显示机型,界面提示 + /// + /// + private string Select_engineType_ByEnergineID() + { + string text = ""; + try + { + System.Data.DataTable dt = null; + string opName = HttpContext.Current.Request["value"];//发动机号 + string energineID = HttpContext.Current.Request["energineID"];//发动机号 + GetEngineID_Select(energineID, opName, out dt); + + string engineType = ""; + if (dt != null) + { + if (dt.Rows.Count > 0) + { + engineType = dt.Rows[0]["发动机型号"].ToString(); + } + } + text = "{\"engineType\":\"" + engineType + "\"}"; + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, "MesWebFun08:Select_engineType_ByEnergineID"); + } + return text; + } + /// + /// 保存手动要求的条码 + /// + /// + private string SavingEngineIDShift() + { + string text = ""; + bool flag = false; + System.Data.DataTable dt = null; + try + { + string opname = HttpContext.Current.Request["value"];//工位号 + string date = HttpContext.Current.Request["date"];//日期 + string num = HttpContext.Current.Request["num"];//流水号 + string[] dates = date.Split('-'); + if (dates.Length > 2) + { + int year = Convert.ToInt32(dates[0]); + int month = Convert.ToInt32(dates[1]); + int day = Convert.ToInt32(dates[2]); + int single = Convert.ToInt32(num); + MES.OpName_MIS_Manual_Insert(opname, year, month, day, single); + flag = true; + } + if (flag) + { + text = "{\"flag\":\"1\"}"; + } + else + { + text = "{\"flag\":\"0\"}"; + } + return text; + } + catch (Exception err) + { + text = "{\"flag\":\"0\"}"; + //ApplicationLog.WriteLog(err, "MesWebFun01:SavingEngineIDShift"); + return text; + } + } + + private static string RepairStatusInit() + { + string Opname = HttpContext.Current.Request["value"];//工位号 + string selectID = HttpContext.Current.Request["text_selectByID"];//工位号 text_selectByID + string outtext = CreateRepairUpLine(Opname, selectID); + return outtext; + } + + + /// + /// 动态创建返修上线工位按钮 + /// + /// + /// + public static string CreateRepairUpLine(string OpName, string selectID) + { + StringBuilder HtmlStr = new StringBuilder();//可修改字符串 + + string BtnData = ""; + int RouteNum = 0; + bool HaveDataOrNot = false; + DataTable dt; + + string StationDataStr;//最近一条返修工位数据 + //查询返修上线字符串及路径数目 + RepairBtnDataSelect(OpName, out BtnData, out RouteNum); + string[] RepairSta = BtnData.Split('^');//目标工位数组 + string TargetStationData = "";//目标工位数据 + //查询之前的返修上线数据 + HaveDataOrNot = selectRepairStrSelect(OpName, selectID, out dt); + //合成界面显示按钮字符串 + if (HaveDataOrNot) + { + StationDataStr = dt.Rows[0]["返修字符串"].ToString(); + if (StationDataStr == "") + { + for (int i = 0; i < RepairSta.Length; i++) + { + if (i < (RepairSta.Length - 1)) + { + TargetStationData = TargetStationData + "1^"; + } + else + { + TargetStationData = TargetStationData + "1"; + } + } + } + else + { + TargetStationData = StationDataStr; + } + } + else + { + + for (int i = 0; i < RepairSta.Length; i++) + { + if (i < (RepairSta.Length - 1)) + { + TargetStationData = TargetStationData + "1^"; + } + else + { + TargetStationData = TargetStationData + "1"; + } + } + } + //页面定义 + HtmlStr.Append("\r\n"); + for (int i = 0; i < RepairSta.Length; i++) + { + //动态生成标签 + //样式定义 + string td_style = "width:20%;height:35px";//td样式 + string btn_style = "width:98%;height:98%;font-family:微软雅黑;font-size:15px;border-color: #99CCFF";//标签样式 + string type = "button"; + string tagID = "Btn_" + RepairSta[i]; + string value = RepairSta[i]; + string onclick = "RepairBtnClick(Btn_" + value + ")"; + string[] StationDataArray = TargetStationData.Split('^'); + string bgColor; + + if (StationDataArray[i] == "1") + { + bgColor = "background-color: green"; + } + else + { + bgColor = "background-color: gray"; + } + //保证每行5个按钮 + if (i < RepairSta.Length - 1) + { + if (i % 5 < 4) + { + HtmlStr.Append(""); + } + else + { + HtmlStr.Append(""); + HtmlStr.Append("\r\n"); + } + } + else + { + HtmlStr.Append(""); + HtmlStr.Append(""); + } + + } + HtmlStr.Append("
"); + //上线路径大于1条则显示上线路径 + if (RouteNum > 1) + { + + } + return HtmlStr.ToString(); + } + + + /// + /// 向数据库写入返修数据 + /// + /// + /// + /// + public static bool updateRepairStatusTo_SQL(string opname, string status) + { + string produceName = "测量数据_返修工位_工位状态_修改"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opname); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@返修状态", status); + + return DataAccess.ExecuteStoredProcedure(produceName, ref thisParms); + } + private static string SaveRepairStatus() + { + + try + { + string RepairStatus = HttpContext.Current.Request["str_value"];//返修工位状态 + string engineID = HttpContext.Current.Request["engineID"];//返修零件总成号 + int RepairMethod = Convert.ToInt32(HttpContext.Current.Request["RepairMethod"]);//返修路径 + string engineType = HttpContext.Current.Request["engineType"];//返修零件总成号 + string RepairOpName = HttpContext.Current.Request["OpName"];//返修上线点 + string[] RepairStatusSplit = RepairStatus.Split('|'); + for (int i = 0; i < RepairStatusSplit.Length - 1; i++) + { + updateRepairStatusTo_SQL(RepairStatusSplit[i].Split('^')[0], RepairStatusSplit[i].Split('^')[1]); + } + + string produceName = "返修上线_返修工位及返修路径_增加"; + SqlParameter[] thisParms = new SqlParameter[5]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@总成编号", engineID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@返修状态", RepairStatus); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@返修路径", RepairMethod); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@发动机型号", engineType); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@返修上线点", RepairOpName); + string result = Convert.ToString(DataAccess.ExecuteStoredProcedure(produceName, ref thisParms)); + return result; + } + catch (Exception err) + { + return "0"; + } + + } + /// [电子看板_发动机号_线首工位_查询_根据发动机号] 20160728 majian + /// + /// + /// + static public bool GetEngineID_Select(string engineID, string opName, out DataTable dt) + { + string errorMessage = ""; + DataSet ds; + bool isOK; + dt = null; + //string connectionString = ApplicationConfig.ConnectionString; + string procedureName; + procedureName = "电子看板_发动机号_线首工位_查询_根据发动机号"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@发动机号", engineID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + isOK = DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out ds); + if (isOK) + { + if (ds.Tables.Count > 0) + { + dt = ds.Tables[0]; + return true; + } + else + { + return false; + } + } + else + { + return false; + } + } + private string QualityDataButton_bgColor_Select_energineSelect() + { + string text = ""; + try + { + System.Data.DataTable dt = null; + //单号 + string energineID = HttpContext.Current.Request["energineID"]; + string opname = HttpContext.Current.Request["value"]; + QualityDataButton_bgColor_Select(opname, energineID, out dt);//此处重新写函数 + if (dt != null) + { + if (dt.Rows.Count >= 0) + { + text = Buttons.Createbuttons(dt); + } + } + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, "MesWebFun02:QualityDataButton_bgColor_Select"); + } + return text; + + } + /// WEB根据工位名称和发动机号查询质量数据合格索引(包括了分线的信息、存储过程中根据工位类型区分) 20140626 wt + /// + /// + /// + /// + /// + public static bool QualityDataButton_bgColor_Select(string opname, string energineID, out DataTable dt) + { + string procedureName = "显示测量数据_工位号_根据发动机型号_查询"; + SqlParameter[] sqlParameters = new SqlParameter[2]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", opname); + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@发动机号", energineID); + return DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + } + + + /// + /// 获取对应工位的质量数据 + /// + /// + private string QualityDataSelectByEnergineID() + { + string qualitydata = ""; + try + { + System.Data.DataTable dt = null; + string energineID = HttpContext.Current.Request["value"]; + string opname = HttpContext.Current.Request["opname"]; + QualityDataSelect(opname, energineID, out dt); + if (dt != null) + { + //if (dt.Rows.Count > 0) + { + qualitydata = JsonHelper.CreateJsonParameters(dt); + } + } + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, "MesWebFun10:QualityDataSelect"); + } + return qualitydata; + + } + + static public bool QualityDataSelect(string opname, string energineID, out DataTable dt) + { + string procedureName; + procedureName = "显示测量数据_根据_工位号_发动机型号_查询"; + SqlParameter[] sqlParameters = new SqlParameter[2]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", opname); + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@发动机号", energineID); + return DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + } + + /// + /// 查询返修上线工位及返修路径数目 + /// + /// + /// + /// + public static void RepairBtnDataSelect(string OpName, out string BtnData, out int RouteNum) + { + + DataTable dt; + string procedureName; + BtnData = ""; + RouteNum = 0; + procedureName = "返修上线_返修工位_返修上线点及返修路径_基础配置_查询"; + SqlParameter[] sqlParameters = new SqlParameter[1]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", OpName); + DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + if (dt != null) + { + if (dt.Rows.Count > 0) + { + BtnData = dt.Rows[0]["待返修工位"].ToString(); + RouteNum = Convert.ToInt32(dt.Rows[0]["返修路径数目"]); + } + } + } + + + /// + /// 查询当前上线点上次选择的返修工位,用于界面按钮颜色原始数据 + /// + /// + /// + /// + public static bool selectRepairData(string OpName, out DataTable dt) + { + + string procedureName; + procedureName = "返修上线_返修工位及返修路径_最近数据_查询"; + SqlParameter[] sqlParameters = new SqlParameter[1]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@返修上线点", OpName); + DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + if (dt.Rows.Count > 0) + { + return true; + } + else + { + + return false; + } + } + /// + /// + /// + /// + /// + /// + public static bool selectRepairStrSelect(string OpName, string selectID, out DataTable dt) + { + string procedureName; + procedureName = "返修上线_返修工位及返修路径_是否工作判断"; + SqlParameter[] sqlParameters = new SqlParameter[2]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@返修上线点", OpName); + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@发动机号", selectID); + DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + if (dt.Rows.Count > 0) + { + return true; + } + else + { + + return false; + } + + } + + } +} diff --git a/Common/08WebFun_base/WebFun_base/SpecialFun/WebFunction07.cs b/Common/08WebFun_base/WebFun_base/SpecialFun/WebFunction07.cs new file mode 100644 index 0000000..32e5dba --- /dev/null +++ b/Common/08WebFun_base/WebFun_base/SpecialFun/WebFunction07.cs @@ -0,0 +1,417 @@ +using DataLinkMesWork; +using bizFacade; +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.SqlClient; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Web; +//using SystemFramework; + +namespace MesWebFun +{ + public class WebFunction07 + { + private HttpContext contextMesWebFun; + + public string ProcessRequest(HttpContext context) + { + contextMesWebFun = context; + context.Response.ContentType = "text/plain"; + string type = contextMesWebFun.Request["type"]; + string responseText = ""; + switch (type) + { + case "SaveRepairStatus"://将返修路径及返修数据保存到数据库 + responseText = SaveRepairStatus(); + break; + + case "RepairStatusInit"://将返修路径及返修数据保存到数据库 + responseText = RepairStatusInit(); + break; + + case "Select_engineType_ByEnergineID": //根据发动机号显示机型 + responseText = Select_engineType_ByEnergineID(); + break; + + case "QualityDataButton_bgColor_Select_ByEnergineID": + responseText = QualityDataButton_bgColor_Select_energineSelect(); + break; + + case "QualityDataSelectByEnergineID": + responseText = QualityDataSelectByEnergineID(); + break; + + default: + responseText = "07"; + break; + } + + return responseText; + } + + private static string RepairStatusInit() + { + string Opname = HttpContext.Current.Request["value"];//工位号 + string outtext = CreateRepairUpLine(Opname); + return outtext; + } + + /// + /// //根据发动机号显示机型,界面提示 + /// + /// + private string Select_engineType_ByEnergineID() + { + string text = ""; + try + { + System.Data.DataTable dt = null; + string opName = HttpContext.Current.Request["value"];//发动机号 + string energineID = HttpContext.Current.Request["energineID"];//发动机号 + GetEngineID_Select(energineID, opName, out dt); + + string engineType = ""; + if (dt != null) + { + if (dt.Rows.Count > 0) + { + engineType = dt.Rows[0]["发动机型号"].ToString(); + } + } + text = "{\"engineType\":\"" + engineType + "\"}"; + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, "MesWebFun08:Select_engineType_ByEnergineID"); + } + return text; + } + + /// + /// 查询返修上线工位及返修路径数目 + /// + /// + /// + /// + public static void RepairBtnDataSelect(string OpName, out string BtnData, out int RouteNum) + { + DataTable dt; + string procedureName; + BtnData = ""; + RouteNum = 0; + procedureName = "返修上线_返修工位_返修上线点及返修路径_基础配置_查询"; + SqlParameter[] sqlParameters = new SqlParameter[1]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", OpName); + DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + if (dt != null) + { + if (dt.Rows.Count > 0) + { + BtnData = dt.Rows[0]["待返修工位"].ToString(); + RouteNum = Convert.ToInt32(dt.Rows[0]["返修路径数目"]); + } + } + } + + /// + /// 查询当前上线点上次选择的返修工位,用于界面按钮颜色原始数据 + /// + /// + /// + /// + public static bool selectRepairData(string OpName, out DataTable dt) + { + string procedureName; + procedureName = "返修上线_返修工位及返修路径_最近数据_查询"; + SqlParameter[] sqlParameters = new SqlParameter[1]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@返修上线点", OpName); + DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + if (dt.Rows.Count > 0) + { + return true; + } + else + { + return false; + } + } + + /// + /// 动态创建返修上线工位按钮 + /// + /// + /// + public static string CreateRepairUpLine(string OpName) + { + StringBuilder HtmlStr = new StringBuilder();//可修改字符串 + + string BtnData = ""; + int RouteNum = 0; + bool HaveDataOrNot = false; + DataTable dt; + + string StationDataStr;//最近一条返修工位数据 + string[] StationData;//最近一条返修工位数据数组 + //查询返修上线字符串及路径数目 + RepairBtnDataSelect(OpName, out BtnData, out RouteNum); + string[] RepairSta = BtnData.Split('^');//目标工位数组 + string TargetStationData = "";//目标工位数据 + //查询之前的返修上线数据 + HaveDataOrNot = selectRepairData(OpName, out dt); + + //合成界面显示按钮字符串 + if (HaveDataOrNot) + { + StationDataStr = dt.Rows[0]["返修工位"].ToString(); + StationData = StationDataStr.Split('|'); + + for (int i = 0; i < RepairSta.Length; i++) + { + string TargetOpName = RepairSta[i];//目标工位号 + + for (int j = 0; j < StationData.Length; j++) + { + string[] OpNameDate; + OpNameDate = StationData[j].Split('^'); + if (TargetOpName == OpNameDate[0]) + { + if (j < (StationData.Length - 1)) + { + TargetStationData = TargetStationData + OpNameDate[1] + "^"; + break; + } + else + { + TargetStationData = TargetStationData + OpNameDate[1]; + break; + } + } + } + } + } + else + { + for (int i = 0; i < RepairSta.Length; i++) + { + if (i < (RepairSta.Length - 1)) + { + TargetStationData = TargetStationData + "1^"; + } + else + { + TargetStationData = TargetStationData + "1"; + } + } + } + + //页面定义 + HtmlStr.Append("\r\n"); + for (int i = 0; i < RepairSta.Length; i++) + { + //动态生成标签 + //样式定义 + string td_style = "width:20%;height:35px";//td样式 + string btn_style = "width:98%;height:98%;font-family:微软雅黑;font-size:15px;border-color: #99CCFF";//标签样式 + string type = "button"; + string tagID = "Btn_" + RepairSta[i]; + string value = RepairSta[i]; + string onclick = "RepairBtnClick(Btn_" + value + ")"; + string[] StationDataArray = TargetStationData.Split('^'); + string bgColor; + + if (StationDataArray[i] == "1") + { + bgColor = "background-color: green"; + } + else + { + bgColor = "background-color: gray"; + } + //保证每行5个按钮 + if (i < RepairSta.Length - 1) + { + if (i % 5 < 4) + { + HtmlStr.Append(""); + } + else + { + HtmlStr.Append(""); + HtmlStr.Append("\r\n"); + } + } + else + { + HtmlStr.Append(""); + HtmlStr.Append(""); + } + } + HtmlStr.Append("
"); + //上线路径大于1条则显示上线路径 + if (RouteNum > 1) + { + } + + return HtmlStr.ToString(); + } + + /// + /// 向数据库写入返修数据 + /// + /// + /// + /// + public static bool updateRepairStatusTo_SQL(string opname, string status) + { + string produceName = "测量数据_返修工位_工位状态_修改"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opname); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@返修状态", status); + + return DataAccess.ExecuteStoredProcedure(produceName, ref thisParms); + } + + private static string SaveRepairStatus() + { + try + { + string RepairStatus = HttpContext.Current.Request["str_value"];//返修工位状态 + string engineID = HttpContext.Current.Request["engineID"];//返修零件总成号 + int RepairMethod = Convert.ToInt32(HttpContext.Current.Request["RepairMethod"]);//返修路径 + string engineType = HttpContext.Current.Request["engineType"];//返修零件总成号 + string RepairOpName = HttpContext.Current.Request["OpName"];//返修上线点 + string[] RepairStatusSplit = RepairStatus.Split('|'); + for (int i = 0; i < RepairStatusSplit.Length - 1; i++) + { + updateRepairStatusTo_SQL(RepairStatusSplit[i].Split('^')[0], RepairStatusSplit[i].Split('^')[1]); + } + + string produceName = "返修上线_返修工位及返修路径_增加"; + SqlParameter[] thisParms = new SqlParameter[5]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@总成编号", engineID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@返修状态", RepairStatus); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@返修路径", RepairMethod); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@发动机型号", engineType); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@返修上线点", RepairOpName); + string result = Convert.ToString(DataAccess.ExecuteStoredProcedure(produceName, ref thisParms)); + return result; + } + catch (Exception err) + { + return "0"; + } + }/// + + /// [电子看板_发动机号_线首工位_查询_根据发动机号] 20160728 majian + /// + /// + /// + static public bool GetEngineID_Select(string engineID, string opName, out DataTable dt) + { + string errorMessage = ""; + DataSet ds; + bool isOK; + dt = null; + //string connectionString = ApplicationConfig.ConnectionString; + string procedureName; + procedureName = "电子看板_发动机号_线首工位_查询_根据发动机号"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@发动机号", engineID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + isOK = DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out ds); + if (isOK) + { + if (ds.Tables.Count > 0) + { + dt = ds.Tables[0]; + return true; + } + else + { + return false; + } + } + else + { + return false; + } + } + + private string QualityDataButton_bgColor_Select_energineSelect() + { + string text = ""; + try + { + System.Data.DataTable dt = null; + //单号 + string energineID = HttpContext.Current.Request["energineID"]; + string opname = HttpContext.Current.Request["value"]; + QualityDataButton_bgColor_Select(opname, energineID, out dt);//此处重新写函数 + if (dt != null) + { + if (dt.Rows.Count >= 0) + { + text = Buttons.Createbuttons(dt); + } + } + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, "MesWebFun07:QualityDataButton_bgColor_Select"); + } + return text; + } + + /// WEB根据工位名称和发动机号查询质量数据合格索引(包括了分线的信息、存储过程中根据工位类型区分) 20140626 wt + /// + /// + /// + /// + /// + public static bool QualityDataButton_bgColor_Select(string opname, string energineID, out DataTable dt) + { + string procedureName = "显示测量数据_工位号_根据发动机型号_查询"; + SqlParameter[] sqlParameters = new SqlParameter[2]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", opname); + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@发动机号", energineID); + return DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + } + + static public bool QualityDataSelect(string opname, string energineID, out DataTable dt) + { + string procedureName; + procedureName = "显示测量数据_根据_工位号_发动机型号_查询"; + SqlParameter[] sqlParameters = new SqlParameter[2]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", opname); + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@发动机号", energineID); + return DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + } + + private string QualityDataSelectByEnergineID() + { + string qualitydata = ""; + try + { + System.Data.DataTable dt = null; + string energineID = HttpContext.Current.Request["value"]; + string opname = HttpContext.Current.Request["opname"]; + QualityDataSelect(opname, energineID, out dt); + if (dt != null) + { + //if (dt.Rows.Count > 0) + { + qualitydata = JsonHelper.CreateJsonParameters(dt); + } + } + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, "MesWebFun10:QualityDataSelect"); + } + return qualitydata; + } + } +} \ No newline at end of file diff --git a/Common/08WebFun_base/WebFun_base/SpecialFun/WebFunction08.cs b/Common/08WebFun_base/WebFun_base/SpecialFun/WebFunction08.cs new file mode 100644 index 0000000..d0ed6c2 --- /dev/null +++ b/Common/08WebFun_base/WebFun_base/SpecialFun/WebFunction08.cs @@ -0,0 +1,695 @@ +using DataLinkMesWork; +using bizFacade; +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.SqlClient; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Web; +//using SystemFramework; + +namespace MesWebFun +{ + public class WebFunction08 + { + HttpContext contextMesWebFun; + public string ProcessRequest(HttpContext context) + { + contextMesWebFun = context; ; + context.Response.ContentType = "text/plain"; + string type = contextMesWebFun.Request["type"]; + string responseText = ""; + switch (type) + { + + case "SelectSublineStatus": + responseText = SelectSublineStatus(); + break; + + case "SelectAssemblylineStatus": + responseText = SelectAssemblylineStatus(); + break; + + case "QueueListDataSelect": + responseText = QueueListDataSelect(); + break; + case "MatchingListDataSelect": + responseText = MatchingListDataSelect(); + break; + //保存手动生成条码 + case "SavingEngineIDShift": + responseText = SavingEngineIDShift(); + break; + case "SaveRepairStatus"://将返修路径及返修数据保存到数据库 + responseText = SaveRepairStatus(); + break; + case "RepairStatusInit"://将返修路径及返修数据保存到数据库 + responseText = RepairStatusInit(); + break; + case "Select_engineType_ByEnergineID": //根据发动机号显示机型 + responseText = Select_engineType_ByEnergineID(); + break; + case "QualityDataButton_bgColor_Select_ByEnergineID": + responseText = QualityDataButton_bgColor_Select_energineSelect(); + break; + ///////////////////////质量查询根据发动机号 + case "QualityDataSelectByEnergineID": + responseText = QualityDataSelectByEnergineID(); + break; + default: + responseText = "08"; + break; + } + return responseText; + } + /// + /// //根据发动机号显示机型,界面提示 + /// + /// + private string Select_engineType_ByEnergineID() + { + string text = ""; + try + { + System.Data.DataTable dt = null; + string opName = HttpContext.Current.Request["value"];//发动机号 + string energineID = HttpContext.Current.Request["energineID"];//发动机号 + GetEngineID_Select(energineID, opName, out dt); + + string engineType = ""; + if (dt != null) + { + if (dt.Rows.Count > 0) + { + engineType = dt.Rows[0]["发动机型号"].ToString(); + } + } + text = "{\"engineType\":\"" + engineType + "\"}"; + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, "MesWebFun08:Select_engineType_ByEnergineID"); + } + return text; + } + /// + /// 保存手动要求的条码 + /// + /// + private string SavingEngineIDShift() + { + string text = ""; + bool flag = false; + System.Data.DataTable dt = null; + try + { + string opname = HttpContext.Current.Request["value"];//工位号 + string date = HttpContext.Current.Request["date"];//日期 + string num = HttpContext.Current.Request["num"];//流水号 + string[] dates = date.Split('-'); + if (dates.Length > 2) + { + int year = Convert.ToInt32(dates[0]); + int month = Convert.ToInt32(dates[1]); + int day = Convert.ToInt32(dates[2]); + int single = Convert.ToInt32(num); + MES.OpName_MIS_Manual_Insert(opname, year, month, day, single); + flag = true; + } + if (flag) + { + text = "{\"flag\":\"1\"}"; + } + else + { + text = "{\"flag\":\"0\"}"; + } + return text; + } + catch (Exception err) + { + text = "{\"flag\":\"0\"}"; + //ApplicationLog.WriteLog(err, "MesWebFun01:SavingEngineIDShift"); + return text; + } + } + + private static string RepairStatusInit() + { + string Opname = HttpContext.Current.Request["value"];//工位号 + string selectID = HttpContext.Current.Request["text_selectByID"];//工位号 text_selectByID + string outtext = CreateRepairUpLine(Opname, selectID); + return outtext; + } + + + /// + /// 动态创建返修上线工位按钮 + /// + /// + /// + public static string CreateRepairUpLine(string OpName, string selectID) + { + StringBuilder HtmlStr = new StringBuilder();//可修改字符串 + + string BtnData = ""; + int RouteNum = 0; + bool HaveDataOrNot = false; + DataTable dt; + + string StationDataStr;//最近一条返修工位数据 + //查询返修上线字符串及路径数目 + RepairBtnDataSelect(OpName, out BtnData, out RouteNum); + string[] RepairSta = BtnData.Split('^');//目标工位数组 + string TargetStationData = "";//目标工位数据 + //查询之前的返修上线数据 + HaveDataOrNot = selectRepairStrSelect(OpName, selectID, out dt); + //合成界面显示按钮字符串 + if (HaveDataOrNot) + { + StationDataStr = dt.Rows[0]["返修字符串"].ToString(); + if (StationDataStr == "") + { + for (int i = 0; i < RepairSta.Length; i++) + { + if (i < (RepairSta.Length - 1)) + { + TargetStationData = TargetStationData + "1^"; + } + else + { + TargetStationData = TargetStationData + "1"; + } + } + } + else + { + TargetStationData = StationDataStr; + } + } + else + { + + for (int i = 0; i < RepairSta.Length; i++) + { + if (i < (RepairSta.Length - 1)) + { + TargetStationData = TargetStationData + "1^"; + } + else + { + TargetStationData = TargetStationData + "1"; + } + } + } + //页面定义 + HtmlStr.Append("\r\n"); + for (int i = 0; i < RepairSta.Length; i++) + { + //动态生成标签 + //样式定义 + string td_style = "width:20%;height:35px";//td样式 + string btn_style = "width:98%;height:98%;font-family:微软雅黑;font-size:15px;border-color: #99CCFF";//标签样式 + string type = "button"; + string tagID = "Btn_" + RepairSta[i]; + string value = RepairSta[i]; + string onclick = "RepairBtnClick(Btn_" + value + ")"; + string[] StationDataArray = TargetStationData.Split('^'); + string bgColor; + + if (StationDataArray[i] == "1") + { + bgColor = "background-color: green"; + } + else + { + bgColor = "background-color: gray"; + } + //保证每行5个按钮 + if (i < RepairSta.Length - 1) + { + if (i % 5 < 4) + { + HtmlStr.Append(""); + } + else + { + HtmlStr.Append(""); + HtmlStr.Append("\r\n"); + } + } + else + { + HtmlStr.Append(""); + HtmlStr.Append(""); + } + + } + HtmlStr.Append("
"); + //上线路径大于1条则显示上线路径 + if (RouteNum > 1) + { + + } + return HtmlStr.ToString(); + } + + + /// + /// 向数据库写入返修数据 + /// + /// + /// + /// + public static bool updateRepairStatusTo_SQL(string opname, string status) + { + string produceName = "测量数据_返修工位_工位状态_修改"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opname); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@返修状态", status); + + return DataAccess.ExecuteStoredProcedure(produceName, ref thisParms); + } + private static string SaveRepairStatus() + { + + try + { + string RepairStatus = HttpContext.Current.Request["str_value"];//返修工位状态 + string engineID = HttpContext.Current.Request["engineID"];//返修零件总成号 + int RepairMethod = Convert.ToInt32(HttpContext.Current.Request["RepairMethod"]);//返修路径 + string engineType = HttpContext.Current.Request["engineType"];//返修零件总成号 + string RepairOpName = HttpContext.Current.Request["OpName"];//返修上线点 + string[] RepairStatusSplit = RepairStatus.Split('|'); + for (int i = 0; i < RepairStatusSplit.Length - 1; i++) + { + updateRepairStatusTo_SQL(RepairStatusSplit[i].Split('^')[0], RepairStatusSplit[i].Split('^')[1]); + } + + string produceName = "返修上线_返修工位及返修路径_增加"; + SqlParameter[] thisParms = new SqlParameter[5]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@总成编号", engineID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@返修状态", RepairStatus); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@返修路径", RepairMethod); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@发动机型号", engineType); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@返修上线点", RepairOpName); + string result = Convert.ToString(DataAccess.ExecuteStoredProcedure(produceName, ref thisParms)); + return result; + } + catch (Exception err) + { + return "0"; + } + + } + /// [电子看板_发动机号_线首工位_查询_根据发动机号] 20160728 majian + /// + /// + /// + static public bool GetEngineID_Select(string engineID, string opName, out DataTable dt) + { + string errorMessage = ""; + DataSet ds; + bool isOK; + dt = null; + //string connectionString = ApplicationConfig.ConnectionString; + string procedureName; + procedureName = "电子看板_发动机号_线首工位_查询_根据发动机号"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@发动机号", engineID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + isOK = DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out ds); + if (isOK) + { + if (ds.Tables.Count > 0) + { + dt = ds.Tables[0]; + return true; + } + else + { + return false; + } + } + else + { + return false; + } + } + private string QualityDataButton_bgColor_Select_energineSelect() + { + string text = ""; + try + { + System.Data.DataTable dt = null; + //单号 + string energineID = HttpContext.Current.Request["energineID"]; + string opname = HttpContext.Current.Request["value"]; + QualityDataButton_bgColor_Select(opname, energineID, out dt);//此处重新写函数 + if (dt != null) + { + if (dt.Rows.Count >= 0) + { + text = Buttons.Createbuttons(dt); + } + } + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, "MesWebFun02:QualityDataButton_bgColor_Select"); + } + return text; + + } + /// WEB根据工位名称和发动机号查询质量数据合格索引(包括了分线的信息、存储过程中根据工位类型区分) 20140626 wt + /// + /// + /// + /// + /// + public static bool QualityDataButton_bgColor_Select(string opname, string energineID, out DataTable dt) + { + string procedureName = "显示测量数据_工位号_根据发动机型号_查询"; + SqlParameter[] sqlParameters = new SqlParameter[2]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", opname); + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@发动机号", energineID); + return DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + } + + + /// + /// 获取对应工位的质量数据 + /// + /// + private string QualityDataSelectByEnergineID() + { + string qualitydata = ""; + try + { + System.Data.DataTable dt = null; + string energineID = HttpContext.Current.Request["value"]; + string opname = HttpContext.Current.Request["opname"]; + QualityDataSelect(opname, energineID, out dt); + if (dt != null) + { + //if (dt.Rows.Count > 0) + { + qualitydata = JsonHelper.CreateJsonParameters(dt); + } + } + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, "MesWebFun10:QualityDataSelect"); + } + return qualitydata; + + } + + static public bool QualityDataSelect(string opname, string energineID, out DataTable dt) + { + string procedureName; + procedureName = "显示测量数据_根据_工位号_发动机型号_查询"; + SqlParameter[] sqlParameters = new SqlParameter[2]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", opname); + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@发动机号", energineID); + return DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + } + + /// + /// 查询返修上线工位及返修路径数目 + /// + /// + /// + /// + public static void RepairBtnDataSelect(string OpName, out string BtnData, out int RouteNum) + { + + DataTable dt; + string procedureName; + BtnData = ""; + RouteNum = 0; + procedureName = "返修上线_返修工位_返修上线点及返修路径_基础配置_查询"; + SqlParameter[] sqlParameters = new SqlParameter[1]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", OpName); + DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + if (dt != null) + { + if (dt.Rows.Count > 0) + { + BtnData = dt.Rows[0]["待返修工位"].ToString(); + RouteNum = Convert.ToInt32(dt.Rows[0]["返修路径数目"]); + } + } + } + + + /// + /// 查询当前上线点上次选择的返修工位,用于界面按钮颜色原始数据 + /// + /// + /// + /// + public static bool selectRepairData(string OpName, out DataTable dt) + { + + string procedureName; + procedureName = "返修上线_返修工位及返修路径_最近数据_查询"; + SqlParameter[] sqlParameters = new SqlParameter[1]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@返修上线点", OpName); + DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + if (dt.Rows.Count > 0) + { + return true; + } + else + { + + return false; + } + } + /// + /// + /// + /// + /// + /// + public static bool selectRepairStrSelect(string OpName, string selectID, out DataTable dt) + { + string procedureName; + procedureName = "返修上线_返修工位及返修路径_是否工作判断"; + SqlParameter[] sqlParameters = new SqlParameter[2]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@返修上线点", OpName); + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@发动机号", selectID); + DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + if (dt.Rows.Count > 0) + { + return true; + } + else + { + + return false; + } + + } + /// + /// 根据总线机型查询轴系线托盘号、发动机型号 + /// + /// + /// + /// + private void SelectSublineEngineIDAndPalletnum(string EngineID, out string EngineID_Subline, out int PalletNumSubline) + { + EngineID_Subline = ""; + PalletNumSubline = 0; + + string produceName; + produceName = "分线上总线_分线托盘号总成编号_根据总线总成编号_查询"; + SqlParameter[] thisParms = new SqlParameter[3]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@总装线总成编号", EngineID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@轴系线总成编号", SqlDbType.NVarChar, 50, "轴系线总成编号"); + thisParms[1].Direction = ParameterDirection.Output; + thisParms[2] = new System.Data.SqlClient.SqlParameter("@轴系线托盘号", SqlDbType.Int, 4, "轴系线托盘号"); + thisParms[2].Direction = ParameterDirection.Output; + DataAccess.ExecuteStoredProcedure(produceName, ref thisParms); + if (thisParms[1].Value != null && thisParms[2].Value != null) + { + EngineID_Subline = thisParms[1].Value.ToString(); + PalletNumSubline = Convert.ToInt32(thisParms[2].Value); + } + } + + private string SelectSublineStatus() + { + + + string data = ""; + try + { + string EngineID_Subline = ""; + int PalletNumSubline = 0; + string EngineID = contextMesWebFun.Request["EngineID"]; + + SelectSublineEngineIDAndPalletnum(EngineID, out EngineID_Subline, out PalletNumSubline); + data = EngineID_Subline + "&" + PalletNumSubline; + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, "SelectSublineStatus"); + } + return data; + + } + + /// + /// ///////////////////////////////////////////////////////////////////////////////////////////////////// + /// + + /// + /// 根据轴系线机型查询总装线托盘号、发动机型号 + /// + /// + /// + /// + private void SelectAssemblylineEngineIDAndPalletnum(string EngineID, out string EngineID_Assemblyline, out int PalletNumAssemblyline) + { + EngineID_Assemblyline = ""; + PalletNumAssemblyline = 0; + + string produceName; + produceName = "分线上总线_总装线托盘号总成编号_根据轴系线总成编号_查询"; + SqlParameter[] thisParms = new SqlParameter[3]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@轴系线总成编号", EngineID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@总装线总成编号", SqlDbType.NVarChar, 50, "总装线总成编号"); + thisParms[1].Direction = ParameterDirection.Output; + thisParms[2] = new System.Data.SqlClient.SqlParameter("@总装线托盘号", PalletNumAssemblyline); + thisParms[2].Direction = ParameterDirection.Output; + DataAccess.ExecuteStoredProcedure(produceName, ref thisParms); + EngineID_Assemblyline = thisParms[1].Value.ToString(); + PalletNumAssemblyline = Convert.ToInt32(thisParms[2].Value); + + } + + private string SelectAssemblylineStatus() + { + + + string data = ""; + try + { + string EngineID_Assemblyline = ""; + int PalletNumAssemblyline = 0; + string EngineID = contextMesWebFun.Request["EngineID"]; + + SelectAssemblylineEngineIDAndPalletnum(EngineID, out EngineID_Assemblyline, out PalletNumAssemblyline); + data = EngineID_Assemblyline + "&" + PalletNumAssemblyline; + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, "SelectSublineStatus"); + } + return data; + + } + + /// + /// 获取排队列表数据 + /// + /// + private string QueueListDataSelect() + { + string qualitydata = ""; + try + { + System.Data.DataTable dt = null; + QueueListSelect(out dt); + if (dt != null) + { + + + qualitydata = JsonHelper.CreateJsonParameters(dt); + + } + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, "MesWebFun12:QueueListDataSelect"); + } + return qualitydata; + + } + + + + + /// + /// 输出轴轴承外圈排队列表_查询 + /// + /// + /// + /// + /// + static public bool QueueListSelect(out DataTable dt) + { + string procedureName; + procedureName = "轴承外圈轴系追踪号排队_查询全部"; + SqlParameter[] sqlParameters = new SqlParameter[0]; + return DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + } + + + + + + + /// + /// 获取匹配列表数据 + /// + /// + private string MatchingListDataSelect() + { + string qualitydata = ""; + try + { + System.Data.DataTable dt = null; + MatchingListSelect(out dt); + if (dt != null) + { + + + qualitydata = JsonHelper.CreateJsonParameters(dt); + + } + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, "MesWebFun12:MatchingListDataSelect"); + } + return qualitydata; + + } + + /// + /// 输出轴轴承外圈匹配列表_查询 + /// + /// + /// + /// + /// + static public bool MatchingListSelect(out DataTable dt) + { + string procedureName; + procedureName = "轴承外圈轴系总成号与总线总成号匹配列表_查询全部"; + SqlParameter[] sqlParameters = new SqlParameter[0]; + return DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + } + + + + + + } +} diff --git a/Common/08WebFun_base/WebFun_base/SpecialFun/WebFunction10.cs b/Common/08WebFun_base/WebFun_base/SpecialFun/WebFunction10.cs new file mode 100644 index 0000000..a763633 --- /dev/null +++ b/Common/08WebFun_base/WebFun_base/SpecialFun/WebFunction10.cs @@ -0,0 +1,482 @@ +using DataLinkMesWork; +using bizFacade; +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.SqlClient; +using System.Linq; +using System.Text; +using System.Web; +//using SystemFramework; + +namespace MesWebFun +{ + public class WebFunction10 + { + + HttpContext contextMesWebFun; + public string ProcessRequest(HttpContext context) + { + contextMesWebFun = context; ; + context.Response.ContentType = "text/plain"; + string type = contextMesWebFun.Request["type"]; + string responseText = ""; + switch (type) + { + //保存手动生成条码 + case "SavingEngineIDShift": + responseText = SavingEngineIDShift(); + break; + case "SaveRepairStatus"://将返修路径及返修数据保存到数据库 + responseText = SaveRepairStatus(); + break; + case "RepairStatusInit"://将返修路径及返修数据保存到数据库 + responseText = RepairStatusInit(); + break; + case "Select_engineType_ByEnergineID": //根据发动机号显示机型 + responseText = Select_engineType_ByEnergineID(); + break; + case "QualityDataButton_bgColor_Select_ByEnergineID": + responseText = QualityDataButton_bgColor_Select_energineSelect(); + break; + ///////////////////////质量查询根据发动机号 + case "QualityDataSelectByEnergineID": + responseText = QualityDataSelectByEnergineID(); + break; + default: + responseText = "10"; + break; + } + return responseText; + } + + /// + /// 保存手动要求的条码 + /// + /// + private string SavingEngineIDShift() + { + string text = ""; + bool flag = false; + System.Data.DataTable dt = null; + try + { + string opname = HttpContext.Current.Request["value"];//工位号 + string date = HttpContext.Current.Request["date"];//日期 + string num = HttpContext.Current.Request["num"];//流水号 + string[] dates = date.Split('-'); + if (dates.Length > 2) + { + int year = Convert.ToInt32(dates[0]); + int month = Convert.ToInt32(dates[1]); + int day = Convert.ToInt32(dates[2]); + int single = Convert.ToInt32(num); + MES.OpName_MIS_Manual_Insert(opname, year, month, day, single); + flag = true; + } + if (flag) + { + text = "{\"flag\":\"1\"}"; + } + else + { + text = "{\"flag\":\"0\"}"; + } + return text; + } + catch (Exception err) + { + text = "{\"flag\":\"0\"}"; + //ApplicationLog.WriteLog(err, "MesWebFun10:SavingEngineIDShift"); + return text; + } + } + + + + private static string RepairStatusInit() + { + string Opname = HttpContext.Current.Request["value"];//工位号 + string outtext = CreateRepairUpLine(Opname); + return outtext; + } + + /// + /// //根据发动机号显示机型,界面提示 + /// + /// + private string Select_engineType_ByEnergineID() + { + string text = ""; + try + { + System.Data.DataTable dt = null; + string opName = HttpContext.Current.Request["value"];//发动机号 + string energineID = HttpContext.Current.Request["energineID"];//发动机号 + GetEngineID_Select(energineID, opName, out dt); + + string engineType = ""; + if (dt != null) + { + if (dt.Rows.Count > 0) + { + engineType = dt.Rows[0]["发动机型号"].ToString(); + } + } + text = "{\"engineType\":\"" + engineType + "\"}"; + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, "MesWebFun08:Select_engineType_ByEnergineID"); + } + return text; + } + + + /// + /// 查询返修上线工位及返修路径数目 + /// + /// + /// + /// + public static void RepairBtnDataSelect(string OpName, out string BtnData, out int RouteNum) + { + + DataTable dt; + string procedureName; + BtnData = ""; + RouteNum = 0; + procedureName = "返修上线_返修工位_返修上线点及返修路径_基础配置_查询"; + SqlParameter[] sqlParameters = new SqlParameter[1]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", OpName); + DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + if (dt != null) + { + if (dt.Rows.Count > 0) + { + BtnData = dt.Rows[0]["待返修工位"].ToString(); + RouteNum = Convert.ToInt32(dt.Rows[0]["返修路径数目"]); + } + } + } + + + /// + /// 查询当前上线点上次选择的返修工位,用于界面按钮颜色原始数据 + /// + /// + /// + /// + public static bool selectRepairData(string OpName, out DataTable dt) + { + + string procedureName; + procedureName = "返修上线_返修工位及返修路径_最近数据_查询"; + SqlParameter[] sqlParameters = new SqlParameter[1]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@返修上线点", OpName); + DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + if (dt.Rows.Count > 0) + { + return true; + } + else + { + + return false; + } + + } + /// + /// 动态创建返修上线工位按钮 + /// + /// + /// + public static string CreateRepairUpLine(string OpName) + { + StringBuilder HtmlStr = new StringBuilder();//可修改字符串 + + string BtnData = ""; + int RouteNum = 0; + bool HaveDataOrNot = false; + DataTable dt; + + string StationDataStr;//最近一条返修工位数据 + string[] StationData;//最近一条返修工位数据数组 + //查询返修上线字符串及路径数目 + RepairBtnDataSelect(OpName, out BtnData, out RouteNum); + string[] RepairSta = BtnData.Split('^');//目标工位数组 + string TargetStationData = "";//目标工位数据 + //查询之前的返修上线数据 + HaveDataOrNot = selectRepairData(OpName, out dt); + + //合成界面显示按钮字符串 + if (HaveDataOrNot) + { + StationDataStr = dt.Rows[0]["返修工位"].ToString(); + StationData = StationDataStr.Split('|'); + + for (int i = 0; i < RepairSta.Length; i++) + { + string TargetOpName = RepairSta[i];//目标工位号 + + for (int j = 0; j < StationData.Length; j++) + { + string[] OpNameDate; + OpNameDate = StationData[j].Split('^'); + if (TargetOpName == OpNameDate[0]) + { + if (j < (StationData.Length - 1)) + { + TargetStationData = TargetStationData + OpNameDate[1] + "^"; + break; + } + else + { + TargetStationData = TargetStationData + OpNameDate[1]; + break; + } + } + + } + + } + + } + else + { + + for (int i = 0; i < RepairSta.Length; i++) + { + if (i < (RepairSta.Length - 1)) + { + TargetStationData = TargetStationData + "1^"; + } + else + { + TargetStationData = TargetStationData + "1"; + + } + } + } + + + + //页面定义 + HtmlStr.Append("\r\n"); + for (int i = 0; i < RepairSta.Length; i++) + { + //动态生成标签 + //样式定义 + string td_style = "width:20%;height:35px";//td样式 + string btn_style = "width:98%;height:98%;font-family:微软雅黑;font-size:15px;border-color: #99CCFF";//标签样式 + string type = "button"; + string tagID = "Btn_" + RepairSta[i]; + string value = RepairSta[i]; + string onclick = "RepairBtnClick(Btn_" + value + ")"; + string[] StationDataArray = TargetStationData.Split('^'); + string bgColor; + + if (StationDataArray[i] == "1") + { + bgColor = "background-color: green"; + } + else + { + bgColor = "background-color: gray"; + } + //保证每行5个按钮 + if (i < RepairSta.Length - 1) + { + if (i % 5 < 4) + { + HtmlStr.Append(""); + } + else + { + HtmlStr.Append(""); + HtmlStr.Append("\r\n"); + } + } + else + { + HtmlStr.Append(""); + HtmlStr.Append(""); + } + + } + HtmlStr.Append("
"); + //上线路径大于1条则显示上线路径 + if (RouteNum > 1) + { + + + + } + + + + return HtmlStr.ToString(); + } + + /// + /// 向数据库写入返修数据 + /// + /// + /// + /// + public static bool updateRepairStatusTo_SQL(string opname, string status) + { + string produceName = "测量数据_返修工位_工位状态_修改"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opname); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@返修状态", status); + + return DataAccess.ExecuteStoredProcedure(produceName, ref thisParms); + } + private static string SaveRepairStatus() + { + + try + { + string RepairStatus = HttpContext.Current.Request["str_value"];//返修工位状态 + string engineID = HttpContext.Current.Request["engineID"];//返修零件总成号 + int RepairMethod = Convert.ToInt32(HttpContext.Current.Request["RepairMethod"]);//返修路径 + string engineType = HttpContext.Current.Request["engineType"];//返修零件总成号 + string RepairOpName = HttpContext.Current.Request["OpName"];//返修上线点 + string[] RepairStatusSplit = RepairStatus.Split('|'); + for (int i = 0; i < RepairStatusSplit.Length - 1; i++) + { + updateRepairStatusTo_SQL(RepairStatusSplit[i].Split('^')[0], RepairStatusSplit[i].Split('^')[1]); + } + + string produceName = "返修上线_返修工位及返修路径_增加"; + SqlParameter[] thisParms = new SqlParameter[5]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@总成编号", engineID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@返修状态", RepairStatus); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@返修路径", RepairMethod); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@发动机型号", engineType); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@返修上线点", RepairOpName); + string result = Convert.ToString(DataAccess.ExecuteStoredProcedure(produceName, ref thisParms)); + return result; + } + catch (Exception err) + { + return "0"; + } + + }/// + /// [电子看板_发动机号_线首工位_查询_根据发动机号] 20160728 majian + /// + /// + /// + static public bool GetEngineID_Select(string engineID, string opName, out DataTable dt) + { + string errorMessage = ""; + DataSet ds; + bool isOK; + dt = null; + //string connectionString = ApplicationConfig.ConnectionString; + string procedureName; + procedureName = "电子看板_发动机号_线首工位_查询_根据发动机号"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@发动机号", engineID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + isOK = DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out ds); + if (isOK) + { + if (ds.Tables.Count > 0) + { + dt = ds.Tables[0]; + return true; + } + else + { + return false; + } + } + else + { + return false; + } + } + private string QualityDataButton_bgColor_Select_energineSelect() + { + string text = ""; + try + { + System.Data.DataTable dt = null; + //单号 + string energineID = HttpContext.Current.Request["energineID"]; + string opname = HttpContext.Current.Request["value"]; + QualityDataButton_bgColor_Select(opname, energineID, out dt);//此处重新写函数 + if (dt != null) + { + if (dt.Rows.Count >= 0) + { + text = Buttons.Createbuttons(dt); + } + } + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, "MesWebFun02:QualityDataButton_bgColor_Select"); + } + return text; + + } + /// WEB根据工位名称和发动机号查询质量数据合格索引(包括了分线的信息、存储过程中根据工位类型区分) 20140626 wt + /// + /// + /// + /// + /// + public static bool QualityDataButton_bgColor_Select(string opname, string energineID, out DataTable dt) + { + string procedureName = "显示测量数据_工位号_根据发动机型号_查询"; + SqlParameter[] sqlParameters = new SqlParameter[2]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", opname); + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@发动机号", energineID); + return DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + } + + + /// + /// 获取对应工位的质量数据 + /// + /// + private string QualityDataSelectByEnergineID() + { + string qualitydata = ""; + try + { + System.Data.DataTable dt = null; + string energineID = HttpContext.Current.Request["value"]; + string opname = HttpContext.Current.Request["opname"]; + QualityDataSelect(opname, energineID, out dt); + if (dt != null) + { + //if (dt.Rows.Count > 0) + { + qualitydata = JsonHelper.CreateJsonParameters(dt); + } + } + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, "MesWebFun10:QualityDataSelect"); + } + return qualitydata; + + } + + static public bool QualityDataSelect(string opname, string energineID, out DataTable dt) + { + string procedureName; + procedureName = "显示测量数据_根据_工位号_发动机型号_查询"; + SqlParameter[] sqlParameters = new SqlParameter[2]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", opname); + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@发动机号", energineID); + return DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + } + } +} diff --git a/Common/08WebFun_base/WebFun_base/SpecialFun/WebFunction11.cs b/Common/08WebFun_base/WebFun_base/SpecialFun/WebFunction11.cs new file mode 100644 index 0000000..1899d94 --- /dev/null +++ b/Common/08WebFun_base/WebFun_base/SpecialFun/WebFunction11.cs @@ -0,0 +1,491 @@ +using DataLinkMesWork; +using bizFacade; +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.SqlClient; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Web; +//using SystemFramework; + +namespace MesWebFun +{ + public class WebFunction11 + { + HttpContext contextMesWebFun; + public string ProcessRequest(HttpContext context) + { + contextMesWebFun = context; ; + context.Response.ContentType = "text/plain"; + string type = contextMesWebFun.Request["type"]; + string responseText = ""; + switch (type) + { + //托盘信息 + case "MobySelect": + // responseText = MobySelect(); + break; + //保存手动生成条码 + case "SavingEngineIDShift": + responseText = SavingEngineIDShift(); + break; + case "SaveRepairStatus"://将返修路径及返修数据保存到数据库 + responseText = SaveRepairStatus(); + break; + case "RepairStatusInit"://将返修路径及返修数据保存到数据库 + responseText = RepairStatusInit(); + break; + case "Select_engineType_ByEnergineID": //根据发动机号显示机型 + responseText = Select_engineType_ByEnergineID(); + break; + case "QualityDataButton_bgColor_Select_ByEnergineID": + responseText = QualityDataButton_bgColor_Select_energineSelect(); + break; + ///////////////////////质量查询根据发动机号 + case "QualityDataSelectByEnergineID": + responseText = QualityDataSelectByEnergineID(); + break; + default: + responseText = "05"; + break; + + + } + return responseText; + } + /// + /// //根据发动机号显示机型,界面提示 + /// + /// + private string Select_engineType_ByEnergineID() + { + string text = ""; + try + { + System.Data.DataTable dt = null; + string opName = HttpContext.Current.Request["value"];//发动机号 + string energineID = HttpContext.Current.Request["energineID"];//发动机号 + GetEngineID_Select(energineID, opName, out dt); + + string engineType = ""; + if (dt != null) + { + if (dt.Rows.Count > 0) + { + engineType = dt.Rows[0]["发动机型号"].ToString(); + } + } + text = "{\"engineType\":\"" + engineType + "\"}"; + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, "MesWebFun08:Select_engineType_ByEnergineID"); + } + return text; + } + /// + /// 保存手动要求的条码 + /// + /// + private string SavingEngineIDShift() + { + string text = ""; + bool flag = false; + System.Data.DataTable dt = null; + try + { + string opname = HttpContext.Current.Request["value"];//工位号 + string date = HttpContext.Current.Request["date"];//日期 + string num = HttpContext.Current.Request["num"];//流水号 + string[] dates = date.Split('-'); + if (dates.Length > 2) + { + int year = Convert.ToInt32(dates[0]); + int month = Convert.ToInt32(dates[1]); + int day = Convert.ToInt32(dates[2]); + int single = Convert.ToInt32(num); + MES.OpName_MIS_Manual_Insert(opname, year, month, day, single); + flag = true; + } + if (flag) + { + text = "{\"flag\":\"1\"}"; + } + else + { + text = "{\"flag\":\"0\"}"; + } + return text; + } + catch (Exception err) + { + text = "{\"flag\":\"0\"}"; + //ApplicationLog.WriteLog(err, "MesWebFun01:SavingEngineIDShift"); + return text; + } + } + + private static string RepairStatusInit() + { + string Opname = HttpContext.Current.Request["value"];//工位号 + string selectID = HttpContext.Current.Request["text_selectByID"];//工位号 text_selectByID + string outtext = CreateRepairUpLine(Opname, selectID); + return outtext; + } + + + /// + /// 动态创建返修上线工位按钮 + /// + /// + /// + public static string CreateRepairUpLine(string OpName, string selectID) + { + StringBuilder HtmlStr = new StringBuilder();//可修改字符串 + + string BtnData = ""; + int RouteNum = 0; + bool HaveDataOrNot = false; + DataTable dt; + + string StationDataStr;//最近一条返修工位数据 + //查询返修上线字符串及路径数目 + RepairBtnDataSelect(OpName, out BtnData, out RouteNum); + string[] RepairSta = BtnData.Split('^');//目标工位数组 + string TargetStationData = "";//目标工位数据 + //查询之前的返修上线数据 + HaveDataOrNot = selectRepairStrSelect(OpName, selectID, out dt); + //合成界面显示按钮字符串 + if (HaveDataOrNot) + { + StationDataStr = dt.Rows[0]["返修字符串"].ToString(); + if (StationDataStr == "") + { + for (int i = 0; i < RepairSta.Length; i++) + { + if (i < (RepairSta.Length - 1)) + { + TargetStationData = TargetStationData + "1^"; + } + else + { + TargetStationData = TargetStationData + "1"; + } + } + } + else + { + TargetStationData = StationDataStr; + } + } + else + { + + for (int i = 0; i < RepairSta.Length; i++) + { + if (i < (RepairSta.Length - 1)) + { + TargetStationData = TargetStationData + "1^"; + } + else + { + TargetStationData = TargetStationData + "1"; + } + } + } + //页面定义 + HtmlStr.Append("\r\n"); + for (int i = 0; i < RepairSta.Length; i++) + { + //动态生成标签 + //样式定义 + string td_style = "width:20%;height:35px";//td样式 + string btn_style = "width:98%;height:98%;font-family:微软雅黑;font-size:15px;border-color: #99CCFF";//标签样式 + string type = "button"; + string tagID = "Btn_" + RepairSta[i]; + string value = RepairSta[i]; + string onclick = "RepairBtnClick(Btn_" + value + ")"; + string[] StationDataArray = TargetStationData.Split('^'); + string bgColor; + + if (StationDataArray[i] == "1") + { + bgColor = "background-color: green"; + } + else + { + bgColor = "background-color: gray"; + } + //保证每行5个按钮 + if (i < RepairSta.Length - 1) + { + if (i % 5 < 4) + { + HtmlStr.Append(""); + } + else + { + HtmlStr.Append(""); + HtmlStr.Append("\r\n"); + } + } + else + { + HtmlStr.Append(""); + HtmlStr.Append(""); + } + + } + HtmlStr.Append("
"); + //上线路径大于1条则显示上线路径 + if (RouteNum > 1) + { + + } + return HtmlStr.ToString(); + } + + + /// + /// 向数据库写入返修数据 + /// + /// + /// + /// + public static bool updateRepairStatusTo_SQL(string opname, string status) + { + string produceName = "测量数据_返修工位_工位状态_修改"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opname); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@返修状态", status); + + return DataAccess.ExecuteStoredProcedure(produceName, ref thisParms); + } + private static string SaveRepairStatus() + { + + try + { + string RepairStatus = HttpContext.Current.Request["str_value"];//返修工位状态 + string engineID = HttpContext.Current.Request["engineID"];//返修零件总成号 + int RepairMethod = Convert.ToInt32(HttpContext.Current.Request["RepairMethod"]);//返修路径 + string engineType = HttpContext.Current.Request["engineType"];//返修零件总成号 + string RepairOpName = HttpContext.Current.Request["OpName"];//返修上线点 + string[] RepairStatusSplit = RepairStatus.Split('|'); + for (int i = 0; i < RepairStatusSplit.Length - 1; i++) + { + updateRepairStatusTo_SQL(RepairStatusSplit[i].Split('^')[0], RepairStatusSplit[i].Split('^')[1]); + } + + string produceName = "返修上线_返修工位及返修路径_增加"; + SqlParameter[] thisParms = new SqlParameter[5]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@总成编号", engineID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@返修状态", RepairStatus); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@返修路径", RepairMethod); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@发动机型号", engineType); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@返修上线点", RepairOpName); + string result = Convert.ToString(DataAccess.ExecuteStoredProcedure(produceName, ref thisParms)); + return result; + } + catch (Exception err) + { + return "0"; + } + + } + /// [电子看板_发动机号_线首工位_查询_根据发动机号] 20160728 majian + /// + /// + /// + static public bool GetEngineID_Select(string engineID, string opName, out DataTable dt) + { + string errorMessage = ""; + DataSet ds; + bool isOK; + dt = null; + //string connectionString = ApplicationConfig.ConnectionString; + string procedureName; + procedureName = "电子看板_发动机号_线首工位_查询_根据发动机号"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@发动机号", engineID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + isOK = DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out ds); + if (isOK) + { + if (ds.Tables.Count > 0) + { + dt = ds.Tables[0]; + return true; + } + else + { + return false; + } + } + else + { + return false; + } + } + private string QualityDataButton_bgColor_Select_energineSelect() + { + string text = ""; + try + { + System.Data.DataTable dt = null; + //单号 + string energineID = HttpContext.Current.Request["energineID"]; + string opname = HttpContext.Current.Request["value"]; + QualityDataButton_bgColor_Select(opname, energineID, out dt);//此处重新写函数 + if (dt != null) + { + if (dt.Rows.Count >= 0) + { + text = Buttons.Createbuttons(dt); + } + } + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, "MesWebFun02:QualityDataButton_bgColor_Select"); + } + return text; + + } + /// WEB根据工位名称和发动机号查询质量数据合格索引(包括了分线的信息、存储过程中根据工位类型区分) 20140626 wt + /// + /// + /// + /// + /// + public static bool QualityDataButton_bgColor_Select(string opname, string energineID, out DataTable dt) + { + string procedureName = "显示测量数据_工位号_根据发动机型号_查询"; + SqlParameter[] sqlParameters = new SqlParameter[2]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", opname); + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@发动机号", energineID); + return DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + } + + + /// + /// 获取对应工位的质量数据 + /// + /// + private string QualityDataSelectByEnergineID() + { + string qualitydata = ""; + try + { + System.Data.DataTable dt = null; + string energineID = HttpContext.Current.Request["value"]; + string opname = HttpContext.Current.Request["opname"]; + QualityDataSelect(opname, energineID, out dt); + if (dt != null) + { + //if (dt.Rows.Count > 0) + { + qualitydata = JsonHelper.CreateJsonParameters(dt); + } + } + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, "MesWebFun10:QualityDataSelect"); + } + return qualitydata; + + } + + static public bool QualityDataSelect(string opname, string energineID, out DataTable dt) + { + string procedureName; + procedureName = "显示测量数据_根据_工位号_发动机型号_查询"; + SqlParameter[] sqlParameters = new SqlParameter[2]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", opname); + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@发动机号", energineID); + return DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + } + + /// + /// 查询返修上线工位及返修路径数目 + /// + /// + /// + /// + public static void RepairBtnDataSelect(string OpName, out string BtnData, out int RouteNum) + { + + DataTable dt; + string procedureName; + BtnData = ""; + RouteNum = 0; + procedureName = "返修上线_返修工位_返修上线点及返修路径_基础配置_查询"; + SqlParameter[] sqlParameters = new SqlParameter[1]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", OpName); + DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + if (dt != null) + { + if (dt.Rows.Count > 0) + { + BtnData = dt.Rows[0]["待返修工位"].ToString(); + RouteNum = Convert.ToInt32(dt.Rows[0]["返修路径数目"]); + } + } + } + + + /// + /// 查询当前上线点上次选择的返修工位,用于界面按钮颜色原始数据 + /// + /// + /// + /// + public static bool selectRepairData(string OpName, out DataTable dt) + { + + string procedureName; + procedureName = "返修上线_返修工位及返修路径_最近数据_查询"; + SqlParameter[] sqlParameters = new SqlParameter[1]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@返修上线点", OpName); + DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + if (dt.Rows.Count > 0) + { + return true; + } + else + { + + return false; + } + } + /// + /// + /// + /// + /// + /// + public static bool selectRepairStrSelect(string OpName, string selectID, out DataTable dt) + { + string procedureName; + procedureName = "返修上线_返修工位及返修路径_是否工作判断"; + SqlParameter[] sqlParameters = new SqlParameter[2]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@返修上线点", OpName); + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@发动机号", selectID); + DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + if (dt.Rows.Count > 0) + { + return true; + } + else + { + + return false; + } + + } + + } +} diff --git a/Common/08WebFun_base/WebFun_base/SpecialFun/WebFunction12.cs b/Common/08WebFun_base/WebFun_base/SpecialFun/WebFunction12.cs new file mode 100644 index 0000000..9150338 --- /dev/null +++ b/Common/08WebFun_base/WebFun_base/SpecialFun/WebFunction12.cs @@ -0,0 +1,491 @@ +using DataLinkMesWork; +using bizFacade; +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.SqlClient; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Web; +//using SystemFramework; + +namespace MesWebFun +{ + public class WebFunction12 + { + HttpContext contextMesWebFun; + public string ProcessRequest(HttpContext context) + { + contextMesWebFun = context; ; + context.Response.ContentType = "text/plain"; + string type = contextMesWebFun.Request["type"]; + string responseText = ""; + switch (type) + { + //托盘信息 + case "MobySelect": + // responseText = MobySelect(); + break; + //保存手动生成条码 + case "SavingEngineIDShift": + responseText = SavingEngineIDShift(); + break; + case "SaveRepairStatus"://将返修路径及返修数据保存到数据库 + responseText = SaveRepairStatus(); + break; + case "RepairStatusInit"://将返修路径及返修数据保存到数据库 + responseText = RepairStatusInit(); + break; + case "Select_engineType_ByEnergineID": //根据发动机号显示机型 + responseText = Select_engineType_ByEnergineID(); + break; + case "QualityDataButton_bgColor_Select_ByEnergineID": + responseText = QualityDataButton_bgColor_Select_energineSelect(); + break; + ///////////////////////质量查询根据发动机号 + case "QualityDataSelectByEnergineID": + responseText = QualityDataSelectByEnergineID(); + break; + default: + responseText = "05"; + break; + + + } + return responseText; + } + /// + /// //根据发动机号显示机型,界面提示 + /// + /// + private string Select_engineType_ByEnergineID() + { + string text = ""; + try + { + System.Data.DataTable dt = null; + string opName = HttpContext.Current.Request["value"];//发动机号 + string energineID = HttpContext.Current.Request["energineID"];//发动机号 + GetEngineID_Select(energineID, opName, out dt); + + string engineType = ""; + if (dt != null) + { + if (dt.Rows.Count > 0) + { + engineType = dt.Rows[0]["发动机型号"].ToString(); + } + } + text = "{\"engineType\":\"" + engineType + "\"}"; + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, "MesWebFun08:Select_engineType_ByEnergineID"); + } + return text; + } + /// + /// 保存手动要求的条码 + /// + /// + private string SavingEngineIDShift() + { + string text = ""; + bool flag = false; + System.Data.DataTable dt = null; + try + { + string opname = HttpContext.Current.Request["value"];//工位号 + string date = HttpContext.Current.Request["date"];//日期 + string num = HttpContext.Current.Request["num"];//流水号 + string[] dates = date.Split('-'); + if (dates.Length > 2) + { + int year = Convert.ToInt32(dates[0]); + int month = Convert.ToInt32(dates[1]); + int day = Convert.ToInt32(dates[2]); + int single = Convert.ToInt32(num); + MES.OpName_MIS_Manual_Insert(opname, year, month, day, single); + flag = true; + } + if (flag) + { + text = "{\"flag\":\"1\"}"; + } + else + { + text = "{\"flag\":\"0\"}"; + } + return text; + } + catch (Exception err) + { + text = "{\"flag\":\"0\"}"; + //ApplicationLog.WriteLog(err, "MesWebFun01:SavingEngineIDShift"); + return text; + } + } + + private static string RepairStatusInit() + { + string Opname = HttpContext.Current.Request["value"];//工位号 + string selectID = HttpContext.Current.Request["text_selectByID"];//工位号 text_selectByID + string outtext = CreateRepairUpLine(Opname, selectID); + return outtext; + } + + + /// + /// 动态创建返修上线工位按钮 + /// + /// + /// + public static string CreateRepairUpLine(string OpName, string selectID) + { + StringBuilder HtmlStr = new StringBuilder();//可修改字符串 + + string BtnData = ""; + int RouteNum = 0; + bool HaveDataOrNot = false; + DataTable dt; + + string StationDataStr;//最近一条返修工位数据 + //查询返修上线字符串及路径数目 + RepairBtnDataSelect(OpName, out BtnData, out RouteNum); + string[] RepairSta = BtnData.Split('^');//目标工位数组 + string TargetStationData = "";//目标工位数据 + //查询之前的返修上线数据 + HaveDataOrNot = selectRepairStrSelect(OpName, selectID, out dt); + //合成界面显示按钮字符串 + if (HaveDataOrNot) + { + StationDataStr = dt.Rows[0]["返修字符串"].ToString(); + if (StationDataStr == "") + { + for (int i = 0; i < RepairSta.Length; i++) + { + if (i < (RepairSta.Length - 1)) + { + TargetStationData = TargetStationData + "1^"; + } + else + { + TargetStationData = TargetStationData + "1"; + } + } + } + else + { + TargetStationData = StationDataStr; + } + } + else + { + + for (int i = 0; i < RepairSta.Length; i++) + { + if (i < (RepairSta.Length - 1)) + { + TargetStationData = TargetStationData + "1^"; + } + else + { + TargetStationData = TargetStationData + "1"; + } + } + } + //页面定义 + HtmlStr.Append("\r\n"); + for (int i = 0; i < RepairSta.Length; i++) + { + //动态生成标签 + //样式定义 + string td_style = "width:20%;height:35px";//td样式 + string btn_style = "width:98%;height:98%;font-family:微软雅黑;font-size:15px;border-color: #99CCFF";//标签样式 + string type = "button"; + string tagID = "Btn_" + RepairSta[i]; + string value = RepairSta[i]; + string onclick = "RepairBtnClick(Btn_" + value + ")"; + string[] StationDataArray = TargetStationData.Split('^'); + string bgColor; + + if (StationDataArray[i] == "1") + { + bgColor = "background-color: green"; + } + else + { + bgColor = "background-color: gray"; + } + //保证每行5个按钮 + if (i < RepairSta.Length - 1) + { + if (i % 5 < 4) + { + HtmlStr.Append(""); + } + else + { + HtmlStr.Append(""); + HtmlStr.Append("\r\n"); + } + } + else + { + HtmlStr.Append(""); + HtmlStr.Append(""); + } + + } + HtmlStr.Append("
"); + //上线路径大于1条则显示上线路径 + if (RouteNum > 1) + { + + } + return HtmlStr.ToString(); + } + + + /// + /// 向数据库写入返修数据 + /// + /// + /// + /// + public static bool updateRepairStatusTo_SQL(string opname, string status) + { + string produceName = "测量数据_返修工位_工位状态_修改"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opname); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@返修状态", status); + + return DataAccess.ExecuteStoredProcedure(produceName, ref thisParms); + } + private static string SaveRepairStatus() + { + + try + { + string RepairStatus = HttpContext.Current.Request["str_value"];//返修工位状态 + string engineID = HttpContext.Current.Request["engineID"];//返修零件总成号 + int RepairMethod = Convert.ToInt32(HttpContext.Current.Request["RepairMethod"]);//返修路径 + string engineType = HttpContext.Current.Request["engineType"];//返修零件总成号 + string RepairOpName = HttpContext.Current.Request["OpName"];//返修上线点 + string[] RepairStatusSplit = RepairStatus.Split('|'); + for (int i = 0; i < RepairStatusSplit.Length - 1; i++) + { + updateRepairStatusTo_SQL(RepairStatusSplit[i].Split('^')[0], RepairStatusSplit[i].Split('^')[1]); + } + + string produceName = "返修上线_返修工位及返修路径_增加"; + SqlParameter[] thisParms = new SqlParameter[5]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@总成编号", engineID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@返修状态", RepairStatus); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@返修路径", RepairMethod); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@发动机型号", engineType); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@返修上线点", RepairOpName); + string result = Convert.ToString(DataAccess.ExecuteStoredProcedure(produceName, ref thisParms)); + return result; + } + catch (Exception err) + { + return "0"; + } + + } + /// [电子看板_发动机号_线首工位_查询_根据发动机号] 20160728 majian + /// + /// + /// + static public bool GetEngineID_Select(string engineID, string opName, out DataTable dt) + { + string errorMessage = ""; + DataSet ds; + bool isOK; + dt = null; + //string connectionString = ApplicationConfig.ConnectionString; + string procedureName; + procedureName = "电子看板_发动机号_线首工位_查询_根据发动机号"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@发动机号", engineID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + isOK = DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out ds); + if (isOK) + { + if (ds.Tables.Count > 0) + { + dt = ds.Tables[0]; + return true; + } + else + { + return false; + } + } + else + { + return false; + } + } + private string QualityDataButton_bgColor_Select_energineSelect() + { + string text = ""; + try + { + System.Data.DataTable dt = null; + //单号 + string energineID = HttpContext.Current.Request["energineID"]; + string opname = HttpContext.Current.Request["value"]; + QualityDataButton_bgColor_Select(opname, energineID, out dt);//此处重新写函数 + if (dt != null) + { + if (dt.Rows.Count >= 0) + { + text = Buttons.Createbuttons(dt); + } + } + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, "MesWebFun02:QualityDataButton_bgColor_Select"); + } + return text; + + } + /// WEB根据工位名称和发动机号查询质量数据合格索引(包括了分线的信息、存储过程中根据工位类型区分) 20140626 wt + /// + /// + /// + /// + /// + public static bool QualityDataButton_bgColor_Select(string opname, string energineID, out DataTable dt) + { + string procedureName = "显示测量数据_工位号_根据发动机型号_查询"; + SqlParameter[] sqlParameters = new SqlParameter[2]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", opname); + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@发动机号", energineID); + return DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + } + + + /// + /// 获取对应工位的质量数据 + /// + /// + private string QualityDataSelectByEnergineID() + { + string qualitydata = ""; + try + { + System.Data.DataTable dt = null; + string energineID = HttpContext.Current.Request["value"]; + string opname = HttpContext.Current.Request["opname"]; + QualityDataSelect(opname, energineID, out dt); + if (dt != null) + { + //if (dt.Rows.Count > 0) + { + qualitydata = JsonHelper.CreateJsonParameters(dt); + } + } + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, "MesWebFun10:QualityDataSelect"); + } + return qualitydata; + + } + + static public bool QualityDataSelect(string opname, string energineID, out DataTable dt) + { + string procedureName; + procedureName = "显示测量数据_根据_工位号_发动机型号_查询"; + SqlParameter[] sqlParameters = new SqlParameter[2]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", opname); + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@发动机号", energineID); + return DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + } + + /// + /// 查询返修上线工位及返修路径数目 + /// + /// + /// + /// + public static void RepairBtnDataSelect(string OpName, out string BtnData, out int RouteNum) + { + + DataTable dt; + string procedureName; + BtnData = ""; + RouteNum = 0; + procedureName = "返修上线_返修工位_返修上线点及返修路径_基础配置_查询"; + SqlParameter[] sqlParameters = new SqlParameter[1]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", OpName); + DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + if (dt != null) + { + if (dt.Rows.Count > 0) + { + BtnData = dt.Rows[0]["待返修工位"].ToString(); + RouteNum = Convert.ToInt32(dt.Rows[0]["返修路径数目"]); + } + } + } + + + /// + /// 查询当前上线点上次选择的返修工位,用于界面按钮颜色原始数据 + /// + /// + /// + /// + public static bool selectRepairData(string OpName, out DataTable dt) + { + + string procedureName; + procedureName = "返修上线_返修工位及返修路径_最近数据_查询"; + SqlParameter[] sqlParameters = new SqlParameter[1]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@返修上线点", OpName); + DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + if (dt.Rows.Count > 0) + { + return true; + } + else + { + + return false; + } + } + /// + /// + /// + /// + /// + /// + public static bool selectRepairStrSelect(string OpName, string selectID, out DataTable dt) + { + string procedureName; + procedureName = "返修上线_返修工位及返修路径_是否工作判断"; + SqlParameter[] sqlParameters = new SqlParameter[2]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@返修上线点", OpName); + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@发动机号", selectID); + DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + if (dt.Rows.Count > 0) + { + return true; + } + else + { + + return false; + } + + } + + } +} diff --git a/Common/08WebFun_base/WebFun_base/SpecialFun/WebFunction13.cs b/Common/08WebFun_base/WebFun_base/SpecialFun/WebFunction13.cs new file mode 100644 index 0000000..529184f --- /dev/null +++ b/Common/08WebFun_base/WebFun_base/SpecialFun/WebFunction13.cs @@ -0,0 +1,491 @@ +using DataLinkMesWork; +using bizFacade; +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.SqlClient; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Web; +//using SystemFramework; + +namespace MesWebFun +{ + public class WebFunction13 + { + HttpContext contextMesWebFun; + public string ProcessRequest(HttpContext context) + { + contextMesWebFun = context; ; + context.Response.ContentType = "text/plain"; + string type = contextMesWebFun.Request["type"]; + string responseText = ""; + switch (type) + { + //托盘信息 + case "MobySelect": + // responseText = MobySelect(); + break; + //保存手动生成条码 + case "SavingEngineIDShift": + responseText = SavingEngineIDShift(); + break; + case "SaveRepairStatus"://将返修路径及返修数据保存到数据库 + responseText = SaveRepairStatus(); + break; + case "RepairStatusInit"://将返修路径及返修数据保存到数据库 + responseText = RepairStatusInit(); + break; + case "Select_engineType_ByEnergineID": //根据发动机号显示机型 + responseText = Select_engineType_ByEnergineID(); + break; + case "QualityDataButton_bgColor_Select_ByEnergineID": + responseText = QualityDataButton_bgColor_Select_energineSelect(); + break; + ///////////////////////质量查询根据发动机号 + case "QualityDataSelectByEnergineID": + responseText = QualityDataSelectByEnergineID(); + break; + default: + responseText = "05"; + break; + + + } + return responseText; + } + /// + /// //根据发动机号显示机型,界面提示 + /// + /// + private string Select_engineType_ByEnergineID() + { + string text = ""; + try + { + System.Data.DataTable dt = null; + string opName = HttpContext.Current.Request["value"];//发动机号 + string energineID = HttpContext.Current.Request["energineID"];//发动机号 + GetEngineID_Select(energineID, opName, out dt); + + string engineType = ""; + if (dt != null) + { + if (dt.Rows.Count > 0) + { + engineType = dt.Rows[0]["发动机型号"].ToString(); + } + } + text = "{\"engineType\":\"" + engineType + "\"}"; + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, "MesWebFun08:Select_engineType_ByEnergineID"); + } + return text; + } + /// + /// 保存手动要求的条码 + /// + /// + private string SavingEngineIDShift() + { + string text = ""; + bool flag = false; + System.Data.DataTable dt = null; + try + { + string opname = HttpContext.Current.Request["value"];//工位号 + string date = HttpContext.Current.Request["date"];//日期 + string num = HttpContext.Current.Request["num"];//流水号 + string[] dates = date.Split('-'); + if (dates.Length > 2) + { + int year = Convert.ToInt32(dates[0]); + int month = Convert.ToInt32(dates[1]); + int day = Convert.ToInt32(dates[2]); + int single = Convert.ToInt32(num); + MES.OpName_MIS_Manual_Insert(opname, year, month, day, single); + flag = true; + } + if (flag) + { + text = "{\"flag\":\"1\"}"; + } + else + { + text = "{\"flag\":\"0\"}"; + } + return text; + } + catch (Exception err) + { + text = "{\"flag\":\"0\"}"; + //ApplicationLog.WriteLog(err, "MesWebFun01:SavingEngineIDShift"); + return text; + } + } + + private static string RepairStatusInit() + { + string Opname = HttpContext.Current.Request["value"];//工位号 + string selectID = HttpContext.Current.Request["text_selectByID"];//工位号 text_selectByID + string outtext = CreateRepairUpLine(Opname, selectID); + return outtext; + } + + + /// + /// 动态创建返修上线工位按钮 + /// + /// + /// + public static string CreateRepairUpLine(string OpName, string selectID) + { + StringBuilder HtmlStr = new StringBuilder();//可修改字符串 + + string BtnData = ""; + int RouteNum = 0; + bool HaveDataOrNot = false; + DataTable dt; + + string StationDataStr;//最近一条返修工位数据 + //查询返修上线字符串及路径数目 + RepairBtnDataSelect(OpName, out BtnData, out RouteNum); + string[] RepairSta = BtnData.Split('^');//目标工位数组 + string TargetStationData = "";//目标工位数据 + //查询之前的返修上线数据 + HaveDataOrNot = selectRepairStrSelect(OpName, selectID, out dt); + //合成界面显示按钮字符串 + if (HaveDataOrNot) + { + StationDataStr = dt.Rows[0]["返修字符串"].ToString(); + if (StationDataStr == "") + { + for (int i = 0; i < RepairSta.Length; i++) + { + if (i < (RepairSta.Length - 1)) + { + TargetStationData = TargetStationData + "1^"; + } + else + { + TargetStationData = TargetStationData + "1"; + } + } + } + else + { + TargetStationData = StationDataStr; + } + } + else + { + + for (int i = 0; i < RepairSta.Length; i++) + { + if (i < (RepairSta.Length - 1)) + { + TargetStationData = TargetStationData + "1^"; + } + else + { + TargetStationData = TargetStationData + "1"; + } + } + } + //页面定义 + HtmlStr.Append("\r\n"); + for (int i = 0; i < RepairSta.Length; i++) + { + //动态生成标签 + //样式定义 + string td_style = "width:20%;height:35px";//td样式 + string btn_style = "width:98%;height:98%;font-family:微软雅黑;font-size:15px;border-color: #99CCFF";//标签样式 + string type = "button"; + string tagID = "Btn_" + RepairSta[i]; + string value = RepairSta[i]; + string onclick = "RepairBtnClick(Btn_" + value + ")"; + string[] StationDataArray = TargetStationData.Split('^'); + string bgColor; + + if (StationDataArray[i] == "1") + { + bgColor = "background-color: green"; + } + else + { + bgColor = "background-color: gray"; + } + //保证每行5个按钮 + if (i < RepairSta.Length - 1) + { + if (i % 5 < 4) + { + HtmlStr.Append(""); + } + else + { + HtmlStr.Append(""); + HtmlStr.Append("\r\n"); + } + } + else + { + HtmlStr.Append(""); + HtmlStr.Append(""); + } + + } + HtmlStr.Append("
"); + //上线路径大于1条则显示上线路径 + if (RouteNum > 1) + { + + } + return HtmlStr.ToString(); + } + + + /// + /// 向数据库写入返修数据 + /// + /// + /// + /// + public static bool updateRepairStatusTo_SQL(string opname, string status) + { + string produceName = "测量数据_返修工位_工位状态_修改"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opname); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@返修状态", status); + + return DataAccess.ExecuteStoredProcedure(produceName, ref thisParms); + } + private static string SaveRepairStatus() + { + + try + { + string RepairStatus = HttpContext.Current.Request["str_value"];//返修工位状态 + string engineID = HttpContext.Current.Request["engineID"];//返修零件总成号 + int RepairMethod = Convert.ToInt32(HttpContext.Current.Request["RepairMethod"]);//返修路径 + string engineType = HttpContext.Current.Request["engineType"];//返修零件总成号 + string RepairOpName = HttpContext.Current.Request["OpName"];//返修上线点 + string[] RepairStatusSplit = RepairStatus.Split('|'); + for (int i = 0; i < RepairStatusSplit.Length - 1; i++) + { + updateRepairStatusTo_SQL(RepairStatusSplit[i].Split('^')[0], RepairStatusSplit[i].Split('^')[1]); + } + + string produceName = "返修上线_返修工位及返修路径_增加"; + SqlParameter[] thisParms = new SqlParameter[5]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@总成编号", engineID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@返修状态", RepairStatus); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@返修路径", RepairMethod); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@发动机型号", engineType); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@返修上线点", RepairOpName); + string result = Convert.ToString(DataAccess.ExecuteStoredProcedure(produceName, ref thisParms)); + return result; + } + catch (Exception err) + { + return "0"; + } + + } + /// [电子看板_发动机号_线首工位_查询_根据发动机号] 20160728 majian + /// + /// + /// + static public bool GetEngineID_Select(string engineID, string opName, out DataTable dt) + { + string errorMessage = ""; + DataSet ds; + bool isOK; + dt = null; + //string connectionString = ApplicationConfig.ConnectionString; + string procedureName; + procedureName = "电子看板_发动机号_线首工位_查询_根据发动机号"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@发动机号", engineID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + isOK = DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out ds); + if (isOK) + { + if (ds.Tables.Count > 0) + { + dt = ds.Tables[0]; + return true; + } + else + { + return false; + } + } + else + { + return false; + } + } + private string QualityDataButton_bgColor_Select_energineSelect() + { + string text = ""; + try + { + System.Data.DataTable dt = null; + //单号 + string energineID = HttpContext.Current.Request["energineID"]; + string opname = HttpContext.Current.Request["value"]; + QualityDataButton_bgColor_Select(opname, energineID, out dt);//此处重新写函数 + if (dt != null) + { + if (dt.Rows.Count >= 0) + { + text = Buttons.Createbuttons(dt); + } + } + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, "MesWebFun02:QualityDataButton_bgColor_Select"); + } + return text; + + } + /// WEB根据工位名称和发动机号查询质量数据合格索引(包括了分线的信息、存储过程中根据工位类型区分) 20140626 wt + /// + /// + /// + /// + /// + public static bool QualityDataButton_bgColor_Select(string opname, string energineID, out DataTable dt) + { + string procedureName = "显示测量数据_工位号_根据发动机型号_查询"; + SqlParameter[] sqlParameters = new SqlParameter[2]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", opname); + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@发动机号", energineID); + return DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + } + + + /// + /// 获取对应工位的质量数据 + /// + /// + private string QualityDataSelectByEnergineID() + { + string qualitydata = ""; + try + { + System.Data.DataTable dt = null; + string energineID = HttpContext.Current.Request["value"]; + string opname = HttpContext.Current.Request["opname"]; + QualityDataSelect(opname, energineID, out dt); + if (dt != null) + { + //if (dt.Rows.Count > 0) + { + qualitydata = JsonHelper.CreateJsonParameters(dt); + } + } + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, "MesWebFun10:QualityDataSelect"); + } + return qualitydata; + + } + + static public bool QualityDataSelect(string opname, string energineID, out DataTable dt) + { + string procedureName; + procedureName = "显示测量数据_根据_工位号_发动机型号_查询"; + SqlParameter[] sqlParameters = new SqlParameter[2]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", opname); + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@发动机号", energineID); + return DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + } + + /// + /// 查询返修上线工位及返修路径数目 + /// + /// + /// + /// + public static void RepairBtnDataSelect(string OpName, out string BtnData, out int RouteNum) + { + + DataTable dt; + string procedureName; + BtnData = ""; + RouteNum = 0; + procedureName = "返修上线_返修工位_返修上线点及返修路径_基础配置_查询"; + SqlParameter[] sqlParameters = new SqlParameter[1]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", OpName); + DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + if (dt != null) + { + if (dt.Rows.Count > 0) + { + BtnData = dt.Rows[0]["待返修工位"].ToString(); + RouteNum = Convert.ToInt32(dt.Rows[0]["返修路径数目"]); + } + } + } + + + /// + /// 查询当前上线点上次选择的返修工位,用于界面按钮颜色原始数据 + /// + /// + /// + /// + public static bool selectRepairData(string OpName, out DataTable dt) + { + + string procedureName; + procedureName = "返修上线_返修工位及返修路径_最近数据_查询"; + SqlParameter[] sqlParameters = new SqlParameter[1]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@返修上线点", OpName); + DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + if (dt.Rows.Count > 0) + { + return true; + } + else + { + + return false; + } + } + /// + /// + /// + /// + /// + /// + public static bool selectRepairStrSelect(string OpName, string selectID, out DataTable dt) + { + string procedureName; + procedureName = "返修上线_返修工位及返修路径_是否工作判断"; + SqlParameter[] sqlParameters = new SqlParameter[2]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@返修上线点", OpName); + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@发动机号", selectID); + DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + if (dt.Rows.Count > 0) + { + return true; + } + else + { + + return false; + } + + } + + } +} diff --git a/Common/08WebFun_base/WebFun_base/SpecialFun/WebFunction14.cs b/Common/08WebFun_base/WebFun_base/SpecialFun/WebFunction14.cs new file mode 100644 index 0000000..c642413 --- /dev/null +++ b/Common/08WebFun_base/WebFun_base/SpecialFun/WebFunction14.cs @@ -0,0 +1,493 @@ +using DataLinkMesWork; +using bizFacade; +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.SqlClient; +using System.Linq; +using System.Text; +using System.Web; +//using SystemFramework; + +namespace MesWebFun +{ + public class WebFunction14 + { + + HttpContext contextMesWebFun; + public string ProcessRequest(HttpContext context) + { + contextMesWebFun = context; ; + context.Response.ContentType = "text/plain"; + string type = contextMesWebFun.Request["type"]; + string responseText = ""; + switch (type) + { + //保存手动生成条码 + case "SavingEngineIDShift": + responseText = SavingEngineIDShift(); + break; + case "SaveRepairStatus"://将返修路径及返修数据保存到数据库 + responseText = SaveRepairStatus(); + break; + case "RepairStatusInit"://将返修路径及返修数据保存到数据库 + responseText = RepairStatusInit(); + break; + case "Select_engineType_ByEnergineID": //根据发动机号显示机型 + responseText = Select_engineType_ByEnergineID(); + break; + case "QualityDataButton_bgColor_Select_ByEnergineID": + responseText = QualityDataButton_bgColor_Select_energineSelect(); + break; + ///////////////////////质量查询根据发动机号 + case "QualityDataSelectByEnergineID": + responseText = QualityDataSelectByEnergineID(); + break; + default: + responseText = "14"; + break; + } + return responseText; + } + + /// + /// 保存手动要求的条码 + /// + /// + private string SavingEngineIDShift() + { + string text = ""; + bool flag = false; + System.Data.DataTable dt = null; + try + { + string opname = HttpContext.Current.Request["value"];//工位号 + string date = HttpContext.Current.Request["date"];//日期 + string num = HttpContext.Current.Request["num"];//流水号 + string[] dates = date.Split('-'); + if (dates.Length > 2) + { + int year = Convert.ToInt32(dates[0]); + int month = Convert.ToInt32(dates[1]); + int day = Convert.ToInt32(dates[2]); + int single = Convert.ToInt32(num); + MES.OpName_MIS_Manual_Insert(opname, year, month, day, single); + flag = true; + } + if (flag) + { + text = "{\"flag\":\"1\"}"; + } + else + { + text = "{\"flag\":\"0\"}"; + } + return text; + } + catch (Exception err) + { + text = "{\"flag\":\"0\"}"; + //ApplicationLog.WriteLog(err, "MesWebFun01:SavingEngineIDShift"); + return text; + } + } + + + + private static string RepairStatusInit() + { + string Opname = HttpContext.Current.Request["value"];//工位号 + string selectID = HttpContext.Current.Request["text_selectByID"];//工位号 text_selectByID + string outtext = CreateRepairUpLine(Opname,selectID); + return outtext; + } + + /// + /// //根据发动机号显示机型,界面提示 + /// + /// + private string Select_engineType_ByEnergineID() + { + string text = ""; + try + { + System.Data.DataTable dt = null; + string opName = HttpContext.Current.Request["value"];//发动机号 + string energineID = HttpContext.Current.Request["energineID"];//发动机号 + GetEngineID_Select(energineID, opName, out dt); + + string engineType = ""; + if (dt != null) + { + if (dt.Rows.Count > 0) + { + engineType = dt.Rows[0]["发动机型号"].ToString(); + } + } + text = "{\"engineType\":\"" + engineType + "\"}"; + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, "MesWebFun08:Select_engineType_ByEnergineID"); + } + return text; + } + + + /// + /// 查询返修上线工位及返修路径数目 + /// + /// + /// + /// + public static void RepairBtnDataSelect(string OpName, out string BtnData, out int RouteNum) + { + + DataTable dt; + string procedureName; + BtnData = ""; + RouteNum = 0; + procedureName = "返修上线_返修工位_返修上线点及返修路径_基础配置_查询"; + SqlParameter[] sqlParameters = new SqlParameter[1]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", OpName); + DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + if (dt != null) + { + if (dt.Rows.Count > 0) + { + BtnData = dt.Rows[0]["待返修工位"].ToString(); + RouteNum = Convert.ToInt32(dt.Rows[0]["返修路径数目"]); + } + } + } + + + /// + /// 查询当前上线点上次选择的返修工位,用于界面按钮颜色原始数据 + /// + /// + /// + /// + public static bool selectRepairData(string OpName, out DataTable dt) + { + + string procedureName; + procedureName = "返修上线_返修工位及返修路径_最近数据_查询"; + SqlParameter[] sqlParameters = new SqlParameter[1]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@返修上线点", OpName); + DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + if (dt.Rows.Count > 0) + { + return true; + } + else + { + + return false; + } + + } + /// + /// + /// + /// + /// + /// + public static bool selectRepairStrSelect(string OpName,string selectID ,out DataTable dt) + { + string procedureName; + procedureName = "返修上线_返修工位及返修路径_是否工作判断"; + SqlParameter[] sqlParameters = new SqlParameter[2]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@返修上线点", OpName); + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@发动机号", selectID); + DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + if (dt.Rows.Count > 0) + { + return true; + } + else + { + + return false; + } + + } + + /// + /// 动态创建返修上线工位按钮 + /// + /// + /// + public static string CreateRepairUpLine(string OpName,string selectID) + { + StringBuilder HtmlStr = new StringBuilder();//可修改字符串 + + string BtnData = ""; + int RouteNum = 0; + bool HaveDataOrNot = false; + DataTable dt; + + string StationDataStr;//最近一条返修工位数据 + //查询返修上线字符串及路径数目 + RepairBtnDataSelect(OpName, out BtnData, out RouteNum); + string[] RepairSta = BtnData.Split('^');//目标工位数组 + string TargetStationData = "";//目标工位数据 + //查询之前的返修上线数据 + HaveDataOrNot = selectRepairStrSelect(OpName, selectID, out dt); + //合成界面显示按钮字符串 + if (HaveDataOrNot) + { + StationDataStr = dt.Rows[0]["返修字符串"].ToString(); + if (StationDataStr == "") + { + for (int i = 0; i < RepairSta.Length; i++) + { + if (i < (RepairSta.Length - 1)) + { + TargetStationData = TargetStationData + "1^"; + } + else + { + TargetStationData = TargetStationData + "1"; + } + } + } + else + { + TargetStationData = StationDataStr; + } + } + else + { + + for (int i = 0; i < RepairSta.Length; i++) + { + if (i < (RepairSta.Length - 1)) + { + TargetStationData = TargetStationData + "1^"; + } + else + { + TargetStationData = TargetStationData + "1"; + } + } + } + //页面定义 + HtmlStr.Append("\r\n"); + for (int i = 0; i < RepairSta.Length; i++) + { + //动态生成标签 + //样式定义 + string td_style = "width:20%;height:35px";//td样式 + string btn_style = "width:98%;height:98%;font-family:微软雅黑;font-size:15px;border-color: #99CCFF";//标签样式 + string type = "button"; + string tagID = "Btn_" + RepairSta[i]; + string value = RepairSta[i]; + string onclick = "RepairBtnClick(Btn_" + value + ")"; + string[] StationDataArray = TargetStationData.Split('^'); + string bgColor; + + if (StationDataArray[i] == "1") + { + bgColor = "background-color: green"; + } + else + { + bgColor = "background-color: gray"; + } + //保证每行5个按钮 + if (i < RepairSta.Length - 1) + { + if (i % 5 < 4) + { + HtmlStr.Append(""); + } + else + { + HtmlStr.Append(""); + HtmlStr.Append("\r\n"); + } + } + else + { + HtmlStr.Append(""); + HtmlStr.Append(""); + } + + } + HtmlStr.Append("
"); + //上线路径大于1条则显示上线路径 + if (RouteNum > 1) + { + + + + } + + + + return HtmlStr.ToString(); + } + + /// + /// 向数据库写入返修数据 + /// + /// + /// + /// + public static bool updateRepairStatusTo_SQL(string opname, string status) + { + string produceName = "测量数据_返修工位_工位状态_修改"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opname); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@返修状态", status); + + return DataAccess.ExecuteStoredProcedure(produceName, ref thisParms); + } + private static string SaveRepairStatus() + { + + try + { + string RepairStatus = HttpContext.Current.Request["str_value"];//返修工位状态 + string engineID = HttpContext.Current.Request["engineID"];//返修零件总成号 + int RepairMethod = Convert.ToInt32(HttpContext.Current.Request["RepairMethod"]);//返修路径 + string engineType = HttpContext.Current.Request["engineType"];//返修零件总成号 + string RepairOpName = HttpContext.Current.Request["OpName"];//返修上线点 + string[] RepairStatusSplit = RepairStatus.Split('|'); + for (int i = 0; i < RepairStatusSplit.Length - 1; i++) + { + updateRepairStatusTo_SQL(RepairStatusSplit[i].Split('^')[0], RepairStatusSplit[i].Split('^')[1]); + } + + string produceName = "返修上线_返修工位及返修路径_增加"; + SqlParameter[] thisParms = new SqlParameter[5]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@总成编号", engineID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@返修状态", RepairStatus); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@返修路径", RepairMethod); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@发动机型号", engineType); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@返修上线点", RepairOpName); + string result = Convert.ToString(DataAccess.ExecuteStoredProcedure(produceName, ref thisParms)); + return result; + } + catch (Exception err) + { + return "0"; + } + + }/// + /// [电子看板_发动机号_线首工位_查询_根据发动机号] 20160728 majian + /// + /// + /// + static public bool GetEngineID_Select(string engineID, string opName, out DataTable dt) + { + string errorMessage = ""; + DataSet ds; + bool isOK; + dt = null; + //string connectionString = ApplicationConfig.ConnectionString; + string procedureName; + procedureName = "电子看板_发动机号_线首工位_查询_根据发动机号"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@发动机号", engineID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + isOK = DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out ds); + if (isOK) + { + if (ds.Tables.Count > 0) + { + dt = ds.Tables[0]; + return true; + } + else + { + return false; + } + } + else + { + return false; + } + } + private string QualityDataButton_bgColor_Select_energineSelect() + { + string text = ""; + try + { + System.Data.DataTable dt = null; + //单号 + string energineID = HttpContext.Current.Request["energineID"]; + string opname = HttpContext.Current.Request["value"]; + QualityDataButton_bgColor_Select(opname, energineID, out dt);//此处重新写函数 + if (dt != null) + { + if (dt.Rows.Count >= 0) + { + text = Buttons.Createbuttons(dt); + } + } + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, "MesWebFun02:QualityDataButton_bgColor_Select"); + } + return text; + + } + /// WEB根据工位名称和发动机号查询质量数据合格索引(包括了分线的信息、存储过程中根据工位类型区分) 20140626 wt + /// + /// + /// + /// + /// + public static bool QualityDataButton_bgColor_Select(string opname, string energineID, out DataTable dt) + { + string procedureName = "显示测量数据_工位号_根据发动机型号_查询"; + SqlParameter[] sqlParameters = new SqlParameter[2]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", opname); + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@发动机号", energineID); + return DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + } + + + /// + /// 获取对应工位的质量数据 + /// + /// + private string QualityDataSelectByEnergineID() + { + string qualitydata = ""; + try + { + System.Data.DataTable dt = null; + string energineID = HttpContext.Current.Request["value"]; + string opname = HttpContext.Current.Request["opname"]; + QualityDataSelect(opname, energineID, out dt); + if (dt != null) + { + //if (dt.Rows.Count > 0) + { + qualitydata = JsonHelper.CreateJsonParameters(dt); + } + } + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, "MesWebFun10:QualityDataSelect"); + } + return qualitydata; + + } + + static public bool QualityDataSelect(string opname, string energineID, out DataTable dt) + { + string procedureName; + procedureName = "显示测量数据_根据_工位号_发动机型号_查询"; + SqlParameter[] sqlParameters = new SqlParameter[2]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", opname); + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@发动机号", energineID); + return DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + } + } +} diff --git a/Common/08WebFun_base/WebFun_base/SpecialFun/WebFunction15.cs b/Common/08WebFun_base/WebFun_base/SpecialFun/WebFunction15.cs new file mode 100644 index 0000000..a7b0bc5 --- /dev/null +++ b/Common/08WebFun_base/WebFun_base/SpecialFun/WebFunction15.cs @@ -0,0 +1,489 @@ +using DataLinkMesWork; +using bizFacade; +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.SqlClient; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Web; +//using SystemFramework; + +namespace MesWebFun +{ + public class WebFunction15 + { + HttpContext contextMesWebFun; + public string ProcessRequest(HttpContext context) + { + contextMesWebFun = context; ; + context.Response.ContentType = "text/plain"; + string type = contextMesWebFun.Request["type"]; + string responseText = ""; + switch (type) + { + //托盘信息 + case "MobySelect": + // responseText = MobySelect(); + break; + //保存手动生成条码 + case "SavingEngineIDShift": + responseText = SavingEngineIDShift(); + break; + case "SaveRepairStatus"://将返修路径及返修数据保存到数据库 + responseText = SaveRepairStatus(); + break; + case "RepairStatusInit"://将返修路径及返修数据保存到数据库 + responseText = RepairStatusInit(); + break; + case "Select_engineType_ByEnergineID": //根据发动机号显示机型 + responseText = Select_engineType_ByEnergineID(); + break; + case "QualityDataButton_bgColor_Select_ByEnergineID": + responseText = QualityDataButton_bgColor_Select_energineSelect(); + break; + ///////////////////////质量查询根据发动机号 + case "QualityDataSelectByEnergineID": + responseText = QualityDataSelectByEnergineID(); + break; + default: + responseText = "15"; + break; + } + return responseText; + } + /// + /// //根据发动机号显示机型,界面提示 + /// + /// + private string Select_engineType_ByEnergineID() + { + string text = ""; + try + { + System.Data.DataTable dt = null; + string opName = HttpContext.Current.Request["value"];//发动机号 + string energineID = HttpContext.Current.Request["energineID"];//发动机号 + GetEngineID_Select(energineID, opName, out dt); + + string engineType = ""; + if (dt != null) + { + if (dt.Rows.Count > 0) + { + engineType = dt.Rows[0]["发动机型号"].ToString(); + } + } + text = "{\"engineType\":\"" + engineType + "\"}"; + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, "MesWebFun08:Select_engineType_ByEnergineID"); + } + return text; + } + /// + /// 保存手动要求的条码 + /// + /// + private string SavingEngineIDShift() + { + string text = ""; + bool flag = false; + System.Data.DataTable dt = null; + try + { + string opname = HttpContext.Current.Request["value"];//工位号 + string date = HttpContext.Current.Request["date"];//日期 + string num = HttpContext.Current.Request["num"];//流水号 + string[] dates = date.Split('-'); + if (dates.Length > 2) + { + int year = Convert.ToInt32(dates[0]); + int month = Convert.ToInt32(dates[1]); + int day = Convert.ToInt32(dates[2]); + int single = Convert.ToInt32(num); + MES.OpName_MIS_Manual_Insert(opname, year, month, day, single); + flag = true; + } + if (flag) + { + text = "{\"flag\":\"1\"}"; + } + else + { + text = "{\"flag\":\"0\"}"; + } + return text; + } + catch (Exception err) + { + text = "{\"flag\":\"0\"}"; + //ApplicationLog.WriteLog(err, "MesWebFun01:SavingEngineIDShift"); + return text; + } + } + + private static string RepairStatusInit() + { + string Opname = HttpContext.Current.Request["value"];//工位号 + string selectID = HttpContext.Current.Request["text_selectByID"];//工位号 text_selectByID + string outtext = CreateRepairUpLine(Opname, selectID); + return outtext; + } + + + /// + /// 动态创建返修上线工位按钮 + /// + /// + /// + public static string CreateRepairUpLine(string OpName, string selectID) + { + StringBuilder HtmlStr = new StringBuilder();//可修改字符串 + + string BtnData = ""; + int RouteNum = 0; + bool HaveDataOrNot = false; + DataTable dt; + + string StationDataStr;//最近一条返修工位数据 + //查询返修上线字符串及路径数目 + RepairBtnDataSelect(OpName, out BtnData, out RouteNum); + string[] RepairSta = BtnData.Split('^');//目标工位数组 + string TargetStationData = "";//目标工位数据 + //查询之前的返修上线数据 + HaveDataOrNot = selectRepairStrSelect(OpName, selectID, out dt); + //合成界面显示按钮字符串 + if (HaveDataOrNot) + { + StationDataStr = dt.Rows[0]["返修字符串"].ToString(); + if (StationDataStr == "") + { + for (int i = 0; i < RepairSta.Length; i++) + { + if (i < (RepairSta.Length - 1)) + { + TargetStationData = TargetStationData + "1^"; + } + else + { + TargetStationData = TargetStationData + "1"; + } + } + } + else + { + TargetStationData = StationDataStr; + } + } + else + { + + for (int i = 0; i < RepairSta.Length; i++) + { + if (i < (RepairSta.Length - 1)) + { + TargetStationData = TargetStationData + "1^"; + } + else + { + TargetStationData = TargetStationData + "1"; + } + } + } + //页面定义 + HtmlStr.Append("\r\n"); + for (int i = 0; i < RepairSta.Length; i++) + { + //动态生成标签 + //样式定义 + string td_style = "width:20%;height:35px";//td样式 + string btn_style = "width:98%;height:98%;font-family:微软雅黑;font-size:15px;border-color: #99CCFF";//标签样式 + string type = "button"; + string tagID = "Btn_" + RepairSta[i]; + string value = RepairSta[i]; + string onclick = "RepairBtnClick(Btn_" + value + ")"; + string[] StationDataArray = TargetStationData.Split('^'); + string bgColor; + + if (StationDataArray[i] == "1") + { + bgColor = "background-color: green"; + } + else + { + bgColor = "background-color: gray"; + } + //保证每行5个按钮 + if (i < RepairSta.Length - 1) + { + if (i % 5 < 4) + { + HtmlStr.Append(""); + } + else + { + HtmlStr.Append(""); + HtmlStr.Append("\r\n"); + } + } + else + { + HtmlStr.Append(""); + HtmlStr.Append(""); + } + + } + HtmlStr.Append("
"); + //上线路径大于1条则显示上线路径 + if (RouteNum > 1) + { + + } + return HtmlStr.ToString(); + } + + + /// + /// 向数据库写入返修数据 + /// + /// + /// + /// + public static bool updateRepairStatusTo_SQL(string opname, string status) + { + string produceName = "测量数据_返修工位_工位状态_修改"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opname); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@返修状态", status); + + return DataAccess.ExecuteStoredProcedure(produceName, ref thisParms); + } + private static string SaveRepairStatus() + { + + try + { + string RepairStatus = HttpContext.Current.Request["str_value"];//返修工位状态 + string engineID = HttpContext.Current.Request["engineID"];//返修零件总成号 + int RepairMethod = Convert.ToInt32(HttpContext.Current.Request["RepairMethod"]);//返修路径 + string engineType = HttpContext.Current.Request["engineType"];//返修零件总成号 + string RepairOpName = HttpContext.Current.Request["OpName"];//返修上线点 + string[] RepairStatusSplit = RepairStatus.Split('|'); + for (int i = 0; i < RepairStatusSplit.Length - 1; i++) + { + updateRepairStatusTo_SQL(RepairStatusSplit[i].Split('^')[0], RepairStatusSplit[i].Split('^')[1]); + } + + string produceName = "返修上线_返修工位及返修路径_增加"; + SqlParameter[] thisParms = new SqlParameter[5]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@总成编号", engineID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@返修状态", RepairStatus); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@返修路径", RepairMethod); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@发动机型号", engineType); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@返修上线点", RepairOpName); + string result = Convert.ToString(DataAccess.ExecuteStoredProcedure(produceName, ref thisParms)); + return result; + } + catch (Exception err) + { + return "0"; + } + + } + /// [电子看板_发动机号_线首工位_查询_根据发动机号] 20160728 majian + /// + /// + /// + static public bool GetEngineID_Select(string engineID, string opName, out DataTable dt) + { + string errorMessage = ""; + DataSet ds; + bool isOK; + dt = null; + //string connectionString = ApplicationConfig.ConnectionString; + string procedureName; + procedureName = "电子看板_发动机号_线首工位_查询_根据发动机号"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@发动机号", engineID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + isOK = DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out ds); + if (isOK) + { + if (ds.Tables.Count > 0) + { + dt = ds.Tables[0]; + return true; + } + else + { + return false; + } + } + else + { + return false; + } + } + private string QualityDataButton_bgColor_Select_energineSelect() + { + string text = ""; + try + { + System.Data.DataTable dt = null; + //单号 + string energineID = HttpContext.Current.Request["energineID"]; + string opname = HttpContext.Current.Request["value"]; + QualityDataButton_bgColor_Select(opname, energineID, out dt);//此处重新写函数 + if (dt != null) + { + if (dt.Rows.Count >= 0) + { + text = Buttons.Createbuttons(dt); + } + } + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, "MesWebFun02:QualityDataButton_bgColor_Select"); + } + return text; + + } + /// WEB根据工位名称和发动机号查询质量数据合格索引(包括了分线的信息、存储过程中根据工位类型区分) 20140626 wt + /// + /// + /// + /// + /// + public static bool QualityDataButton_bgColor_Select(string opname, string energineID, out DataTable dt) + { + string procedureName = "显示测量数据_工位号_根据发动机型号_查询"; + SqlParameter[] sqlParameters = new SqlParameter[2]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", opname); + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@发动机号", energineID); + return DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + } + + + /// + /// 获取对应工位的质量数据 + /// + /// + private string QualityDataSelectByEnergineID() + { + string qualitydata = ""; + try + { + System.Data.DataTable dt = null; + string energineID = HttpContext.Current.Request["value"]; + string opname = HttpContext.Current.Request["opname"]; + QualityDataSelect(opname, energineID, out dt); + if (dt != null) + { + //if (dt.Rows.Count > 0) + { + qualitydata = JsonHelper.CreateJsonParameters(dt); + } + } + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, "MesWebFun10:QualityDataSelect"); + } + return qualitydata; + + } + + static public bool QualityDataSelect(string opname, string energineID, out DataTable dt) + { + string procedureName; + procedureName = "显示测量数据_根据_工位号_发动机型号_查询"; + SqlParameter[] sqlParameters = new SqlParameter[2]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", opname); + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@发动机号", energineID); + return DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + } + + /// + /// 查询返修上线工位及返修路径数目 + /// + /// + /// + /// + public static void RepairBtnDataSelect(string OpName, out string BtnData, out int RouteNum) + { + + DataTable dt; + string procedureName; + BtnData = ""; + RouteNum = 0; + procedureName = "返修上线_返修工位_返修上线点及返修路径_基础配置_查询"; + SqlParameter[] sqlParameters = new SqlParameter[1]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", OpName); + DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + if (dt != null) + { + if (dt.Rows.Count > 0) + { + BtnData = dt.Rows[0]["待返修工位"].ToString(); + RouteNum = Convert.ToInt32(dt.Rows[0]["返修路径数目"]); + } + } + } + + + /// + /// 查询当前上线点上次选择的返修工位,用于界面按钮颜色原始数据 + /// + /// + /// + /// + public static bool selectRepairData(string OpName, out DataTable dt) + { + + string procedureName; + procedureName = "返修上线_返修工位及返修路径_最近数据_查询"; + SqlParameter[] sqlParameters = new SqlParameter[1]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@返修上线点", OpName); + DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + if (dt.Rows.Count > 0) + { + return true; + } + else + { + + return false; + } + } + /// + /// + /// + /// + /// + /// + public static bool selectRepairStrSelect(string OpName, string selectID, out DataTable dt) + { + string procedureName; + procedureName = "返修上线_返修工位及返修路径_是否工作判断"; + SqlParameter[] sqlParameters = new SqlParameter[2]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@返修上线点", OpName); + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@发动机号", selectID); + DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + if (dt.Rows.Count > 0) + { + return true; + } + else + { + + return false; + } + + } + + } +} diff --git a/Common/08WebFun_base/WebFun_base/SpecialFun/WebFunction16.cs b/Common/08WebFun_base/WebFun_base/SpecialFun/WebFunction16.cs new file mode 100644 index 0000000..0c41b22 --- /dev/null +++ b/Common/08WebFun_base/WebFun_base/SpecialFun/WebFunction16.cs @@ -0,0 +1,483 @@ +using bizFacade; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Web; +//using SystemFramework; +using System.Data; +using System.Data.SqlClient; +using DataLinkMesWork; +namespace MesWebFun +{ + public class WebFunction16 + { + HttpContext contextMesWebFun; + public string ProcessRequest(HttpContext context) + { + contextMesWebFun = context; ; + context.Response.ContentType = "text/plain"; + string type = contextMesWebFun.Request["type"]; + string responseText = ""; + switch (type) + { + //保存手动生成条码 + case "SavingEngineIDShift": + responseText = SavingEngineIDShift(); + break; + case "SaveRepairStatus"://将返修路径及返修数据保存到数据库 + responseText = SaveRepairStatus(); + break; + case "RepairStatusInit"://将返修路径及返修数据保存到数据库 + responseText = RepairStatusInit(); + break; + case "Select_engineType_ByEnergineID": //根据发动机号显示机型 + responseText = Select_engineType_ByEnergineID(); + break; + case "QualityDataButton_bgColor_Select_ByEnergineID": + responseText = QualityDataButton_bgColor_Select_energineSelect(); + break; + ///////////////////////质量查询根据发动机号 + case "QualityDataSelectByEnergineID": + responseText = QualityDataSelectByEnergineID(); + break; + default: + responseText = "01"; + break; + } + return responseText; + } + /// + /// //根据发动机号显示机型,界面提示 + /// + /// + private string Select_engineType_ByEnergineID() + { + string text = ""; + try + { + System.Data.DataTable dt = null; + string opName = HttpContext.Current.Request["value"];//发动机号 + string energineID = HttpContext.Current.Request["energineID"];//发动机号 + GetEngineID_Select(energineID, opName, out dt); + + string engineType = ""; + if (dt != null) + { + if (dt.Rows.Count > 0) + { + engineType = dt.Rows[0]["发动机型号"].ToString(); + } + } + text = "{\"engineType\":\"" + engineType + "\"}"; + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, "MesWebFun08:Select_engineType_ByEnergineID"); + } + return text; + } + /// + /// 保存手动要求的条码 + /// + /// + private string SavingEngineIDShift() + { + string text = ""; + bool flag = false; + System.Data.DataTable dt = null; + try + { + string opname = HttpContext.Current.Request["value"];//工位号 + string date = HttpContext.Current.Request["date"];//日期 + string num = HttpContext.Current.Request["num"];//流水号 + string[] dates = date.Split('-'); + if (dates.Length > 2) + { + int year = Convert.ToInt32(dates[0]); + int month = Convert.ToInt32(dates[1]); + int day = Convert.ToInt32(dates[2]); + int single = Convert.ToInt32(num); + MES.OpName_MIS_Manual_Insert(opname, year, month, day, single); + flag = true; + } + if (flag) + { + text = "{\"flag\":\"1\"}"; + } + else + { + text = "{\"flag\":\"0\"}"; + } + return text; + } + catch (Exception err) + { + text = "{\"flag\":\"0\"}"; + //ApplicationLog.WriteLog(err, "MesWebFun01:SavingEngineIDShift"); + return text; + } + } + + private static string RepairStatusInit() + { + string Opname = HttpContext.Current.Request["value"];//工位号 + string selectID = HttpContext.Current.Request["text_selectByID"];//工位号 text_selectByID + string outtext = CreateRepairUpLine(Opname, selectID); + return outtext; + } + + + /// + /// 动态创建返修上线工位按钮 + /// + /// + /// + public static string CreateRepairUpLine(string OpName, string selectID) + { + StringBuilder HtmlStr = new StringBuilder();//可修改字符串 + + string BtnData = ""; + int RouteNum = 0; + bool HaveDataOrNot = false; + DataTable dt; + + string StationDataStr;//最近一条返修工位数据 + //查询返修上线字符串及路径数目 + RepairBtnDataSelect(OpName, out BtnData, out RouteNum); + string[] RepairSta = BtnData.Split('^');//目标工位数组 + string TargetStationData = "";//目标工位数据 + //查询之前的返修上线数据 + HaveDataOrNot = selectRepairStrSelect(OpName, selectID, out dt); + //合成界面显示按钮字符串 + if (HaveDataOrNot) + { + StationDataStr = dt.Rows[0]["返修字符串"].ToString(); + if (StationDataStr == "") + { + for (int i = 0; i < RepairSta.Length; i++) + { + if (i < (RepairSta.Length - 1)) + { + TargetStationData = TargetStationData + "1^"; + } + else + { + TargetStationData = TargetStationData + "1"; + } + } + } + else + { + TargetStationData = StationDataStr; + } + } + else + { + + for (int i = 0; i < RepairSta.Length; i++) + { + if (i < (RepairSta.Length - 1)) + { + TargetStationData = TargetStationData + "1^"; + } + else + { + TargetStationData = TargetStationData + "1"; + } + } + } + //页面定义 + HtmlStr.Append("\r\n"); + for (int i = 0; i < RepairSta.Length; i++) + { + //动态生成标签 + //样式定义 + string td_style = "width:20%;height:35px";//td样式 + string btn_style = "width:98%;height:98%;font-family:微软雅黑;font-size:15px;border-color: #99CCFF";//标签样式 + string type = "button"; + string tagID = "Btn_" + RepairSta[i]; + string value = RepairSta[i]; + string onclick = "RepairBtnClick(Btn_" + value + ")"; + string[] StationDataArray = TargetStationData.Split('^'); + string bgColor; + + if (StationDataArray[i] == "1") + { + bgColor = "background-color: green"; + } + else + { + bgColor = "background-color: gray"; + } + //保证每行5个按钮 + if (i < RepairSta.Length - 1) + { + if (i % 5 < 4) + { + HtmlStr.Append(""); + } + else + { + HtmlStr.Append(""); + HtmlStr.Append("\r\n"); + } + } + else + { + HtmlStr.Append(""); + HtmlStr.Append(""); + } + + } + HtmlStr.Append("
"); + //上线路径大于1条则显示上线路径 + if (RouteNum > 1) + { + + } + return HtmlStr.ToString(); + } + + + /// + /// 向数据库写入返修数据 + /// + /// + /// + /// + public static bool updateRepairStatusTo_SQL(string opname, string status) + { + string produceName = "测量数据_返修工位_工位状态_修改"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opname); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@返修状态", status); + + return DataAccess.ExecuteStoredProcedure(produceName, ref thisParms); + } + private static string SaveRepairStatus() + { + + try + { + string RepairStatus = HttpContext.Current.Request["str_value"];//返修工位状态 + string engineID = HttpContext.Current.Request["engineID"];//返修零件总成号 + int RepairMethod = Convert.ToInt32(HttpContext.Current.Request["RepairMethod"]);//返修路径 + string engineType = HttpContext.Current.Request["engineType"];//返修零件总成号 + string RepairOpName = HttpContext.Current.Request["OpName"];//返修上线点 + string[] RepairStatusSplit = RepairStatus.Split('|'); + for (int i = 0; i < RepairStatusSplit.Length - 1; i++) + { + updateRepairStatusTo_SQL(RepairStatusSplit[i].Split('^')[0], RepairStatusSplit[i].Split('^')[1]); + } + + string produceName = "返修上线_返修工位及返修路径_增加"; + SqlParameter[] thisParms = new SqlParameter[5]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@总成编号", engineID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@返修状态", RepairStatus); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@返修路径", RepairMethod); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@发动机型号", engineType); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@返修上线点", RepairOpName); + string result = Convert.ToString(DataAccess.ExecuteStoredProcedure(produceName, ref thisParms)); + return result; + } + catch (Exception err) + { + return "0"; + } + + } + /// [电子看板_发动机号_线首工位_查询_根据发动机号] 20160728 majian + /// + /// + /// + static public bool GetEngineID_Select(string engineID, string opName, out DataTable dt) + { + string errorMessage = ""; + DataSet ds; + bool isOK; + dt = null; + //string connectionString = ApplicationConfig.ConnectionString; + string procedureName; + procedureName = "电子看板_发动机号_线首工位_查询_根据发动机号"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@发动机号", engineID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + isOK = DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out ds); + if (isOK) + { + if (ds.Tables.Count > 0) + { + dt = ds.Tables[0]; + return true; + } + else + { + return false; + } + } + else + { + return false; + } + } + private string QualityDataButton_bgColor_Select_energineSelect() + { + string text = ""; + try + { + System.Data.DataTable dt = null; + //单号 + string energineID = HttpContext.Current.Request["energineID"]; + string opname = HttpContext.Current.Request["value"]; + QualityDataButton_bgColor_Select(opname, energineID, out dt);//此处重新写函数 + if (dt != null) + { + if (dt.Rows.Count >= 0) + { + text = Buttons.Createbuttons(dt); + } + } + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, "MesWebFun02:QualityDataButton_bgColor_Select"); + } + return text; + + } + /// WEB根据工位名称和发动机号查询质量数据合格索引(包括了分线的信息、存储过程中根据工位类型区分) 20140626 wt + /// + /// + /// + /// + /// + public static bool QualityDataButton_bgColor_Select(string opname, string energineID, out DataTable dt) + { + string procedureName = "显示测量数据_工位号_根据发动机型号_查询"; + SqlParameter[] sqlParameters = new SqlParameter[2]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", opname); + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@发动机号", energineID); + return DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + } + + + /// + /// 获取对应工位的质量数据 + /// + /// + private string QualityDataSelectByEnergineID() + { + string qualitydata = ""; + try + { + System.Data.DataTable dt = null; + string energineID = HttpContext.Current.Request["value"]; + string opname = HttpContext.Current.Request["opname"]; + QualityDataSelect(opname, energineID, out dt); + if (dt != null) + { + //if (dt.Rows.Count > 0) + { + qualitydata = JsonHelper.CreateJsonParameters(dt); + } + } + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, "MesWebFun10:QualityDataSelect"); + } + return qualitydata; + + } + + static public bool QualityDataSelect(string opname, string energineID, out DataTable dt) + { + string procedureName; + procedureName = "显示测量数据_根据_工位号_发动机型号_查询"; + SqlParameter[] sqlParameters = new SqlParameter[2]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", opname); + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@发动机号", energineID); + return DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + } + + /// + /// 查询返修上线工位及返修路径数目 + /// + /// + /// + /// + public static void RepairBtnDataSelect(string OpName, out string BtnData, out int RouteNum) + { + + DataTable dt; + string procedureName; + BtnData = ""; + RouteNum = 0; + procedureName = "返修上线_返修工位_返修上线点及返修路径_基础配置_查询"; + SqlParameter[] sqlParameters = new SqlParameter[1]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", OpName); + DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + if (dt != null) + { + if (dt.Rows.Count > 0) + { + BtnData = dt.Rows[0]["待返修工位"].ToString(); + RouteNum = Convert.ToInt32(dt.Rows[0]["返修路径数目"]); + } + } + } + + + /// + /// 查询当前上线点上次选择的返修工位,用于界面按钮颜色原始数据 + /// + /// + /// + /// + public static bool selectRepairData(string OpName, out DataTable dt) + { + + string procedureName; + procedureName = "返修上线_返修工位及返修路径_最近数据_查询"; + SqlParameter[] sqlParameters = new SqlParameter[1]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@返修上线点", OpName); + DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + if (dt.Rows.Count > 0) + { + return true; + } + else + { + + return false; + } + } + /// + /// + /// + /// + /// + /// + public static bool selectRepairStrSelect(string OpName, string selectID, out DataTable dt) + { + string procedureName; + procedureName = "返修上线_返修工位及返修路径_是否工作判断"; + SqlParameter[] sqlParameters = new SqlParameter[2]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@返修上线点", OpName); + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@发动机号", selectID); + DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + if (dt.Rows.Count > 0) + { + return true; + } + else + { + + return false; + } + + } + } +} diff --git a/Common/08WebFun_base/WebFun_base/SpecialFun/WebFunction17.cs b/Common/08WebFun_base/WebFun_base/SpecialFun/WebFunction17.cs new file mode 100644 index 0000000..03bd217 --- /dev/null +++ b/Common/08WebFun_base/WebFun_base/SpecialFun/WebFunction17.cs @@ -0,0 +1,483 @@ +using bizFacade; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Web; +//using SystemFramework; +using System.Data; +using System.Data.SqlClient; +using DataLinkMesWork; +namespace MesWebFun +{ + public class WebFunction17 + { + HttpContext contextMesWebFun; + public string ProcessRequest(HttpContext context) + { + contextMesWebFun = context; ; + context.Response.ContentType = "text/plain"; + string type = contextMesWebFun.Request["type"]; + string responseText = ""; + switch (type) + { + //保存手动生成条码 + case "SavingEngineIDShift": + responseText = SavingEngineIDShift(); + break; + case "SaveRepairStatus"://将返修路径及返修数据保存到数据库 + responseText = SaveRepairStatus(); + break; + case "RepairStatusInit"://将返修路径及返修数据保存到数据库 + responseText = RepairStatusInit(); + break; + case "Select_engineType_ByEnergineID": //根据发动机号显示机型 + responseText = Select_engineType_ByEnergineID(); + break; + case "QualityDataButton_bgColor_Select_ByEnergineID": + responseText = QualityDataButton_bgColor_Select_energineSelect(); + break; + ///////////////////////质量查询根据发动机号 + case "QualityDataSelectByEnergineID": + responseText = QualityDataSelectByEnergineID(); + break; + default: + responseText = "17"; + break; + } + return responseText; + } + /// + /// //根据发动机号显示机型,界面提示 + /// + /// + private string Select_engineType_ByEnergineID() + { + string text = ""; + try + { + System.Data.DataTable dt = null; + string opName = HttpContext.Current.Request["value"];//发动机号 + string energineID = HttpContext.Current.Request["energineID"];//发动机号 + GetEngineID_Select(energineID, opName, out dt); + + string engineType = ""; + if (dt != null) + { + if (dt.Rows.Count > 0) + { + engineType = dt.Rows[0]["发动机型号"].ToString(); + } + } + text = "{\"engineType\":\"" + engineType + "\"}"; + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, "MesWebFun08:Select_engineType_ByEnergineID"); + } + return text; + } + /// + /// 保存手动要求的条码 + /// + /// + private string SavingEngineIDShift() + { + string text = ""; + bool flag = false; + System.Data.DataTable dt = null; + try + { + string opname = HttpContext.Current.Request["value"];//工位号 + string date = HttpContext.Current.Request["date"];//日期 + string num = HttpContext.Current.Request["num"];//流水号 + string[] dates = date.Split('-'); + if (dates.Length > 2) + { + int year = Convert.ToInt32(dates[0]); + int month = Convert.ToInt32(dates[1]); + int day = Convert.ToInt32(dates[2]); + int single = Convert.ToInt32(num); + MES.OpName_MIS_Manual_Insert(opname, year, month, day, single); + flag = true; + } + if (flag) + { + text = "{\"flag\":\"1\"}"; + } + else + { + text = "{\"flag\":\"0\"}"; + } + return text; + } + catch (Exception err) + { + text = "{\"flag\":\"0\"}"; + //ApplicationLog.WriteLog(err, "MesWebFun01:SavingEngineIDShift"); + return text; + } + } + + private static string RepairStatusInit() + { + string Opname = HttpContext.Current.Request["value"];//工位号 + string selectID = HttpContext.Current.Request["text_selectByID"];//工位号 text_selectByID + string outtext = CreateRepairUpLine(Opname, selectID); + return outtext; + } + + + /// + /// 动态创建返修上线工位按钮 + /// + /// + /// + public static string CreateRepairUpLine(string OpName, string selectID) + { + StringBuilder HtmlStr = new StringBuilder();//可修改字符串 + + string BtnData = ""; + int RouteNum = 0; + bool HaveDataOrNot = false; + DataTable dt; + + string StationDataStr;//最近一条返修工位数据 + //查询返修上线字符串及路径数目 + RepairBtnDataSelect(OpName, out BtnData, out RouteNum); + string[] RepairSta = BtnData.Split('^');//目标工位数组 + string TargetStationData = "";//目标工位数据 + //查询之前的返修上线数据 + HaveDataOrNot = selectRepairStrSelect(OpName, selectID, out dt); + //合成界面显示按钮字符串 + if (HaveDataOrNot) + { + StationDataStr = dt.Rows[0]["返修字符串"].ToString(); + if (StationDataStr == "") + { + for (int i = 0; i < RepairSta.Length; i++) + { + if (i < (RepairSta.Length - 1)) + { + TargetStationData = TargetStationData + "1^"; + } + else + { + TargetStationData = TargetStationData + "1"; + } + } + } + else + { + TargetStationData = StationDataStr; + } + } + else + { + + for (int i = 0; i < RepairSta.Length; i++) + { + if (i < (RepairSta.Length - 1)) + { + TargetStationData = TargetStationData + "1^"; + } + else + { + TargetStationData = TargetStationData + "1"; + } + } + } + //页面定义 + HtmlStr.Append("\r\n"); + for (int i = 0; i < RepairSta.Length; i++) + { + //动态生成标签 + //样式定义 + string td_style = "width:20%;height:35px";//td样式 + string btn_style = "width:98%;height:98%;font-family:微软雅黑;font-size:15px;border-color: #99CCFF";//标签样式 + string type = "button"; + string tagID = "Btn_" + RepairSta[i]; + string value = RepairSta[i]; + string onclick = "RepairBtnClick(Btn_" + value + ")"; + string[] StationDataArray = TargetStationData.Split('^'); + string bgColor; + + if (StationDataArray[i] == "1") + { + bgColor = "background-color: green"; + } + else + { + bgColor = "background-color: gray"; + } + //保证每行5个按钮 + if (i < RepairSta.Length - 1) + { + if (i % 5 < 4) + { + HtmlStr.Append(""); + } + else + { + HtmlStr.Append(""); + HtmlStr.Append("\r\n"); + } + } + else + { + HtmlStr.Append(""); + HtmlStr.Append(""); + } + + } + HtmlStr.Append("
"); + //上线路径大于1条则显示上线路径 + if (RouteNum > 1) + { + + } + return HtmlStr.ToString(); + } + + + /// + /// 向数据库写入返修数据 + /// + /// + /// + /// + public static bool updateRepairStatusTo_SQL(string opname, string status) + { + string produceName = "测量数据_返修工位_工位状态_修改"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opname); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@返修状态", status); + + return DataAccess.ExecuteStoredProcedure(produceName, ref thisParms); + } + private static string SaveRepairStatus() + { + + try + { + string RepairStatus = HttpContext.Current.Request["str_value"];//返修工位状态 + string engineID = HttpContext.Current.Request["engineID"];//返修零件总成号 + int RepairMethod = Convert.ToInt32(HttpContext.Current.Request["RepairMethod"]);//返修路径 + string engineType = HttpContext.Current.Request["engineType"];//返修零件总成号 + string RepairOpName = HttpContext.Current.Request["OpName"];//返修上线点 + string[] RepairStatusSplit = RepairStatus.Split('|'); + for (int i = 0; i < RepairStatusSplit.Length - 1; i++) + { + updateRepairStatusTo_SQL(RepairStatusSplit[i].Split('^')[0], RepairStatusSplit[i].Split('^')[1]); + } + + string produceName = "返修上线_返修工位及返修路径_增加"; + SqlParameter[] thisParms = new SqlParameter[5]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@总成编号", engineID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@返修状态", RepairStatus); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@返修路径", RepairMethod); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@发动机型号", engineType); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@返修上线点", RepairOpName); + string result = Convert.ToString(DataAccess.ExecuteStoredProcedure(produceName, ref thisParms)); + return result; + } + catch (Exception err) + { + return "0"; + } + + } + /// [电子看板_发动机号_线首工位_查询_根据发动机号] 20160728 majian + /// + /// + /// + static public bool GetEngineID_Select(string engineID, string opName, out DataTable dt) + { + string errorMessage = ""; + DataSet ds; + bool isOK; + dt = null; + //string connectionString = ApplicationConfig.ConnectionString; + string procedureName; + procedureName = "电子看板_发动机号_线首工位_查询_根据发动机号"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@发动机号", engineID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + isOK = DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out ds); + if (isOK) + { + if (ds.Tables.Count > 0) + { + dt = ds.Tables[0]; + return true; + } + else + { + return false; + } + } + else + { + return false; + } + } + private string QualityDataButton_bgColor_Select_energineSelect() + { + string text = ""; + try + { + System.Data.DataTable dt = null; + //单号 + string energineID = HttpContext.Current.Request["energineID"]; + string opname = HttpContext.Current.Request["value"]; + QualityDataButton_bgColor_Select(opname, energineID, out dt);//此处重新写函数 + if (dt != null) + { + if (dt.Rows.Count >= 0) + { + text = Buttons.Createbuttons(dt); + } + } + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, "MesWebFun02:QualityDataButton_bgColor_Select"); + } + return text; + + } + /// WEB根据工位名称和发动机号查询质量数据合格索引(包括了分线的信息、存储过程中根据工位类型区分) 20140626 wt + /// + /// + /// + /// + /// + public static bool QualityDataButton_bgColor_Select(string opname, string energineID, out DataTable dt) + { + string procedureName = "显示测量数据_工位号_根据发动机型号_查询"; + SqlParameter[] sqlParameters = new SqlParameter[2]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", opname); + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@发动机号", energineID); + return DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + } + + + /// + /// 获取对应工位的质量数据 + /// + /// + private string QualityDataSelectByEnergineID() + { + string qualitydata = ""; + try + { + System.Data.DataTable dt = null; + string energineID = HttpContext.Current.Request["value"]; + string opname = HttpContext.Current.Request["opname"]; + QualityDataSelect(opname, energineID, out dt); + if (dt != null) + { + //if (dt.Rows.Count > 0) + { + qualitydata = JsonHelper.CreateJsonParameters(dt); + } + } + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, "MesWebFun10:QualityDataSelect"); + } + return qualitydata; + + } + + static public bool QualityDataSelect(string opname, string energineID, out DataTable dt) + { + string procedureName; + procedureName = "显示测量数据_根据_工位号_发动机型号_查询"; + SqlParameter[] sqlParameters = new SqlParameter[2]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", opname); + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@发动机号", energineID); + return DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + } + + /// + /// 查询返修上线工位及返修路径数目 + /// + /// + /// + /// + public static void RepairBtnDataSelect(string OpName, out string BtnData, out int RouteNum) + { + + DataTable dt; + string procedureName; + BtnData = ""; + RouteNum = 0; + procedureName = "返修上线_返修工位_返修上线点及返修路径_基础配置_查询"; + SqlParameter[] sqlParameters = new SqlParameter[1]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@工位号", OpName); + DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + if (dt != null) + { + if (dt.Rows.Count > 0) + { + BtnData = dt.Rows[0]["待返修工位"].ToString(); + RouteNum = Convert.ToInt32(dt.Rows[0]["返修路径数目"]); + } + } + } + + + /// + /// 查询当前上线点上次选择的返修工位,用于界面按钮颜色原始数据 + /// + /// + /// + /// + public static bool selectRepairData(string OpName, out DataTable dt) + { + + string procedureName; + procedureName = "返修上线_返修工位及返修路径_最近数据_查询"; + SqlParameter[] sqlParameters = new SqlParameter[1]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@返修上线点", OpName); + DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + if (dt.Rows.Count > 0) + { + return true; + } + else + { + + return false; + } + } + /// + /// + /// + /// + /// + /// + public static bool selectRepairStrSelect(string OpName, string selectID, out DataTable dt) + { + string procedureName; + procedureName = "返修上线_返修工位及返修路径_是否工作判断"; + SqlParameter[] sqlParameters = new SqlParameter[2]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@返修上线点", OpName); + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@发动机号", selectID); + DataAccess.ExecuteStoredProcedure(procedureName, ref sqlParameters, out dt); + if (dt.Rows.Count > 0) + { + return true; + } + else + { + + return false; + } + + } + } +} diff --git a/Common/08WebFun_base/WebFun_base/SpecialFun/vssver2.scc b/Common/08WebFun_base/WebFun_base/SpecialFun/vssver2.scc new file mode 100644 index 0000000..1146cc5 Binary files /dev/null and b/Common/08WebFun_base/WebFun_base/SpecialFun/vssver2.scc differ diff --git a/Common/09MesDataFunction/MesDataFunction.sln b/Common/09MesDataFunction/MesDataFunction.sln new file mode 100644 index 0000000..5cc56d6 --- /dev/null +++ b/Common/09MesDataFunction/MesDataFunction.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.32901.82 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MesDataFunction", "MesDataFunction\MesDataFunction.csproj", "{90E76FB4-646D-45E2-95DB-0B8AB4E465D6}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {90E76FB4-646D-45E2-95DB-0B8AB4E465D6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {90E76FB4-646D-45E2-95DB-0B8AB4E465D6}.Debug|Any CPU.Build.0 = Debug|Any CPU + {90E76FB4-646D-45E2-95DB-0B8AB4E465D6}.Release|Any CPU.ActiveCfg = Release|Any CPU + {90E76FB4-646D-45E2-95DB-0B8AB4E465D6}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {48DF007D-B08C-43B9-9AC7-78F6B2C23954} + EndGlobalSection +EndGlobal diff --git a/Common/09MesDataFunction/MesDataFunction/09-MesDataFunction.csproj b/Common/09MesDataFunction/MesDataFunction/09-MesDataFunction.csproj new file mode 100644 index 0000000..6afc4d8 --- /dev/null +++ b/Common/09MesDataFunction/MesDataFunction/09-MesDataFunction.csproj @@ -0,0 +1,149 @@ + + + + + Debug + AnyCPU + {90E76FB4-646D-45E2-95DB-0B8AB4E465D6} + Library + Properties + MesDataFunction + 09MesDataFunction + v4.8 + 512 + true + + + + true + full + false + ..\..\dll\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + ..\..\..\dll_common\BasicData.dll + + + ..\..\..\dll_common\ConLink.dll + + + ..\..\..\dll_common\MesWork.DeviceDriver.dll + + + ..\..\..\dll_common\MesWork.PLC.dll + + + ..\..\..\dll_common\Monitor.MesWork.dll + + + ..\..\dll\MQTTnet.dll + + + ..\..\dll\MQTTnet.Extensions.ManagedClient.dll + + + False + ..\..\..\dll_common\Newtonsoft.Json.dll + + + ..\..\..\dll_common\NPOI.dll + + + ..\..\..\dll_common\NPOI.OOXML.dll + + + ..\..\..\dll_common\NPOI.OpenXml4Net.dll + + + ..\..\..\dll_common\NPOI.OpenXmlFormats.dll + + + ..\..\..\dll_common\Opc.Ua.Client.dll + + + ..\..\..\dll_common\Opc.Ua.Configuration.dll + + + ..\..\..\dll_common\Opc.Ua.Core.dll + + + ..\..\..\dll_common\OpcUaHelper.dll + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Form + + + + + + + + + + + {f55da1a0-a982-4479-8c47-0d9a5aaf3e18} + 00MesWorkMqtt + + + {0d1af432-439a-4920-8692-43ae139f5530} + 01_01DoWhatPlc + + + {f434e066-4c59-47c8-aa82-6f48cc84501a} + 04-DataBaseAccess + + + {f0a0c525-03fd-428a-9b17-7f54aa0e4475} + 07BusinessFacade + + + {d98be764-adeb-488d-9714-61e308aa8201} + 08-WebFun_base + + + + + + + \ No newline at end of file diff --git a/Common/09MesDataFunction/MesDataFunction/LoadTagTypeCodeID.cs b/Common/09MesDataFunction/MesDataFunction/LoadTagTypeCodeID.cs new file mode 100644 index 0000000..102968a --- /dev/null +++ b/Common/09MesDataFunction/MesDataFunction/LoadTagTypeCodeID.cs @@ -0,0 +1,128 @@ +//using BasicData; +//using MesWork; +//using OpcBasic; +using DoWhatPlc; +using MesServerWork; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.Specialized; +using System.Data; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MesDataFunction +{ + public class LoadTagTypeCodeID + { + + + public static void Load(string path) + { + MIS_BASE.hashtable_TagType = new NameValueCollection(); + MIS_BASE.hashtable_TagTypeTagName = new NameValueCollection(); + MIS_BASE.hashtable_TagTypeChange = new NameValueCollection(); + MIS_BASE.hashtable_MesTagTypeChange = new NameValueCollection(); + MIS_BASE.hashtable_WebTagTypeChange = new NameValueCollection(); + MIS_BASE.hashtable_TagTypeDataType = new NameValueCollection(); + + var dt = NPOITest.ExeclHelper.ExcelToDataTable(path, "变量类型代码", true); + for (int i = 0; i < dt.Rows.Count; i++) + { + //序号 变量类型 TagTypeDataType TagName 变量类型代码 TagTypeChange MesTagTypeChange WebTagTypeChange 信号点名称 变量类型名称 + + var TagTypeDataType = dt.Rows[i]["TagTypeDataType"].ToString(); + var TagName = dt.Rows[i]["TagName"].ToString(); + var 变量类型代码 = dt.Rows[i]["变量类型代码"].ToString(); + var TagTypeChange = dt.Rows[i]["TagTypeChange"].ToString(); + var WebTagTypeChange = dt.Rows[i]["WebTagTypeChange"].ToString(); + var MesTagTypeChange = dt.Rows[i]["MesTagTypeChange"].ToString(); + + //OpcOperation.hashtable_TagType.Add(TagName, 变量类型代码); + //OpcOperation.hashtable_TagTypeTagName.Add(变量类型代码, TagName); + //OpcOperation.hashtable_TagTypeChange.Add(TagName, TagTypeChange); + //OpcOperation.hashtable_MesTagTypeChange.Add(TagName, MesTagTypeChange); + //OpcOperation.hashtable_WebTagTypeChange.Add(TagName, WebTagTypeChange); + //OpcOperation.hashtable_TagTypeDataType.Add(变量类型代码, TagTypeDataType); + if (!MIS_BASE.hashtable_TagType.AllKeys.Contains(TagName)) + MIS_BASE.hashtable_TagType.Add(TagName, 变量类型代码); + if (!MIS_BASE.hashtable_TagTypeTagName.AllKeys.Contains(变量类型代码)) + MIS_BASE.hashtable_TagTypeTagName.Add(变量类型代码, TagName); + if (!MIS_BASE.hashtable_TagTypeChange.AllKeys.Contains(TagName)) + MIS_BASE.hashtable_TagTypeChange.Add(TagName, TagTypeChange); + if (!MIS_BASE.hashtable_MesTagTypeChange.AllKeys.Contains(TagName)) + MIS_BASE.hashtable_MesTagTypeChange.Add(TagName, MesTagTypeChange); + if (!MIS_BASE.hashtable_WebTagTypeChange.AllKeys.Contains(TagName)) + MIS_BASE.hashtable_WebTagTypeChange.Add(TagName, WebTagTypeChange); + if (!MIS_BASE.hashtable_TagTypeDataType.AllKeys.Contains(变量类型代码)) + MIS_BASE.hashtable_TagTypeDataType.Add(变量类型代码, TagTypeDataType); + } + HashtableList.hashtable_TagTypeTagName_Temp = new Hashtable(); + foreach (string key in MIS_BASE.hashtable_TagTypeTagName.Keys) + { + HashtableList.hashtable_TagTypeTagName_Temp.Add(key, MIS_BASE.hashtable_TagTypeTagName[key]); + } + HashtableList.hashtable_TagTypeDataType_Temp = new NameValueCollection(); + foreach (string key in MIS_BASE.hashtable_TagTypeDataType.Keys) + { + HashtableList.hashtable_TagTypeDataType_Temp.Add(key, MIS_BASE.hashtable_TagTypeDataType[key]); + } + HashtableList.hashtable_TagType_Temp = new NameValueCollection(); + foreach (string key in MIS_BASE.hashtable_TagType.Keys) + { + HashtableList.hashtable_TagType_Temp.Add(key, MIS_BASE.hashtable_TagType[key]); + } + } + + public static void Load(DataTable dt) + { + MIS_BASE.hashtable_TagType = new NameValueCollection(); + MIS_BASE.hashtable_TagTypeTagName = new NameValueCollection(); + MIS_BASE.hashtable_TagTypeChange = new NameValueCollection(); + MIS_BASE.hashtable_MesTagTypeChange = new NameValueCollection(); + MIS_BASE.hashtable_WebTagTypeChange = new NameValueCollection(); + MIS_BASE.hashtable_TagTypeDataType = new NameValueCollection(); + + for (int i = 0; i < dt.Rows.Count; i++) + { + //序号 变量类型 TagTypeDataType TagName 变量类型代码 TagTypeChange MesTagTypeChange WebTagTypeChange 信号点名称 变量类型名称 + var TagTypeDataType = dt.Rows[i]["TagTypeDataType"].ToString(); + var TagName = dt.Rows[i]["TagName"].ToString(); + var 变量类型代码 = dt.Rows[i]["变量类型代码"].ToString(); + var TagTypeChange = dt.Rows[i]["TagTypeChange"].ToString(); + var WebTagTypeChange = dt.Rows[i]["WebTagTypeChange"].ToString(); + var MesTagTypeChange = dt.Rows[i]["MesTagTypeChange"].ToString(); + if (!MIS_BASE.hashtable_TagType.AllKeys.Contains(TagName)) + MIS_BASE.hashtable_TagType.Add(TagName, 变量类型代码); + if (!MIS_BASE.hashtable_TagTypeTagName.AllKeys.Contains(变量类型代码)) + MIS_BASE.hashtable_TagTypeTagName.Add(变量类型代码, TagName); + if (!MIS_BASE.hashtable_TagTypeChange.AllKeys.Contains(TagName)) + MIS_BASE.hashtable_TagTypeChange.Add(TagName, TagTypeChange); + if (!MIS_BASE.hashtable_MesTagTypeChange.AllKeys.Contains(TagName)) + MIS_BASE.hashtable_MesTagTypeChange.Add(TagName, MesTagTypeChange); + if (!MIS_BASE.hashtable_WebTagTypeChange.AllKeys.Contains(TagName)) + MIS_BASE.hashtable_WebTagTypeChange.Add(TagName, WebTagTypeChange); + if (!MIS_BASE.hashtable_TagTypeDataType.AllKeys.Contains(变量类型代码)) + MIS_BASE.hashtable_TagTypeDataType.Add(变量类型代码, TagTypeDataType); + } + HashtableList.hashtable_TagTypeTagName_Temp = new Hashtable(); + foreach (string key in MIS_BASE.hashtable_TagTypeTagName.Keys) + { + HashtableList.hashtable_TagTypeTagName_Temp.Add(key, MIS_BASE.hashtable_TagTypeTagName[key]); + } + HashtableList.hashtable_TagTypeDataType_Temp = new NameValueCollection(); + foreach (string key in MIS_BASE.hashtable_TagTypeDataType.Keys) + { + HashtableList.hashtable_TagTypeDataType_Temp.Add(key, MIS_BASE.hashtable_TagTypeDataType[key]); + } + HashtableList.hashtable_TagType_Temp = new NameValueCollection(); + foreach (string key in MIS_BASE.hashtable_TagType.Keys) + { + HashtableList.hashtable_TagType_Temp.Add(key, MIS_BASE.hashtable_TagType[key]); + } + } + + } + +} diff --git a/Common/09MesDataFunction/MesDataFunction/MesDataFunction/InitTagValueListData.cs b/Common/09MesDataFunction/MesDataFunction/MesDataFunction/InitTagValueListData.cs new file mode 100644 index 0000000..0d66024 --- /dev/null +++ b/Common/09MesDataFunction/MesDataFunction/MesDataFunction/InitTagValueListData.cs @@ -0,0 +1,84 @@ +//using DataLinkMesWork; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Data; +using System.Linq; +using System.Text; +//using SystemFramework; + +namespace MesServerWork +{ + public class InitTagValueListData + { + public InitTagValueListData() + { + DataTable dt = ReadMesServerData(); + + InitMesReadTagKey(); + initAllItemValue(dt); + } + + DataTable ReadMesServerData() + { + return null;// MesWork.PlcLinkForm.dt_BasicData.Select($"是否启用 = 1 and 监控属性代码 = '{1}'").CopyToDataTable(); + } + + void InitMesReadTagKey() + { + DataTable dt = null;// MesWork.PlcLinkForm.dt_BasicData.Select($"是否启用 = 1 and 变量类型代码=19 and 监控属性代码 = '{1}'").CopyToDataTable(); ; + + for (int i = 0; i < dt.Rows.Count; i++) + { + if (MesReadTagKey_Hash.ContainsKey(dt.Rows[i]["工位号"].ToString())) + { + MesReadTagKey_Hash[dt.Rows[i]["工位号"].ToString()] = dt.Rows[i]["TagID"].ToString(); + } + else + { + MesReadTagKey_Hash.Add(dt.Rows[i]["工位号"].ToString(), dt.Rows[i]["TagID"].ToString()); + } + + } + + } + void initAllItemValue(DataTable dt) + { + for (int i = 0; i < dt.Rows.Count; i++) + { + if (ItemValue_Hash.ContainsKey(dt.Rows[i]["TagID"])) + { + if (Convert.ToInt32(dt.Rows[i]["列位置"]) != 0) + { + ItemValue_Hash[dt.Rows[i]["TagID"]] = dt.Rows[i]["测量项目"].ToString() + "(" + dt.Rows[i]["列位置"].ToString() + ")"; + } + else + { + ItemValue_Hash[dt.Rows[i]["TagID"]] = dt.Rows[i]["测量项目"].ToString(); + } + + } + else + { + if (Convert.ToInt32(dt.Rows[i]["列位置"]) != 0) + { + ItemValue_Hash[dt.Rows[i]["TagID"]] = dt.Rows[i]["测量项目"].ToString() + "(" + dt.Rows[i]["列位置"].ToString() + ")"; + } + else + { + ItemValue_Hash[dt.Rows[i]["TagID"]] = dt.Rows[i]["测量项目"].ToString(); + } + } + + } + + + } + + + + public static Hashtable MesReadTagKey_Hash = new Hashtable(); + public static Hashtable ItemValue_Hash = new Hashtable(); + + } +} diff --git a/Common/09MesDataFunction/MesDataFunction/MesDataFunction/MIS.Functions.Barcode.cs b/Common/09MesDataFunction/MesDataFunction/MesDataFunction/MIS.Functions.Barcode.cs new file mode 100644 index 0000000..1df2dfe --- /dev/null +++ b/Common/09MesDataFunction/MesDataFunction/MesDataFunction/MIS.Functions.Barcode.cs @@ -0,0 +1,95 @@ +using System; +using System.Data; +using System.Collections; + +using System.Windows.Forms; +//using bizFacade; +using System.Collections.Specialized; +//using MesWork; +//using SystemFramework; +using bizFacade; + +namespace MesServerWork +{ + public partial class MIS_BASE + { + static object lockerBarcode = new object(); + + /// + ///1.扫描配送单号,用于接收物料,扫描单号的时候,将接收的物料信息显示在“物料拉动”Tab区域 + ///2.扫描料箱标签/看板卡,用于追溯物料批次信息 + ///3.扫描零件条码,根据零件图号进行防错 + ///第一步,判断条码类型,根据条码类型,执行对应的存储过程 + ///第二步,条码类型(将扫描的条码保存到对应的表中) + ///第三步,扫描完成之后给出允许工作信号 + /// 处理页面扫描条码 + /// + /// + /// + static public void Barcode(object e) + { + lock (lockerBarcode) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + string barcode = Convert.ToString(msgEvent.TagValue); + string AlarmStr = ""; + + int IsAllowWork; + bool IsSuccess = false; + bool EngineGetOver_PLC_NextWorkStep; + //传递机型是否到位 + MIS_BASE.Read_EngineGetOver_PLC(OpName, out EngineGetOver_PLC_NextWorkStep); + + BaseDataSystemMES.PartMaterial_DM_Update(OpName, barcode, out IsSuccess); + if (!IsSuccess) + { + AsyncSendMessage_Notice(OpName, "条码无效,请确认"); + return; + } + else + { + SendInfomation("MaterialList", "1", OpName);//通知界面更新零件信息 + } + + + + //获取是否允许工作 + BaseDataSystemMES.MesServer_Judge_IsCanWork(OpName, out IsAllowWork); + + //此处逻辑有问题 需要考虑到批次扫描 提示PLC未传递机型的情况 + if (EngineGetOver_PLC_NextWorkStep && IsSuccess) + { + if (IsAllowWork == 1) + { + BaseDataSystemMES.Material_Insert(OpName, 1); + + //if (!BaseDataSystemMES.QualityVerifyStatusOutline(OpName, out AlarmStr)) + //{ + // SendInfomation("LineoutAlert", AlarmStr, OpName); + // return; + //} + //通知PLC允许工作,允许工作在保存完成时清空 + MIS_BASE.Write_FixAllow(OpName, true); + } + else + { + AsyncSendMessage_Notice(OpName, "请扫描物料!"); + } + } + else + { + AsyncSendMessage_Notice(OpName, "PLC未传递机型"); + } + + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:Barcode"); + } + } + } + } +} diff --git a/Common/09MesDataFunction/MesDataFunction/MesDataFunction/MIS.Functions.ConfirmOkGo.cs b/Common/09MesDataFunction/MesDataFunction/MesDataFunction/MIS.Functions.ConfirmOkGo.cs new file mode 100644 index 0000000..26b9cfa --- /dev/null +++ b/Common/09MesDataFunction/MesDataFunction/MesDataFunction/MIS.Functions.ConfirmOkGo.cs @@ -0,0 +1,47 @@ +using System; +using System.Data; +using System.Collections; + +using System.Windows.Forms; +//using bizFacade; +using System.Collections.Specialized; +//using MesWork; +//using SystemFramework; + +namespace MesServerWork +{ + public partial class MIS_BASE + { + static object lockerConfirmOkGo = new object(); + + static public void ConfirmOkGo(object e) + { + lock (lockerConfirmOkGo) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + + if (tagValue == 1) + { + + //BaseDataSystemMES.Material_Insert(OpName, 1); + + //更新订单完工数量及物料 + Sendmessage("24", "11", OpName); + + //工作完成 + MIS_BASE.Write_MaterialVerifyOver(OpName, true); + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:ConfirmOkGo"); + } + } + + } + } +} diff --git a/Common/09MesDataFunction/MesDataFunction/MesDataFunction/MIS.Functions.EngineTypeGetOver_PLC_Work.cs b/Common/09MesDataFunction/MesDataFunction/MesDataFunction/MIS.Functions.EngineTypeGetOver_PLC_Work.cs new file mode 100644 index 0000000..670819c --- /dev/null +++ b/Common/09MesDataFunction/MesDataFunction/MesDataFunction/MIS.Functions.EngineTypeGetOver_PLC_Work.cs @@ -0,0 +1,139 @@ +using System; +using System.Data; +using System.Collections; + +using System.Windows.Forms; +//using bizFacade; +using System.Collections.Specialized; +//using MesWork; +//using SystemFramework; +using bizFacade; + +namespace MesServerWork +{ + public partial class MIS_BASE + { + static object lockerEngineTypeGetOver_PLC_Work = new object(); + + + static public void EngineTypeGetOver_PLC_Work(string OpName, int EngineTypeID, string EngineType, string EngineID, int PartPallet_Code,string OrderForm) + { + lock (lockerEngineTypeGetOver_PLC_Work) + { + int IsAllowWork; + int RepairPartStatusPLC = 0; + int MES_QualityMask = 1; + //string OrderForm = "";//订单号 + DataTable dt; + + if (EngineTypeID <= 0) + { + AsyncSendMessage_Notice(OpName, "PLC传递机型为空"); + return; + } + + //第一步,查询订单号,保存机型、机型代码、总成号、托盘号、订单号到数据库 + BaseDataSystemMES.GetEngineID_Select(OpName, EngineID, out dt); + if (dt != null && dt.Rows.Count > 0) + { + OrderForm = Convert.ToString(dt.Rows[0]["订单号"]); + } + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, OrderForm, EngineTypeID, EngineType, EngineID, PartPallet_Code, 0, 0, ""); + SaveMobyMessage(OpName, EngineTypeID, EngineType, EngineID, OrderForm); + + //第二步,将零件信息转移到零件_临时表中(本地BOM与订单BOM的选择显示关系) + BaseDataSystemMES.MesServer_Process_EngineTypeOver(OpName); + + //通知web显示 + Sendmessage("5123", "1111", OpName); + MIS_BASE.Read_PalletInfo(OpName, out MES_QualityMask);//合格标志 + MIS_BASE.Read_RepairStatus_PLC(OpName, out RepairPartStatusPLC);//返修标志 + SendInfomation("QualityMask", Convert.ToString(MES_QualityMask), OpName);//显示合格标志 + SendInfomation("RepairPartStatusPLC", Convert.ToString(RepairPartStatusPLC), OpName);//显示返修标志 + + if (MES_QualityMask == 2) + { + //工作完成 + MIS_BASE.Write_MaterialVerifyOver(OpName, true); + SendInfomation("NgGO", "1", OpName);//显示不合格标志 + return; + } + + + //第三步,用于工件离开后完工数量统计及工件编号追溯 + BaseDataSystemMES.MaterialPush_EngineIDStatus_Insert(OpName);//更新订单产量 + + //第四步,获取是否允许工作 + BaseDataSystemMES.MesServer_Judge_IsCanWork(OpName, out IsAllowWork); + + //暂时先定义为扫描完成才能进行压装工作,因为考虑到工作完成后,操作工未必会去扫描物料的情况 + if (IsAllowWork == 1) + { + //通知PLC允许工作,允许工作在保存完成时清空 + MIS_BASE.Write_FixAllow(OpName, true); + } + else + { + AsyncSendMessage_Notice(OpName, "请扫描物料!"); + } + } + + + } + + /// + /// 保存MOBY信息 + /// + /// + /// + /// + /// + static private void SaveMobyMessage(string OpName, int engineTypeID, string engineType, string engineID, string orderForm) + { + if (MIS_BASE.hashtable_EngineGetOver_EngineTypeID == null) + { + MIS_BASE.InitHashtable_MesServerCode(); + } + if (MIS_BASE.hashtable_EngineGetOver_EngineTypeID.ContainsKey(OpName)) + { + MIS_BASE.hashtable_EngineGetOver_EngineTypeID[OpName] = engineTypeID; + } + if (MIS_BASE.hashtable_EngineGetOver_EngineType.ContainsKey(OpName)) + { + MIS_BASE.hashtable_EngineGetOver_EngineType[OpName] = engineType; + } + if (MIS_BASE.hashtable_EngineGetOver_EngineID.ContainsKey(OpName)) + { + MIS_BASE.hashtable_EngineGetOver_EngineID[OpName] = engineID; + } + if (MIS_BASE.hashtable_EngineGetOver_OrderForm.ContainsKey(OpName)) + { + MIS_BASE.hashtable_EngineGetOver_OrderForm[OpName] = orderForm; + } + } + + /// + /// 返修件需要工作 + /// + /// 工位号 + static private void IsNeedRepaire_OK(string OpName) + { + string orderForm = ""; + int engineTypeID; + string engineType = ""; + string engineID = ""; + string palletCode = ""; + int isRepair; + string repairCode = ""; + //从监控系统中查询出本工位信息 + BaseDataSystemMES.OpName_MIS_Moby_Select(OpName, + out orderForm, out engineTypeID, out engineType, + out engineID, out palletCode, out isRepair, out repairCode); + + EngineTypeGetOver_PLC_Work(OpName, engineTypeID, engineType, engineID, Convert.ToInt32(palletCode),orderForm); + } + + + + } +} diff --git a/Common/09MesDataFunction/MesDataFunction/MesDataFunction/MIS.Functions.FalseGO.cs b/Common/09MesDataFunction/MesDataFunction/MesDataFunction/MIS.Functions.FalseGO.cs new file mode 100644 index 0000000..92ee314 --- /dev/null +++ b/Common/09MesDataFunction/MesDataFunction/MesDataFunction/MIS.Functions.FalseGO.cs @@ -0,0 +1,48 @@ +using System; +using System.Data; +using System.Collections; + +using System.Windows.Forms; +//using bizFacade; +using System.Collections.Specialized; +//using MesWork; +//using SystemFramework; + +namespace MesServerWork +{ + public partial class MIS_BASE + { + static object lockerFalseGO = new object(); + + + static public void FalseGO(object e) + { + lock (lockerConfirmOkGo) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + + if (tagValue == 1) + { + //总合格标志2(不合格) + + //BaseDataSystemMES.Material_Insert_NG(OpName, 2); + + Sendmessage("24", "11", OpName); + + //工作完成 + MIS_BASE.Write_MaterialVerifyOver(OpName, true); + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:FalseGO"); + } + } + + } + } +} diff --git a/Common/09MesDataFunction/MesDataFunction/MesDataFunction/MIS.Functions.Material_Insert.cs b/Common/09MesDataFunction/MesDataFunction/MesDataFunction/MIS.Functions.Material_Insert.cs new file mode 100644 index 0000000..fc78eb6 --- /dev/null +++ b/Common/09MesDataFunction/MesDataFunction/MesDataFunction/MIS.Functions.Material_Insert.cs @@ -0,0 +1,59 @@ +using System; +using System.Data; +using System.Collections; + +using System.Windows.Forms; +//using bizFacade; +using System.Collections.Specialized; +//using MesWork; +//using SystemFramework; +using bizFacade; + +namespace MesServerWork +{ + public partial class MIS_BASE + { + static object lockerMaterial_Insert = new object(); + + static public void Material_Insert(string OpName) + { + lock (lockerMaterial_Insert) + { + try + { + //int tagValue = Convert.ToInt32(msgEvent.TagValue); + int IsAllowWork; + //第四步,获取是否允许工作 + BaseDataSystemMES.MesServer_Judge_IsCanWork(OpName, out IsAllowWork); + bool EngineGetOver_PLC_NextWorkStep; + //传递机型是否到位 + MIS_BASE.Read_EngineGetOver_PLC(OpName, out EngineGetOver_PLC_NextWorkStep); + + //暂时先定义为扫描完成才能进行压装工作,因为考虑到工作完成后,操作工未必会去扫描物料的情况 + if (EngineGetOver_PLC_NextWorkStep&&IsAllowWork == 1) + { + BaseDataSystemMES.Material_Insert(OpName, 1); + + //更新订单完工数量及物料 + Sendmessage("24", "11", OpName); + + //工作完成 + MIS_BASE.Write_MaterialVerifyOver(OpName, true); + //通知PLC允许工作,允许工作在保存完成时清空 + MIS_BASE.Write_FixAllow(OpName, true); + } + else + { + AsyncSendMessage_Notice(OpName, "请扫描物料!"); + } + + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:ConfirmOkGo"); + } + } + + } + } +} diff --git a/Common/09MesDataFunction/MesDataFunction/MesDataFunction/MIS.Functions.MesReadOver.cs b/Common/09MesDataFunction/MesDataFunction/MesDataFunction/MIS.Functions.MesReadOver.cs new file mode 100644 index 0000000..260cd1a --- /dev/null +++ b/Common/09MesDataFunction/MesDataFunction/MesDataFunction/MIS.Functions.MesReadOver.cs @@ -0,0 +1,66 @@ +using System; +using System.Data; +using System.Collections; + +using System.Windows.Forms; +//using bizFacade; +using System.Collections.Specialized; +//using MesWork; +//using SystemFramework; + +namespace MesServerWork +{ + public partial class MIS_BASE + { + static object lockerMesReadOver = new object(); + + /// + /// 保存完成(针对半自动和手动压装工位) + /// + /// + /// + static public void MesReadOver(object e) + { + lock (lockerMesReadOver) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + var tagValue = msgEvent.TagValue.ToString(); + + if (tagValue == "1" | tagValue.ToLower() == "true") + { + int qualityMask; + MIS_BASE.Read_QualityMask(OpName, out qualityMask); + + SendInfomation("ShowTimelyQuality", "1&" + qualityMask.ToString(), OpName);//发给Web页面显示质量数据 + + if (qualityMask == 1)//全部OK,给出合格放行 + { + //如果存在线外扫描工位,根据扫描条码绑定线外数据 需要时解除禁用 + //BaseDataSystemMES.TransLaunchDataByMainMaterial(OpName, EngineType, EngineID, EngineTypeID); + + //如果存在线外排队工位,根据排队编号绑定线外数据 需要时解除禁用 + ////BaseDataSystemMES.MailLineAndSubLineData_InsertByEngineID_Subline(OpName,EngineID, EngineTypeID, EngineType); + + MIS_BASE.Write_ConfirmOkGo(OpName, true); + //MIS_BASE.Write_FalseGO(OpName, false); + } + else + { + //MIS_BASE.Write_ConfirmOkGo(OpName, false); + MIS_BASE.Write_FalseGO(OpName, true); + } + + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:MesReadOver"); + } + } + + } + } +} diff --git a/Common/09MesDataFunction/MesDataFunction/MesDataFunction/MIS.Functions.SendMessage.cs b/Common/09MesDataFunction/MesDataFunction/MesDataFunction/MIS.Functions.SendMessage.cs new file mode 100644 index 0000000..92bfe0a --- /dev/null +++ b/Common/09MesDataFunction/MesDataFunction/MesDataFunction/MIS.Functions.SendMessage.cs @@ -0,0 +1,162 @@ +using System; +using System.Data; +using System.Collections; + +using System.Windows.Forms; +//using bizFacade; +using System.Collections.Specialized; +//using MesWork; +//using SystemFramework; +using bizFacade; + +namespace MesServerWork +{ + public partial class MIS_BASE + { + + /// + /// 发送提示消息 + /// + /// + static private void AsyncSendMessage_Notice(string opname, string notice) + { + //通知Web界面 + BaseDataSystemMES.Web_Notice_Insert(opname, notice); + string SendMessage = "MES|Notice|" + opname + "|" + "1"; + MIS_BASE.asyncSendMessage(SendMessage); + } + + /// + /// 向WEB发送信息(value为字符串) + /// + /// 消息种类 + /// 消息内容 + /// 工位号 + static public string SendInfomation(string Command, string Value, string OpName) + { + string SendMessage = "MES|" + Command + "|" + OpName + "|" + Value; + return AsyncSendMessage(SendMessage); + } + + /// + /// 发送信息到MES通讯服务器或者其他的 + /// + /// + static private string AsyncSendMessage(string Message) + { + return MIS_BASE.asyncSendMessage(Message); + } + + + /// + /// 批量发送WEB消息(Value为BOOL值) + /// + /// 消息编号组合 + /// 消息值组合 + /// 工位号 + static void Sendmessage(string MessageNumm, string Value, string OpName) + { + for (int i = 0; i < MessageNumm.Length; i++) + { + Sendmessage(MessageNumm[i], Value[i].ToString(), OpName); + + } + } + /// + /// 选择发送给WEB的消息 + /// + /// 消息类型 + /// 消息工位 + static string Sendmessage(char Num, string Value, string OpName) + { + string SendMessage; + string result = ""; + switch (Num) + { + case '1': + //1(直接在界面通过选择机型确认工序内容) + SendMessage = "MES|ProcessList|" + OpName + "|" + Value; + result = AsyncSendMessage(SendMessage); + break; + case '2': + //2显示物料 + SendMessage = "MES|MaterialList|" + OpName + "|" + Value; + result = AsyncSendMessage(SendMessage); + break; + case '3': + //3显示操作指导图片 + SendMessage = "MES|PicShow|" + OpName + "|" + Value; + result = AsyncSendMessage(SendMessage); + break; + case '4': + //4订单完工模块刷新完成数量 + SendMessage = "MES|OrderFormList|" + OpName + "|" + Value; + AsyncSendMessage(SendMessage); + break; + case '5': + SendMessage = "MES|ShowMoby|" + OpName + "|" + Value; + result = AsyncSendMessage(SendMessage); + break; + case '6': + SendMessage = "MES|MaterialCheckPosition|" + OpName + "|" + Value; + result = AsyncSendMessage(SendMessage); + break; + case '7': + SendMessage = "MES|WorkStart|" + OpName + "|" + Value; + result = AsyncSendMessage(SendMessage); + break; + case '8'://清除MES生成编号 + + break; + case '9': + SendMessage = "MES|ConfirmOkGo|" + OpName + "|" + Value; + result = AsyncSendMessage(SendMessage); + break; + case 'a': + SendMessage = "MES|FixAllow|" + OpName + "|" + Value; + result = AsyncSendMessage(SendMessage); + break; + } + return result; + } + ///// + ///// 向WEB发送信息(value为字符串) + ///// + ///// 消息种类 + ///// 消息内容 + ///// 工位号 + //string SendInfomation(string Command, string Value, string OpName) + //{ + // string SendMessage = "MES|" + Command + "|" + OpName + "|" + Value; + // return AsyncSendMessage(SendMessage); + //} + + + /// + /// 发送在线产量、在线节拍 + /// + /// + /// + private void SendActuallyCount(string OpName, int tagValue) + { + //当工件离开时,更新在线产量、在线节拍 + if (tagValue == 0) + { + try + { + int opNameCount = 0;//在线产量 + int opNameCountTime = 0;//在线节拍 + //基本数据_工作日历_班次产量查询_New + BaseDataSystemMES.OpNameCount_New(OpName, out opNameCount, out opNameCountTime); + string SendMessage; + SendMessage = "MES|ActuallyCount|" + OpName + "|" + opNameCount.ToString() + "&" + opNameCountTime.ToString(); + AsyncSendMessage(SendMessage); + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:SendActuallyCount"); + } + } + } + } +} diff --git a/Common/09MesDataFunction/MesDataFunction/MesDataFunction/MIS.Functions.WebSubmit.cs b/Common/09MesDataFunction/MesDataFunction/MesDataFunction/MIS.Functions.WebSubmit.cs new file mode 100644 index 0000000..e472489 --- /dev/null +++ b/Common/09MesDataFunction/MesDataFunction/MesDataFunction/MIS.Functions.WebSubmit.cs @@ -0,0 +1,282 @@ +using System; +using System.Data; +using System.Collections; + +using System.Windows.Forms; +//using bizFacade; +using System.Collections.Specialized; +//using MesWork; +//using SystemFramework; +using System.Threading; +using bizFacade; + +namespace MesServerWork +{ + public partial class MIS_BASE + { + static object lockerWebSubmit = new object(); + + + /// + /// 处理WEB页面发送过来的请求(m_Command + "|" + m_Value;) + /// + /// + /// + static public void WebSubmit(object e) + { + lock (lockerWebSubmit) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + string Content = Convert.ToString(msgEvent.TagValue); + + string[] dataArray = Content.Split('|'); + if (dataArray.Length != 2) + return; + //消息类型 + string m_Command = dataArray[0].ToString(); + //消息参数 + string m_Value = dataArray[1].ToString(); + //消息参数数量 + string[] m_Value_array = m_Value.Split('&'); + //消息参数长度 + int m_Value_length = m_Value_array.Length; + + //工件信息 + string engineID = ""; + if (MIS_BASE.hashtable_EngineGetOver_EngineTypeID == null) + { + MIS_BASE.InitHashtable_MesServerCode(); + } + if (MIS_BASE.hashtable_EngineGetOver_EngineID.ContainsKey(OpName)) + { + engineID = MIS_BASE.hashtable_EngineGetOver_EngineID[OpName].ToString(); + } + + DoWhatPlc.CustomeEvetnArgs _e = new DoWhatPlc.CustomeEvetnArgs(); + _e.OpName = OpName; + _e.TagValue = m_Value; + + //根据请求的命令处理逻辑 + switch (m_Command) + { + case "Barcode": + if (m_Value_length > 1) return; + fun_Barcode(_e); + break; + case "ConfirmOkGo"://合格放行 + //删除不合格放行记录 + //修改托盘状态 + //Update_PalletStatus(OpName, 1, false); + BaseDataSystemMES.BaseData_tagTable_Engine_IsNG_Delete(OpName, engineID); + MIS_BASE.Write_ConfirmOkGo(OpName, true); + MIS_BASE.Write_FalseGO(OpName, false); + break; + case "FalseGO"://返修放行 + //修改托盘状态 + //Update_PalletStatus(OpName, 3, false); + BaseDataSystemMES.BaseData_tagTable_Engine_IsNG_Delete(OpName, engineID); + MIS_BASE.Write_FalseGO(OpName, true); + MIS_BASE.Write_ConfirmOkGo(OpName, false); + break; + case "NgGO"://不合格放行 + //修改托盘状态 + //Update_PalletStatus(OpName, 2, false); + //保存不合格信息(必须保存不合格放行信息,由于B5A的Moby没有不合格标志位) + BaseDataSystemMES.BaseData_tagTable_Engine_IsNG_Insert(OpName, engineID, "", ""); + MIS_BASE.Write_FalseGO(OpName, true); + MIS_BASE.Write_ConfirmOkGo(OpName, false); + break; + case "OnLineState"://在线0、离线1、屏蔽2 + try + { + if (m_Value_length > 1) return; + int a = Convert.ToInt32(m_Value); + if (a <= 2) + { + BaseDataSystemMES.IsOnLine_Update(OpName, m_Value.ToString()); + MIS_BASE.Write_OnLineState(OpName, Convert.ToInt32(m_Value)); + } + } + catch + { + + } + break; + case "Reset"://复位,将MES所有的信息都复位了 + SetMoby(OpName);//将MES所有信号清空 + break; + case "FixAllow"://重新拧紧 + MIS_BASE.Write_FixAllow(OpName, false); + MIS_BASE.Write_FixAllow(OpName, true); + break; + case "IsAutoGetEngineID"://自动手动申请编号(线首) + if (m_Value_length > 1) return; + MIS_BASE.Write_IsAutoGetEngineID(OpName, Convert.ToInt32(m_Value)); + break; + case "PartPalletGoOver"://空托盘放行 + int Is_PartPalletGoOver; + MIS_BASE.Read_PartPalletGoOver(OpName, out Is_PartPalletGoOver); + if (Is_PartPalletGoOver == 1) + { + MIS_BASE.Write_PartPalletGoOver(OpName, 1); + } + else + { + MIS_BASE.Write_PartPalletGoOver(OpName, 0); + } + break; + case "SetMoby"://清空托盘(线首) + SetMoby(OpName);//将MES所有信号清空 + //MIS_BASE.Write_PartPalletCode_PLC(OpName, 1); + break; + case "RepairUplineMES"://返修上线 + MIS_BASE.Write_RepairUpline_MES(OpName, true); + break; + case "CancelRepair"://将返修件置为正常件 + + break; + case "PartPalletCode"://申请写入托盘号 + //MIS_BASE.Write_PartPalletCode_PLC(OpName, 1); + break; + case "WritePartPalletCode"://写入托盘号 + if (m_Value_length > 1) return; + MIS_BASE.Write_PalletCode(OpName, Convert.ToInt32(m_Value)); + break; + case "Normal"://启用正常拧紧工位 + MIS_BASE.Write_Normal(OpName, 1); + MIS_BASE.Write_UnNormal(OpName, 0); + break; + case "UnNormal"://启用备用拧紧工位 + MIS_BASE.Write_Normal(OpName, 0); + MIS_BASE.Write_UnNormal(OpName, 1); + break; + case "ResetDevice"://复位设备 + MIS_BASE.Write_ResetDevice(OpName, true); + System.Threading.Thread.Sleep(1000); + MIS_BASE.Write_ResetDevice(OpName, false); + break; + case "IsNeedRepaire"://返修上线(返修上线点) + if (Convert.ToInt32(m_Value) == 1) + { + //修改托盘状态 + MIS_BASE.Write_PalletInfo(OpName, 3); + //通知修改成功 + MIS_BASE.Write_UpdatePalletOK(OpName, true); + IsNeedRepaire_OK(OpName); + + } + else if (Convert.ToInt32(m_Value) == 0) + { + //通知修改成功 + MIS_BASE.Write_UpdatePalletOK(OpName, true); + //直接给出工作完成 + MIS_BASE.Write_MaterialVerifyOver(OpName, true); + } + else + { } + + break; + case "ContinueMatch": + BaseDataSystemMES.QualityVerifyStatus_Hash_Write(OpName, true); + break; + //初始化网页信号 + case "IniSingalToWeb": + InitializeSingalToWeb(OpName); + break; + case "Reset_Engine"://返修上线(返修上线点) + SetMoby(OpName);//将MES所有信号清空 + //fun_EngineTypeGetOverPLC(OpName, 0); + //fun_EngineTypeGetOverPLC(OpName, 1); + break; + + + default: break; + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:WebSubmit"); + } + } + + } + + //1.工件到位后,PLC给MES传递机型(DBX0.4)(44), + //MES判断条码是否全部扫描完成 + //PLC给出允许保存(DBX100.2)(19),MES见到(DBX100.2)(19)为1后给出保存完成(DBX102.2)(20), + //PLC见到保存完成(DBX102.2)(20)为1后,清空允许保存(DBX100.2)(19), + //MES见到允许保存(DBX100.2)(19)为0后,清空保存完成(DBX102.2)(20) + //MES判断总合格标志(INT104)(21)为1后,给出合格放行(DBX2.5)(51) + /// + /// 扫描条码 + /// + /// + /// + static public void fun_Barcode(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(Barcode, e); + } + static private void SetMoby(string OpName) + { + try + { + //清空Moby时,需要将MES信号清空 + MIS_BASE.Write_ClearMesMoby(OpName); + + BaseDataSystemMES.MesServer_Process_EngineTypeOver(OpName); + + Sendmessage("5123", "1111", OpName); + + MIS_BASE.Write_ResetDevice(OpName, true); + System.Threading.Thread.Sleep(1000); + MIS_BASE.Write_ResetDevice(OpName, false); + } + catch + { + + } + } + /// 网页重现登录,恢复关闭前的页面状态 + /// + /// 工位号 + static private void InitializeSingalToWeb(string Opname) + { + + //工件到位 DBX0.1 + bool S_WorkStart; + bool S_FixAllow; + bool S_EngineGetOver; + bool S_MaterialVerifyOver; + + MIS_BASE.Read_WorkStart(Opname, out S_WorkStart); + MIS_BASE.Read_FixAllow(Opname, out S_FixAllow); + MIS_BASE.Read_EngineGetOver_PLC(Opname, out S_EngineGetOver); + MIS_BASE.Read_MaterialVerifyOver(Opname, out S_MaterialVerifyOver); + + + + if (S_WorkStart == true) + { + SendInfomation("WorkStart", Convert.ToString(Convert.ToInt32(S_WorkStart)), Opname); + } + + if (S_EngineGetOver == true) + { + + SendInfomation("EngineTypeGetOverPLC", Convert.ToString(Convert.ToInt32(S_EngineGetOver)), Opname); + Sendmessage("5123", "1111", Opname); + } + if (S_FixAllow == true) + { + SendInfomation("FixAllow", Convert.ToString(Convert.ToInt32(S_FixAllow)), Opname); + } + if (S_MaterialVerifyOver == true) + { + SendInfomation("MaterialVerifyOver", Convert.ToString(Convert.ToInt32(S_MaterialVerifyOver)), Opname); + } + } + } +} diff --git a/Common/09MesDataFunction/MesDataFunction/MesDataFunction/MIS.Functions.WorkStart.cs b/Common/09MesDataFunction/MesDataFunction/MesDataFunction/MIS.Functions.WorkStart.cs new file mode 100644 index 0000000..ec1d4c4 --- /dev/null +++ b/Common/09MesDataFunction/MesDataFunction/MesDataFunction/MIS.Functions.WorkStart.cs @@ -0,0 +1,45 @@ +using System; +using System.Data; +using System.Collections; + +using System.Windows.Forms; +////using bizFacade; +using System.Collections.Specialized; +//using MesWork; +//using SystemFramework; +using System.Threading; + +namespace MesServerWork +{ + public partial class MIS_BASE + { + static object lockerWorkStart = new object(); + + + + /// + /// 工件到位与离开时,清空MES自身信号 + /// + /// + /// + static private void WorkStart(object e) + { + lock (lockerWorkStart) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:WorkStart"); + } + } + + } + + } +} diff --git a/Common/09MesDataFunction/MesDataFunction/MesDataFunction/MIS.Hashtable.TagID.cs b/Common/09MesDataFunction/MesDataFunction/MesDataFunction/MIS.Hashtable.TagID.cs new file mode 100644 index 0000000..4f7074b --- /dev/null +++ b/Common/09MesDataFunction/MesDataFunction/MesDataFunction/MIS.Hashtable.TagID.cs @@ -0,0 +1,806 @@ +using System; +using System.Data; +using System.Collections; + +using System.Windows.Forms; +//using bizFacade; +using System.Collections.Specialized; +//using MesWork; +using bizFacade; +using DoWhatPlc; +using MesWork; + +namespace MesServerWork +{ + public partial class MIS_BASE // : Form + { + /// + /// 全部数据列表 + /// + public static DataTable BasicDataTagValue; + /// + /// MES_基本数据_测量范围 + /// + public static DataTable BasicDataTagValueUpDown; + /// + /// 是否通过监控系统保存数据 + /// 1:通过监控系统保存采集的质量数据;0:不通过监控系统保存采集的质量数据 + /// + static public Hashtable hashtable_tagTable_OpName_SaveData; + /// + /// 变量代码与列位置 + /// + static public Hashtable hashtable_tagTable_TagID_TagOrderBy; + /// + /// 变量代码与变量排序 + /// + static public Hashtable hashtable_tagTable_TagID_TagItemOrderBy; + /// + /// 变量代码与变量特点 + /// 0:没定义1:工位合格标志2:需要合格标志的测量数据3:每个工位的合格标志4:物料5:IQA码6:压装数据7:压装合格标志8:(自动拧紧)工位合格标志 + /// + static public Hashtable hashtable_tagTable_TagID_TagProperty; + /// + /// 发动机类型转换表 + /// SELECT ID,发动机机型代码 FROM MES_计划BOM_发动机型号代码 + /// + public static Hashtable hashtable_EngineTypeID; + + /// + /// 工位号与工位上下线类型 + /// (0普通工位)(1正常上线)(2正常下线)(3返修上线)(4返修下线) + /// (5分线上线 总线)(6分线上线 分线) + /// + public static Hashtable hashtableOpName_OpType; + /// + /// 工位号与大屏幕代码 + /// 对应LED大屏幕(1,2,3,4) + /// + public static Hashtable hashtableOpName_LedID; + /// + /// 大屏幕显示产量端口(41104) + /// + public static Hashtable hashtableOpName_LedID_Port; + + /// + /// 大屏幕显示Andon大屏幕代码 1 + /// + public static Hashtable hashtableOpName_AndonID; + + /// + /// 大屏幕显示Andon端口 (41105) + /// + public static Hashtable hashtableOpName_AndonID_Port; + + + /// + /// 是否有打印机(0,1) + /// + public static Hashtable hashtableOpName_IsPrinter; + + /// + /// 打印机通讯端口 + /// + public static Hashtable hashtableOpName_IsPrinter_Port; + + + + /// + /// 工位号与目标循环时间 + /// + public static Hashtable hashtableOpName_TargetTime; + /// + /// 工位号与线体类型 + /// + public static Hashtable hashtableOpName_LineType; + /// + /// 是否有工位计算机 + /// + public static Hashtable hashtableOpName_IsHaveComputer; + /// + /// 变量名称 + /// + public static Hashtable hashtableTagID_TagName; + /// + /// 工位号 + /// + public static Hashtable hashtableTagID_OpName; + /// + /// 数据来源 + /// + public static Hashtable hashtableTagID_OpNameFrom; + + /// + /// 工位名称 + /// + static Hashtable hashtableTagID_OpName_Name; + /// + /// 测量位置 + /// + public static Hashtable hashtableTagID_ShaftID; + /// + /// 测量项目 + /// + public static Hashtable hashtableTagID_ItemVale; + /// + /// 变量代码与变量类型 + /// + public static Hashtable hashtable_tagTable_TagID_TagTypeID_All; + + + + /// + ///工位号与机床状态 + /// [测量数据机床状态] + /// + public static Hashtable m_MachineStatus_OpName; + /// + ///工位号与工件离开 1->0 =0 无工件或工件离开 + ///工位号与工件到位 0->1 =1 有工件或工件到达 + ///[测量数据发动机在线状态] + /// + public static Hashtable m_WorkStart_OpName; + + /// + ///工位号与工件到位时间 + ///工位号与工件到位 0->1 + ///[测量数据发动机在线状态] + /// + public static Hashtable m_WorkStart_OpName_Time; + + /// + ///工位号与工件到位时间 + ///工位号与工件到位 0->1,零件运动方向 + /// + public static Hashtable m_WorkStart_OpName_PartMoveDirection; + + + /// + ///工位号与发动机号 + /// + public static Hashtable m_EngineTrace_OpName; + /// + ///工位号与发动机号_时间 + /// + public static Hashtable m_EngineTrace_OpName_Time; + /// + ///工位号与合格标志 + ///[测量数据发动机在线状态] + /// + public static Hashtable m_QualityMask_OpName; + + /// + ///工位号与机型 + ///[测量数据发动机在线状态] + /// + public static Hashtable m_EngineNumberType_OpName; + /// + ///工位号与发动机号 + ///[测量数据发动机在线状态] + /// + public static Hashtable m_EngineNumber_OpName; + + /// + ///工位号与订单号 + ///[测量数据发动机在线状态] + /// + public static Hashtable m_OrderForm_OpName; + /// + ///工位号与操作者工号 + ///[测量数据发动机在线状态] + /// + public static Hashtable m_OperatorCode_OpName; + + + /// + /// 测量合格标志 + /// 全部测量数据的测量工位 + /// 全部测量数据的测量工位的数据来源 + /// 全部测量数据的测量工位的数据来源的测量变量 + /// + public static Hashtable hashtable_QualityData_GoodBad_MIS_OpName; + /// + /// 列位置 + /// + public static Hashtable hashtable_QualityData_GoodBad_Index; + + /// + /// MesServerCode + /// + public static Hashtable hashtable_MesServerCode; + /// + /// MesDll + /// + public static Hashtable hashtable_MesDll; + /// + /// 各个工位是否允许工作 + /// + public static Hashtable hashtable_IsAllowWork; + + /// + /// 返修工位是否需要强制合格放行 + /// //20141104 ljl + /// + public static Hashtable hashtable_IsConfirmOkGo; + + + /// + /// 工步属性哈西表 + /// + public static Hashtable hashtable_workStepProperty; + + /// + /// 工作顺序哈西表 + /// + public static Hashtable hashtable_WorkGroupIndex; + + /// + /// 返修工位哈西表 + /// + public static Hashtable hashtable_OpNameRepair; + + /// + /// 记录工件到位的发动机机型代码 + /// + public static Hashtable hashtable_EngineGetOver_EngineTypeID; + /// + /// 记录工件到位的发动机机型 + /// + public static Hashtable hashtable_EngineGetOver_EngineType; + /// + /// 记录工件到位的发动机号 + /// + public static Hashtable hashtable_EngineGetOver_EngineID; + /// + /// 记录工件到位的订单号 + /// + public static Hashtable hashtable_EngineGetOver_OrderForm; + + /// + /// 拧紧/压装过程中的合格标志 + /// + public static Hashtable hashtable_QualityMesRead; + + + /// + /// 物料检测哈希表 + /// + public static Hashtable hashtable_CheckMaterial; + + /// + /// 托盘状态哈希表 + /// + public static Hashtable hashtable_PalletInfo; + /// + ///[测量数据机床状态_分拆统计] + ///各个工位机床上电开始时间 + ///机床上电产生 0->1 + ///机床上电解除 1->0 + /// + public static Hashtable m_MachineStatusPutOn_OpName_Time; + /// + ///[测量数据机床状态_分拆统计] + ///各个工位循环开始 开始时间 + ///循环开始产生 0->1 + ///循环开始解除 1->0 + /// + public static Hashtable m_MachineStatusWorkOn_OpName_Time; + /// + ///[测量数据机床状态_分拆统计] + ///各个工位机床故障开始时间 + ///机床故障产生 0->1 + ///机床故障解除 1->0 + /// + public static Hashtable m_MachineStatusAlarm_OpName_Time; + /// + ///[测量数据机床状态_分拆统计] + ///各个工位上料无件开始时间 + ///上料无件产生 0->1 + ///上料无件解除 1->0 + /// + public static Hashtable m_MachineStatusNoPart_OpName_Time; + /// + ///[测量数据机床状态_分拆统计] + ///各个工位下料堵塞开始时间 + ///下料堵塞产生 0->1 + ///下料堵塞解除 1->0 + /// + public static Hashtable m_MachineStatusBlock_OpName_Time; + + /// + ///工位号与托盘离开 1->0 + ///工位号与托盘到位 0->1 + ///[测量数据_监控系统_托盘到位] + /// + public static Hashtable m_PartPalletStatus_OpName; + /// + ///工位号与托盘离开 1->0 + ///工位号与托盘到位 0->1 + ///[测量数据_监控系统_托盘到位] + /// + public static Hashtable m_PartPalletStatus_OpName_Time; + /// + /// 托盘到位(1)托盘离开(0) (DBX101.7)(13) + /// + /// + /// + + /// + ///[测量数据机床状态_分拆统计] + ///各个工位机床上电开始时间 + ///机床上电产生 0->1 + ///机床上电解除 1->0 + /// + public static Hashtable m_MachineStatusPutOn_OpName; + /// + ///[测量数据机床状态_分拆统计] + ///各个工位循环开始 开始时间 + ///循环开始产生 0->1 + ///循环开始解除 1->0 + /// + public static Hashtable m_MachineStatusWorkOn_OpName; + /// + ///[测量数据机床状态_分拆统计] + ///各个工位机床故障开始时间 + ///机床故障产生 0->1 + ///机床故障解除 1->0 + /// + public static Hashtable m_MachineStatusAlarm_OpName; + /// + ///[测量数据机床状态_分拆统计] + ///各个工位上料无件开始时间 + ///上料无件产生 0->1 + ///上料无件解除 1->0 + /// + public static Hashtable m_MachineStatusNoPart_OpName; + /// + ///[测量数据机床状态_分拆统计] + ///各个工位下料堵塞开始时间 + ///下料堵塞产生 0->1 + ///下料堵塞解除 1->0 + /// + public static Hashtable m_MachineStatusBlock_OpName; + + public static NameValueCollection hashtable_TagTypeDataType ; + public static NameValueCollection hashtable_TagType; + /// + /// 托盘代码(DBB86)(80) + /// + /// + /// + + /// + /// 创建MesServerCode哈西表 + /// + static public void InitHashtable_MesServerCode() + { + hashtable_MesServerCode = new Hashtable(); + hashtable_IsAllowWork = new Hashtable(); + hashtable_WorkGroupIndex = new Hashtable(); + hashtable_EngineGetOver_EngineTypeID = new Hashtable(); + hashtable_EngineGetOver_EngineType = new Hashtable(); + hashtable_EngineGetOver_EngineID = new Hashtable(); + hashtable_EngineGetOver_OrderForm = new Hashtable(); + hashtable_QualityMesRead = new Hashtable(); + hashtable_CheckMaterial = new Hashtable(); + hashtable_PalletInfo = new Hashtable(); + hashtable_IsConfirmOkGo = new Hashtable(); + hashtable_MesDll = new Hashtable(); + + string OpName; + string MesServerCode; + string MesDll; + string workStepProperty; + string OpNameRepair; + DataTable dt; + dt = BaseDataSystemMES.GetMesServerCodeFromMIS(); + if (dt != null) + { + for (int i = 0; i < dt.Rows.Count; i++) + { + OpName = dt.Rows[i]["工位号"].ToString(); + MesServerCode = dt.Rows[i]["MesServerCode"].ToString(); + MesDll = dt.Rows[i]["MesDll"].ToString(); + hashtable_MesDll.Add(OpName, MesDll); + hashtable_MesServerCode.Add(OpName, MesServerCode); + hashtable_IsAllowWork.Add(OpName, 1); + hashtable_IsConfirmOkGo.Add(OpName, 0);//20141104 ljl + hashtable_PalletInfo.Add(OpName, 0);//20141104 ljl + hashtable_WorkGroupIndex.Add(OpName, 1); + hashtable_EngineGetOver_EngineTypeID.Add(OpName, 0); + hashtable_EngineGetOver_EngineType.Add(OpName, ""); + hashtable_EngineGetOver_EngineID.Add(OpName, ""); + hashtable_EngineGetOver_OrderForm.Add(OpName, ""); + hashtable_QualityMesRead.Add(OpName, 0); + hashtable_CheckMaterial.Add(OpName, new bool[16]); + } + } + DoWhatPlc.HashtableList.hashtable_MesServerCode_Temp = hashtable_MesServerCode; + DoWhatPlc.HashtableList.hashtable_MesDll_Temp = hashtable_MesDll; + + DoWhatPlc.HashtableList.hashtable_EngineGetOver_EngineID_Temp = hashtable_EngineGetOver_EngineID; + DoWhatPlc.HashtableList.hashtable_EngineGetOver_EngineTypeID_Temp = hashtable_EngineGetOver_EngineTypeID; + DoWhatPlc.HashtableList.hashtable_EngineGetOver_EngineType_Temp = hashtable_EngineGetOver_EngineType; + DoWhatPlc.HashtableList.hashtable_EngineGetOver_OrderForm_Temp = hashtable_EngineGetOver_OrderForm; + + //初始化工步属性 + hashtable_workStepProperty = new Hashtable(); + dt = BaseDataSystemMES.GetworkStepPropertyFromMIS(); + if (dt != null) + { + for (int i = 0; i < dt.Rows.Count; i++) + { + OpName = dt.Rows[i]["工位号"].ToString(); + workStepProperty = dt.Rows[i]["工步属性"].ToString(); + hashtable_workStepProperty.Add(OpName, workStepProperty); + } + } + + //返修工位 + hashtable_OpNameRepair = new Hashtable(); + dt = BaseDataSystemMES.GetOpNameRepairFromMIS(); + if (dt != null) + { + for (int i = 0; i < dt.Rows.Count; i++) + { + OpName = dt.Rows[i]["工位号"].ToString(); + OpNameRepair = dt.Rows[i]["返修工位号"].ToString(); + hashtable_OpNameRepair.Add(OpName, OpNameRepair); + } + } + + DoWhatPlc.HashtableList.hashtable_OpNameRepair_Temp = hashtable_OpNameRepair; + DoWhatPlc.HashtableList.hashtable_workStepProperty_Temp = hashtable_workStepProperty; + DoWhatPlc.HashtableList.hashtable_QualityMesRead_Temp = hashtable_QualityMesRead; + DoWhatPlc.HashtableList.hashtable_IsAllowWork_Temp = hashtable_IsAllowWork; + DoWhatPlc.HashtableList.hashtable_WorkGroupIndex_Temp = hashtable_WorkGroupIndex; + + + + } + + + /// + /// 创建合格标志哈西表 + /// + private static void InitHashtable_QualityData_GoodBad() + { + //列位置 + string index; + // + int tagID; + DataTable dt ; + dt = BaseDataSystemMES.BaseData_tagTable_All_B5A(); + + hashtable_QualityData_GoodBad_Index = new Hashtable(); + for (int i = 0; i < dt.Rows.Count; i++) + { + tagID = Convert.ToInt32(dt.Rows[i]["TagID"]); + index = (dt.Rows[i]["列位置"]).ToString(); + hashtable_QualityData_GoodBad_Index.Add(tagID, index); + } + + hashtable_EngineTypeID = new Hashtable(); + dt = BaseDataSystemMES.BaseData_tagTable_QualityData_EngineTypeID(); + for (int i = 0; i < dt.Rows.Count; i++) + { + tagID = Convert.ToInt32(dt.Rows[i]["发动机机型代码"]); + index = (dt.Rows[i]["ID"]).ToString(); + hashtable_EngineTypeID.Add(tagID, index); + } + //工位号 + DataTable dt_OpName; + //工位号数据来源 + DataTable dt_OpNameFrom; + //数据来源对应的TagID + DataTable dt_OpNameTagID; + string opName; + string opNameFrom; + hashtable_QualityData_GoodBad_MIS_OpName = new Hashtable(); + // 测量合格标志 + // 全部测量数据的测量工位的数据来源 + Hashtable hashtable_QualityData_GoodBad_MIS_OpName_OpNameFrom; + + // 测量合格标志 + // 全部测量数据的测量工位的数据来源的测量变量 + Hashtable hashtable_QualityData_GoodBad_MIS_OpName_OpNameFrom_TagID; + dt_OpName = BaseDataSystemMES.BaseData_tagTable_QualityData_GoodBad_MIS_OpName_B5A(); + if (dt_OpName != null) + { + //有不合格标志的测量工位 + for (int i = 0; i < dt_OpName.Rows.Count; i++) + { + //有不合格标志的测量工位 对应的 数据来源工位号 + hashtable_QualityData_GoodBad_MIS_OpName_OpNameFrom = new Hashtable(); + opName = dt_OpName.Rows[i]["工位号"].ToString(); + dt_OpNameFrom = BaseDataSystemMES.BaseData_tagTable_QualityData_GoodBad_MIS_OpName(opName); + if (dt_OpNameFrom != null) + { + for (int j = 0; j < dt_OpNameFrom.Rows.Count; j++) + { + opNameFrom = dt_OpNameFrom.Rows[j]["数据来源"].ToString(); + dt_OpNameTagID = BaseDataSystemMES.BaseData_tagTable_QualityData_GoodBad_MIS_OpName(opName, opNameFrom); + // + hashtable_QualityData_GoodBad_MIS_OpName_OpNameFrom_TagID = new Hashtable(); + if (dt_OpNameTagID != null) + { + for (int k = 0; k < dt_OpNameTagID.Rows.Count; k++) + { + tagID = Convert.ToInt32(dt_OpNameTagID.Rows[k]["TagID"]); + hashtable_QualityData_GoodBad_MIS_OpName_OpNameFrom_TagID.Add(tagID, tagID); + } + } + tagID = Convert.ToInt32(dt_OpNameFrom.Rows[j]["TagID"]); + //全部测量数据的测量工位的数据来源的测量变量 + hashtable_QualityData_GoodBad_MIS_OpName_OpNameFrom.Add(tagID, hashtable_QualityData_GoodBad_MIS_OpName_OpNameFrom_TagID); + } + } + hashtable_QualityData_GoodBad_MIS_OpName.Add(opName, hashtable_QualityData_GoodBad_MIS_OpName_OpNameFrom); + } + } + } + + + public static NameValueCollection hashtable_TagTypeID_OpName_ToTagID; + + /// + /// 变量代码与其他字段的对应关系 + /// + public static void InitHashtableTagID() + { + //变量代码 + string tagID; + //变量名称 + string tagName; + //工位号 + string opNmae; + //测量位置 + string shaftID; + //测量项目 + string itemVale; + //变量排序 + int tagItemOrderBy; + //变量特点 + // 0:没定义1:工位合格标志2:需要合格标志的测量数据3:每个工位的合格标志4:物料5:IQA码6:压装数据7:压装合格标志8:(自动拧紧)工位合格标志 + int tagProperty; + //列位置 + int tagOrderBy; + InitHashtable_QualityData_GoodBad(); + //MesServerCode哈希表创建 + InitHashtable_MesServerCode(); + //列位置 + hashtable_tagTable_TagID_TagOrderBy = new Hashtable(); + // 变量代码与变量排序 + hashtable_tagTable_TagID_TagItemOrderBy = new Hashtable(); + // 变量代码与变量特点 + // 0:没定义1:工位合格标志2:需要合格标志的测量数据3:每个工位的合格标志4:物料5:IQA码6:压装数据7:压装合格标志8:(自动拧紧)工位合格标志 + hashtable_tagTable_TagID_TagProperty = new Hashtable(); + hashtable_tagTable_OpName_SaveData = new Hashtable(); + //工位号与机床状态 + //[测量数据发动机在线状态] + m_MachineStatus_OpName = new Hashtable(); + ////工位号与工件离开 0 + ////工位号与工件到位 1 + ////[测量数据发动机在线状态] + //m_WorkStart_OpName = new Hashtable(); + ////工位号与工件到位时间 + ////工位号与工件到位 0->1 + ////[测量数据发动机在线状态] + //m_WorkStart_OpName_Time = new Hashtable(); + //工位号与发动机号 + //[测量数据发动机在线状态] + m_EngineTrace_OpName = new Hashtable(); + m_EngineTrace_OpName_Time = new Hashtable(); + //工位号与合格标志 + //[测量数据发动机在线状态] + m_QualityMask_OpName = new Hashtable(); + //工位号与目标循环时间 + hashtableOpName_TargetTime = new Hashtable(); + //工位号与线体类型 + hashtableOpName_LineType = new Hashtable(); + //是否有工位计算机 + hashtableOpName_IsHaveComputer = new Hashtable(); + + //工位号与机型 + //[测量数据发动机在线状态] + m_EngineNumberType_OpName = new Hashtable(); + //工位号与发动机号 + //[测量数据发动机在线状态] + m_EngineNumber_OpName = new Hashtable(); + //工位号与订单号 + //[测量数据发动机在线状态] + m_OrderForm_OpName = new Hashtable(); + //工位号与操作者工号 + //[测量数据发动机在线状态] + m_OperatorCode_OpName = new Hashtable(); + + + // + // 变量名称 + // + hashtableTagID_TagName = new Hashtable(); + // + // 工位号 + // + hashtableTagID_OpName = new Hashtable(); + // + // 数据来源 + // + hashtableTagID_OpNameFrom = new Hashtable(); + // + // 工位名称 + // + hashtableTagID_OpName_Name = new Hashtable(); + // + // 测量位置 + // + hashtableTagID_ShaftID = new Hashtable(); + // + // 测量项目 + // + hashtableTagID_ItemVale = new Hashtable(); + + hashtable_tagTable_TagID_TagTypeID_All = new Hashtable(); + + // 工位号与工位上下线类型 + // (0普通工位)(1正常上线)(2正常下线)(3返修上线)(4返修下线) + // (5 分线上线 总线) (6 分线上线 总线) + hashtableOpName_OpType = new Hashtable(); + // 工位号与大屏幕代码 + // 对应LED大屏幕(1,2,3,4) + hashtableOpName_LedID = new Hashtable(); + + + + + // 大屏幕显示产量端口(41104) + hashtableOpName_LedID_Port = new Hashtable(); + // 大屏幕显示Andon大屏幕代码 1 + hashtableOpName_AndonID = new Hashtable(); + // 大屏幕显示Andon端口 (41105) + hashtableOpName_AndonID_Port = new Hashtable(); + // 是否有打印机(0,1) + hashtableOpName_IsPrinter = new Hashtable(); + // 打印机通讯端口 (缸盖打印机 41101) (发动机上线打印机 41102) (发动机下线打印机 41103) + hashtableOpName_IsPrinter_Port = new Hashtable(); + + m_WorkStart_OpName_Time = new Hashtable(); + m_WorkStart_OpName = new Hashtable(); + + + m_MachineStatusPutOn_OpName_Time = new Hashtable(); + m_MachineStatusPutOn_OpName = new Hashtable(); + m_MachineStatusWorkOn_OpName_Time = new Hashtable(); + m_MachineStatusWorkOn_OpName = new Hashtable(); + m_MachineStatusAlarm_OpName_Time = new Hashtable(); + m_MachineStatusAlarm_OpName = new Hashtable(); + m_MachineStatusNoPart_OpName_Time = new Hashtable(); + m_MachineStatusNoPart_OpName = new Hashtable(); + m_MachineStatusBlock_OpName_Time = new Hashtable(); + m_MachineStatusBlock_OpName = new Hashtable(); + + + + + m_WorkStart_OpName_PartMoveDirection = new Hashtable(); + m_PartPalletStatus_OpName_Time = new Hashtable(); + m_PartPalletStatus_OpName = new Hashtable(); + + hashtable_TagTypeID_OpName_ToTagID = new NameValueCollection(); + + + + DataTable dt; + DateTime dateTime; + dateTime = DateTime.Now; + dt = BaseDataSystemMES.BaseData_tagTable_All(); + + //变量类型代码 + int TagTypeID; + for (int i = 0; i < dt.Rows.Count; i++) + { + tagID = dt.Rows[i]["TagID"].ToString (); + tagName = Convert.ToString(dt.Rows[i]["TagName"]); + opNmae = Convert.ToString(dt.Rows[i]["工位号"]); + shaftID = Convert.ToString(dt.Rows[i]["测量位置"]); + itemVale = Convert.ToString(dt.Rows[i]["测量项目"]); + TagTypeID = Convert.ToInt32(dt.Rows[i]["变量类型代码"]); + tagItemOrderBy = Convert.ToInt32(dt.Rows[i]["变量排序"]); + tagProperty = Convert.ToInt32(dt.Rows[i]["变量特点"]); + tagOrderBy = Convert.ToInt32(dt.Rows[i]["列位置"]); + + hashtableTagID_TagName.Add(tagID, tagName); + hashtableTagID_OpName.Add(tagID, opNmae); + hashtableTagID_ShaftID.Add(tagID, shaftID); + hashtableTagID_ItemVale.Add(tagID, itemVale);//列位置 + hashtable_tagTable_TagID_TagTypeID_All.Add(tagID, TagTypeID); + hashtable_tagTable_TagID_TagItemOrderBy.Add(tagID, tagItemOrderBy); + hashtable_tagTable_TagID_TagProperty.Add(tagID, tagProperty); + hashtable_tagTable_TagID_TagOrderBy.Add(tagID, tagOrderBy); + + + } + dt = BaseDataSystemMES.BaseData_tagTable_OpName(); + for (int i = 0; i < dt.Rows.Count; i++) + { + //是否通过监控系统保存数据 + // 1:通过监控系统保存采集的质量数据;0:不通过监控系统保存采集的质量数据 + hashtable_tagTable_OpName_SaveData.Add(Convert.ToString(dt.Rows[i]["工位号"]), Convert.ToInt32(dt.Rows[i]["是否通过监控系统保存数据"])); + + hashtableOpName_TargetTime.Add(Convert.ToString(dt.Rows[i]["工位号"]), Convert.ToString(dt.Rows[i]["目标循环时间"])); + hashtableOpName_LineType.Add(Convert.ToString(dt.Rows[i]["工位号"]), Convert.ToString(dt.Rows[i]["线体类型"])); + hashtableOpName_IsHaveComputer.Add(Convert.ToString(dt.Rows[i]["工位号"]), Convert.ToString(dt.Rows[i]["是否有工位计算机"])); + //用于LED显示 + // [MES_计划BOM_工位与名称] + // 工位上下线类型 + //(0普通工位)(1正常上线)(2正常下线)(3返修上线)(4返修下线) + hashtableOpName_OpType.Add(Convert.ToString(dt.Rows[i]["工位号"]), Convert.ToInt32(dt.Rows[i]["工位上下线类型"])); + hashtableOpName_LedID.Add(Convert.ToString(dt.Rows[i]["工位号"]), Convert.ToInt32(dt.Rows[i]["大屏幕代码"])); + m_WorkStart_OpName_Time.Add(Convert.ToString(dt.Rows[i]["工位号"]), dateTime); + m_WorkStart_OpName.Add(Convert.ToString(dt.Rows[i]["工位号"]), 0); + + + m_MachineStatusPutOn_OpName_Time.Add(Convert.ToString(dt.Rows[i]["工位号"]), dateTime); + m_MachineStatusPutOn_OpName.Add(Convert.ToString(dt.Rows[i]["工位号"]), 0); + m_MachineStatusWorkOn_OpName_Time.Add(Convert.ToString(dt.Rows[i]["工位号"]), dateTime); + m_MachineStatusWorkOn_OpName.Add(Convert.ToString(dt.Rows[i]["工位号"]), 0); + m_MachineStatusAlarm_OpName_Time.Add(Convert.ToString(dt.Rows[i]["工位号"]), dateTime); + m_MachineStatusAlarm_OpName.Add(Convert.ToString(dt.Rows[i]["工位号"]), 0); + m_MachineStatusNoPart_OpName_Time.Add(Convert.ToString(dt.Rows[i]["工位号"]), dateTime); + m_MachineStatusNoPart_OpName.Add(Convert.ToString(dt.Rows[i]["工位号"]), 0); + m_MachineStatusBlock_OpName_Time.Add(Convert.ToString(dt.Rows[i]["工位号"]), dateTime); + m_MachineStatusBlock_OpName.Add(Convert.ToString(dt.Rows[i]["工位号"]), 0); + + + + m_WorkStart_OpName_PartMoveDirection.Add(Convert.ToString(dt.Rows[i]["工位号"]), 0); + + + m_PartPalletStatus_OpName_Time.Add(Convert.ToString(dt.Rows[i]["工位号"]), dateTime); + m_PartPalletStatus_OpName.Add(Convert.ToString(dt.Rows[i]["工位号"]), 0); + try + { + hashtableOpName_LedID_Port.Add(Convert.ToString(dt.Rows[i]["工位号"]), Convert.ToInt32(dt.Rows[i]["大屏幕显示产量端口"])); + } + catch { } + try + { + hashtableOpName_AndonID.Add(Convert.ToString(dt.Rows[i]["工位号"]), Convert.ToInt32(dt.Rows[i]["大屏幕显示Andon大屏幕代码"])); + } + catch { } + try + { + hashtableOpName_AndonID_Port.Add(Convert.ToString(dt.Rows[i]["工位号"]), Convert.ToInt32(dt.Rows[i]["大屏幕显示Andon端口"])); + } + catch { } + try { hashtableOpName_IsPrinter.Add(Convert.ToString(dt.Rows[i]["工位号"]), Convert.ToInt32(dt.Rows[i]["是否有打印机"])); } + catch { } + try + { + hashtableOpName_IsPrinter_Port.Add(Convert.ToString(dt.Rows[i]["工位号"]), Convert.ToInt32(dt.Rows[i]["打印机通讯端口"])); + } + catch { } + } + + + //20170310 CLB新加 + dt = BaseDataSystemMES.BaseData_tagTable_OpcServerMES_ALL_CF(); + for (int i = 0; i < dt.Rows.Count; i++) + { + try + { + hashtable_TagTypeID_OpName_ToTagID.Add(Convert.ToString(dt.Rows[i]["工位号"]) + "_" + Convert.ToString(dt.Rows[i]["变量类型代码"]), Convert.ToString(dt.Rows[i]["TagID"])); + //hashtable_TagTypeID_OpName_ToTagID; + } + catch(Exception err) + { + + } + } + + + + + } + } +} diff --git a/Common/09MesDataFunction/MesDataFunction/MesDataFunction/MIS.Machine.ServicePlan.cs b/Common/09MesDataFunction/MesDataFunction/MesDataFunction/MIS.Machine.ServicePlan.cs new file mode 100644 index 0000000..61d5684 --- /dev/null +++ b/Common/09MesDataFunction/MesDataFunction/MesDataFunction/MIS.Machine.ServicePlan.cs @@ -0,0 +1,98 @@ +using System; +using System.Data; +using System.Windows.Forms; +//using bizFacade; +//using DataLinkMesWork; +//using SystemFramework; + +namespace MesServerWork +{ + public partial class MIS_BASE + { + /// + /// 设备保养计划 + /// + /// + /// + /// + public delegate void MachinePlan_Invoke(string OpName, string MachineType, string PlanID); + /// + /// 设备保养计划 + /// + public MachinePlan_Invoke machinePlan_Invoke; + /// + /// 设备保养 + /// + /// + /// 设备保养类型 + /// 工作日历流水号 + public void MachinePlan(string OpName, string MachineType, string PlanID) + { + try + { + string SendMessage; + SendMessage = "MES|MachinePlan|" + OpName + "|" + MachineType + "&" + PlanID; + asyncSendMessage(SendMessage); + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "MachinePlan"); + } + } + + /// + /// 设备保养计划Timer + /// + private Timer timer_Machine; + /// + /// 初始化设备保养计划 + /// + public void InitMachinePlan(MachinePlan_Invoke machinePlan_Invoke) + { + this.machinePlan_Invoke = machinePlan_Invoke; + timer_Machine = new Timer(); + timer_Machine.Interval = 60000;//每隔一分钟查询一次 + timer_Machine.Tick += new EventHandler(timer_Machine_Tick); + timer_Machine.Start(); + } + + /// + /// 分钟调度 + /// + /// + /// + private void timer_Machine_Tick(object sender, EventArgs e) + { + try + { + //if (ApplicationConfig.Is_MachinePlan == 1) + //{ + // DataTable dt; + // string opName; + // string machineType;//保养类型代码 + // string planID;//工作日历流水号 + // BaseDataSystemMES.MachinePlan_Select(out dt); + // if (dt != null) + // { + // if (dt.Rows.Count > 0) + // { + // for (int i = 0; i < dt.Rows.Count; i++) + // { + // opName = dt.Rows[i]["工位号"].ToString(); + // machineType = dt.Rows[i]["保养类型代码"].ToString(); + // planID = dt.Rows[i]["工作日历流水号"].ToString(); + // BaseDataSystemMES.Rolling_news_Add(opName, opName + "工位有设备保养计划,请相关人员进行保养!!!"); + // BeginInvoke(machinePlan_Invoke, new object[] { opName, machineType, planID }); + // } + // } + // } + //} + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "timer_Machine_Tick"); + } + } + + } +} diff --git a/Common/09MesDataFunction/MesDataFunction/MesDataFunction/MIS.OpcServerMIS.Read.cs b/Common/09MesDataFunction/MesDataFunction/MesDataFunction/MIS.OpcServerMIS.Read.cs new file mode 100644 index 0000000..4663bc7 --- /dev/null +++ b/Common/09MesDataFunction/MesDataFunction/MesDataFunction/MIS.OpcServerMIS.Read.cs @@ -0,0 +1,1202 @@ +using bizFacade; +using System; +using SystemFramework; +//using SystemFramework; +//using bizFacade; + +namespace MesServerWork +{ + + public partial class MIS_BASE + { + + + /// + /// 通过TagTypeName读取PLC数据 + /// + /// + /// + static private void Read_TagValueByTagTypeName(string cmd, string opName, out string tagValue) + { + tagValue = "-1"; + int tagTypeID; + try + { + tagTypeID = Convert.ToInt32(MIS_BASE.hashtable_TagType[cmd]); + string msg = "MES|" + tagTypeID.ToString() + "|" + opName + "|" + tagValue; + //tagValue = ChatService.MesReadWhisperMessage(msg); + MIS_BASE.ReadTagValue(tagTypeID, opName, out tagValue); + } + catch (Exception err) + { + ApplicationLog.WriteLog(err, "Read_TagValueByTagTypeName_FUNC;工位号:" + opName + ";命令:" + cmd + ";值:" + tagValue); + } + + } + + /// + /// 通过TagID读取对应值 + /// + /// + /// + static private void Read_TagValueByTagID(string TagID, out object tagValue) + { + tagValue = "0"; + try + { + tagValue = MIS_BASE.ReadPLC(TagID).ToString(); + } + catch (Exception err) + { + ApplicationLog.WriteLog(err, "Read_TagValueByTagID_FUNC"); + } + } + + /// + /// 根据数据类型代码、工位号获得对应值 + /// + /// + /// + /// + private static void Read_TagValueByTagTypeID(int tagTypeID, string opName, out string tagValueStr) + { + tagValueStr = "-1"; + + try + { + MIS_BASE.ReadTagValue(tagTypeID, opName, out tagValueStr); + } + catch (Exception err) + { + ApplicationLog.WriteLog(err, "Read_TagValueByTagTypeID_FUNC"); + } + } + + /// + /// 根据数据类型代码、工位号获得对应值 + /// + /// + /// + /// + private static void Read_TagValueByTagTypeID(int tagTypeID, string opName, out object tagValueStr) + { + tagValueStr = "-1"; + + try + { + tagValueStr = MIS_BASE.ReadPLC(tagTypeID, opName); + } + catch (Exception err) + { + ApplicationLog.WriteLog(err, "Read_TagValueByTagTypeID_FUNC"); + } + } + + /// + /// 读取数据通过(TagID) + /// + /// + /// + public static void Read_TagID(string TagID, out object tagValueOb) + { + Read_TagValueByTagID(TagID, out tagValueOb); + } + + /// + /// 读取数据通过(TagTypeName&opName) + /// + /// + /// + public static void Read_TagTypeName(string cmd, string opName, out string tagValueStr) + { + Read_TagValueByTagTypeName(cmd, opName, out tagValueStr); + } + + /// + /// 读取数据通过(TagTypeID&opName) + /// + /// + /// + public static void Read_TagTypeID(int tagTypeID, string opName, out string tagValueStr) + { + Read_TagValueByTagTypeID(tagTypeID, opName, out tagValueStr); + } + + public static void Read_TagTypeID(int tagTypeID, string opName, out object tagValueStr) + { + Read_TagValueByTagTypeID(tagTypeID, opName, out tagValueStr); + } + + + + + /// + /// 订单号(string)(25) + /// + /// + /// + public static void Read_OrderForm(string opName, out string tagValue) + { + tagValue = ""; + string cmd = "OrderForm"; + string tagValueStr; + Read_TagValueByTagTypeName(cmd, opName, out tagValue); + //tagValue = Convert.ToBoolean(Convert.ToInt32(tagValueStr)); + } + /// + /// 总成编号(string)(26) + /// + /// + /// + public static void Read_AssemblyCode(string opName, out string tagValue) + { + tagValue = ""; + string cmd = "AssemblyCode"; + Read_TagValueByTagTypeName(cmd, opName, out tagValue); + //tagValue = Convert.ToBoolean(Convert.ToInt32(tagValueStr)); + } + /// + /// 配方号1(dint)(27) + /// + /// + /// + public static void Read_Recipe1(string opName, out int tagValue) + { + tagValue = 0; + string cmd = "Recipe1"; + string tagValueStr; + Read_TagValueByTagTypeName(cmd, opName, out tagValueStr); + tagValue = Convert.ToInt32(tagValueStr); + } + /// + /// 配方号2(dint)(28) + /// + /// + /// + public static void Read_Recipe2(string opName, out int tagValue) + { + tagValue = 0; + string cmd = "Recipe2"; + string tagValueStr; + Read_TagValueByTagTypeName(cmd, opName, out tagValueStr); + tagValue = Convert.ToInt32(tagValueStr); + } + + + /// + /// 订单号(string)(61) + /// + /// + /// + public static void Read_OrderForm_MES(string opName, out string tagValue) + { + tagValue = ""; + string cmd = "OrderForm_MES"; + string tagValueStr; + Read_TagValueByTagTypeName(cmd, opName, out tagValue); + //tagValue = Convert.ToBoolean(Convert.ToInt32(tagValueStr)); + } + /// + /// 总成编号(string)(62) + /// + /// + /// + public static void Read_AssemblyCode_MES(string opName, out string tagValue) + { + tagValue = ""; + string cmd = "AssemblyCode_MES"; + Read_TagValueByTagTypeName(cmd, opName, out tagValue); + //tagValue = Convert.ToBoolean(Convert.ToInt32(tagValueStr)); + } + /// + /// 配方号1(dint)(63) + /// + /// + /// + public static void Read_Recipe1_MES(string opName, out int tagValue) + { + tagValue = 0; + string cmd = "Recipe1_MES"; + string tagValueStr; + Read_TagValueByTagTypeName(cmd, opName, out tagValueStr); + tagValue = Convert.ToInt32(tagValueStr); + } + /// + /// 配方号2(dint)(64) + /// + /// + /// + public static void Read_Recipe2_MES(string opName, out int tagValue) + { + tagValue = 0; + string cmd = "Recipe2_MES"; + string tagValueStr; + Read_TagValueByTagTypeName(cmd, opName, out tagValueStr); + tagValue = Convert.ToInt32(tagValueStr); + } + + /// + /// 匹配结果(DBX3.4)(69) + /// 匹配是否成功 + /// + /// + /// + public static void Read_MatchSuccess(string opName, out int tagValue) + { + tagValue = 0; + string cmd = "Match"; + string tagValueStr; + Read_TagValueByTagTypeName(cmd, opName, out tagValueStr); + tagValue = Convert.ToInt32(tagValueStr); + + } + + /// + /// 是否匹配(DBX3.3)(68) + /// + /// + /// + public static void Read_MatchingCompleted(string opName, out int tagValue) + { + tagValue = 0; + string cmd = "MatchingCompleted"; + string tagValueStr; + Read_TagValueByTagTypeName(cmd, opName, out tagValueStr); + tagValue = Convert.ToInt32(tagValueStr); + + } + + + /// + /// MES保存完数据(必须MIS)(X102.2)(20) + /// + /// + /// + public static void Read_MesReadOver(string opName, out bool tagValue) + { + tagValue = false; + string cmd = "MesReadOver"; + string tagValueStr; + Read_TagValueByTagTypeName(cmd, opName, out tagValueStr); + tagValue = Convert.ToBoolean(Convert.ToInt32(tagValueStr)); + + } + + /// + /// 发动机到位(X0.1)(2) + /// + /// + /// + public static void Read_WorkStart(string opName, out bool tagValue) + { + tagValue = false; + string cmd = "WorkStart"; + string tagValueStr; + Read_TagValueByTagTypeName(cmd, opName, out tagValueStr); + tagValue = Convert.ToBoolean(Convert.ToInt32(tagValueStr)); + } + + /// + /// 发动机机型标志(INT4)(9) + /// + public static void Read_EngineTypeID(string opName, out int tagValue) + { + tagValue = 0; + string cmd = "EngineTypeID"; + string tagValueStr; + Read_TagValueByTagTypeName(cmd, opName, out tagValueStr); + tagValue = Convert.ToInt32(tagValueStr); + + } + /// + /// 发动机ID(STRING6.38)(10) + /// + public static void Read_EngineID(string opName, out string tagValue) + { + tagValue = ""; + string cmd = "EngineID"; + string tagValueStr; + Read_TagValueByTagTypeName(cmd, opName, out tagValueStr); + tagValue = tagValueStr; + } + //public static void Read_OrderForm(string opName, out string tagValue) + //{ + // tagValue = ""; + // string tagTypeID = "39"; + // string tagValueStr; + // tagValueStr = DtWebApi.ReadWritePLC.ReadPLC(tagTypeID, opName).ToString(); + // tagValue = tagValueStr; + //} + /// + /// 发动机型号(STRING46.38)(11) + /// + public static void Read_EngineType(string opName, out string tagValue) + { + tagValue = ""; + string cmd = "EngineType"; + string tagValueStr; + Read_TagValueByTagTypeName(cmd, opName, out tagValueStr); + tagValue = tagValueStr; + + } + + /// + /// 工位直通(X101.6)(1006) + /// + public static void Read_PartGoOver(string opName, out int tagValue) + { + tagValue = 0; + string cmd = "PartGoOver"; + string tagValueStr; + Read_TagValueByTagTypeName(cmd, opName, out tagValueStr); + tagValue = Convert.ToInt32(tagValueStr); + + } + + /// + /// 托盘到位(1)托盘离开(0) (DBX101.5)(13) + /// + public static void Read_PartPalletStatus(string opName, out bool tagValue) + { + tagValue = false; + string cmd = "PartPalletStatus"; + string tagValueStr; + Read_TagValueByTagTypeName(cmd, opName, out tagValueStr); + tagValue = Convert.ToBoolean(Convert.ToInt32(tagValueStr)); + } + + /// + /// 加工时间变量目标时间 (DINT 106)(17) + /// + public static void Read_MachineTime_TargetTime(string opName, out int tagValue) + { + tagValue = 0; + string cmd = "TargetTime"; + string tagValueStr; + Read_TagValueByTagTypeName(cmd, opName, out tagValueStr); + tagValue = Convert.ToInt32(tagValueStr); + + } + /// + /// 加工时间变量实际时间 (DINT 110)(18) + /// + public static void Read_MachineTime_ActualTime(string opName, out int tagValue) + { + tagValue = 0; + string cmd = "ActualTime"; + string tagValueStr; + Read_TagValueByTagTypeName(cmd, opName, out tagValueStr); + tagValue = Convert.ToInt32(tagValueStr); + + } + + /// + /// 质量数据总成合格标志(INT104)(21) + /// + public static void Read_QualityMask(string opName, out int tagValue) + { + tagValue = 0; + string cmd = "QualityMask"; + string tagValueStr; + Read_TagValueByTagTypeName(cmd, opName, out tagValueStr); + if (tagValueStr == "1" | tagValueStr.ToLower () == "true") + { + tagValueStr = "1"; + } + tagValue = Convert.ToInt32(tagValueStr); + + } + + /// + /// 机体流向标志(1 BYTE): + /// 0普通工位: + /// 1:上线(发动机上线); + /// 2:下线(发动机下线);(INT114)(41) + /// + public static void Read_PartMoveDirection(string opName, out int tagValue) + { + tagValue = 0; + string cmd = "PartMoveDirection"; + string tagValueStr; + Read_TagValueByTagTypeName(cmd, opName, out tagValueStr); + tagValue = Convert.ToInt32(tagValueStr); + } + + + /// + /// 强制MES(X103.0)(78) + /// + public static void Read_Mes_MustTest(string opName, out int tagValue) + { + tagValue = 0; + string cmd = "IsMES"; + string tagValueStr; + Read_TagValueByTagTypeName(cmd, opName, out tagValueStr); + tagValue = Convert.ToInt32(tagValueStr); + + } + /// + /// 工位三种状态:在线、离线、屏蔽(0,1,2)(DBB116)(79) + /// + public static void Read_OnLineState(string opName, out int tagValue) + { + tagValue = 0; + string cmd = "OnLineState"; + string tagValueStr; + Read_TagValueByTagTypeName(cmd, opName, out tagValueStr); + tagValue = Convert.ToInt32(tagValueStr); + } + + /// + /// 变量类型代码=44 CF0.4 + /// PLC向MES传递机型,机型代码,零件编号完成,通知PLC。 + /// 机型可读 + /// + /// + /// + public static void Read_EngineGetOver_PLC(string opName, out bool tagValue) + { + tagValue = false; + string cmd = "EngineTypeGetOverPLC"; + string tagValueStr; + Read_TagValueByTagTypeName(cmd, opName, out tagValueStr); + tagValue = Convert.ToBoolean(Convert.ToInt32(tagValueStr)); + + } + + /// + /// X100.2允许保存质量数据(19) + /// + /// + /// + public static void Read_QualityData_Read_CF(string opName, out bool tagValue) + { + tagValue = false; + string cmd = "MesRead"; + string tagValueStr; + Read_TagValueByTagTypeName(cmd, opName, out tagValueStr); + tagValue = Convert.ToBoolean(Convert.ToInt64(tagValueStr)); + + } + + /// + /// MES向PLC传递机型(DBX2.1)(5) + /// + /// + /// + public static void Read_EngineTypeGetOver_MES(string opName, out bool tagValue) + { + tagValue = false; + string cmd = "EngineTypeGetOverMES"; + string tagValueStr; + Read_TagValueByTagTypeName(cmd, opName, out tagValueStr); + tagValue = Convert.ToBoolean(Convert.ToInt32(tagValueStr)); + + } + + /// + /// X2.3 工作完成 + /// + /// + /// + public static void Read_MaterialVerifyOver(string opName, out bool tagValue) + { + tagValue = false; + string cmd = "MaterialVerifyOver"; + string tagValueStr; + Read_TagValueByTagTypeName(cmd, opName, out tagValueStr); + tagValue = Convert.ToBoolean(Convert.ToInt32(tagValueStr)); + + } + + /// + /// 申请上线(DBX0.3)(43) + /// + /// + /// + public static void Read_PartLoad(string opName, out bool tagValue) + { + tagValue = false; + string cmd = "PartLoad"; + string tagValueStr; + Read_TagValueByTagTypeName(cmd, opName, out tagValueStr); + tagValue = Convert.ToBoolean(Convert.ToInt32(tagValueStr)); + + } + + /// + /// 上线完成(DBX0.3)(48) + /// + /// + /// + public static void Read_PartLoad_OK(string opName, out bool tagValue) + { + tagValue = false; + string cmd = "PartLoadOK"; + string tagValueStr; + Read_TagValueByTagTypeName(cmd, opName, out tagValueStr); + tagValue = Convert.ToBoolean(Convert.ToInt32(tagValueStr)); + + } + + /// + /// 合格放行(51) + /// + /// + /// + public static void Read_ConfirmOkGo(string opName, out bool tagValue) + { + tagValue = false; + string cmd = "ConfirmOkGo"; + string tagValueStr; + Read_TagValueByTagTypeName(cmd, opName, out tagValueStr); + tagValue = Convert.ToBoolean(Convert.ToInt32(tagValueStr)); + + } + + /// + /// 拧紧结束(DBX1.1)(59) + /// + /// + /// + public static void Read_FixOK(string opName, out bool tagValue) + { + tagValue = false; + string cmd = "FixOK"; + string tagValueStr; + Read_TagValueByTagTypeName(cmd, opName, out tagValueStr); + tagValue = Convert.ToBoolean(Convert.ToInt32(tagValueStr)); + + } + + /// + /// 蘑菇按钮(DBX1.3)(61) + /// + /// + /// + public static void Read_NextPushButton(string opName, out bool tagValue) + { + tagValue = false; + string cmd = "NextPushButton"; + string tagValueStr; + Read_TagValueByTagTypeName(cmd, opName, out tagValueStr); + tagValue = Convert.ToBoolean(Convert.ToInt32(tagValueStr)); + + } + + /// + /// 允许拧紧(DBX3.1)(66) + /// + /// + /// + public static void Read_FixAllow(string opName, out bool tagValue) + { + tagValue = false; + string cmd = "FixAllow"; + string tagValueStr; + Read_TagValueByTagTypeName(cmd, opName, out tagValueStr); + tagValue = Convert.ToBoolean(Convert.ToInt32(tagValueStr)); + + } + + /// + /// 拧紧结束确认(DBX3.2)(67) + /// + /// + /// + public static void Read_FixOver(string opName, out bool tagValue) + { + tagValue = false; + string cmd = "FixOver"; + string tagValueStr; + Read_TagValueByTagTypeName(cmd, opName, out tagValueStr); + tagValue = Convert.ToBoolean(Convert.ToInt32(tagValueStr)); + + } + + /// + ///返修上线,在上线工位,MES依据工件情况,设定为返修件,PLC见到MES设定为1后,将返修标志写入到DBX0.2为1 + ///MES设定完返修返修上线后,MES清空该信号 + ///DBX3.7(72) + /// + /// + /// + public static void Read_RepairUpline_MES(string opName, out int tagValue) + { + tagValue = 0; + string cmd = "RepairUplineMES"; + string tagValueStr; + Read_TagValueByTagTypeName(cmd, opName, out tagValueStr); + tagValue = Convert.ToInt32(tagValueStr); + + } + + + + /// + /// 匹配结果(DBX3.4)(69) + /// + /// + /// + public static void Read_Match(string opName, out int tagValue) + { + tagValue = 0; + string cmd = "Match"; + string tagValueStr; + Read_TagValueByTagTypeName(cmd, opName, out tagValueStr); + tagValue = Convert.ToInt32(tagValueStr); + } + + /// + /// 发动机机型代码(DBB404)(73)[false] + /// + /// + /// + public static void Read_EngineTypeID_MES(string opName, out int EngineTypeID) + { + EngineTypeID = 0; + string cmd = "EngineTypeID_MES"; + string tagValueStr; + Read_TagValueByTagTypeName(cmd, opName, out tagValueStr); + EngineTypeID = Convert.ToInt32(tagValueStr); + + } + + /// + /// 发动机机型(DBB446)(75) + /// + /// + /// + public static void Read_EngineType_MES(string opName, out string EngineType) + { + EngineType = ""; + string cmd = "EngineType_MES"; + string tagValueStr; + Read_TagValueByTagTypeName(cmd, opName, out tagValueStr); + EngineType = tagValueStr; + + } + + /// + /// 发动机号(DBB406)(74) + /// + /// + /// + public static void Read_EngineID_MES(string opName, out string EngineID) + { + EngineID = ""; + string cmd = "EngineID_MES"; + string tagValueStr; + Read_TagValueByTagTypeName(cmd, opName, out tagValueStr); + EngineID = tagValueStr; + + } + + /// + /// 拧紧序号(拧紧或者称重的顺序)(DBB88)(77)[false] + /// + /// + /// + public static void Read_OrderBy(string opName, out int tagValue) + { + tagValue =0; + string cmd = "ProcessCode"; + string tagValueStr; + Read_TagValueByTagTypeName(cmd, opName, out tagValueStr); + tagValue = Convert.ToInt32(tagValueStr); + + } + + /// + /// 工步属性(工作性质)(DBB90)(88)[false] + /// + /// + /// + public static void Read_ProcessCode(string opName, out int tagValue) + { + tagValue = 0; + string cmd = "ProcessCode"; + string tagValueStr; + Read_TagValueByTagTypeName(cmd, opName, out tagValueStr); + tagValue = Convert.ToInt32(tagValueStr); + + } + + + /// + /// 套筒号、子程序代码子程序(DBB26)(2025)[false] + /// + /// + /// + public static void Read_BoltCode(string opName, out int tagValue) + { + tagValue = 0; + string cmd = "BoltCode"; + string tagValueStr; + Read_TagValueByTagTypeName(cmd, opName, out tagValueStr); + tagValue = Convert.ToInt32(tagValueStr); + + } + + + /// + /// 托盘代码(DBB86)(80) + /// + public static void Read_PalletCode(string opName, out int tagValue) + { + tagValue = 0; + string cmd = "PartPalletCode"; + string tagValueStr; + Read_TagValueByTagTypeName(cmd, opName, out tagValueStr); + tagValue = Convert.ToInt32(tagValueStr); + } + + + /// + /// 获得机型,零件编号,机型代码,托盘号,(从PLC) + /// + /// + /// + /// + /// + /// + public static void GetEngineTypeFromPLC(string opName, out int EngineTypeID, out string EngineType, out string EngineID, out int PartPallet_Code,out string OrderForm) + { + Read_EngineTypeID(opName,out EngineTypeID); + Read_EngineType(opName, out EngineType); + Read_EngineID(opName, out EngineID); + Read_TagTypeID(39, opName, out OrderForm); + Read_PalletCode(opName, out PartPallet_Code); + } + + public static void GetEngineTypeFromPLC_MES(string opName, out int EngineTypeID, out string EngineType, out string EngineID, out string OrderForm) + { + Read_EngineTypeID_MES(opName, out EngineTypeID); + Read_EngineType_MES(opName, out EngineType); + Read_EngineID_MES(opName, out EngineID); + Read_OrderForm_MES(opName, out OrderForm); + + + } + + /// + /// 获得机型,零件编号,机型代码,托盘号,(从DB) + /// + /// + /// + /// + /// + /// + public static void GetEngineTypeFromDB(string opName, out int EngineTypeID, out string EngineType, out string EngineID, out int PartPallet_Code) + { + string orderForm = ""; + int isRepair = 0; + string repairCode = ""; + string palletCode = "0"; + BaseDataSystemMES.OpName_MIS_Moby_Select(opName, + out orderForm, out EngineTypeID, out EngineType, + out EngineID, out palletCode, out isRepair, out repairCode); + PartPallet_Code = Convert.ToInt32(palletCode); + } + + /// + /// 0:不修改;1:可以修改。(上线工位)通知PLC。(DBX1.2)(76) + /// + /// + /// + public static void Read_PartPalletCode_PLC_ToMES(string opName, out int tagValue) + { + tagValue = 0; + string cmd = "PartPalletCodePLCToMES"; + string tagValueStr; + Read_TagValueByTagTypeName(cmd, opName, out tagValueStr); + tagValue = Convert.ToInt32(tagValueStr); + + } + + /// + /// 通知写入托盘号(DBX3.5)(70) + /// + /// + /// + public static void Read_PartPalletCode_PLC(string opName, out int tagValue) + { + tagValue = 0; + string cmd = "PartPalletCodePLC"; + string tagValueStr; + Read_TagValueByTagTypeName(cmd, opName, out tagValueStr); + tagValue = Convert.ToInt32(tagValueStr); + + } + + /// + /// 变量类型代码=86,打印第一行(机型),用于线首打印机。STRING 486 .38 + /// + /// + /// + public static void Read_PrintBarCode1_MES(string opName, out string tagValue) + { + tagValue = ""; + string cmd = "PrintBarCode1MES"; + string tagValueStr; + Read_TagValueByTagTypeName(cmd, opName, out tagValueStr); + tagValue = tagValueStr; + + } + + /// + /// 变量类型代码=87,打印第二行(流水号),用于线首打印机。STRING 526 .38 + /// + /// + /// + public static void Read_PrintBarCode2_MES(string opName, out string tagValue) + { + tagValue = ""; + string cmd = "PrintBarCode2MES"; + string tagValueStr; + Read_TagValueByTagTypeName(cmd, opName, out tagValueStr); + tagValue = tagValueStr; + + } + + + /// + /// 上线工位。0:正常工作;1:空托盘放行(DBX2.2)(6) + /// + /// + /// + public static void Read_PartPalletGoOver(string opName, out int tagValue) + { + tagValue = 0; + string cmd = "PartPalletGoOver"; + string tagValueStr; + Read_TagValueByTagTypeName(cmd, opName, out tagValueStr); + tagValue = Convert.ToInt32(tagValueStr); + + } + + /// + /// 自动手动申请工件编号,0是自动方式;1:手动方式。切换时,(DBX2.1)(71) + /// + /// + /// + public static void Read_IsAutoGetEngineID(string opName, out int tagValue) + { + tagValue = 0; + string cmd = "IsAutoGetEngineID"; + string tagValueStr; + Read_TagValueByTagTypeName(cmd, opName, out tagValueStr); + tagValue = Convert.ToInt32(tagValueStr); + + } + + /// + /// 正常拧紧时选择(DBX100.3)(81) + /// + /// + /// + public static void Read_Normal(string opName, out int tagValue) + { + tagValue = 0; + string cmd = "Normal"; + string tagValueStr; + Read_TagValueByTagTypeName(cmd, opName, out tagValueStr); + tagValue = Convert.ToInt32(tagValueStr); + + } + + /// + /// 备用拧紧时选择(DBX100.4)(82) + /// + /// + /// + public static void Read_UnNormal(string opName, out int tagValue) + { + tagValue = 0; + string cmd = "UnNormal"; + string tagValueStr; + Read_TagValueByTagTypeName(cmd, opName, out tagValueStr); + tagValue = Convert.ToInt32(tagValueStr); + + } + + /// + /// 允许拧紧2(DBX100.5)(83) + /// + /// + /// + public static void Read_FixAllow_2(string opName, out int tagValue) + { + tagValue = 0; + string cmd = "FixAllow2"; + string tagValueStr; + Read_TagValueByTagTypeName(cmd, opName, out tagValueStr); + tagValue = Convert.ToInt32(tagValueStr); + + } + + /// + /// 拧紧结束2(DBX100.6)(84) + /// + /// + /// + public static void Read_FixOK_2(string opName, out int tagValue) + { + tagValue = 0; + string cmd = "FixOK2"; + string tagValueStr; + Read_TagValueByTagTypeName(cmd, opName, out tagValueStr); + tagValue = Convert.ToInt32(tagValueStr); + + } + + /// + /// 拧紧结束确认2(DBX100.7)(85) + /// + /// + /// + public static void Read_FixOver_2(string opName, out int tagValue) + { + tagValue = 0; + string cmd = "FixOver2"; + string tagValueStr; + Read_TagValueByTagTypeName(cmd, opName, out tagValueStr); + tagValue = Convert.ToInt32(tagValueStr); + + } + + /// + /// 拧紧顺序2(DBX101.7)(1007) + /// MES通知PLC开始拧紧顺序(0为其他位,1为第一位置)(必须MES) + /// + /// + /// + public static void Read_WriteShaft_2(string opName, out int tagValue) + { + tagValue = 0; + string cmd = "WriteShaft2"; + string tagValueStr; + Read_TagValueByTagTypeName(cmd, opName, out tagValueStr); + tagValue = Convert.ToInt32(tagValueStr); + } + + + /// + /// 返修上线(DBX2.6)(52) + /// + /// + /// + public static void Read_PartLoadFinish(string opName, out int tagValue) + { + tagValue = 0; + string cmd = "PartLoadFinish"; + string tagValueStr; + Read_TagValueByTagTypeName(cmd, opName, out tagValueStr); + tagValue = Convert.ToInt32(tagValueStr); + + } + + /// + /// 返修上线后,PLC确认(DBX1.0)(58) + /// + /// + /// + public static void Read_PartLoadOver(string opName, out int tagValue) + { + tagValue = 0; + string cmd = "PartLoadOver"; + string tagValueStr; + Read_TagValueByTagTypeName(cmd, opName, out tagValueStr); + tagValue = Convert.ToInt32(tagValueStr); + + } + + /// + /// 变量类型代码=22,读取托盘信息 DBW126 + /// + /// + /// + public static void Read_PalletInfo(string opName, out int tagValue) + { + tagValue = 0; + string cmd = "PalletInfo"; + string tagValueStr; + Read_TagValueByTagTypeName(cmd, opName, out tagValueStr); + tagValue = Convert.ToInt32(tagValueStr); + } + + /// + /// 变量类型代码=23,读取托盘信息 DBW194 + /// + /// + /// + public static void Read_RepairStatus_PLC(string opName, out int tagValue) + { + tagValue = 0; + string cmd = "RepairStatusPLC"; + string tagValueStr; + Read_TagValueByTagTypeName(cmd, opName, out tagValueStr); + tagValue = Convert.ToInt32(tagValueStr); + + } + + /// + /// PLC将MOBY信息成功写入到了对应的DB,然后通知MES(DBX1.5)(63) + /// + /// + /// + public static void Read_PalletMobyReadOver(string opName, out int tagValue) + { + tagValue = 0; + string cmd = "PalletMobyReadOver"; + string tagValueStr; + Read_TagValueByTagTypeName(cmd, opName, out tagValueStr); + tagValue = Convert.ToInt32(tagValueStr); + + } + + + /// + /// 在线返修状态(DBX4.0)(91) + /// + /// + /// + public static void Read_OnlineRepair(string opName, out int tagValue) + { + tagValue = 0; + string cmd = "OnlineRepair"; + string tagValueStr; + Read_TagValueByTagTypeName(cmd, opName, out tagValueStr); + tagValue = Convert.ToInt32(tagValueStr); + + } + + /// + /// 离线返修状态(DBX4.1)(92) + /// + /// + /// + public static void Read_OutLineRepair(string opName, out bool tagValue) + { + tagValue = false; + string cmd = "OutLineRepair"; + string tagValueStr; + Read_TagValueByTagTypeName(cmd, opName, out tagValueStr); + tagValue = Convert.ToBoolean(Convert.ToInt32(tagValueStr)); + + } + + /// + /// MES通知PLC修改托盘状态成功(DBX4.2)(93) + /// + /// + /// + public static void Read_UpdatePalletOK(string opName, out bool tagValue) + { + tagValue = false; + string cmd = "UpdatePalletOK"; + string tagValueStr; + Read_TagValueByTagTypeName(cmd, opName, out tagValueStr); + tagValue = Convert.ToBoolean(Convert.ToInt32(tagValueStr)); + } + + + /// + /// MES向PLC要求申请下线(DBX0.7)(50) + /// + /// + /// + public static void Read_PalletDown(string opName, out bool tagValue) + { + tagValue = false; + string cmd = "PalletDown"; + string tagValueStr; + Read_TagValueByTagTypeName(cmd, opName, out tagValueStr); + tagValue = Convert.ToBoolean(Convert.ToInt32(tagValueStr)); + + } + + + /// + /// 物料检测(99) + /// + /// + /// + public static void Read_CheckMaterial(string opName, out object tagValue) + { + tagValue = new bool[16]; + string cmd = "CheckMaterial"; + string tagValueStr; + Read_TagValueByTagTypeName(cmd, opName, out tagValueStr); + tagValue = Convert.ToBoolean(Convert.ToInt32(tagValueStr)); + + } + + /// + /// 备用功能是否启用(95) + /// + /// + /// + public static void Read_BakOpNameIsWork(string opName, out bool tagValue) + { + tagValue = false; + string cmd = "BakOpNameIsWork"; + string tagValueStr; + Read_TagValueByTagTypeName(cmd, opName, out tagValueStr); + tagValue = Convert.ToBoolean(Convert.ToInt32(tagValueStr)); + } + + + /// + /// 质量呼叫(DBX301.2)(2011) + /// + /// + /// + public static void Read_QualityCall(string opName, out bool tagValue) + { + tagValue = false; + string cmd = "QualityCall"; + string tagValueStr; + Read_TagValueByTagTypeName(cmd, opName, out tagValueStr); + tagValue = Convert.ToBoolean(Convert.ToInt32(tagValueStr)); + } + + /// + /// 物料呼叫(DBX301.3)(2012) + /// + /// + /// + public static void Read_MaterialCall(string opName, out bool tagValue) + { + tagValue = false; + string cmd = "MaterialCall"; + string tagValueStr; + Read_TagValueByTagTypeName(cmd, opName, out tagValueStr); + tagValue = Convert.ToBoolean(Convert.ToInt32(tagValueStr)); + + } + + /// + /// 故障呼叫(DBX301.4)(2013) + /// + /// + /// + public static void Read_FaultCall(string opName, out bool tagValue) + { + tagValue = false; + string cmd = "FaultCall"; + string tagValueStr; + Read_TagValueByTagTypeName(cmd, opName, out tagValueStr); + tagValue = Convert.ToBoolean(Convert.ToInt32(tagValueStr)); + } + + public static void Read_PartScanCode(int tagTypeID, string opName, out string tagValue) + { + tagValue = ""; + string tagValueStr; + Read_TagValueByTagTypeID(tagTypeID, opName, out tagValueStr); + tagValue = tagValueStr; + } + + } +} diff --git a/Common/09MesDataFunction/MesDataFunction/MesDataFunction/MIS.OpcServerMIS.Write.cs b/Common/09MesDataFunction/MesDataFunction/MesDataFunction/MIS.OpcServerMIS.Write.cs new file mode 100644 index 0000000..98d7e4d --- /dev/null +++ b/Common/09MesDataFunction/MesDataFunction/MesDataFunction/MIS.OpcServerMIS.Write.cs @@ -0,0 +1,531 @@ +using DoWhatPlc; +using System; +//using SystemFramework; +//using OpcData; + +namespace MesServerWork +{ + + public partial class MIS_BASE + { + + + //static public void WritePLC(int tagType, string opName, object tagValue) + //{ + // Write_TagTypeID(tagType, opName, tagValue); + //} + /// + /// + /// + /// + public delegate void DemoHandler(object sender, CustomeEvetnArgs e); + /// + /// + /// + public static event DemoHandler OPCTagDataDemo; + //static private void Write_MesReadOver(string opName, object tagValue) + //{ + // int tagTypeID = 0; + // string msg; + // try + // { + // string tagTypeCodeID = "20"; + // DtWebApi.ReadWritePLC.Write_TagValueByTagTypeID(tagTypeCodeID, opName, tagValue); ; + // } + // catch (Exception err) + // { + // ////ApplicationLog.WriteLog(err, "Write_TagValueByTagTypeName_FUNC"); + // } + + //} + /// + /// 根据tagType,工位号写入PLC对应值 + /// + /// + /// + static private void Write_TagValueByTagTypeName(string cmd, string opName,object tagValue) + { + int tagTypeID = 0; + string msg; + try + { + tagTypeID = Convert.ToInt32(MIS_BASE.hashtable_TagType[cmd]); + MIS_BASE.WriteTagValue(tagTypeID, opName, tagValue); + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Write_TagValueByTagTypeName_FUNC"); + } + + } + + /// + /// 根据TagTypeID,工位号写入PLC对应值 + /// + /// + /// + static public void Write_TagValueByTagTypeID(int tagTypeID, string opName, object tagValue) + { + string msg; + object tagValueOb; + object newTagValue= tagValue; + try + { + MIS_BASE.WriteTagValue(tagTypeID, opName, tagValue); + + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Write_TagValueByTagTypeID_FUNC"); + } + + } + + + + + /// + /// 通过TagID写入PLC数据 + /// + /// + /// + static private void Write_TagValueByTagID(string TagID, object tagValue) + { + string msg; + //tagValue = "0"; + try + { + MIS_BASE.WritePLC(TagID, tagValue); + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Write_TagValueByTagID_FUNC"); + } + } + + public static void Write_TagTypeID(int tagTypeID, string opName, object tagValue) + { + Write_TagValueByTagTypeID(tagTypeID, opName, tagValue); + } + + public static void Write_TagID(string TagID, object tagValue) + { + Write_TagValueByTagID(TagID, tagValue); + } + + + /// + /// 清空MES信号 MES传递机型(5) 允许工作(66) 合格放行(51) 不合格放行(8) 拧紧结束(67) 工作完成(7) 保存完成(20) 加工时间保存完成(54) 匹配完成(68) 默认false + /// + /// + /// + public static void Write_ClearMesMoby(string opName) + { + MIS_BASE.Write_EngineTypeGetOver_MES(opName, false); + MIS_BASE.Write_FixAllow(opName, false); + MIS_BASE.Write_ConfirmOkGo(opName, false); + MIS_BASE.Write_FalseGO(opName, false); + MIS_BASE.Write_FixOver(opName, false); + MIS_BASE.Write_MaterialVerifyOver(opName, false); + MIS_BASE.Write_MesReadOver(opName, false); + MIS_BASE.Write_MachineTime_ReadOver(opName, false); + MIS_BASE.Write_MatchingCompleted(opName, false); + } + + + /// + /// 订单号(string)(25) + /// + /// + /// + public static void Write_OrderForm(string opName, string tagValue) + { + string cmd = "OrderForm"; + Write_TagValueByTagTypeName(cmd, opName, tagValue); + } + /// + /// 总成编号(string)(26) + /// + /// + /// + public static void Write_AssemblyCode(string opName, string tagValue) + { + string cmd = "AssemblyCode"; + Write_TagValueByTagTypeName(cmd, opName, tagValue); + } + /// + /// 配方号1(dint)(27) + /// + /// + /// + public static void Write_Recipe1(string opName, int tagValue) + { + string cmd = "Recipe1"; + Write_TagValueByTagTypeName(cmd, opName, tagValue); + } + /// + /// 配方号2(dint)(28) + /// + /// + /// + public static void Write_Recipe2(string opName, int tagValue) + { + tagValue = 0; + string cmd = "Recipe2"; + Write_TagValueByTagTypeName(cmd, opName, tagValue); + } + + + /// + /// 订单号(string)(61) + /// + /// + /// + public static void Write_OrderForm_MES(string opName, string tagValue) + { + string cmd = "OrderForm_MES"; + Write_TagValueByTagTypeName(cmd, opName, tagValue); + } + /// + /// 总成编号(string)(62) + /// + /// + /// + public static void Write_AssemblyCode_MES(string opName, string tagValue) + { + + string cmd = "AssemblyCode_MES"; + Write_TagValueByTagTypeName(cmd, opName, tagValue); + } + /// + /// 配方号1(dint)(63) + /// + /// + /// + public static void Write_Recipe1_MES(string opName, int tagValue) + { + string cmd = "Recipe1_MES"; + Write_TagValueByTagTypeName(cmd, opName, tagValue); + } + /// + /// 配方号2(dint)(64) + /// + /// + /// + public static void Write_Recipe2_MES(string opName, int tagValue) + { + string cmd = "Recipe2_MES"; + Write_TagValueByTagTypeName(cmd, opName, tagValue); + } + + + /// + /// 各个工位返修状态(4) + /// + /// + /// + public static void Write_RepairPathString(string opName, string tagValue) + { + string cmd = "RepairPathString"; + Write_TagValueByTagTypeName(cmd, opName, tagValue); + } + /// + /// MES保存完数据(必须MIS)(X102.2)(20) + /// + /// + /// + public static void Write_MesReadOver(string opName, bool tagValue) + { + string cmd = "MesReadOver"; + Write_TagValueByTagTypeName(cmd, opName, tagValue); + } + + /// + /// 加工时间保存完数据 DBX102.1 (54) + /// + /// + /// + public static void Write_MachineTime_ReadOver(string opName, bool tagValue) + { + string cmd = "MachineTime_ReadOver"; + Write_TagValueByTagTypeName(cmd, opName, tagValue); + + } + + /// + /// 工位三种状态:在线、离线、屏蔽(0,1,2)(DBB116)(79) + /// + /// + /// + public static void Write_OnLineState(string opName, int tagValue) + { + string cmd = "OnLineState"; + Write_TagValueByTagTypeName(cmd, opName,Convert .ToInt16 ( tagValue)); + } + + /// + /// 托盘编号(PLC)(80) + /// + /// + /// + public static void Write_PalletCode(string opName, int tagValue) + { + string cmd = "PartPalletCode"; + Write_TagValueByTagTypeName(cmd, opName, Convert.ToInt16(tagValue)); + } + + /// + /// MES向PLC传递机型(5) + /// + /// + /// + public static void Write_EngineTypeGetOver_MES(string opName, bool tagValue) + { + string cmd = "EngineTypeGetOverMES"; + Write_TagValueByTagTypeName(cmd, opName, tagValue); + } + + /// + /// 工作完成(7) + /// + /// + /// + public static void Write_MaterialVerifyOver(string opName, bool tagValue) + { + string cmd = "MaterialVerifyOver"; + Write_TagValueByTagTypeName(cmd, opName, tagValue); + } + + /// + /// 合格方式放行(51) + /// + /// + /// + public static void Write_ConfirmOkGo(string opName, bool tagValue) + { + string cmd = "ConfirmOkGo"; + Write_TagValueByTagTypeName(cmd, opName, tagValue); + } + + /// + /// 允许拧紧(66) + /// + /// + /// + public static void Write_FixAllow(string opName, bool tagValue) + { + string cmd = "FixAllow"; + Write_TagValueByTagTypeName(cmd, opName, tagValue); + } + + /// + /// 拧紧结束(67) + /// + /// + /// + public static void Write_FixOver(string opName, bool tagValue) + { + string cmd = "FixOver"; + Write_TagValueByTagTypeName(cmd, opName, tagValue); + } + + /// + ///返修上线,在上线工位,MES依据工件情况,设定为返修件,PLC见到MES设定为1后,将返修标志写入到DBX0.2为1 + ///MES设定完返修返修上线后,MES清空该信号 + ///DBX3.7(72) + /// + /// + /// + public static void Write_RepairUpline_MES(string opName, bool tagValue) + { + string cmd = "RepairUplineMES"; + Write_TagValueByTagTypeName(cmd, opName, tagValue); + } + + /// + /// 匹配完成(68) + /// + /// + /// + public static void Write_MatchingCompleted(string opName, bool tagValue) + { + string cmd = "MatchingCompleted"; + Write_TagValueByTagTypeName(cmd, opName, tagValue); + } + + + /// + /// 不合格放行(8) + /// + /// + /// + public static void Write_FalseGO(string opName, bool tagValue) + { + string cmd = "FalseGo"; + Write_TagValueByTagTypeName(cmd, opName, tagValue); + } + + /// + /// 匹配结果(69) + /// + /// + /// + public static void Write_Match(string opName, bool tagValue) + { + string cmd = "Match"; + Write_TagValueByTagTypeName(cmd, opName, tagValue); + + } + + /// + /// 变量类型代码=73,机型代码。DBB404~405 机型标志 + /// + /// + /// + public static void Write_EngineTypeID_MES(string opName, int tagValue) + { + string cmd = "EngineTypeID_MES"; + Write_TagValueByTagTypeName(cmd, opName, Convert.ToInt16(tagValue)); + } + /// + /// 变量类型代码=74,零件编号。DBB406~445 发动机编号 + /// + /// + /// + public static void Write_EngineID_MES(string opName, string tagValue) + { + string cmd = "EngineID_MES"; + Write_TagValueByTagTypeName(cmd, opName, tagValue); + } + //public static void Write_OrderForm_MES(string opName, string tagValue) + //{ + // string tagTypeCodeID = "116"; + // DtWebApi.ReadWritePLC.WritePLC(tagTypeCodeID, opName, tagValue); + //} + + //WritePLC(string tagTypeCodeID, string opName, object tagValue) + /// + /// 变量类型代码=75,零件机型。DBB446~485 发动机机型 + /// + /// + /// + public static void Write_EngineType_MES(string opName, string tagValue) + { + string cmd = "EngineType_MES"; + Write_TagValueByTagTypeName(cmd, opName, tagValue); + } + + /// + /// 拧紧序号(77) + /// + /// + /// + public static void Write_ProcessCode(string opName, int tagValue) + { + string cmd = "ProcessCode"; + Write_TagValueByTagTypeName(cmd, opName, Convert.ToInt16(tagValue)); + } + + + /// + /// 套筒号(88) + /// + /// + /// + public static void Write_BoltCode(string opName, int tagValue) + { + string cmd = "BoltCode"; + Write_TagValueByTagTypeName(cmd, opName, Convert.ToInt16(tagValue)); + } + + /// + /// 空托盘放行(DBX2.2)(6) + /// + /// + /// + public static void Write_PartPalletGoOver(string opName, int tagValue) + { + string cmd = "PartPalletGoOver"; + Write_TagValueByTagTypeName(cmd, opName, Convert.ToInt16(tagValue)); + } + + + /// + /// 自动手动申请工件编号,0是自动方式;1:手动方式。切换时,(DBX2.1)(71) + /// + /// + /// + public static void Write_IsAutoGetEngineID(string opName, int tagValue) + { + string cmd = "IsAutoGetEngineID"; + Write_TagValueByTagTypeName(cmd, opName, Convert.ToInt16(tagValue)); + } + + + /// + /// 正常拧紧时选择(DBX100.3)(81) + /// + /// + /// + public static void Write_Normal(string opName, int tagValue) + { + string cmd = "Normal"; + Write_TagValueByTagTypeName(cmd, opName, Convert.ToInt16(tagValue)); + } + /// + /// 备用拧紧时选择(DBX100.4)(82) + /// + /// + /// + public static void Write_UnNormal(string opName, int tagValue) + { + string cmd = "UnNormal"; + Write_TagValueByTagTypeName(cmd, opName, Convert.ToInt16(tagValue)); + } + + /// + /// 变量类型代码=52,复位设备(MES)DBX0.6 + /// 通知PLC复位设备 + /// + /// + /// + public static void Write_ResetDevice(string opName, bool tagValue) + { + string cmd = "PartLoadFinish"; + Write_TagValueByTagTypeName(cmd, opName, tagValue); + } + + /// + ///托盘状态(22) + /// + /// + /// + public static void Write_PalletInfo(string opName, int tagValue) + { + string cmd = "PalletInfo"; + Write_TagValueByTagTypeName(cmd, opName, Convert.ToInt16(tagValue)); + } + /// + /// 返修标志(93) + /// + /// + /// + public static void Write_RepairStatusMES(string opName, int tagValue) + { + string cmd = "RepairStatusMES"; + Write_TagValueByTagTypeName(cmd, opName, Convert.ToInt16(tagValue)); + } + + /// + /// MES通知PLC修改托盘状态成功 + /// + /// + /// + public static void Write_UpdatePalletOK(string opName, bool tagValue) + { + string cmd = "UpdatePalletOK"; + Write_TagValueByTagTypeName(cmd, opName, tagValue); + } + + } +} diff --git a/Common/09MesDataFunction/MesDataFunction/MesDataFunction/MIS.QualityData.Read.cs b/Common/09MesDataFunction/MesDataFunction/MesDataFunction/MIS.QualityData.Read.cs new file mode 100644 index 0000000..73d5dd7 --- /dev/null +++ b/Common/09MesDataFunction/MesDataFunction/MesDataFunction/MIS.QualityData.Read.cs @@ -0,0 +1,119 @@ +using System; +using System.Data; +using System.Collections; +//using BasicData; +//using bizFacade; +//using SystemFramework; +using System.Configuration; +using bizFacade; +using DoWhatPlc; +using MesWork; +using System.Collections.Generic; + +namespace MesServerWork +{ + public partial class MIS_BASE + { + + /// + /// 读取质量数据 + /// + /// + public static void ReadPLC_Sync_ValueList(string opName, out Hashtable valueList) + { + valueList = null; + ReadPLCData(opName, out valueList); + } + /// + /// 根据工位号 同步读取数据 + /// + /// 工位号 + /// PLC仅仅值列表 + private static void ReadPLCData(string opName, out Hashtable valueList) + { + valueList = new Hashtable(); + QualityDataType qualityDataType; + qualityDataType = new QualityDataType(); + System.Data.DataTable dt; + dt = BaseDataSystemMES.BaseData_tagTable_QualityData_Item_B5A(); + + object tagValueStr = "0"; + for (int i = 0; i < dt.Rows.Count; i++) + { + if (opName == dt.Rows[i]["工位号"].ToString()) + { + qualityDataType.tagID = dt.Rows[i]["TagID"].ToString (); + qualityDataType.tagTypeID = Convert.ToInt32(dt.Rows[i]["TagTypeID"]);//变量类型 + qualityDataType.opName = opName;// + qualityDataType.isGoodBad = 192;// + qualityDataType.tagQuality = 192;// + qualityDataType.tagValueType = Convert.ToInt32(dt.Rows[i]["变量类型代码"]); + qualityDataType.tagOrderBy = Convert.ToInt32(dt.Rows[i]["列位置"]); + qualityDataType.tagItemOrderBy = Convert.ToInt32(dt.Rows[i]["变量排序"]); + qualityDataType.tagProperty = Convert.ToInt32(dt.Rows[i]["变量特点"]); ;//变量特点 + + MIS_BASE.Read_TagID(qualityDataType.tagID, out tagValueStr); + + if (qualityDataType.tagTypeID == 18) + { + qualityDataType.tagValue = Convert.ToInt32(tagValueStr);//变量值 + } + else + { + qualityDataType.tagValue = tagValueStr;//变量值 + } + valueList.Add(qualityDataType.tagID, qualityDataType); + } + } + } + public static QualityDataSaveList ReadPLC_Sync_DataList_MesRead(string opName) + { + + QualityDataSaveList qualityDataSaveList = new QualityDataSaveList(); + qualityDataSaveList.BasicDataTagValue = MIS_BASE.BasicDataTagValue; + qualityDataSaveList.BasicDataTagValueUpDown = MIS_BASE.BasicDataTagValueUpDown; + qualityDataSaveList.hashtable_EngineTypeID = MIS_BASE.hashtable_EngineTypeID; + qualityDataSaveList.hashtable_tagTable_OpName_SaveData = MIS_BASE.hashtable_tagTable_OpName_SaveData; + //List TagIDQualityDataTypeList = new List(); + + Hashtable ht = new Hashtable(); + + var cd = PlcLinkForm.ReadPLC_GroupData(opName); + foreach (KeyValuePair _cd in cd) + { + var tagID = Convert.ToInt32(_cd.Key); + var TF = (TagFormat)_cd.Value; + + QualityDataType qualityDataType; + qualityDataType = new QualityDataType(); + + qualityDataType.tagID = TF.TagID; + qualityDataType.tagTypeID = TF.TagTypeID;//变量类型 + qualityDataType.opName = opName; + qualityDataType.isGoodBad = 192; + int.TryParse(TF.TagQuality, out int TagQuality); + qualityDataType.tagQuality = TagQuality; + qualityDataType.tagValueType = TF.TagTypeCodeID; + int.TryParse(TF.TagOrderBy, out int TagOrderBy); + qualityDataType.tagOrderBy = TagOrderBy; + int.TryParse(TF.TagItemOrderBy, out int TagItemOrderBy); + qualityDataType.tagItemOrderBy = TagItemOrderBy; + qualityDataType.tagProperty = TF.TagProperty;//变量特点 + qualityDataType.tagValue = TF.TagValue;//变量值 + + ht.Add(tagID, qualityDataType); + } + qualityDataSaveList.valuList = ht; + return qualityDataSaveList; + + //string api = ""; + //string type = "GET"; + //string controlStr = "PLC1"; + //string actionStr = "ReadPLC_Sync_DataList_MesRead"; + //Dictionary dic = new Dictionary(); + //dic.Add("opName", opName); + //var rc = new CallWebApi().InvokeWebapiQualityDataSaveList(controlStr, actionStr, api, type, dic); + //return rc; + } + } +} diff --git a/Common/09MesDataFunction/MesDataFunction/MesDataFunction/MIS.SendMessage.cs b/Common/09MesDataFunction/MesDataFunction/MesDataFunction/MIS.SendMessage.cs new file mode 100644 index 0000000..a56b188 --- /dev/null +++ b/Common/09MesDataFunction/MesDataFunction/MesDataFunction/MIS.SendMessage.cs @@ -0,0 +1,127 @@ +using System; +using System.Data; +using System.Collections; +//using BasicData; +////using bizFacade; +//using SystemFramework; +using System.Configuration; +//using MesWork; +using MQTTnet.Client.Connecting; +using MQTTnet.Client.Disconnecting; +using MQTTnet.Client.Receiving; +using MQTTnet; +using MesWorkMqtt; +using System.Threading.Tasks; + +namespace MesServerWork +{ + public partial class MIS_BASE + { + /// + /// + /// + public static string MqttTargetTopic = ConfigurationManager.AppSettings["MqttTargetTopic"]; + /// + /// + /// + static new MesWebFun_base.MisWebInterface misWebInterface = new MesWebFun_base.MisWebInterface(); + /// + /// + /// + static readonly Object locker = new Object(); + /// + /// 发消息给通讯服务器 + /// + /// + public static string asyncSendMessage(string Message) + { + lock (locker) + { + //"MES|MachinePlan|OpName|Value + var array = Message.Split('|'); + var cmd = array[1]; + var opName = array[2]; + var topic = $"{MqttTargetTopic}/{opName}"; + Task.Run(() => Mqtt.Publish(topic, Message)); + + var responseStr = misWebInterface.WebSocket_Function(Message); + if (responseStr.Length > 0) + { + Task.Run(() => Mqtt.Publish(topic, $"MES|{cmd}_Resources|{opName}|{responseStr}")); + } + return responseStr; + } + } + //public static string asyncSendMessage(Mqtt Mqtt1, string Message) + //{ + // lock (locker) + // { + // //"MES|MachinePlan|OpName|Value + // var array = Message.Split('|'); + // var cmd = array[1]; + // var opName = array[2]; + // var topic = $"{MqttTargetTopic}/{opName}"; + // Task.Run(() => Mqtt1.Publish(topic, Message)); + + + + // var responseStr = misWebInterface.WebSocket_Function(Message); + // if (responseStr.Length > 0) + // { + // Task.Run(() => Mqtt1.Publish(topic, $"MES|{cmd}_Resources|{opName}|{responseStr}")); + // } + // return responseStr; + // return ""; + // } + //} + public static string asyncSendMessageDemo(string Message) + { + lock (locker) + { + //"MES|MachinePlan|OpName|Value + var array = Message.Split('|'); + var cmd = array[1]; + var opName = array[2]; + var topic = $"{MqttTargetTopic}/{opName}"; + + //Mqtt.Publish(topic, Message); + string responseStr = ""; + //var responseStr = misWebInterface.WebSocket_Function(Message); + //if (responseStr.Length > 0) + //{ + + // Mqtt.Publish(topic, $"MES|{cmd}_Resources|{opName}|{responseStr}"); + //} + return responseStr; + } + } + + /// + /// 发消息给通讯服务器 + /// + /// + public static string asyncSendMessageQos0(string Message) + { + lock (locker) + { + //"MES|MachinePlan|OpName|Value + var array = Message.Split('|'); + var cmd = array[1]; + var opName = array[2]; + var topic = $"{MqttTargetTopic}/{opName}"; + Mqtt.PublishQos0(topic, Message); + //var responseStr = misWebInterface.WebSocket_Function(Message); + //if (responseStr.Length > 0) + //{ + // Mqtt.Publish(topic, $"MES|{cmd}_Resources|{opName}|{responseStr}"); + //} + //return responseStr; + return ""; + } + } + + + + } +} + diff --git a/Common/09MesDataFunction/MesDataFunction/MesDataFunction/MIS_BASE.cs b/Common/09MesDataFunction/MesDataFunction/MesDataFunction/MIS_BASE.cs new file mode 100644 index 0000000..3e3f609 --- /dev/null +++ b/Common/09MesDataFunction/MesDataFunction/MesDataFunction/MIS_BASE.cs @@ -0,0 +1,431 @@ +using BasicData; + +using MesWork; +using Newtonsoft.Json; +using OpcBasic; +using System; +using System.Collections; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Collections.Specialized; +using System.Linq; +using System.Net.Http; +using System.Runtime.Remoting.Messaging; +using System.Text; +using System.Threading.Tasks; + +namespace MesServerWork +{ + + /* +HeartBeatMIS 15 +EngineTypeGetOverMES 5 +PartPalletGoOver 6 +MaterialVerifyOver 7 +FalseGo 8 +ConfirmOkGo 51 +PartLoadFinish 52 +UnloadCompleted 53 +MachineTime_ReadOver 54 +FixAllow 66 +FixOver 67 +MatchingCompleted 68 +Match 69 +Reserved_1 70 +IsAutoGetEngineID 71 +RepairUplineMES 72 +ProcessCode 77 +BoltCode 88 +RepairStatus 93 +Reserved_3 24 +Reserved_4 25 +Reserved_5 26 +Reserved_6 27 +Reserved_7 28 +Reserved_8 29 +Reserved_9 30 +Reserved_10 31 +Reserved_11 32 +Reserved_12 33 +Reserved_13 34 +Reserved_14 35 +MesReadOver 20 +Reserved_15 110 +Reserved_16 111 +Reserved_17 112 +OnLineState 79 +EngineTypeID_MES 73 +EngineID_MES 74 +EngineType_MES 75 +MarkID 42 +RepairPathString 4 +SPareint1 113 +SPareint2 114 +SPareint3 115 +Sparestring1 116 +Sparestring2 117 +HeartBeatPLC 14 +WorkStart 2 +RepairPartStatusPLC 3 +PartLoad 43 +EngineTypeGetOverPLC 44 +PartLoadOK 48 +Reserved_18 49 +PalletDown 50 +Reserved_19 58 +FixOK 59 +Reserved_20 76 +Reserved_21 61 +Reserved_22 62 +Reserved_23 63 +Reserved_24 64 +Reserved_25 65 +EngineTypeID 9 +EngineID 10 +EngineType 11 +PartPalletCode 80 +PalletInfo 22 +MesRead 19 +PutOn 1000 +WorkOn 1001 +Alarm 1002 +NoPart 1003 +Block 1004 +PartPalletStatus 13 +TargetTimeRead 16 +QualityMask 21 +RepairStatusPLC 23 +MachineTargetTime 17 +MachineActualTime 18 +PLCSPareint1 36 +PLCSPareint2 37 +PLCSPareint3 38 +PLCSarestring1 39 +PLCSarestring2 40 + */ + + + + public partial class MIS_BASE + { + + + /// + ///引用程序集Hashtable + /// + public static Hashtable Hashtable_assembly = new Hashtable(); + /// + /// + /// + static public NameValueCollection hashtable_TagTypeTagName = null; + + /// + /// + /// + static public NameValueCollection hashtable_TagTypeChange = null; + /// + /// + /// + static public NameValueCollection hashtable_WebTagTypeChange = null; + /// + /// + /// + static public NameValueCollection hashtable_MesTagTypeChange = null; + /// + /// + /// + static readonly object l = new object(); + /// + /// + /// + /// + /// + /// + public static object ReadPLC(int tagTypeCodeID, string opName) + { + try + { + return PlcLinkForm.ReadPLC(tagTypeCodeID, opName); + + } + catch { return "-3"; } + } + /// + /// + /// + /// + /// + public static object ReadPLC(string tagID) + { + return PlcLinkForm.ReadPLC(tagID); + } + /// + /// 20230218 + /// 按组读质量数据,返回带合格标志的质量数据列表 + /// + /// + /// + public static Hashtable ReadPLC_Sync_DataList_MesRead_ByOnlyDataGroup(string opName) + { + lock (l) + { + + var tagValues = GetDbAndMaxLengthByOpNameByBytes(opName); + + var keyValues = tagValues.OrderBy(x => x.Key).ToDictionary(k => k.Key, v => v.Value); + + TagFormat tagFormatTemp; + int tagIndex = 1; + int isOK = 0; + + Hashtable ht = new Hashtable(); + + + foreach (KeyValuePair _cd in keyValues) + { + if (_cd.Key.ToString()[0].ToString() == "7") + { + tagFormatTemp = (TagFormat)_cd.Value; + if (tagIndex % 3 == 1) + { + isOK = Convert.ToInt32(tagFormatTemp.TagValue); + } + else if (tagIndex % 3 == 2) + { + var TF = (TagFormat)_cd.Value; + + QualityDataType qualityDataType; + qualityDataType = GetQualityDataType(TF); + qualityDataType.isGoodBad = isOK; + ht.Add(qualityDataType.tagID, qualityDataType); + } + else if (tagIndex % 3 == 0) + { + var TF = (TagFormat)_cd.Value; + + QualityDataType qualityDataType; + qualityDataType = GetQualityDataType(TF); + qualityDataType.isGoodBad = isOK; + ht.Add(qualityDataType.tagID, qualityDataType); + } + + tagIndex++; + } + //Console.WriteLine($"key:{kv.Key} value:{kv.Value}"); + } + return ht; + } + } + + public static ConcurrentDictionary GetDbAndMaxLengthByOpNameByBytes(string opName) + { + string tagStartAdr = ""; + ushort tagAdrListMaxLength = 0; + PlcLinkForm.GetDbAndMaxLengthByOpName(opName, out tagStartAdr, out tagAdrListMaxLength); + var tagAdrListTagFormat = PlcLinkForm.ReadQualityDataList(opName, tagStartAdr, tagAdrListMaxLength); + return tagAdrListTagFormat; + } + + + public static BasicData.QualityDataType GetQualityDataType(TagFormat TF) + { + QualityDataType qualityDataType; + + qualityDataType = new QualityDataType(); + + qualityDataType.tagID = TF.TagID; + qualityDataType.tagTypeID = TF.TagTypeID;//变量类型 + qualityDataType.opName = TF.OpName; + int.TryParse(TF.TagQuality, out int TagQuality); + qualityDataType.tagQuality = TagQuality; + qualityDataType.tagValueType = TF.TagTypeCodeID; + int.TryParse(TF.TagOrderBy, out int TagOrderBy); + qualityDataType.tagOrderBy = TagOrderBy; + int.TryParse(TF.TagItemOrderBy, out int TagItemOrderBy); + qualityDataType.tagItemOrderBy = TagItemOrderBy; + qualityDataType.tagProperty = TF.TagProperty;//变量特点 + qualityDataType.tagValue = TF.TagValue;//变量值 + + return qualityDataType; + } + /// + /// + /// + /// + /// + /// + public static void ReadTagValue(int tagTypeCodeID, string opName, out string tagValue) + { + tagValue = "0"; + try + { + var tagValueObj = PlcLinkForm.ReadPLC(tagTypeCodeID, opName); + var type = tagValueObj.GetType().Name.ToLower(); + if (type == "bool" | type == "boolean") + { + var val = tagValueObj.ToString().ToLower(); + + if (val == "true") + { + tagValue = "1"; + } + } + else + { + tagValue = tagValueObj.ToString(); + } + } + catch { } + } + + /// + /// + /// + /// + /// + /// + public static bool WritePLC(string tagID, object tagValue) + { + return PlcLinkForm.WritePLC(tagID, tagValue); + } + /// + /// + /// + /// + /// + /// + /// + public static bool WritePLC(int tagTypeCodeID, string opName, object tagValue) + { + return PlcLinkForm.WritePLC(tagTypeCodeID, opName, tagValue); + } + /// + /// + /// + /// + /// + /// + /// + public static bool WriteTagValue(int tagTypeCodeID, string opName, object tagValue) + { + return PlcLinkForm.WritePLC(tagTypeCodeID, opName, tagValue); + } + + public static ConcurrentDictionary ReadPLC_OpName(string opName) + { + try + { + string tagStartAdr = ""; + ushort tagAdrListMaxLength = 0; + PlcLinkForm.GetDbAndMaxLengthByOpName(opName, out tagStartAdr, out tagAdrListMaxLength); + var tagAdrListTagFormat = PlcLinkForm.ReadQualityDataList(opName, tagStartAdr, tagAdrListMaxLength); + + return tagAdrListTagFormat; + } + catch (Exception err) + { + return null; + + } + + } + + public static List Get_opNameList() + { + return PlcLinkForm.opNameList; + } + public static DoWhatPlc.HashtableList GetHashtableList() + { + DoWhatPlc.HashtableList hsList = new DoWhatPlc.HashtableList(); + hsList.hashtable_MesDll = DoWhatPlc.HashtableList.hashtable_MesDll_Temp; + hsList.hashtable_MesServerCode = DoWhatPlc.HashtableList.hashtable_MesServerCode_Temp; + hsList.hashtable_TagTypeDataType = DoWhatPlc.HashtableList.hashtable_TagTypeDataType_Temp; + hsList.hashtable_TagType = DoWhatPlc.HashtableList.hashtable_TagType_Temp; + hsList.hashtable_OpNameRepair = DoWhatPlc.HashtableList.hashtable_OpNameRepair_Temp; + hsList.hashtable_TagTypeTagName = DoWhatPlc.HashtableList.hashtable_TagTypeTagName_Temp; + + + hsList.hashtable_workStepProperty = DoWhatPlc.HashtableList.hashtable_workStepProperty_Temp; + hsList.hashtable_QualityMesRead = DoWhatPlc.HashtableList.hashtable_QualityMesRead_Temp; + hsList.hashtable_IsAllowWork = DoWhatPlc.HashtableList.hashtable_IsAllowWork_Temp; + hsList.hashtable_WorkGroupIndex = DoWhatPlc.HashtableList.hashtable_WorkGroupIndex_Temp; + hsList.hashtableOpName_OpType = DoWhatPlc.HashtableList.hashtableOpName_OpType_Temp; + hsList.hashtable_tagTable_OpName_SaveData = DoWhatPlc.HashtableList.hashtable_tagTable_OpName_SaveData_Temp; + + + + hsList.hashtable_EngineGetOver_EngineID = DoWhatPlc.HashtableList.hashtable_EngineGetOver_EngineID_Temp; + hsList.hashtable_EngineGetOver_EngineTypeID = DoWhatPlc.HashtableList.hashtable_EngineGetOver_EngineTypeID_Temp; + hsList.hashtable_EngineGetOver_EngineType = DoWhatPlc.HashtableList.hashtable_EngineGetOver_EngineType_Temp; + hsList.hashtable_EngineGetOver_OrderForm = DoWhatPlc.HashtableList.hashtable_EngineGetOver_OrderForm_Temp; + + hsList.BasicDataTagValue = MesServerWork.MIS_BASE.BasicDataTagValue; + hsList.BasicDataTagValueUpDown = MesServerWork.MIS_BASE.BasicDataTagValueUpDown; + hsList.hashtable_EngineTypeID = MesServerWork.MIS_BASE.hashtable_EngineTypeID; + hsList.hashtable_tagTable_OpName_SaveData = MesServerWork.MIS_BASE.hashtable_tagTable_OpName_SaveData; + return hsList; + } + + + public static List ReadPLC_GroupMonitor(string opName) + { + List TagIDTagFormatList = new List(); + var cd = MesWork.PlcLinkForm.ReadPLC_GroupMonitor(opName); + foreach (KeyValuePair _cd in cd) + { + var tagID = _cd.Key; + + var pp1 = JsonConvert.SerializeObject(_cd.Value); + var pp2 = JsonConvert.DeserializeObject(pp1); + DoWhatPlc.TagIDTagFormat TagTF = new DoWhatPlc.TagIDTagFormat(tagID, pp2); + + TagIDTagFormatList.Add(TagTF); + } + return TagIDTagFormatList; + } + + public static List ReadPLC_GroupData_Qd(string opName) + { + List TagIDTagFormatList = new List(); + var cd = MesWork.PlcLinkForm.ReadPLC_GroupData_Qd(opName); + foreach (KeyValuePair _cd in cd) + { + var tagID = _cd.Key; + var pp1 = JsonConvert.SerializeObject(_cd.Value); + var pp2 = JsonConvert.DeserializeObject(pp1); + DoWhatPlc.TagIDTagFormat TagTF = new DoWhatPlc.TagIDTagFormat(tagID, pp2); + + TagIDTagFormatList.Add(TagTF); + } + return TagIDTagFormatList; + } + public static List ReadPLC_GroupData(string opName) + { + try + { + List TagIDTagFormatList = new List(); + var cd = MesWork.PlcLinkForm.ReadPLC_GroupData(opName); + foreach (KeyValuePair _cd in cd) + { + var tagID = _cd.Key; + + var pp1 = JsonConvert.SerializeObject(_cd.Value); + var pp2 = JsonConvert.DeserializeObject(pp1); + DoWhatPlc.TagIDTagFormat TagTF = new DoWhatPlc.TagIDTagFormat(tagID, pp2); + + TagIDTagFormatList.Add(TagTF); + } + return TagIDTagFormatList; + } + catch (Exception err) + { + return null; + + } + + } + } + + + +} diff --git a/Common/09MesDataFunction/MesDataFunction/MesWorkPlc.cs b/Common/09MesDataFunction/MesDataFunction/MesWorkPlc.cs new file mode 100644 index 0000000..40cc46e --- /dev/null +++ b/Common/09MesDataFunction/MesDataFunction/MesWorkPlc.cs @@ -0,0 +1,40 @@ +using MesWork; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MesDataFunction +{ + public class MesWorkPlc: PlcLinkForm + { + + public static Action D_OPCTagData_TagDataOnChangeMIS = null; + + /// + /// 监控数据的所有变化,从这里产生 + /// + /// + /// + public override void OPCTagData_TagDataOnChangeMIS(object sender, OpcData.CustomeEvetnArgs e) + { + Console.WriteLine($"【【{e.TagName}【【{e.TagValueBefore}->{e.TagValue}【【{e.TagKeepTime}"); + + if (D_OPCTagData_TagDataOnChangeMIS != null) + D_OPCTagData_TagDataOnChangeMIS(e); + // OPCTagData_TagDataOnChange(sender, e); + } + + /// + /// 定时触发,检测PLC在线状态,周期:3 s + /// + /// + /// + public override void PlcStateEvent(object sender, OpcData.PlcStateEvetnArgs eState) + { + + } + + } +} diff --git a/Common/09MesDataFunction/MesDataFunction/MisDataFunction/Heartbeat.cs b/Common/09MesDataFunction/MesDataFunction/MisDataFunction/Heartbeat.cs new file mode 100644 index 0000000..2df0434 --- /dev/null +++ b/Common/09MesDataFunction/MesDataFunction/MisDataFunction/Heartbeat.cs @@ -0,0 +1,25 @@ +//using bizFacade; +using System; +using System.Collections; +using System.Data; +//using SystemFramework; + +namespace MisDataFunction +{ + partial class Function + { + + private static void Heartbeat(string opName, string tagValue) + { + if (tagValue == "1") + { + Write_TagTypeID(15, opName, true); + } + else + { + Write_TagTypeID(15, opName, false); + } + } + + } +} diff --git a/Common/09MesDataFunction/MesDataFunction/MisDataFunction/MIS.Interface.cs b/Common/09MesDataFunction/MesDataFunction/MisDataFunction/MIS.Interface.cs new file mode 100644 index 0000000..904c975 --- /dev/null +++ b/Common/09MesDataFunction/MesDataFunction/MisDataFunction/MIS.Interface.cs @@ -0,0 +1,326 @@ + +using bizFacade; +using DoWhatPlc; +using MesServerWork; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +//using SystemFramework; + +namespace MisDataFunction +{ + public partial class Function: MIS_BASE + { + + + + /// + /// 处理MIS逻辑 TagName 变量类型代码 变量类型名称 + /// WorkStart 2 工件到位。托盘到达工位,并且托盘上有工件。 + ///RepairPartStatusPLC 3 备用 + ///RepairPathString 4 工位返修字符串(121211112222111),前2位是西门子字符串格式,第一位是总长度,第二位是实际长度 + ///EngineTypeGetOverMES 5 MES传递总成信息给PLC(上线工位) + ///PartPalletGoOver 6 上线工位。0:正常工作;1:空托盘放行,PLC读取到此标志不走申请上线逻辑。 + ///MaterialVerifyOver 7 MES保存完质量数据,物料数据等与PLC信号交互完成后通知PLC,所以工步都完成,才可以放行工件,正常工作时工件放行的必要条件。 + ///FalseGo 8 按MES界面[不合格放行] 按钮,MES发送此信号。操作者判断工件不合格,通知设备,按不合格方式放行工件,工件流转到返修下线工位后,返修下线。MES工作完成MES0.3=1,MES合格放行MES0.5=0,MES0.4=1 + ///EngineTypeID 9 MES发动机机型标志(必须PLC) + ///EngineID 10 MES发动机编号(必须PLC) + ///EngineType 11 MES发动机机型(必须PLC) + ///PartPalletStatus 13 MES激发变量托盘到位离开(必须PLC) + ///HeartBeatPLC 14 心跳处理:PLC收到MES心跳信号后,PLC延时5秒后,数值取反再写回PLC,写回PLC开始计时,如果5秒钟MES无反馈报通讯故障。 + ///HeartBeatMIS 15 间隔时间5S,心跳处理。收到PLC心跳信号后,MES按原值回写。PLC收到MES信号后延时5秒,取反写入,以此循环。 + ///TargetTimeRead 16 MES允许可读工位运行时间 + ///MachineTargetTime 17 目标运行时间 + ///MachineActualTime 18 实际运行时间 + ///MesRead 19 质量数据可以读数据 + ///MesReadOver 20 MES保存完数据(必须MIS) + ///QualityMask 21 质量数据工位合格标志0:没有工作;1:合格 ;2 :不合格(必须PLC) + ///PalletInfo 22 0空托盘,1合格件,2不合格件 + ///RepairStatusPLC 23 0正常件,1返修件 + ///Reserved_3 24 备用 + ///Reserved_4 25 备用 + ///Reserved_5 26 备用 + ///Reserved_6 27 备用 + ///Reserved_7 28 备用 + ///Reserved_8 29 备用 + ///Reserved_9 30 备用 + ///Reserved_10 31 备用 + ///Reserved_11 32 备用 + ///Reserved_12 33 备用 + ///Reserved_13 34 备用 + ///Reserved_14 35 备用 + ///PLCSPareint1 36 备用 + ///PLCSPareint2 37 备用 + ///PLCSPareint3 38 备用 + ///PLCSarestring1 39 备用 + ///PLCSarestring2 40 备用 + ///MarkID 42 机体打标号(MES)前2位是西门子字符串格式,第一位是总长度,第二位是实际长度 + ///PartLoad 43 上线工位,PLC向MES申请总成编号。收到该信号后,MES将机型标志(DBB22 ~23)、总成号(DBB24 ~63)、总成机型DBB64 ~103写入PLC。之后MES通过信号“传递机型(DBX0.1)”通知PLC。 + ///EngineTypeGetOverPLC 44 PLC将机型标志(DBB50…51)、工件编号(DBB52…101)、产品型号(DBB102…187)、托盘编号(DBB188…189)准备完毕后,通知MES。 + ///PartLoadOK 48 备用 + ///Reserved_18 49 备用 + ///PalletDown 50 暂时保留,项目未使用 + ///ConfirmOkGo 51 按MES界面[合格放行] 按钮,MES发送此信号。操作者判断工件合格,通知设备,工件按合格方式放行工件。MES工作完成MES0.3=1,MES合格放行MES0.5=1,MES0.4=0 + ///ResetDevice 52 针对手动工位,无HMI,需要复位设备在MES页面操作。 + ///UnloadCompleted 53 暂时保留,项目未使用 + ///MachineTime_ReadOver 54 备用 + ///Reserved_19 58 备用 + ///FixOK 59 手动拧紧工位,单工步螺栓拧紧完成,通知PC读取数据。 + ///Reserved_21 61 备用 + ///Reserved_22 62 备用 + ///Reserved_23 63 备用 + ///Reserved_24 64 备用 + ///Reserved_25 65 备用 + ///FixAllow 66 设备工作的必须信号,对于有物料验证的工位,MES验证完成给出此信号,对于无物料验证工位,MES直接给出此信号。 + ///FixOver 67 用于手动拧紧且有质量数据工位。通知设备当前工步拧紧螺钉工作结束。 + ///MatchingCompleted 68 分线上总线,匹配成功是1;不成功是0。 + ///Match 69 分线上总线,匹配成功是1;不成功是0。 + ///Reserved_2 70 备用 + ///IsAutoGetEngineID 71 自动手动申请工件编号。0是自动方式;1:手动方式。暂时保留,生成流水号方式是在数据库中实现的 + ///RepairUplineMES 72 上线清空MOBY(针对上线工位):通知PLC从新开始申请上线流程 + ///EngineTypeID_MES 73 MES发动机机型标志(必须MES) + ///EngineID_MES 74 MES发动机编号(必须MES) + ///EngineType_MES 75 MES发动机机型(必须MES) + ///Reserved_20 76 备用 + ///ProcessCode 77 手动拧紧工位:由MES通知PLC拧紧序号 + ///OnLineState 79 通过线体工位PC实现下达工位工作状态:工位有三种状态:在线、离线、屏蔽。在线:0正常状态,实现正常功能。1离线:设备脱离MES工作,进入不交互模式。 + ///PartPalletCode 80 托盘编号(B5A) + ///BoltCode 88 手动拧紧工位:指导PLC所用套筒 + ///RepairStatus 93 0正常件,1返修件。对于上线工位MES给出是正常上线还是返修上线,返修路径 + ///Reserved_15 110 备用 + ///Reserved_16 111 备用 + ///Reserved_17 112 备用 + ///SPareint1 113 备用int1 + ///SPareint2 114 备用int2 + ///SPareint3 115 备用int3 + ///Sparestring1 116 备用字符串1 + ///Sparestring2 117 备用字符串2 + ///MachineStatusPutOn 1000 机床上电(必须PLC) + ///MachineStatusWorkOn 1001 循环开始(必须PLC) + ///MachineStatusAlarm 1002 机床故障(必须PLC) + ///MachineStatusNoPart 1003 上料无件(必须PLC) + ///MachineStatusBlock 1004 下料堵塞(必须PLC) + ///Alarm 103 设备报警 + /// + /// + public static void MIS_Funtion(object e) + { + try + { + + string recData = e.ToString(); + string[] dataArray = recData.Split('|'); + if (dataArray.Length != 4) + return; + //消息来源 + string m_Source = dataArray[0].ToString(); + //消息类型 + string m_Command = dataArray[1].ToString(); + //工位号 + string m_OpName = dataArray[2].ToString(); + //消息参数 + string m_Value = dataArray[3].ToString(); + + DoWhatPlc.ReturnValueString rv = Newtonsoft.Json.JsonConvert.DeserializeObject(m_Value); + //Console.WriteLine($"【【{rv.TagID}【【【【{ rv.TagKeepTime}"); + + int tagType; + string opName; + string tagValue; + int tagid; + DoWhatPlc.ReturnValueString msgEvent = rv; + if (msgEvent.TagValue == null) return; + tagType = Convert.ToInt32(msgEvent.TagTypeID); + opName = msgEvent.OpName.ToString(); + tagid = Convert.ToInt32(msgEvent.TagID); + + + //int tagType; + //string opName; + //string tagValue; + //int tagid; + //DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + //if (msgEvent.TagValue == null) return; + //tagType = Convert.ToInt32(msgEvent.TagType); + //opName = msgEvent.OpName.ToString(); + //tagid = Convert.ToInt32(msgEvent.TagKey); + switch (Convert.ToInt32(msgEvent.TagTypeCodeID)) + { + case 11: + switch (msgEvent.TagValue.ToLower()) + { + case "1": + case "true": + tagValue = "1"; + break; + default: + tagValue = "0"; + break; + } + break; + default: + tagValue = msgEvent.TagValue.ToString(); + break; + } + ///根据信号处理逻辑 + switch (tagType) + { + case 19: + //允许保存 + MesRead(opName, tagValue, tagid); + break; + case 14: + //心跳 + Heartbeat(opName, tagValue); + break; + case 44://PLC传递机型过后 才允许保存过站信息,否则不允许保存 + //if (tagValue == "1") + //{ + // IsEngTypeGetOver_Write(opName, true); + + // EngineData Enginedata = new EngineData(DtWebApi.ReadWritePLC.ReadPLC("10", opName).ToString(), Convert.ToInt32(DtWebApi.ReadWritePLC.ReadPLC("80", opName))); + // //EngineData Enginedata = new EngineData(MesDataFunction.OpcOperation.ReadPLC(10, opName).ToString(), Convert.ToInt32(MesDataFunction.OpcOperation.ReadPLC(80, opName))); + // //保存产品编号、托盘号 保存过站信息用 + // EngineData_Hash_Write(opName, Enginedata); + //} + break; + case 2://工件到位 + WorkStart( rv); + + + //WorkStart(opName, tagValue); + break; + case 51: + if (hashtableOpName_IsHaveComputer[opName].ToString() == "1") + { + SaveProductLeaveData(opName, 1); + } + + break; + case 8: + if (hashtableOpName_IsHaveComputer[opName].ToString() == "1") + { + SaveProductLeaveData(opName, 2); + } + break; + case 103: + + Alarm_Insert(rv); + + break; + } + + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, err.Message); + } + } + private static void Alarm_Insert(ReturnValueString rv) + { + string TagID; + string opName; + string tagTypeID; + int TagValue; + + DateTime alarmStartTime; + DateTime alarmEndTime; + int TimeDiff; + string TagOrderBy; + string Text1; + string Text2; + TagID = rv.TagID; + tagTypeID = rv.TagTypeID; + opName = rv.OpName; + TagValue = Convert.ToInt32( rv.TagValue); + + alarmStartTime = Convert.ToDateTime( rv.TimeStampBefore); + alarmEndTime = Convert.ToDateTime( rv.TimeStamp); + TimeDiff = Convert.ToInt32(rv.TagKeepTime); + TagOrderBy = rv.TagOrderBy; + Text1 = rv.ItemName; + Text2 = rv.ShaftID; + + BaseDataSystemMES.Alarm_Insert(TagID, tagTypeID, opName, TagValue, + alarmStartTime, alarmEndTime, TimeDiff, Text1, Text2, TagOrderBy); + } + private static void WorkStart(ReturnValueString rv) + { + + + + var ro = rv.ReturnValueToObject(); + + string opName = ro.OpName; + DateTime arrivedTime = ro.TimeStampBefore; + DateTime leavedTime = ro.TimeStamp; + int TimeDiff = ro.TagKeepTime; + int targetTime = 0; + string isPass = ""; + + int QualityMark=0; + string tagValue="0"; + switch (ro.TagValue.ToString().ToLower()) + { + case "1": + case "true": + tagValue = "1"; + break; + default: + tagValue = "0"; + break; + } + //if (ro.TagValue.ToString() == "0") + //{ + // //Write_TagTypeID(5, opName, false);//MES传递机型 + // //Write_TagTypeID(66, opName, false);//允许工作 + // //Write_TagTypeID(51, opName, false);//合格放行 + // //Write_TagTypeID(8, opName, false);//不合格放行 + // //Write_TagTypeID(7, opName, false);//工作完成 + // //Write_TagTypeID(20, opName, false);//保存完成 + + // //string isHaveComputer = hashtableOpName_IsHaveComputer[opName].ToString(); + // //if (Convert.ToInt32(isHaveComputer) == 0)//自动工位 读合格标志 + // //{ + // // if (IsEngTypeGetOver_Read(opName)) + // // { + // // //PLC未传递机型 不保存过站信息 + // // SaveProductLeaveData_AutoWorkStation(opName, Convert.ToInt32(DtWebApi.ReadWritePLC.ReadPLC("21", opName))); + // // //SaveProductLeaveData_AutoWorkStation(opName, Convert.ToInt32(MesDataFunction.OpcOperation.ReadPLC(21, opName))); + // // } + + // //} + + // ////清空信号 + // ////m_WorkStart_OpName[opName] = 0;//清空工件到位标志 + // ////通知WEB更新产量 + // //SendActuallyCount(opName, 0); + //} + + QualityMark = Convert.ToInt32(ReadPLC(21, opName)); + + if (QualityMark == 1) + { + isPass = "1"; + } + else + { + isPass = "0"; + } + int EngineTypeID;//机型代码 + int PartPallet_Code;//托盘编号 + string EngineType;//机型 + string EngineID;//工件编号 + string OrderForm; + MIS_BASE.GetEngineTypeFromPLC(opName, out EngineTypeID, out EngineType, out EngineID, out PartPallet_Code,out OrderForm); + + //EngineData Enginedata = (EngineData)EngineData_Hash_Read(opName); + BaseDataSystemMES.WorkStartInsert_AutoWorkStation(opName, EngineID, PartPallet_Code, arrivedTime, leavedTime, TimeDiff, targetTime, null, isPass, 0); + + } + + + + } +} diff --git a/Common/09MesDataFunction/MesDataFunction/MisDataFunction/MesRead.cs b/Common/09MesDataFunction/MesDataFunction/MisDataFunction/MesRead.cs new file mode 100644 index 0000000..cc1fd54 --- /dev/null +++ b/Common/09MesDataFunction/MesDataFunction/MisDataFunction/MesRead.cs @@ -0,0 +1,465 @@ +//using BasicData; +using bizFacade; +using DoWhatPlc; +using Newtonsoft.Json; +//using bizFacade; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Data; +//using SystemFramework; + +namespace MisDataFunction +{ + partial class Function + { + /// + /// 获取质量数据Hashtable + /// + /// + /// + //static public Hashtable ReadPLC_Sync_DataList_MesRead(string opName) + //{ + // return (Hashtable)MesDataFunction.OpcOperation.ReadPLC_Sync_DataList_MesRead(opName); + //} + static object lockerReadPLC_Sync_DataList_MesRead1 = new object(); + public static void ReadPLC_Sync_DataList_MesRead(string opName, out Hashtable valueList, out DataTable BasicDataTagValue, out DataTable BasicDataTagValueUpDown, out Hashtable hashtable_EngineTypeID, out Hashtable hashtable_tagTable_OpName_SaveData) + { + //QualityDataSaveList QualityDataType + valueList = new Hashtable(); + //var qualityDataSaveList = DtWebApi.SaveData.ReadPLC_Sync_DataList_MesRead(opName); + var qualityDataSaveList = MesServerWork.MIS_BASE.ReadPLC_Sync_DataList_MesRead(opName); + foreach (DictionaryEntry de in qualityDataSaveList.valuList) + { + valueList.Add(de.Key, JsonConvert.DeserializeObject(de.Value.ToString())); + } + BasicDataTagValue = qualityDataSaveList.BasicDataTagValue; + BasicDataTagValueUpDown = qualityDataSaveList.BasicDataTagValueUpDown; + hashtable_EngineTypeID = qualityDataSaveList.hashtable_EngineTypeID; + hashtable_tagTable_OpName_SaveData = qualityDataSaveList.hashtable_tagTable_OpName_SaveData; + } + public static Hashtable ReadPLC_Sync_DataList_MesRead(string opName) + { + lock (lockerReadPLC_Sync_DataList_MesRead1) + { + Hashtable ht = new Hashtable(); + var cd = ReadPLC_GroupData(opName); + //var cd = PlcLinkForm.ReadPLC_GroupData(opName); + + foreach (var _cd in cd) + { + var tagID = Convert.ToInt32(_cd.TagID); + var TF =_cd.TF; + + QualityDataType qualityDataType; + qualityDataType = new QualityDataType(); + + qualityDataType.tagID = TF.TagID; + qualityDataType.tagTypeID = TF.TagTypeID;//变量类型 + qualityDataType.opName = opName; + qualityDataType.isGoodBad = 192; + int.TryParse(TF.TagQuality, out int TagQuality); + qualityDataType.tagQuality = TagQuality; + qualityDataType.tagValueType = TF.TagTypeCodeID; + int.TryParse(TF.TagOrderBy, out int TagOrderBy); + qualityDataType.tagOrderBy = TagOrderBy; + int.TryParse(TF.TagItemOrderBy, out int TagItemOrderBy); + qualityDataType.tagItemOrderBy = TagItemOrderBy; + qualityDataType.tagProperty = TF.TagProperty;//变量特点 + qualityDataType.tagValue = TF.TagValue;//变量值 + + ht.Add(tagID, qualityDataType); + } + return ht; + } + + } + + /// + /// 允许保存(针对半自动和手动压装工位) + /// + /// + /// + private static void MesRead(string opName, string tagValue, int tagid) + { + if (tagValue == "0") + { + Write_TagTypeID(20, opName, false); + } + else + { + SaveQualityData(opName, Convert.ToInt32(tagValue), tagid); + } + } + + private static void SaveQualityData(string opName, int tagValue, int tagID) + { + try + { + int id_tagCF; + int qualityMask = 0; + int engineTypeID = 0; + string engineID = ""; + string engineType = ""; + string engineTraceCode = ""; + string engineCap = ""; + string partPallet = ""; + DataTable dt_WWW; + dt_WWW = BaseDataSystemMES.BuildDataTables_WWW(); + Hashtable valueList; + //valueList = ReadPLC_Sync_DataList_MesRead(opName); + ReadPLC_Sync_DataList_MesRead(opName, out valueList, out BasicDataTagValue, out BasicDataTagValueUpDown, out hashtable_EngineTypeID, out hashtable_tagTable_OpName_SaveData); + valueList = GetQualityData_GoodBad_Values(valueList); + int mes_MustTest = 0; + int onLineState = 0; + int partMoveDirection = 0; + int pressIsOK = 0; + int pressIsNoOK = 0; + BaseDataSystemMES.GetQualityDataTable_B5A(valueList, opName, BasicDataTagValue, + BasicDataTagValueUpDown, + out dt_WWW,//数据列表 + out qualityMask,//工位合格标志 + out engineTypeID,//发动机类型代码 + out engineID,//发动机编号 + out engineType, //发动机型号 + out partPallet,//托盘编号 + out engineTraceCode, //发动机条码 + out engineCap,//缸盖号, + hashtable_EngineTypeID,//发动机类型转换表 + out mes_MustTest, out onLineState, out partMoveDirection, out pressIsOK, out pressIsNoOK); + + + + + // 1:通过监控系统保存采集的质量数据;0:不通过监控系统保存采集的质量数据 + if (Convert.ToInt32(hashtable_tagTable_OpName_SaveData[opName]) != 0) + { + DateTime lastupdatetime = DateTime.Now; + + BaseDataSystemMES.BaseData_tagTable_QualityData_B5A_IndexInsert(engineID, tagID, engineType, engineTypeID, opName, qualityMask, partPallet, out id_tagCF); + BaseDataSystemMES.BaseData_tagTable_QualityData_B5A_Insert(id_tagCF, engineTypeID, engineID, opName, dt_WWW); + + } + Write_TagTypeID(20, opName, true); + #region + //string orderForm = ""; + //string operatorCode = ""; + //int shiftCode = 1; + //DateTime arrivedTime; + //DateTime leavedTime; + //int TimeDiff; + //int targetTime = 0; + //string lineType = ""; + //string isPass; + //int machineWorkOn = 0; + //int arrivedOrLeaved = 2; + //int cartColorOpName = 0; + //int cartColorConfirm = 0; + //// int partMoveDirection; + //int partGoOver = 0; + //if (qualityMask == 1) + //{ + // isPass = "PASS"; + //} + //else + //{ + // isPass = "FAIL"; + //} + + ////工位上下线类型 + ////(0普通工位)(1正常上线)(2正常下线)(3返修上线)(4返修下线) + //int OpNameUpDownType; + //OpNameUpDownType = Convert.ToInt32(hashtableOpName_OpType[opName]); + //arrivedTime = (DateTime)m_WorkStart_OpName_Time[opName]; + //leavedTime = DateTime.Now; + //TimeDiff = Convert.ToInt32(leavedTime.Subtract(arrivedTime).TotalSeconds); + + //lineType = hashtableOpName_LineType[opName].ToString(); + + //string isHaveComputer = hashtableOpName_IsHaveComputer[opName].ToString(); + ////isHaveComputer = MIS_BASE.hashtable_tagTable_OpName_SaveData[opName].ToString(); + ////有计算机的工位,通过工位计算机保存[测量数据发动机在线状态]。 + //if (Convert.ToInt32(isHaveComputer) == 0) + //{ + // //1->0 工件离开 工件刚刚离开 + // if (Convert.ToInt32(m_WorkStart_OpName[opName]) == 1) + // { + + // //[测量数据发动机在线状态] + // QualityDataSystem.WorkStartInsert + // (opName, orderForm, engineTypeID, engineType, engineID, partPallet.ToString(), operatorCode, shiftCode, + // arrivedTime, leavedTime, TimeDiff, targetTime, lineType, isPass, machineWorkOn, + // arrivedOrLeaved, cartColorOpName, cartColorConfirm, partMoveDirection, partGoOver, mes_MustTest, onLineState, OpNameUpDownType); + // } + //} + #endregion + } + catch (Exception err) + { + Write_TagTypeID(20, opName, true); + ////ApplicationLog.WriteLog(err, err.Message); + } + + } + public static void SaveQualityData_Mes(string opName, int tagID) + { + try + { + int id_tagCF; + int qualityMask = 0; + int engineTypeID = 0; + string engineID = ""; + string engineType = ""; + string engineTraceCode = ""; + string engineCap = ""; + string partPallet = ""; + DataTable dt_WWW; + dt_WWW = BaseDataSystemMES.BuildDataTables_WWW(); + Hashtable valueList; + valueList = ReadPLC_Sync_DataList_MesRead(opName); + valueList = GetQualityData_GoodBad_Values(valueList); + int mes_MustTest = 0; + int onLineState = 0; + int partMoveDirection = 0; + int pressIsOK = 0; + int pressIsNoOK = 0; + BaseDataSystemMES.GetQualityDataTable_B5A(valueList, opName, BasicDataTagValue, + BasicDataTagValueUpDown, + out dt_WWW,//数据列表 + out qualityMask,//工位合格标志 + out engineTypeID,//发动机类型代码 + out engineID,//发动机编号 + out engineType, //发动机型号 + out partPallet,//托盘编号 + out engineTraceCode, //发动机条码 + out engineCap,//缸盖号, + hashtable_EngineTypeID,//发动机类型转换表 + out mes_MustTest, out onLineState, out partMoveDirection, out pressIsOK, out pressIsNoOK); + // 1:通过监控系统保存采集的质量数据;0:不通过监控系统保存采集的质量数据 + if (Convert.ToInt32(hashtable_tagTable_OpName_SaveData[opName]) != 0) + { + DateTime lastupdatetime = DateTime.Now; + BaseDataSystemMES.BaseData_tagTable_QualityData_B5A_IndexInsert(engineID, tagID, engineType, engineTypeID, opName, qualityMask, partPallet, out id_tagCF); + //BaseDataSystemMES.BaseData_tagTable_QualityData_B5A_Insert(id_tagCF, engineTypeID, engineID, opName, dt_WWW); + + } + + + } + catch (Exception err) + { + Write_TagTypeID(20, opName, true); + ////ApplicationLog.WriteLog(err, err.Message); + } + + } + + /// + /// 确定合格标志 + /// + /// + /// + static public Hashtable GetQualityData_GoodBad_Values(Hashtable valuList) + { + try + { + Hashtable valuList_Temp; + valuList_Temp = (Hashtable)valuList.Clone(); + int[] value_GoodBad_New = new int[128]; + int tagID; + QualityDataType value; + //1:获得合格标志 + foreach (DictionaryEntry de in valuList) //ht为一个Hashtable实例 + { + tagID = Convert.ToInt32(de.Key); + value = (QualityDataType)de.Value; + + //拧紧数据合格标志 + if (value.tagProperty == 1) + { + if (value.tagTypeID == 8203) + { + value_GoodBad_New = (int[])value.tagValue; + break; + } + else + { + value_GoodBad_New[value.tagOrderBy - 1] = Convert.ToInt32(value.tagValue); + } + } + //拧紧数据合格标志 + if (value.tagProperty == 8) + { + if (value.tagTypeID == 8203) + { + value_GoodBad_New = (int[])value.tagValue; + break; + } + else + { + value_GoodBad_New[value.tagOrderBy - 1] = Convert.ToInt32(value.tagValue); + } + } + //压装数据合格标志 + if (value.tagProperty == 7) + { + value_GoodBad_New[value.tagOrderBy - 1] = Convert.ToInt32(value.tagValue); + } + } + //将合格标志赋予每个变量 + foreach (DictionaryEntry de in valuList) //ht为一个Hashtable实例 + { + tagID = Convert.ToInt32(de.Key); + value = (QualityDataType)de.Value; + //201706061720新加 + if (value .tagTypeID ==11) + { + if (value.tagValue.ToString ()=="False") + { + value.tagValue ="0"; + } + else + { + value.tagValue = "1"; + } + valuList_Temp[tagID] = value; + //value.tagValue = Convert.ToInt32(value.tagValue); + } + + + //测量变量 + if (value.tagProperty == 2 || value.tagProperty == 6) + { + try + { + if (value_GoodBad_New != null) + { + value.isGoodBad = Convert.ToInt32(value_GoodBad_New[value.tagOrderBy - 1]); + valuList_Temp[tagID] = value; + } + else + { + value.isGoodBad = 0; + valuList_Temp[tagID] = value; + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, err.Message); + + } + } + + + + } + return valuList_Temp; + } + catch//转换出了故障时 + { + return valuList; + } + } + + + + /// + /// 制定工位PLC是否传递过机型 (默认不传递机型不保存过站信息) + /// + static Hashtable EngTypeGetOver = new Hashtable(); + + static Hashtable EngineData_Hash = new Hashtable(); //保存 + + public static void IsEngTypeGetOver_Write(string OpName, bool value) + { + if (EngTypeGetOver.ContainsKey(OpName)) + { + EngTypeGetOver[OpName] = value; + } + else + { + EngTypeGetOver.Add(OpName, value); + } + } + + + public static bool IsEngTypeGetOver_Read(string OpName) + { + if (EngTypeGetOver.ContainsKey(OpName)) + { + return Convert.ToBoolean(EngTypeGetOver[OpName]); + } + else + { + return true; + } + } + + public static void EngineData_Hash_Write(string OpName, object value) + { + if (EngineData_Hash.ContainsKey(OpName)) + { + EngineData_Hash[OpName] = value; + + } + else + { + EngineData_Hash.Add(OpName, value); + } + } + + public static object EngineData_Hash_Read(string OpName) + { + if (EngineData_Hash.ContainsKey(OpName)) + { + return EngineData_Hash[OpName]; + } + else + { + return null; + } + + } + + + private DataTable ChangeQualificationMark(DataTable dt) + { + var dtNew = dt.Copy(); + for (int i = 0; i < dt.Rows.Count; i++) + { + var 变量排序 = dt.Rows[i]["变量排序"].ToString(); + if (变量排序 == "0") + { + + } + } + + + return dtNew; + } + + + + + } + struct EngineData + { + public EngineData(string engineID, int pallet) + { + EngineID = engineID; + Pallet = pallet; + } + + public string EngineID;//工件编号 + //public string EngineType; + //public int EngineTypeID; + public int Pallet;//托盘号 + + } + + + + + + +} diff --git a/Common/09MesDataFunction/MesDataFunction/MisDataFunction/WorkStart.cs b/Common/09MesDataFunction/MesDataFunction/MisDataFunction/WorkStart.cs new file mode 100644 index 0000000..d3901e8 --- /dev/null +++ b/Common/09MesDataFunction/MesDataFunction/MisDataFunction/WorkStart.cs @@ -0,0 +1,236 @@ +//using BasicData; +using bizFacade; +//using DataBaseAccess; +//using bizFacade; +using DataLinkMesWork; +using MesServerWork; +using System; +using System.Collections; +using System.Data; +using System.Data.SqlClient; +//using SystemFramework; + +namespace MisDataFunction +{ + partial class Function + { + /// + /// 工件到位与离开时,清空MES自身信号 + /// + /// + /// + private static void WorkStart(string opName, string tagValue) + { + try + { + //工位没有工件,或工件刚刚离开 工件离开工位后,清空该工位的发动机号 + if (tagValue == "0") + { + Write_TagTypeID(5, opName, false);//MES传递机型 + Write_TagTypeID(66, opName, false);//允许工作 + Write_TagTypeID(51, opName, false);//合格放行 + Write_TagTypeID(8, opName, false);//不合格放行 + Write_TagTypeID(7, opName, false);//工作完成 + Write_TagTypeID(20, opName, false);//保存完成 + + //string isHaveComputer = hashtableOpName_IsHaveComputer[opName].ToString(); + //if (Convert.ToInt32(isHaveComputer) == 0)//自动工位 读合格标志 + { + if (IsEngTypeGetOver_Read(opName)) + { + //PLC未传递机型 不保存过站信息 + SaveProductLeaveData_AutoWorkStation(opName, Convert.ToInt32(ReadPLC(21, opName))); + //SaveProductLeaveData_AutoWorkStation(opName, Convert.ToInt32(MesDataFunction.OpcOperation.ReadPLC(21, opName))); + } + + } + + //清空信号 + //m_WorkStart_OpName[opName] = 0;//清空工件到位标志 + //通知WEB更新产量 + SendActuallyCount(opName,0); + } + else + { + //保存工件到达数据 + //m_WorkStart_OpName_Time[opName] = DateTime.Now; + //m_WorkStart_OpName[opName] = 1; + } + + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, err.Message); + + } + } + /// + /// 保存过站信息 (数据库读机型信息) + /// + /// + /// + static void SaveProductLeaveData(string opName, int QualityMark) + { + try + { + if (!IsEngTypeGetOver_Read(opName)) + { + //PLC未传递机型 不保存过站信息 + return; + } + IsEngTypeGetOver_Write(opName, false);//清空传递机型标志 + + DateTime arrivedTime; + DateTime leavedTime; + int TimeDiff; + int targetTime = 0; + string lineType = ""; + string isPass; + if (QualityMark == 1) + { + isPass = "PASS"; + } + else + { + isPass = "FAIL"; + } + //工位上下线类型 + //(0普通工位)(1正常上线)(2正常下线)(3返修上线)(4返修下线) + int OpNameUpDownType; + OpNameUpDownType = Convert.ToInt32(hashtableOpName_OpType[opName]); + arrivedTime = (DateTime)m_WorkStart_OpName_Time[opName]; + leavedTime = DateTime.Now; + TimeDiff = Convert.ToInt32(leavedTime.Subtract(arrivedTime).TotalSeconds); + lineType = hashtableOpName_LineType[opName].ToString(); + + //1->0 工件离开 工件刚刚离开 + //if (Convert.ToInt32(m_WorkStart_OpName[opName]) == 1) + //{ + // WorkStartInsert(opName, arrivedTime, leavedTime, TimeDiff, targetTime, lineType, isPass, OpNameUpDownType); + //} + //通知WEB更新产量 + SendActuallyCount(opName, 0); + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, err.Message); + + } + + + } + /// + /// 保存过站信息 (数据库读机型信息) + /// + /// + /// + static void SaveProductLeaveData_AutoWorkStation(string opName, int QualityMark) + { + try + { + if (!IsEngTypeGetOver_Read(opName)) + { + //PLC未传递机型 不保存过站信息 + return; + } + IsEngTypeGetOver_Write(opName, false);//清空传递机型标志 + + DateTime arrivedTime; + DateTime leavedTime; + int TimeDiff; + int targetTime = 0; + string lineType = ""; + string isPass; + if (QualityMark == 1) + { + isPass = "PASS"; + } + else + { + isPass = "FAIL"; + } + //工位上下线类型 + //(0普通工位)(1正常上线)(2正常下线)(3返修上线)(4返修下线) + int OpNameUpDownType; + //OpNameUpDownType = Convert.ToInt32(hashtableOpName_OpType[opName]); + // arrivedTime = (DateTime)m_WorkStart_OpName_Time[opName]; + leavedTime = DateTime.Now; + //TimeDiff = Convert.ToInt32(leavedTime.Subtract(arrivedTime).TotalSeconds); + //lineType = hashtableOpName_LineType[opName].ToString(); + + //1->0 工件离开 工件刚刚离开 + //if (Convert.ToInt32(m_WorkStart_OpName[opName]) == 1) + //{ + // //查询工件编号、托盘号 + //EngineData Enginedata = (EngineData)EngineData_Hash_Read(opName); + //WorkStartInsert_AutoWorkStation(opName, Enginedata.EngineID, Enginedata.Pallet, arrivedTime, leavedTime, TimeDiff, targetTime, lineType, isPass, OpNameUpDownType); + //} + + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, err.Message); + + } + + + } + + /// + /// 测量数据发动机在线状态_增加数据 + /// + /// + /// + /// + /// + /// + /// + static public void WorkStartInsert(string opName, DateTime arrivedTime, DateTime leavedTime, int TimeDiff, int Target, string lineType, string isPass, int OpNameUpDownType) + { + string procedureName; + procedureName = "测量数据发动机在线状态_增加数据"; + SqlParameter[] thisParms = new SqlParameter[8]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@到达时间", arrivedTime); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@离开时间", leavedTime); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@在线时间", TimeDiff); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@目标时间", Target); + thisParms[5] = new System.Data.SqlClient.SqlParameter("@线体类型", lineType); + thisParms[6] = new System.Data.SqlClient.SqlParameter("@是否合格", isPass); + thisParms[7] = new System.Data.SqlClient.SqlParameter("@工位上下线类型", OpNameUpDownType); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } + + + + /// + /// 发送在线产量、在线节拍 + /// + /// + /// + static void SendActuallyCount(string OpName, int tagValue) + { + //当工件离开时,更新在线产量、在线节拍 + if (tagValue == 0) + { + try + { + int opNameCount = 0;//在线产量 + int opNameCountTime = 0;//在线节拍 + //基本数据_工作日历_班次产量查询_New + BaseDataSystemMES.OpNameCount_New(OpName, out opNameCount, out opNameCountTime); + + string SendMessage; + SendMessage = "MES|ActuallyCount|" + OpName + "|" + opNameCount.ToString() + "&" + opNameCountTime.ToString(); + + MIS_BASE.asyncSendMessage(SendMessage); + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function01:SendActuallyCount"); + } + } + } + + } +} diff --git a/Common/09MesDataFunction/MesDataFunction/Properties/AssemblyInfo.cs b/Common/09MesDataFunction/MesDataFunction/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..057bcf1 --- /dev/null +++ b/Common/09MesDataFunction/MesDataFunction/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// 有关程序集的一般信息由以下 +// 控制。更改这些特性值可修改 +// 与程序集关联的信息。 +[assembly: AssemblyTitle("MesDataFunction")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("MesDataFunction")] +[assembly: AssemblyCopyright("Copyright © 2022")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// 将 ComVisible 设置为 false 会使此程序集中的类型 +//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型 +//请将此类型的 ComVisible 特性设置为 true。 +[assembly: ComVisible(false)] + +// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID +[assembly: Guid("90e76fb4-646d-45e2-95db-0b8ab4e465d6")] + +// 程序集的版本信息由下列四个值组成: +// +// 主版本 +// 次版本 +// 生成号 +// 修订号 +// +//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值 +//通过使用 "*",如下所示: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Common/10SignalChangeMonitorControl/10MesControl.csproj b/Common/10SignalChangeMonitorControl/10MesControl.csproj new file mode 100644 index 0000000..7bd2621 --- /dev/null +++ b/Common/10SignalChangeMonitorControl/10MesControl.csproj @@ -0,0 +1,139 @@ + + + + + Debug + AnyCPU + {FAB322CC-531D-4AEA-986A-B921B64D8D3F} + Library + Properties + MesControl + MesControl + v4.8 + 512 + + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + false + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + false + + + + + + + + + + + + + + + UserControl + + + MesBoolSignal.cs + + + UserControl + + + PlcWorkStationSignal.cs + + + UserControl + + + PlcConnect.cs + + + + True + True + Resources.resx + + + UserControl + + + + + + MesBoolSignal.cs + + + PlcWorkStationSignal.cs + + + ResXFileCodeGenerator + Designer + Resources.Designer.cs + + + PlcConnect.cs + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Common/10SignalChangeMonitorControl/MesBoolSignal.Designer.cs b/Common/10SignalChangeMonitorControl/MesBoolSignal.Designer.cs new file mode 100644 index 0000000..2989846 --- /dev/null +++ b/Common/10SignalChangeMonitorControl/MesBoolSignal.Designer.cs @@ -0,0 +1,79 @@ +namespace MesControl +{ + partial class MesBoolSignal + { + /// + /// 必需的设计器变量。 + /// + private System.ComponentModel.IContainer components = null; + + /// + /// 清理所有正在使用的资源。 + /// + /// 如果应释放托管资源,为 true;否则为 false。 + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region 组件设计器生成的代码 + + /// + /// 设计器支持所需的方法 - 不要修改 + /// 使用代码编辑器修改此方法的内容。 + /// + private void InitializeComponent() + { + this.pictureBox_Signal = new System.Windows.Forms.PictureBox(); + this.label_SignalName = new System.Windows.Forms.Label(); + ((System.ComponentModel.ISupportInitialize)(this.pictureBox_Signal)).BeginInit(); + this.SuspendLayout(); + // + // pictureBox_Signal + // + this.pictureBox_Signal.BackgroundImage = global::MesControl.Properties.Resources.none; + this.pictureBox_Signal.Location = new System.Drawing.Point(3, 1); + this.pictureBox_Signal.Name = "pictureBox_Signal"; + this.pictureBox_Signal.Size = new System.Drawing.Size(20, 20); + this.pictureBox_Signal.TabIndex = 0; + this.pictureBox_Signal.TabStop = false; + // + // label_SignalName + // + this.label_SignalName.AutoSize = true; + this.label_SignalName.Font = new System.Drawing.Font("宋体", 12F); + this.label_SignalName.Location = new System.Drawing.Point(32, 3); + this.label_SignalName.MaximumSize = new System.Drawing.Size(72, 16); + this.label_SignalName.MinimumSize = new System.Drawing.Size(72, 16); + this.label_SignalName.Name = "label_SignalName"; + this.label_SignalName.Size = new System.Drawing.Size(72, 16); + this.label_SignalName.TabIndex = 1; + this.label_SignalName.Text = "心跳信号"; + // + // MesBoolSignal + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.BackColor = System.Drawing.Color.Transparent; + this.Controls.Add(this.label_SignalName); + this.Controls.Add(this.pictureBox_Signal); + this.MaximumSize = new System.Drawing.Size(110, 22); + this.MinimumSize = new System.Drawing.Size(110, 22); + this.Name = "MesBoolSignal"; + this.Size = new System.Drawing.Size(110, 22); + ((System.ComponentModel.ISupportInitialize)(this.pictureBox_Signal)).EndInit(); + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private System.Windows.Forms.PictureBox pictureBox_Signal; + private System.Windows.Forms.Label label_SignalName; + } +} diff --git a/Common/10SignalChangeMonitorControl/MesBoolSignal.cs b/Common/10SignalChangeMonitorControl/MesBoolSignal.cs new file mode 100644 index 0000000..c3e1d98 --- /dev/null +++ b/Common/10SignalChangeMonitorControl/MesBoolSignal.cs @@ -0,0 +1,111 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Drawing; +using System.Data; +using System.Linq; +using System.Text; +using System.Windows.Forms; + +namespace MesControl +{ + public partial class MesBoolSignal : UserControl + { + public MesBoolSignal() + { + InitializeComponent(); + } + + /// + /// 外部调用控件触发的信号 + /// + /// + public void InputBoolSignal(bool Signal) + { + + if (Signal) + { + + pictureBox_Signal.BackgroundImage = Properties.Resources.green; + } + else + { + pictureBox_Signal.BackgroundImage = Properties.Resources.init; + } + + } + + [Browsable(true)] + [Description("控件中显示的文本内容"), Category("SignalText"), DefaultValue("")] + public string SignalText + { + get + { + return label_SignalName.Text; + } + + set + { + label_SignalName.Text = value; + } + + } + + SignalImage_Enum enum1; + + [Browsable(true)] + [Description("控件用于显示状态的图片"), Category("SignalImage"), DefaultValue("none")] + public SignalImage_Enum SignalImage + { + get + { + return enum1; + } + set + { + SetSignalImage(value); + enum1 = value; + + + + } + + + } + + + + public enum SignalImage_Enum + { + + none, init, green, yellow, red + + } + + void SetSignalImage(SignalImage_Enum Image) + { + switch (Image) + { + case SignalImage_Enum.none: + pictureBox_Signal.BackgroundImage = Properties.Resources.none; + break; + case SignalImage_Enum.init: + pictureBox_Signal.BackgroundImage = Properties.Resources.init; + break; + case SignalImage_Enum.green: + pictureBox_Signal.BackgroundImage = Properties.Resources.green; + break; + case SignalImage_Enum.yellow: + pictureBox_Signal.BackgroundImage = Properties.Resources.yellow; + break; + case SignalImage_Enum.red: + pictureBox_Signal.BackgroundImage = Properties.Resources.red; + break; + + } + + } + + + } +} diff --git a/Common/10SignalChangeMonitorControl/MesBoolSignal.resx b/Common/10SignalChangeMonitorControl/MesBoolSignal.resx new file mode 100644 index 0000000..1810bb4 --- /dev/null +++ b/Common/10SignalChangeMonitorControl/MesBoolSignal.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 + + + True + + + True + + \ No newline at end of file diff --git a/Common/10SignalChangeMonitorControl/MesControl.sln b/Common/10SignalChangeMonitorControl/MesControl.sln new file mode 100644 index 0000000..542454f --- /dev/null +++ b/Common/10SignalChangeMonitorControl/MesControl.sln @@ -0,0 +1,55 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.32901.82 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MesControl", "MesControl.csproj", "{FAB322CC-531D-4AEA-986A-B921B64D8D3F}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "00-0Json8.3.1", "..\..\Common\00-1Json8.3\Json8.3\00-0Json8.3.1.csproj", "{1A10FDB2-1A6A-44A8-AB4D-33387563247E}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "00MesWorkMqtt", "..\..\Common\00MesWorkMqtt\MesWorkMqtt\00MesWorkMqtt.csproj", "{F55DA1A0-A982-4479-8C47-0D9A5AAF3E18}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "01_01DoWhatPlc", "..\..\Common\01DoWhatPlc\01_01DoWhatPlc.csproj", "{0D1AF432-439A-4920-8692-43AE139F5530}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "02_02WebApiCallPLC", "..\..\Common\02WebApiCall\02_02WebApiCallPLC.csproj", "{3E6D1DD5-01C9-435F-9941-61F906CE35BB}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MonitorForm", "..\MonitorForm\MonitorForm.csproj", "{488BADD9-579F-4BF3-91DC-9FA95E3181A5}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {FAB322CC-531D-4AEA-986A-B921B64D8D3F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {FAB322CC-531D-4AEA-986A-B921B64D8D3F}.Debug|Any CPU.Build.0 = Debug|Any CPU + {FAB322CC-531D-4AEA-986A-B921B64D8D3F}.Release|Any CPU.ActiveCfg = Release|Any CPU + {FAB322CC-531D-4AEA-986A-B921B64D8D3F}.Release|Any CPU.Build.0 = Release|Any CPU + {1A10FDB2-1A6A-44A8-AB4D-33387563247E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {1A10FDB2-1A6A-44A8-AB4D-33387563247E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {1A10FDB2-1A6A-44A8-AB4D-33387563247E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {1A10FDB2-1A6A-44A8-AB4D-33387563247E}.Release|Any CPU.Build.0 = Release|Any CPU + {F55DA1A0-A982-4479-8C47-0D9A5AAF3E18}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F55DA1A0-A982-4479-8C47-0D9A5AAF3E18}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F55DA1A0-A982-4479-8C47-0D9A5AAF3E18}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F55DA1A0-A982-4479-8C47-0D9A5AAF3E18}.Release|Any CPU.Build.0 = Release|Any CPU + {0D1AF432-439A-4920-8692-43AE139F5530}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {0D1AF432-439A-4920-8692-43AE139F5530}.Debug|Any CPU.Build.0 = Debug|Any CPU + {0D1AF432-439A-4920-8692-43AE139F5530}.Release|Any CPU.ActiveCfg = Release|Any CPU + {0D1AF432-439A-4920-8692-43AE139F5530}.Release|Any CPU.Build.0 = Release|Any CPU + {3E6D1DD5-01C9-435F-9941-61F906CE35BB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {3E6D1DD5-01C9-435F-9941-61F906CE35BB}.Debug|Any CPU.Build.0 = Debug|Any CPU + {3E6D1DD5-01C9-435F-9941-61F906CE35BB}.Release|Any CPU.ActiveCfg = Release|Any CPU + {3E6D1DD5-01C9-435F-9941-61F906CE35BB}.Release|Any CPU.Build.0 = Release|Any CPU + {488BADD9-579F-4BF3-91DC-9FA95E3181A5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {488BADD9-579F-4BF3-91DC-9FA95E3181A5}.Debug|Any CPU.Build.0 = Debug|Any CPU + {488BADD9-579F-4BF3-91DC-9FA95E3181A5}.Release|Any CPU.ActiveCfg = Release|Any CPU + {488BADD9-579F-4BF3-91DC-9FA95E3181A5}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {6372AD35-C9E4-4A9A-A52E-4F41531AC05B} + EndGlobalSection +EndGlobal diff --git a/Common/10SignalChangeMonitorControl/PlcConnect.Designer.cs b/Common/10SignalChangeMonitorControl/PlcConnect.Designer.cs new file mode 100644 index 0000000..5e44fd1 --- /dev/null +++ b/Common/10SignalChangeMonitorControl/PlcConnect.Designer.cs @@ -0,0 +1,81 @@ +namespace MesControl +{ + partial class PlcConnect + { + /// + /// 必需的设计器变量。 + /// + private System.ComponentModel.IContainer components = null; + + /// + /// 清理所有正在使用的资源。 + /// + /// 如果应释放托管资源,为 true;否则为 false。 + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region 组件设计器生成的代码 + + /// + /// 设计器支持所需的方法 - 不要修改 + /// 使用代码编辑器修改此方法的内容。 + /// + private void InitializeComponent() + { + this.pictureBox_OpName = new System.Windows.Forms.PictureBox(); + this.label_OpName = new System.Windows.Forms.Label(); + ((System.ComponentModel.ISupportInitialize)(this.pictureBox_OpName)).BeginInit(); + this.SuspendLayout(); + // + // pictureBox_OpName + // + this.pictureBox_OpName.BackgroundImage = global::MesControl.Properties.Resources.BreakPLC; + this.pictureBox_OpName.Location = new System.Drawing.Point(3, 1); + this.pictureBox_OpName.MaximumSize = new System.Drawing.Size(20, 20); + this.pictureBox_OpName.MinimumSize = new System.Drawing.Size(20, 20); + this.pictureBox_OpName.Name = "pictureBox_OpName"; + this.pictureBox_OpName.Size = new System.Drawing.Size(20, 20); + this.pictureBox_OpName.TabIndex = 0; + this.pictureBox_OpName.TabStop = false; + // + // label_OpName + // + this.label_OpName.AutoSize = true; + this.label_OpName.Font = new System.Drawing.Font("宋体", 12F); + this.label_OpName.Location = new System.Drawing.Point(32, 3); + this.label_OpName.MaximumSize = new System.Drawing.Size(72, 16); + this.label_OpName.MinimumSize = new System.Drawing.Size(72, 16); + this.label_OpName.Name = "label_OpName"; + this.label_OpName.Size = new System.Drawing.Size(72, 16); + this.label_OpName.TabIndex = 1; + this.label_OpName.Text = "通讯状态"; + // + // PlcConnect + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.BackColor = System.Drawing.Color.Transparent; + this.Controls.Add(this.label_OpName); + this.Controls.Add(this.pictureBox_OpName); + this.MaximumSize = new System.Drawing.Size(110, 22); + this.MinimumSize = new System.Drawing.Size(110, 22); + this.Name = "PlcConnect"; + this.Size = new System.Drawing.Size(110, 22); + ((System.ComponentModel.ISupportInitialize)(this.pictureBox_OpName)).EndInit(); + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private System.Windows.Forms.PictureBox pictureBox_OpName; + private System.Windows.Forms.Label label_OpName; + } +} diff --git a/Common/10SignalChangeMonitorControl/PlcConnect.cs b/Common/10SignalChangeMonitorControl/PlcConnect.cs new file mode 100644 index 0000000..6bbf2e1 --- /dev/null +++ b/Common/10SignalChangeMonitorControl/PlcConnect.cs @@ -0,0 +1,221 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Drawing; +using System.Data; +using System.Linq; +using System.Text; +using System.Windows.Forms; + +namespace MesControl +{ + public delegate void PlcStatusHandle(); + public partial class PlcConnect: UserControl + { + public PlcConnect() + { + InitializeComponent(); + + } + public static PlcStatusHandle PlcBreakChange,PlcConnectChange; + + + #region 内部变量 + int externalTimerTimes =0; + + int testPlcBreakInterval=10000; + + int testPlcBreakTime=0; + + int externalTimerInterval = 200; + + bool isBreakPLC = true; + + bool plcTestEnable; + + bool plcBreakIsChanged=false; + bool plcConnectIsChanged = false; + + #endregion + #region 内部方法 + + void TimerTimeChange() + { + if (externalTimerTimes == 999) + { + externalTimerTimes = 0; + } + else + { + externalTimerTimes++; + } + + if (testPlcBreakTime > 0) + { + testPlcBreakTime--; + plcBreakIsChanged = false; + + if (PlcConnectChange!=null&&!plcConnectIsChanged) + { + PlcConnectChange(); + plcConnectIsChanged = true; + } + } + else + { + if (plcTestEnable) + { + if(PlcBreakChange != null&& !plcBreakIsChanged) + { + PlcBreakChange(); + plcBreakIsChanged = true; + } + plcConnectIsChanged = false; + } + isBreakPLC = true; + } + + } + #endregion + + #region 外部方法 + public void ExternalTimer() + { + + if (!isBreakPLC) + { + switch (externalTimerTimes % 5) + { + case 0: + pictureBox_OpName.BackgroundImage = Properties.Resources.PlcConnect0; + break; + case 1: + pictureBox_OpName.BackgroundImage = Properties.Resources.PlcConnect1; + break; + case 2: + pictureBox_OpName.BackgroundImage = Properties.Resources.PlcConnect2; + break; + case 3: + pictureBox_OpName.BackgroundImage = Properties.Resources.PlcConnect3; + break; + case 4: + pictureBox_OpName.BackgroundImage = Properties.Resources.PlcConnect4; + break; + + } + } + else + { + pictureBox_OpName.BackgroundImage = Properties.Resources.BreakPLC; + } + + + TimerTimeChange(); + } + + + + + public void ExternalPlcConnect() + { + testPlcBreakTime = (testPlcBreakInterval / externalTimerInterval) + 1; + isBreakPLC = false; + + } + + public void PlcBreak() + { + pictureBox_OpName.BackgroundImage = Properties.Resources.BreakPLC; + isBreakPLC = true; + } + + #endregion + + #region 属性 + + [Browsable(true)] + [Description("控件中显示的文本内容"), Category("外观"), DefaultValue("OP0000")] + public string LabelText + { + get + { + return label_OpName.Text; + } + + set + { + label_OpName.Text = value; + } + + } + + + [Browsable(true)] + [Description("外部定时器周期"), Category("行为"), DefaultValue("200")] + public int ExternalTimerInterval + { + get + { + return externalTimerInterval; + } + + set + { + externalTimerInterval = value; + } + + } + + [Browsable(true)] + [Description("检测PLC在线状态超时,超过此时间,PLC为离线状态"), Category("行为"), DefaultValue("200")] + public int TestPlcBreakInterval + { + get + { + return testPlcBreakInterval; + } + + set + { + testPlcBreakInterval = value; + } + + } + + [Browsable(true)] + [Description("指示PLC是否为断开状态"), Category("行为"), DefaultValue("True")] + public bool IsBreakPLC + { + get + { + return isBreakPLC; + } + + set + { + isBreakPLC = value; + } + + } + + [Browsable(true)] + [Description("是否启用检测PLC在线状态功能"), Category("行为"), DefaultValue("True")] + public bool PlcTestEnable + { + get + { + return plcTestEnable; + } + + set + { + plcTestEnable = value; + } + + } + + #endregion + + + } +} diff --git a/Common/10SignalChangeMonitorControl/PlcConnect.resx b/Common/10SignalChangeMonitorControl/PlcConnect.resx new file mode 100644 index 0000000..0abf881 --- /dev/null +++ b/Common/10SignalChangeMonitorControl/PlcConnect.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/Common/10SignalChangeMonitorControl/PlcWorkStationSignal.Designer.cs b/Common/10SignalChangeMonitorControl/PlcWorkStationSignal.Designer.cs new file mode 100644 index 0000000..e4e1488 --- /dev/null +++ b/Common/10SignalChangeMonitorControl/PlcWorkStationSignal.Designer.cs @@ -0,0 +1,80 @@ +namespace MesControl +{ + partial class PlcWorkStationSignal + { + /// + /// 必需的设计器变量。 + /// + private System.ComponentModel.IContainer components = null; + + /// + /// 清理所有正在使用的资源。 + /// + /// 如果应释放托管资源,为 true;否则为 false。 + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region 组件设计器生成的代码 + + /// + /// 设计器支持所需的方法 - 不要修改 + /// 使用代码编辑器修改此方法的内容。 + /// + private void InitializeComponent() + { + this.groupBox_WorkStationGrp = new System.Windows.Forms.GroupBox(); + this.plcConnect_WorkStation = new MesControl.PlcConnect(); + this.groupBox_WorkStationGrp.SuspendLayout(); + this.SuspendLayout(); + // + // groupBox_WorkStationGrp + // + this.groupBox_WorkStationGrp.BackColor = System.Drawing.Color.Transparent; + this.groupBox_WorkStationGrp.Controls.Add(this.plcConnect_WorkStation); + this.groupBox_WorkStationGrp.Location = new System.Drawing.Point(4, 4); + this.groupBox_WorkStationGrp.Name = "groupBox_WorkStationGrp"; + this.groupBox_WorkStationGrp.Size = new System.Drawing.Size(125, 50); + this.groupBox_WorkStationGrp.TabIndex = 0; + this.groupBox_WorkStationGrp.TabStop = false; + this.groupBox_WorkStationGrp.Text = "OP0000"; + // + // plcConnect_WorkStation + // + this.plcConnect_WorkStation.BackColor = System.Drawing.Color.Transparent; + this.plcConnect_WorkStation.ExternalTimerInterval = 200; + this.plcConnect_WorkStation.IsBreakPLC = false; + this.plcConnect_WorkStation.LabelText = "通讯状态"; + this.plcConnect_WorkStation.Location = new System.Drawing.Point(7, 21); + this.plcConnect_WorkStation.MaximumSize = new System.Drawing.Size(110, 22); + this.plcConnect_WorkStation.MinimumSize = new System.Drawing.Size(110, 22); + this.plcConnect_WorkStation.Name = "plcConnect_WorkStation"; + this.plcConnect_WorkStation.PlcTestEnable = false; + this.plcConnect_WorkStation.Size = new System.Drawing.Size(110, 22); + this.plcConnect_WorkStation.TabIndex = 0; + this.plcConnect_WorkStation.TestPlcBreakInterval = 0; + // + // PlcWorkStationSignal + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.BackColor = System.Drawing.Color.Transparent; + this.Controls.Add(this.groupBox_WorkStationGrp); + this.Name = "PlcWorkStationSignal"; + this.Size = new System.Drawing.Size(136, 60); + this.groupBox_WorkStationGrp.ResumeLayout(false); + this.ResumeLayout(false); + + } + + #endregion + + private System.Windows.Forms.GroupBox groupBox_WorkStationGrp; + private PlcConnect plcConnect_WorkStation; + } +} diff --git a/Common/10SignalChangeMonitorControl/PlcWorkStationSignal.cs b/Common/10SignalChangeMonitorControl/PlcWorkStationSignal.cs new file mode 100644 index 0000000..da90c09 --- /dev/null +++ b/Common/10SignalChangeMonitorControl/PlcWorkStationSignal.cs @@ -0,0 +1,228 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Drawing; +using System.Data; +using System.Linq; +using System.Text; +using System.Windows.Forms; + +namespace MesControl +{ + public delegate void WorkStationPlcBreakChanged(); + public partial class PlcWorkStationSignal : UserControl + { + public PlcWorkStationSignal() + { + InitializeComponent(); + PlcConnect.PlcBreakChange = new PlcStatusHandle(internalPlcBreak); + PlcConnect.PlcConnectChange = new PlcStatusHandle(internalPlcConnect); + this.SetStyle(ControlStyles.UserPaint, true); + this.SetStyle(ControlStyles.AllPaintingInWmPaint, true); + this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true); + + } + + public EventHandler WorkStationPlcStatusChange; + + #region 工位信号方法与属性 + + public void InitSignalControl() + { + + + for (int i = 0; i < SignalItems.Count; i++) + { + + MesBoolSignal mesBoolSignalNew = new MesBoolSignal(); + this.groupBox_WorkStationGrp.Controls.Add(mesBoolSignalNew);//扩展GroupBox + mesBoolSignalNew.BackColor = System.Drawing.Color.Transparent; + mesBoolSignalNew.Location = new System.Drawing.Point(7, 46 + (25 * i)); + mesBoolSignalNew.Name = SignalItems[i].Name; + mesBoolSignalNew.SignalImage = MesBoolSignal.SignalImage_Enum.none; + mesBoolSignalNew.SignalText = SignalItems[i].SignalText; + mesBoolSignalNew.Size = new System.Drawing.Size(110, 22); + mesBoolSignalNew.TabIndex = i; + + } + + //groupbox大小 + groupBox_WorkStationGrp.Size = new Size(125, 50 + (SignalItems.Count * 25)); + //控件大小 + this.Size = new Size(136, 60 + (SignalItems.Count * 25)); + + } + + private List signalItems = new List(); + [Browsable(true)] + [Description("MES信号控件集合"), Category("数据")] + [TypeConverter(typeof(System.ComponentModel.CollectionConverter))] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] + public List SignalItems + { + get + { + return signalItems; + } + + set + { + signalItems = value; + InitSignalControl(); + } + } + + /// + ///更改工位各个信号状态(默认) + /// + /// + /// + public void SignalChange(string SignalName, bool Value) + { + MesBoolSignal thisControl = (MesBoolSignal)Controls.Find(SignalName, true)[0]; + if (thisControl != null) + thisControl.SignalImage = Value ? MesBoolSignal.SignalImage_Enum.green : MesBoolSignal.SignalImage_Enum.init; + + } + + #endregion + + #region PLC在线状态属性与方法 + + ///////////////////////////////////////////////方法/////////////////////////////////////////////////// + + public void PlcConnectStatusChange(bool value) + { + plcConnect_WorkStation.ExternalPlcConnect(); + + } + public void ExternalTimerExcute() + { + plcConnect_WorkStation.ExternalTimer(); + } + + public void PlcBreak() + { + plcConnect_WorkStation.PlcBreak(); + } + + void internalPlcBreak() + { + if (WorkStationPlcStatusChange != null) + { + WorkStationPlcStatusChange(groupBox_WorkStationGrp.Text+"&Breaked",null); + } + + } + + void internalPlcConnect() + { + if (WorkStationPlcStatusChange != null) + { + WorkStationPlcStatusChange(groupBox_WorkStationGrp.Text + "&Connected", null); + } + } + + + //////////////////////////////////////////////////////////////属性/////////////////////////////////////////////// + + [Browsable(true)] + [Description("检测PLC在线状态开关"), Category("行为"), DefaultValue(true)] + public bool TestPLC_Enable + { + get + { + return plcConnect_WorkStation.PlcTestEnable; + } + set + { + plcConnect_WorkStation.PlcTestEnable = value; + } + } + + [Browsable(true)] + [Description("PLC心跳超时(超过此时间认为PLC离线)"), Category("行为"), DefaultValue(10000)] + public int TestPLC_Interval + { + get + { + return plcConnect_WorkStation.TestPlcBreakInterval; + } + set + { + + plcConnect_WorkStation.TestPlcBreakInterval = value; + + } + } + + + [Browsable(true)] + [Description("外部定时器循环时间"), Category("行为"), DefaultValue(200)] + public int ExternalTimerInterval + { + get + { + return plcConnect_WorkStation.ExternalTimerInterval; + } + set + { + plcConnect_WorkStation.ExternalTimerInterval = value; + } + } + + [Browsable(true)] + [Description("PLC在线状态"), Category("行为"), DefaultValue(false)] + public bool PLC_ConnectStatus + { + get + { + return plcConnect_WorkStation.IsBreakPLC; + } + set + { + plcConnect_WorkStation.IsBreakPLC = value; + } + } + + #endregion + + #region 当前控件方法与属性 + + [Browsable(true)] + [Description("控件显示的工位号"), Category("外观"), DefaultValue("OP0000")] + public string WorkStationNameText + { + get + { + return groupBox_WorkStationGrp.Text; + } + set + { + groupBox_WorkStationGrp.Text = value; + + } + + } + + [Browsable(true)] + [Description("控件中plc通讯显示的文本内容"), Category("外观"), DefaultValue("PLC连接")] + public string WS_PlcLabelText + { + get + { + return plcConnect_WorkStation.LabelText ; + } + + set + { + plcConnect_WorkStation.LabelText = value; + } + + } + + + #endregion + + } +} diff --git a/Common/10SignalChangeMonitorControl/PlcWorkStationSignal.resx b/Common/10SignalChangeMonitorControl/PlcWorkStationSignal.resx new file mode 100644 index 0000000..48f62a6 --- /dev/null +++ b/Common/10SignalChangeMonitorControl/PlcWorkStationSignal.resx @@ -0,0 +1,123 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + \ No newline at end of file diff --git a/Common/10SignalChangeMonitorControl/Properties/AssemblyInfo.cs b/Common/10SignalChangeMonitorControl/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..68d5529 --- /dev/null +++ b/Common/10SignalChangeMonitorControl/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// 有关程序集的一般信息由以下 +// 控制。更改这些特性值可修改 +// 与程序集关联的信息。 +[assembly: AssemblyTitle("MesControl")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("MesControl")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +//将 ComVisible 设置为 false 将使此程序集中的类型 +//对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型, +//请将此类型的 ComVisible 特性设置为 true。 +[assembly: ComVisible(false)] + +// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID +[assembly: Guid("fab322cc-531d-4aea-986a-b921b64d8d3f")] + +// 程序集的版本信息由下列四个值组成: +// +// 主版本 +// 次版本 +// 生成号 +// 修订号 +// +//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, +// 方法是按如下所示使用“*”: : +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Common/10SignalChangeMonitorControl/Properties/Resources.Designer.cs b/Common/10SignalChangeMonitorControl/Properties/Resources.Designer.cs new file mode 100644 index 0000000..3b13928 --- /dev/null +++ b/Common/10SignalChangeMonitorControl/Properties/Resources.Designer.cs @@ -0,0 +1,193 @@ +//------------------------------------------------------------------------------ +// +// 此代码由工具生成。 +// 运行时版本:4.0.30319.42000 +// +// 对此文件的更改可能会导致不正确的行为,并且如果 +// 重新生成代码,这些更改将会丢失。 +// +//------------------------------------------------------------------------------ + +namespace MesControl.Properties { + using System; + + + /// + /// 一个强类型的资源类,用于查找本地化的字符串等。 + /// + // 此类是由 StronglyTypedResourceBuilder + // 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。 + // 若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen + // (以 /str 作为命令选项),或重新生成 VS 项目。 + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.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 (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("MesControl.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; + } + } + + /// + /// 查找 System.Drawing.Bitmap 类型的本地化资源。 + /// + internal static System.Drawing.Bitmap BreakPLC { + get { + object obj = ResourceManager.GetObject("BreakPLC", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// 查找 System.Drawing.Bitmap 类型的本地化资源。 + /// + internal static System.Drawing.Bitmap green { + get { + object obj = ResourceManager.GetObject("green", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// 查找 System.Drawing.Bitmap 类型的本地化资源。 + /// + internal static System.Drawing.Bitmap init { + get { + object obj = ResourceManager.GetObject("init", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// 查找 System.Drawing.Bitmap 类型的本地化资源。 + /// + internal static System.Drawing.Bitmap none { + get { + object obj = ResourceManager.GetObject("none", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// 查找 System.Drawing.Bitmap 类型的本地化资源。 + /// + internal static System.Drawing.Bitmap PlcConnect0 { + get { + object obj = ResourceManager.GetObject("PlcConnect0", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// 查找 System.Drawing.Bitmap 类型的本地化资源。 + /// + internal static System.Drawing.Bitmap PlcConnect1 { + get { + object obj = ResourceManager.GetObject("PlcConnect1", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// 查找 System.Drawing.Bitmap 类型的本地化资源。 + /// + internal static System.Drawing.Bitmap PlcConnect2 { + get { + object obj = ResourceManager.GetObject("PlcConnect2", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// 查找 System.Drawing.Bitmap 类型的本地化资源。 + /// + internal static System.Drawing.Bitmap PlcConnect3 { + get { + object obj = ResourceManager.GetObject("PlcConnect3", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// 查找 System.Drawing.Bitmap 类型的本地化资源。 + /// + internal static System.Drawing.Bitmap PlcConnect4 { + get { + object obj = ResourceManager.GetObject("PlcConnect4", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// 查找 System.Drawing.Bitmap 类型的本地化资源。 + /// + internal static System.Drawing.Bitmap PlcConnectBig { + get { + object obj = ResourceManager.GetObject("PlcConnectBig", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// 查找 System.Drawing.Bitmap 类型的本地化资源。 + /// + internal static System.Drawing.Bitmap PlcConnectSmall { + get { + object obj = ResourceManager.GetObject("PlcConnectSmall", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// 查找 System.Drawing.Bitmap 类型的本地化资源。 + /// + internal static System.Drawing.Bitmap red { + get { + object obj = ResourceManager.GetObject("red", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// 查找 System.Drawing.Bitmap 类型的本地化资源。 + /// + internal static System.Drawing.Bitmap yellow { + get { + object obj = ResourceManager.GetObject("yellow", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + } +} diff --git a/Common/10SignalChangeMonitorControl/Properties/Resources.resx b/Common/10SignalChangeMonitorControl/Properties/Resources.resx new file mode 100644 index 0000000..e9eebfc --- /dev/null +++ b/Common/10SignalChangeMonitorControl/Properties/Resources.resx @@ -0,0 +1,160 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + + ..\Resources\red.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\yellow.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\PlcConnect1.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\PlcConnect0.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\PlcConnect3.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\none.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\PlcConnectSmall.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\PlcConnect2.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\init.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\PlcConnectBig.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\BreakPLC.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\green.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\PlcConnect4.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + \ No newline at end of file diff --git a/Common/10SignalChangeMonitorControl/Properties/_system~.ini b/Common/10SignalChangeMonitorControl/Properties/_system~.ini new file mode 100644 index 0000000..e69de29 diff --git a/Common/10SignalChangeMonitorControl/Resources/BreakPLC.png b/Common/10SignalChangeMonitorControl/Resources/BreakPLC.png new file mode 100644 index 0000000..4873366 Binary files /dev/null and b/Common/10SignalChangeMonitorControl/Resources/BreakPLC.png differ diff --git a/Common/10SignalChangeMonitorControl/Resources/PlcConnect0.png b/Common/10SignalChangeMonitorControl/Resources/PlcConnect0.png new file mode 100644 index 0000000..73e71bd Binary files /dev/null and b/Common/10SignalChangeMonitorControl/Resources/PlcConnect0.png differ diff --git a/Common/10SignalChangeMonitorControl/Resources/PlcConnect1.png b/Common/10SignalChangeMonitorControl/Resources/PlcConnect1.png new file mode 100644 index 0000000..8c0a417 Binary files /dev/null and b/Common/10SignalChangeMonitorControl/Resources/PlcConnect1.png differ diff --git a/Common/10SignalChangeMonitorControl/Resources/PlcConnect2.png b/Common/10SignalChangeMonitorControl/Resources/PlcConnect2.png new file mode 100644 index 0000000..671a278 Binary files /dev/null and b/Common/10SignalChangeMonitorControl/Resources/PlcConnect2.png differ diff --git a/Common/10SignalChangeMonitorControl/Resources/PlcConnect3.png b/Common/10SignalChangeMonitorControl/Resources/PlcConnect3.png new file mode 100644 index 0000000..165eaeb Binary files /dev/null and b/Common/10SignalChangeMonitorControl/Resources/PlcConnect3.png differ diff --git a/Common/10SignalChangeMonitorControl/Resources/PlcConnect4.png b/Common/10SignalChangeMonitorControl/Resources/PlcConnect4.png new file mode 100644 index 0000000..9fc042d Binary files /dev/null and b/Common/10SignalChangeMonitorControl/Resources/PlcConnect4.png differ diff --git a/Common/10SignalChangeMonitorControl/Resources/PlcConnectBig.png b/Common/10SignalChangeMonitorControl/Resources/PlcConnectBig.png new file mode 100644 index 0000000..f2a21c0 Binary files /dev/null and b/Common/10SignalChangeMonitorControl/Resources/PlcConnectBig.png differ diff --git a/Common/10SignalChangeMonitorControl/Resources/PlcConnectSmall.png b/Common/10SignalChangeMonitorControl/Resources/PlcConnectSmall.png new file mode 100644 index 0000000..8f43514 Binary files /dev/null and b/Common/10SignalChangeMonitorControl/Resources/PlcConnectSmall.png differ diff --git a/Common/10SignalChangeMonitorControl/Resources/_system~.ini b/Common/10SignalChangeMonitorControl/Resources/_system~.ini new file mode 100644 index 0000000..e69de29 diff --git a/Common/10SignalChangeMonitorControl/Resources/green.png b/Common/10SignalChangeMonitorControl/Resources/green.png new file mode 100644 index 0000000..c4b463e Binary files /dev/null and b/Common/10SignalChangeMonitorControl/Resources/green.png differ diff --git a/Common/10SignalChangeMonitorControl/Resources/init.png b/Common/10SignalChangeMonitorControl/Resources/init.png new file mode 100644 index 0000000..c148366 Binary files /dev/null and b/Common/10SignalChangeMonitorControl/Resources/init.png differ diff --git a/Common/10SignalChangeMonitorControl/Resources/none.png b/Common/10SignalChangeMonitorControl/Resources/none.png new file mode 100644 index 0000000..8ec6c8d Binary files /dev/null and b/Common/10SignalChangeMonitorControl/Resources/none.png differ diff --git a/Common/10SignalChangeMonitorControl/Resources/red.png b/Common/10SignalChangeMonitorControl/Resources/red.png new file mode 100644 index 0000000..26a05cb Binary files /dev/null and b/Common/10SignalChangeMonitorControl/Resources/red.png differ diff --git a/Common/10SignalChangeMonitorControl/Resources/yellow.png b/Common/10SignalChangeMonitorControl/Resources/yellow.png new file mode 100644 index 0000000..ee71881 Binary files /dev/null and b/Common/10SignalChangeMonitorControl/Resources/yellow.png differ diff --git a/Common/10SignalChangeMonitorControl/SignalInit.cs b/Common/10SignalChangeMonitorControl/SignalInit.cs new file mode 100644 index 0000000..3b5b0a8 --- /dev/null +++ b/Common/10SignalChangeMonitorControl/SignalInit.cs @@ -0,0 +1,37 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace MesControl +{ + public partial class PlcWorkStationSignal + { + void initsignal() + { + //private PlcConnect plcConnect_WorkStation; + //this.plcConnect_WorkStation = new MesControl.PlcConnect(); + //this.groupBox_WorkStationGrp.Controls.Add(this.plcConnect_WorkStation); + + //// + //// plcConnect_WorkStation + //// + //this.plcConnect_WorkStation.BackColor = System.Drawing.Color.Transparent; + //this.plcConnect_WorkStation.ExternalTimerInterval = 200; + //this.plcConnect_WorkStation.IsBreakPLC = false; + //this.plcConnect_WorkStation.LabelText = "通讯状态"; + //this.plcConnect_WorkStation.Location = new System.Drawing.Point(7, 21); + //this.plcConnect_WorkStation.MaximumSize = new System.Drawing.Size(110, 22); + //this.plcConnect_WorkStation.MinimumSize = new System.Drawing.Size(110, 22); + //this.plcConnect_WorkStation.Name = "plcConnect_WorkStation"; + //this.plcConnect_WorkStation.PlcTestEnable = false; + //this.plcConnect_WorkStation.Size = new System.Drawing.Size(110, 22); + //this.plcConnect_WorkStation.TabIndex = 0; + //this.plcConnect_WorkStation.TestPlcBreakInterval = 0; + + } + + + + } +} diff --git a/Common/10SignalChangeMonitorControl/_system~.ini b/Common/10SignalChangeMonitorControl/_system~.ini new file mode 100644 index 0000000..e69de29 diff --git a/Common/11MonitorForm/11MonitorForm.csproj b/Common/11MonitorForm/11MonitorForm.csproj new file mode 100644 index 0000000..d096bcf --- /dev/null +++ b/Common/11MonitorForm/11MonitorForm.csproj @@ -0,0 +1,137 @@ + + + + + Debug + AnyCPU + {488BADD9-579F-4BF3-91DC-9FA95E3181A5} + Library + MonitorFrom + MonitorFrom + v4.8 + 512 + true + true + + + + AnyCPU + true + full + false + bin\MonitorForm\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + Mes32X32.ico + + + + + + + False + ..\..\Common\dll\MQTTnet.dll + + + False + ..\..\Common\dll\MQTTnet.Extensions.ManagedClient.dll + + + + + + + + + + + + + + + + + Form + + + Form1.cs + + + + Form + + + Form + + + + + Form + + + SecondForm.cs + + + Form + + + ResXFileCodeGenerator + Resources.Designer.cs + Designer + + + True + Resources.resx + True + + + SecondForm.cs + + + SettingsSingleFileGenerator + Settings.Designer.cs + + + True + Settings.settings + True + + + + + + + + {f55da1a0-a982-4479-8c47-0d9a5aaf3e18} + 00MesWorkMqtt + + + {0d1af432-439a-4920-8692-43ae139f5530} + 01_01DoWhatPlc + + + {90e76fb4-646d-45e2-95db-0b8ab4e465d6} + 09-MesDataFunction + + + {fab322cc-531d-4aea-986a-b921b64d8d3f} + 10MesControl + + + + + + + \ No newline at end of file diff --git a/Common/11MonitorForm/App.config b/Common/11MonitorForm/App.config new file mode 100644 index 0000000..91dd9a9 --- /dev/null +++ b/Common/11MonitorForm/App.config @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + diff --git a/Common/11MonitorForm/Form1.Designer.cs b/Common/11MonitorForm/Form1.Designer.cs new file mode 100644 index 0000000..a594139 --- /dev/null +++ b/Common/11MonitorForm/Form1.Designer.cs @@ -0,0 +1,41 @@ + +namespace MonitorFrom +{ + partial class Form1 + { + /// + /// 必需的设计器变量。 + /// + 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.components = new System.ComponentModel.Container(); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(800, 450); + this.Text = "Form1"; + } + + #endregion + } +} + diff --git a/Common/11MonitorForm/Form1.cs b/Common/11MonitorForm/Form1.cs new file mode 100644 index 0000000..94de9ff --- /dev/null +++ b/Common/11MonitorForm/Form1.cs @@ -0,0 +1,20 @@ +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 MonitorFrom +{ + public partial class Form1 : Form + { + public Form1() + { + InitializeComponent(); + } + } +} diff --git a/Common/11MonitorForm/FunctionForm_HashiTable.cs b/Common/11MonitorForm/FunctionForm_HashiTable.cs new file mode 100644 index 0000000..6e6efd4 --- /dev/null +++ b/Common/11MonitorForm/FunctionForm_HashiTable.cs @@ -0,0 +1,103 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace MisDataName +{ + class FunctionForm_HashiTable + { + public static Hashtable OpName_Hash = new Hashtable(); + public static object OpName_Hash_Read(string Key) + { + if (OpName_Hash.ContainsKey(Key)) + { + return OpName_Hash[Key]; + + } + else + { + return null; + } + + } + + public static void OpName_Hash_Write(string Key, object obj) + { + + if (OpName_Hash.ContainsKey(Key)) + { + + OpName_Hash[Key] = obj; + } + else + { + OpName_Hash.Add(Key, obj); + } + + } + + + public static Hashtable SignalName = new Hashtable(); + public static string SignalName_Hash_Read(string Key) + { + if (SignalName.ContainsKey(Key)) + { + return SignalName[Key].ToString (); + + } + else + { + return null; + } + + } + + public static void SignalName_Hash_Write(string Key, string str) + { + + if (SignalName.ContainsKey(Key)) + { + + SignalName[Key] = str; + } + else + { + SignalName.Add(Key, str); + } + + } + + + public static Hashtable SignalConfig = new Hashtable(); + public static object SignalConfig_Hash_Read(string Key) + { + if (SignalConfig.ContainsKey(Key)) + { + return SignalConfig[Key]; + + } + else + { + return null; + } + + } + + public static void SignalConfig_Write(string Key, object str) + { + + if (SignalConfig.ContainsKey(Key)) + { + + SignalConfig[Key] = str; + } + else + { + SignalConfig.Add(Key, str); + } + + } + } +} diff --git a/Common/11MonitorForm/MainSignalChangeEvent.cs b/Common/11MonitorForm/MainSignalChangeEvent.cs new file mode 100644 index 0000000..8311d1b --- /dev/null +++ b/Common/11MonitorForm/MainSignalChangeEvent.cs @@ -0,0 +1,127 @@ +using DoWhatPlc; +using MesControl; +using MQTTnet; +using MQTTnet.Client.Connecting; +using MQTTnet.Client.Disconnecting; +using MQTTnet.Client.Receiving; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading; +//using SystemFramework; + +namespace MisDataName +{ + public partial class SecondForm + { + public MesWorkMqtt.Mqtt2 mqtt2; + //public void InitMqtt2(string url, string topic) + //{ + // mqtt2 = new MesWorkMqtt.Mqtt2(); + // mqtt2.MqttUrl = url; + // mqtt2.topic = topic; + // mqtt2.StartAsync(); + // mqtt2.mqttClient.ConnectedHandler = new MqttClientConnectedHandlerDelegate(OnSubscriberConnected); + // mqtt2.mqttClient.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(OnSubscriberDisconnected); + // mqtt2.mqttClient.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(OnSubscriberMessageReceived); + + // //MesServerCode哈希表创建 + // //MesServerWork.MIS_BASE.InitHashtable_MesServerCode(); + + //} + //private void OnSubscriberConnected(MqttClientConnectedEventArgs x) + //{ + // var rec = x.AuthenticateResult.ResultCode.ToString(); + + //} + + //private void OnSubscriberDisconnected(MqttClientDisconnectedEventArgs x) + //{ + + //} + + //private void OnSubscriberMessageReceived(MqttApplicationMessageReceivedEventArgs x) + //{ + // var rec = x.ApplicationMessage.ConvertPayloadToString(); + + + // //处理MES业务 + // ThreadPool.QueueUserWorkItem(MainSignalChange, rec); + //} + + + void WorkStation_RefreshWorkStationStatus(string OpName, bool value) + { + try + { + PlcWorkStationSignal plcWorkStationSignal = (PlcWorkStationSignal)Controls.Find("plcWorkStationSignal_" + OpName, true)[0]; + plcWorkStationSignal.PlcConnectStatusChange(value); + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, err.Message); + } + } + void InitMainSignalEvent() + { + //MisData.PlcChange = new PlcChangeEvent(MainSignalChange); + } + + //void MainSignalChange(object e) + //{ + // string recData = e.ToString(); + // string[] dataArray = recData.Split('|'); + // if (dataArray.Length != 4) + // return; + // //消息来源 + // string m_Source = dataArray[0].ToString(); + // //消息类型 + // string m_Command = dataArray[1].ToString(); + // //工位号 + // string m_OpName = dataArray[2].ToString(); + // //消息参数 + // string m_Value = dataArray[3].ToString(); + // if (m_Source == "BarCode") return; + + // DoWhatPlc.ReturnValueString rv = Newtonsoft.Json.JsonConvert.DeserializeObject(m_Value); + // //Console.WriteLine($"【【{rv.TagID}【【【【{ rv.TagKeepTime}"); + // if (rv == null) return; + // int tagType; + // string opName; + // string tagValue; + // int tagid; + // DoWhatPlc.ReturnValueString msgEvent = rv; + // if (msgEvent.TagValue == null) return; + // tagType = Convert.ToInt32(msgEvent.TagTypeID); + // opName = msgEvent.OpName.ToString(); + // tagid = Convert.ToInt32(msgEvent.TagID); + // int tagTypeCodeID = Convert.ToInt32(msgEvent.TagTypeCodeID); + // switch (tagType) + // { + // case 11: + // switch (msgEvent.TagValue.ToLower()) + // { + // case "1": + // case "true": + // tagValue = "1"; + // break; + // default: + // tagValue = "0"; + // break; + // } + // break; + // default: + // tagValue = msgEvent.TagValue.ToString(); + // break; + // } + // if (tagType == 11) + // { + + // WriteWorkStationSignal(opName, tagTypeCodeID.ToString(), Convert.ToBoolean(Convert.ToInt32(tagValue))); + // } + //} + + + } +} diff --git a/Common/11MonitorForm/Mes32X32.ico b/Common/11MonitorForm/Mes32X32.ico new file mode 100644 index 0000000..ec465b2 Binary files /dev/null and b/Common/11MonitorForm/Mes32X32.ico differ diff --git a/Common/11MonitorForm/PlcSignalDynamicCreate.cs b/Common/11MonitorForm/PlcSignalDynamicCreate.cs new file mode 100644 index 0000000..5ea19d6 --- /dev/null +++ b/Common/11MonitorForm/PlcSignalDynamicCreate.cs @@ -0,0 +1,139 @@ +using MesControl; +using MesServerWork; +using System; +using System.Collections.Generic; +using System.Data; +using System.Linq; +using System.Text; +using System.Xml.Linq; +//using SystemFramework; + +namespace MisDataName +{ + public delegate void ControlConnectPLC(); + public partial class SecondForm + { + ControlConnectPLC PlcConnectTimer; + + void InitFormDynamicControls() + { + try + { + // DataTable dt_OpName=(DataTable) FunctionForm_HashiTable.OpName_Hash_Read("OpNameList"); + + List signalItems = InitWorkStationSignal(); + RecordWorkStationSignal(signalItems); + + int RowsWidth = SignalPanel.Width-20; + int RowsNum = RowsWidth / 133; + int i = 0; + var opNameList = MIS_BASE.Get_opNameList(); + foreach (var opName in opNameList) + { + PlcWorkStationSignal plcWorkStationSignal = new PlcWorkStationSignal(); + + plcWorkStationSignal.BackColor = System.Drawing.Color.Transparent; + plcWorkStationSignal.Location = new System.Drawing.Point(3 + ((i % RowsNum) * 133), (i / RowsNum) * ((signalItems.Count * 25) + 60)); + plcWorkStationSignal.MaximumSize = new System.Drawing.Size(0, 0); + plcWorkStationSignal.MinimumSize = new System.Drawing.Size(0, 0); + plcWorkStationSignal.Name = "plcWorkStationSignal_" + opName; + plcWorkStationSignal.Size = new System.Drawing.Size(136, 60); + plcWorkStationSignal.TabIndex = i; + plcWorkStationSignal.SignalItems = signalItems; + plcWorkStationSignal.WorkStationNameText = opName; + plcWorkStationSignal.WS_PlcLabelText = "PLC连接"; + plcWorkStationSignal.TestPLC_Interval = 10000; + + plcWorkStationSignal.TestPLC_Enable = true; + PlcConnectTimer += plcWorkStationSignal.ExternalTimerExcute; + + this.SignalPanel.Controls.Add(plcWorkStationSignal); + i++; + } + + + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, err.Message); + } + + } + + public List InitWorkStationSignal() + { + try + { + List signalItems = new List(); + MesBoolSignal MBS; + signalItems.Clear(); + XDocument SystemConfig = XDocument.Load("SystemConfig.xml"); + IEnumerable plc = SystemConfig.Descendants ("PLC"); + IEnumerable plcSignal = plc.Elements(); + foreach (XElement PlcSignal in plcSignal) + { + XElement Name = PlcSignal.Element("Name"); + XElement TagType = PlcSignal.Element("TagType"); + XElement Text = PlcSignal.Element("Text"); + XElement Index = PlcSignal.Element("Index"); + XElement Enabled = PlcSignal.Element("Enabled"); + + MBS = new MesBoolSignal(); + MBS.Name = "TagType_" + TagType.Value ; + MBS.SignalText = Text.Value ; + MBS.SignalImage = MesBoolSignal.SignalImage_Enum.none; + + if (Convert.ToBoolean(Enabled.Value)) + { + signalItems.Add(MBS); + } + } + IEnumerable mes = SystemConfig.Descendants("MES"); + IEnumerable mesSignal = mes.Elements(); + foreach (XElement MesSignal in mesSignal) + { + XElement Name = MesSignal.Element("Name"); + XElement TagType = MesSignal.Element("TagType"); + XElement Text = MesSignal.Element("Text"); + XElement Index = MesSignal.Element("Index"); + XElement Enabled = MesSignal.Element("Enabled"); + + MBS = new MesBoolSignal(); + MBS.Name = "TagType_" + TagType.Value; + MBS.SignalText = Text.Value; + MBS.SignalImage = MesBoolSignal.SignalImage_Enum.none; + + if (Convert .ToBoolean ( Enabled .Value)) + { + signalItems.Add(MBS); + } + + } + + return signalItems; + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, err.Message); + return null; + } + } + + + string[] SignalNames; + + void RecordWorkStationSignal(List items) + { + SignalNames = new string[items.Count]; + for (int i=0;i< items.Count;i++) + { + SignalNames[i] = items[i].Name; + } + + + } + + + + } +} diff --git a/Common/11MonitorForm/Program.cs b/Common/11MonitorForm/Program.cs new file mode 100644 index 0000000..67147e1 --- /dev/null +++ b/Common/11MonitorForm/Program.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace MisDataName +{ + static class Program + { + /// + /// 应用程序的主入口点。 + /// + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + Application.Run(new SecondForm()); + } + } +} diff --git a/Common/11MonitorForm/Properties/AssemblyInfo.cs b/Common/11MonitorForm/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..53b0405 --- /dev/null +++ b/Common/11MonitorForm/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// 有关程序集的一般信息由以下 +// 控制。更改这些特性值可修改 +// 与程序集关联的信息。 +[assembly: AssemblyTitle("MonitorFrom")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("MonitorFrom")] +[assembly: AssemblyCopyright("Copyright © 2022")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// 将 ComVisible 设置为 false 会使此程序集中的类型 +//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型 +//请将此类型的 ComVisible 特性设置为 true。 +[assembly: ComVisible(false)] + +// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID +[assembly: Guid("488badd9-579f-4bf3-91dc-9fa95e3181a5")] + +// 程序集的版本信息由下列四个值组成: +// +// 主版本 +// 次版本 +// 生成号 +// 修订号 +// +//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值 +//通过使用 "*",如下所示: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Common/11MonitorForm/Properties/Resources.Designer.cs b/Common/11MonitorForm/Properties/Resources.Designer.cs new file mode 100644 index 0000000..554b127 --- /dev/null +++ b/Common/11MonitorForm/Properties/Resources.Designer.cs @@ -0,0 +1,63 @@ +//------------------------------------------------------------------------------ +// +// 此代码由工具生成。 +// 运行时版本:4.0.30319.42000 +// +// 对此文件的更改可能会导致不正确的行为,并且如果 +// 重新生成代码,这些更改将会丢失。 +// +//------------------------------------------------------------------------------ + +namespace MonitorFrom.Properties { + using System; + + + /// + /// 一个强类型的资源类,用于查找本地化的字符串等。 + /// + // 此类是由 StronglyTypedResourceBuilder + // 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。 + // 若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen + // (以 /str 作为命令选项),或重新生成 VS 项目。 + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.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 (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("MonitorFrom.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/Common/11MonitorForm/Properties/Resources.resx b/Common/11MonitorForm/Properties/Resources.resx new file mode 100644 index 0000000..af7dbeb --- /dev/null +++ b/Common/11MonitorForm/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/Common/11MonitorForm/Properties/Settings.Designer.cs b/Common/11MonitorForm/Properties/Settings.Designer.cs new file mode 100644 index 0000000..422dbaa --- /dev/null +++ b/Common/11MonitorForm/Properties/Settings.Designer.cs @@ -0,0 +1,26 @@ +//------------------------------------------------------------------------------ +// +// 此代码由工具生成。 +// 运行时版本:4.0.30319.42000 +// +// 对此文件的更改可能会导致不正确的行为,并且如果 +// 重新生成代码,这些更改将会丢失。 +// +//------------------------------------------------------------------------------ + +namespace MonitorFrom.Properties { + + + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "17.0.3.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/Common/11MonitorForm/Properties/Settings.settings b/Common/11MonitorForm/Properties/Settings.settings new file mode 100644 index 0000000..3964565 --- /dev/null +++ b/Common/11MonitorForm/Properties/Settings.settings @@ -0,0 +1,7 @@ + + + + + + + diff --git a/Common/11MonitorForm/SecondForm.Designer.cs b/Common/11MonitorForm/SecondForm.Designer.cs new file mode 100644 index 0000000..fdf10cb --- /dev/null +++ b/Common/11MonitorForm/SecondForm.Designer.cs @@ -0,0 +1,83 @@ +namespace MisDataName +{ + partial class SecondForm + { + /// + /// 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.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(SecondForm)); + this.groupBox_PlcSignal = new System.Windows.Forms.GroupBox(); + this.SignalPanel = new MisDataName.MyPanel(); + this.groupBox_PlcSignal.SuspendLayout(); + this.SuspendLayout(); + // + // groupBox_PlcSignal + // + this.groupBox_PlcSignal.Controls.Add(this.SignalPanel); + this.groupBox_PlcSignal.Location = new System.Drawing.Point(12, 12); + this.groupBox_PlcSignal.Name = "groupBox_PlcSignal"; + this.groupBox_PlcSignal.Size = new System.Drawing.Size(718, 807); + this.groupBox_PlcSignal.TabIndex = 1; + this.groupBox_PlcSignal.TabStop = false; + this.groupBox_PlcSignal.Text = "LineStatus"; + // + // SignalPanel + // + this.SignalPanel.AutoScroll = true; + this.SignalPanel.Location = new System.Drawing.Point(6, 20); + this.SignalPanel.Name = "SignalPanel"; + this.SignalPanel.Size = new System.Drawing.Size(706, 780); + this.SignalPanel.TabIndex = 0; + // + // SecondForm + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(741, 831); + this.Controls.Add(this.groupBox_PlcSignal); + this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); + this.MaximizeBox = false; + this.MaximumSize = new System.Drawing.Size(757, 870); + this.MinimizeBox = false; + this.MinimumSize = new System.Drawing.Size(757, 870); + this.Name = "SecondForm"; + this.ShowIcon = false; + this.ShowInTaskbar = false; + this.StartPosition = System.Windows.Forms.FormStartPosition.Manual; + this.Text = "PlcSignal 2022-10-16"; + this.TopMost = true; + this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.SecondForm_FormClosing); + this.groupBox_PlcSignal.ResumeLayout(false); + this.ResumeLayout(false); + + } + + #endregion + + private MyPanel SignalPanel; + private System.Windows.Forms.GroupBox groupBox_PlcSignal; + } +} \ No newline at end of file diff --git a/Common/11MonitorForm/SecondForm.cs b/Common/11MonitorForm/SecondForm.cs new file mode 100644 index 0000000..6fe053f --- /dev/null +++ b/Common/11MonitorForm/SecondForm.cs @@ -0,0 +1,86 @@ +using MesControl; +using MQTTnet; +using MQTTnet.Client.Connecting; +using MQTTnet.Client.Disconnecting; +using MQTTnet.Client.Receiving; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading; +using System.Windows.Forms; +//using SystemFramework; + +namespace MisDataName +{ + public partial class SecondForm : Form + { + public SecondForm() + { + InitializeComponent(); + InitFormDynamicControls(); + InitMainSignalEvent(); + //InitOtherFormAction(); + //SyncForm_Init(); + + string url; + string topic; + url = System.Configuration.ConfigurationManager.AppSettings["MqttUrl"]; + topic = System.Configuration.ConfigurationManager.AppSettings["MqttTargetTopicPLC"]; + + //InitMqtt2(url, topic); + + } + + + + + //void WriteWorkStationSignal(string OpName,string SignalName,bool value) + //{ + // try + // { + // if (Array.IndexOf(SignalNames, "TagType_"+SignalName)!=-1) + // { + // PlcWorkStationSignal plcWorkStationSignal = (PlcWorkStationSignal)Controls.Find("plcWorkStationSignal_" + OpName, true)[0]; + // plcWorkStationSignal.SignalChange("TagType_"+SignalName, value); + // if (SignalName=="14") + // { + // WorkStation_RefreshWorkStationStatus(OpName, value); + // } + + // } + // } + // catch (Exception err) + // { + // //ApplicationLog.WriteLog(err, err.Message); + // } + + //} + + + private void SecondForm_FormClosing(object sender, FormClosingEventArgs e) + { + try + { + this.Dispose(); + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, err.Message); + } + } + } + + class MyPanel : Panel + { + public MyPanel() + { + this.SetStyle(ControlStyles.UserPaint, true); + this.SetStyle(ControlStyles.AllPaintingInWmPaint, true); + this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true); + } + } +} diff --git a/Common/11MonitorForm/SecondForm.resx b/Common/11MonitorForm/SecondForm.resx new file mode 100644 index 0000000..900f82a --- /dev/null +++ b/Common/11MonitorForm/SecondForm.resx @@ -0,0 +1,197 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + + + AAABAAEAICAAAAEAIACoEAAAFgAAACgAAAAgAAAAQAAAAAEAIAAAAAAAABAAABMLAAATCwAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMgChADIAoQIyAKEgMgChczIA + occyAKHqMgChmTIAoTwyAKEJMgChAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMgChADIAoQQyAKEvMgChdzIA + odYyAKH7MgCh/zIAof8yAKH/MgCh6jIAoacyAKFJMgChEjIAoQAyAKEAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAyAKEAMgChADIAoQoyAKE+MgChkTIA + oeoyAKH+MgCh+TIAoe0yAKH+MgCh/zIAofwyAKH3MgCh/jIAofgyAKHBMgChZDIAoR4yAKEBMgChAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAyAKEAMgChATIAoRUyAKFcMgChujIA + ofEyAKH/MgCh9DIAobcyAKFPMgChfjIAof8yAKH/MgCh5TIAoVUyAKGLMgCh4jIAofwyAKH9MgCh2TIA + oYcyAKEoMgChBTIAoQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAyAKEAMgChAjIAoSYyAKF2MgCh0DIA + ofcyAKH+MgCh8zIAof8yAKGjMgChDTIAoQAyAKFpMgCh/zIAof8yAKHhMgChHjIAoQIyAKEiMgChbjIA + ocoyAKH3MgCh/jIAoeUyAKGfMgChQTIAoQsyAKEAAAAAAAAAAAAAAAAAMgChCDIAoUEyAKGXMgCh4jIA + of4yAKH/MgChzzIAoW0yAKFoMgCh+zIAoZcyAKEAMgChADIAoWkyAKH/MgCh/zIAoeEyAKEeMgChADIA + oQAyAKEBMgChETIAoVAyAKGiMgCh8DIAof8yAKH0MgChuTIAoW0yAKEVMgChADIAoQAyAKG2MgCh7TIA + of8yAKHvMgCh7jIAofgyAKFLMgChADIAoTcyAKH1MgChlzIAoQAyAKEAMgChaTIAof8yAKH/MgCh4TIA + oR4yAKEAAAAAAAAAAAAAAAAAMgChADIAoQcyAKE4MgChijIAod8yAKH9MgCh+zIAoc4yAKFdMgChADIA + of8yAKHlMgChlDIAoToyAKGgMgCh7jIAoSwyAKEAMgChFzIAodgyAKGZMgChADIAoQAyAKFpMgCh/zIA + of8yAKHxMgChfDIAoSkyAKEBMgChAAAAAAAAAAAAAAAAADIAoQAyAKECMgChITIAoW8yAKG/MgCh/zIA + oZYyAKEAMgCh/zIAoZoyAKEBMgChADIAoZkyAKHSMgChEjIAoQAyAKEGMgChujIAoZoyAKEAMgChADIA + oWkyAKH/MgCh/zIAof0yAKH+MgCh4TIAoZIyAKFEMgChDjIAoQAyAKEAAAAAAAAAAAAAAAAAMgChADIA + oUIyAKH7MgChlzIAoQAyAKH/MgChlzIAoQAyAKEAMgChmjIAobMyAKEEMgChADIAoQAyAKGcMgChmzIA + oQAyAKEAMgChaTIAof8yAKH/MgCh4zIAoZYyAKHRMgCh+zIAofQyAKHDMgChZDIAoSIyAKEBMgChAAAA + AAAyAKEAMgChPzIAofsyAKGXMgChADIAof8yAKGXMgChADIAoQAyAKGaMgChiDIAoQAAAAAAMgChADIA + oYgyAKGaMgChADIAoQAyAKFpMgCh/zIAof8yAKHhMgChIDIAoRIyAKFeMgChqzIAoe0yAKH+MgCh3jIA + oYYyAKEqMgChADIAoQAyAKE/MgCh+zIAoZcyAKEAMgCh/zIAoZcyAKEAMgChADIAoZgyAKFtMgChAAAA + AAAyAKEAMgChXDIAoZQyAKEAMgChADIAoWkyAKH/MgCh/zIAoeEyAKEeMgChADIAoQAyAKEGMgChMDIA + oX8yAKHTMgCh+jIAoWkyAKEAMgChADIAoT8yAKH7MgChlzIAoQAyAKH/MgChlzIAoQAyAKEAMgChlTIA + oWMyAKEAAAAAADIAoQAyAKE2MgChhTIAoQAyAKEAMgChaTIAof8yAKH/MgCh4TIAoR4yAKEAAAAAAAAA + AAAyAKEAMgChATIAoRUyAKFYMgChQDIAoQAyAKEAMgChPzIAofsyAKGXMgChADIAof8yAKGXMgChADIA + oQAyAKGLMgChQTIAoQAyAKEFMgChADIAoSMyAKF4MgChADIAoQAyAKFpMgCh/zIAof8yAKHhMgChHjIA + oQAAAAAAAAAAAAAAAAAAAAAAMgChADIAoQAyAKEBMgChADIAoQAyAKE/MgCh+zIAoZcyAKEAMgCh/zIA + oZcyAKEAMgChADIAoXcyAKEkMgChBzIAoUIyAKEBMgChFjIAoWUyAKEBMgChADIAoWkyAKH/MgCh/zIA + oeEyAKEeMgChADIAoQAyAKE5MgChSTIAoQ8yAKEBMgChAAAAAAAAAAAAMgChADIAoT8yAKH7MgChlzIA + oQAyAKH/MgChlzIAoQAyAKECMgChWzIAoQ8yAKEVMgChhTIAoQoyAKEHMgChMzIAoQEyAKEAMgChaTIA + of8yAKH/MgCh4TIAoR4yAKEAMgChADIAoWkyAKH1MgChyzIAoX8yAKE4MgChBTIAoQAyAKEAMgChPzIA + ofsyAKGXMgChADIAof8yAKGXMgChADIAoQMyAKFZMgChCzIAoS4yAKHDMgChGjIAoQAAAAAAAAAAADIA + oQAyAKFpMgCh/zIAof8yAKHhMgChHjIAoQAyAKEAMgChLDIAoaEyAKHkMgCh/DIAoe8yAKGrMgChUzIA + oREyAKFBMgCh+zIAoZcyAKEAMgCh/zIAoZcyAKEAMgChBzIAoVAyAKEEMgChQTIAodoyAKEjMgChAAAA + AAAAAAAAMgChADIAoWkyAKH/MgCh/zIAoeEyAKEeMgChAAAAAAAyAKEAMgChBjIAoSAyAKFyMgChwjIA + ofMyAKH4MgCh0zIAobMyAKH9MgChljIAoQAyAKH/MgChlzIAoQAyAKEBMgChBDIAoQAyAKFKMgCh7jIA + oT0yAKEAAAAAADIAoQAyAKEAMgChbDIAof8yAKH/MgCh4TIAoR8yAKEAAAAAAAAAAAAAAAAAMgChADIA + oQEyAKELMgChRzIAoZYyAKHeMgCh/TIAof8yAKGWMgChADIAof8yAKGXMgChAAAAAAAAAAAAMgChADIA + oW0yAKH/MgChZDIAoQAyAKEEMgChHDIAoWAyAKHPMgCh/zIAof8yAKH3MgChkTIAoS8yAKELMgChADIA + oQAAAAAAAAAAAAAAAAAyAKEAMgChATIAoSAyAKF2MgCh/zIAoZYyAKEAMgCh/zIAoZcyAKEAAAAAADIA + oQAyAKEAMgChljIAof8yAKGeMgChOTIAoZEyAKHcMgCh+TIAof8yAKH/MgCh/zIAof8yAKH+MgCh6jIA + obgyAKFXMgChITIAoQEyAKEAAAAAAAAAAAAAAAAAMgChADIAoT8yAKH7MgChlzIAoQAyAKH/MgChlzIA + oQAAAAAAMgChADIAoQwyAKG9MgCh/zIAofMyAKHyMgCh/jIAof8yAKH/MgCh/zIAofoyAKH3MgCh/jIA + of8yAKH/MgCh/zIAofsyAKHbMgChmzIAoUwyAKENMgChATIAoQAyAKEAMgChPzIAofsyAKGXMgChADIA + of8yAKGXMgChATIAoRkyAKFbMgChsTIAofAyAKH/MgCh/zIAof8yAKH/MgCh/DIAoeYyAKGxMgChVTIA + oUIyAKGFMgCh1TIAofUyAKH/MgCh/zIAof8yAKH/MgCh9DIAocUyAKGDMgChMDIAoQYyAKE/MgCh+zIA + oZcyAKEAMgCh/zIAocEyAKGOMgCh2TIAofcyAKH/MgCh/zIAof8yAKH/MgCh7jIAobMyAKFwMgChJjIA + oQoyAKEAMgChADIAoQEyAKEXMgChTTIAoZsyAKHYMgCh/TIAof8yAKH/MgCh/zIAof4yAKHqMgChszIA + oZgyAKH+MgChljIAoQAyAKH/MgCh/zIAof8yAKH/MgCh/zIAof8yAKH0MgChyTIAoYEyAKE/MgChBzIA + oQAAAAAAMgChADIAoSIyAKF2MgChQjIAoRIyAKEAMgChATIAoR4yAKFjMgChrjIAoecyAKH9MgCh/zIA + of8yAKH/MgCh/zIAof8yAKGWMgChADIAof8yAKH/MgCh/zIAofkyAKHWMgChmjIAoUIyAKERMgChATIA + oQAyAKEGMgChFTIAoQMyAKEAMgChKDIAoZUyAKHHMgChxjIAoXcyAKE3MgChBzIAoQAyAKEGMgChKTIA + oXYyAKHDMgCh7jIAof4yAKH/MgCh/zIAoZYyAKEAMgChrjIAoeYyAKH+MgCh0zIAoVcyAKELMgChADIA + oQAyAKEAMgChADIAoVUyAKHAMgChkjIAoVYyAKEUMgChATIAoRYyAKFhMgChqzIAodUyAKGmMgChZTIA + oR8yAKEDMgChBDIAoS0yAKGiMgCh9DIAofUyAKHGMgChWTIAoQAyAKEGMgChKjIAoWsyAKHBMgCh3DIA + ocEyAKFwMgChJTIAoQYyAKEAMgChDDIAoTgyAKF/MgChyjIAocMyAKGUMgChMzIAoQsyAKEEMgChJjIA + oWUyAKG/MgCh0TIAoaYyAKGoMgCh1TIAodYyAKGNMgChQTIAoRAyAKEAMgChAAAAAAAyAKEAMgChADIA + oQ8yAKE8MgChkDIAoc8yAKHfMgChpDIAoVIyAKEcMgChADIAoQEyAKETMgChRzIAoZ8yAKHGMgChvzIA + oWQyAKEtMgChMzIAoY8yAKHvMgCh5zIAoa8yAKFcMgChHDIAoQMyAKEAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAADIAoQAyAKECMgChFTIAoVcyAKGaMgCh3DIAodEyAKGaMgChSDIAoQsyAKEAMgChATIA + oSUyAKGGMgCh6TIAofEyAKHhMgChtzIAoXAyAKErMgChBTIAoQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMgChADIAoQIyAKElMgChXTIAobgyAKHbMgChxTIA + oYUyAKFbMgChqzIAodEyAKHLMgChhDIAoTsyAKELMgChAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAyAKEAMgChCzIA + oTcyAKGTMgCh0zIAofAyAKG2MgChWjIAoRcyAKEBMgChAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAA/+Af//+AB//8AAD/8AAAP8AIAA8AGDABARg+AQEYD4ERGAPxMZgAcTOY + ADEzmDAxM5g8MTKIPzEgCDDxIAgwMSB4MAEgeDgBJHg+ATxAD8E8AAHxOAAAMQAAAAEAAwABABwgAQBE + BAEBwAABAEAAA+AAAA/4AAB//wAD///gD/8= + + + \ No newline at end of file diff --git a/Common/11MonitorForm/SecondFormDelegate.cs b/Common/11MonitorForm/SecondFormDelegate.cs new file mode 100644 index 0000000..434652c --- /dev/null +++ b/Common/11MonitorForm/SecondFormDelegate.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace MisDataName +{ + public delegate void SecondAct(string ControlName); + + public partial class SecondForm + { + public static SecondAct MainMenuRefresh; + + } +} diff --git a/Common/99DataBaseAccess2/Common/dll/DataBaseAccess.dll b/Common/99DataBaseAccess2/Common/dll/DataBaseAccess.dll new file mode 100644 index 0000000..137dc82 Binary files /dev/null and b/Common/99DataBaseAccess2/Common/dll/DataBaseAccess.dll differ diff --git a/Common/99DataBaseAccess2/Common/dll/DataBaseAccess.pdb b/Common/99DataBaseAccess2/Common/dll/DataBaseAccess.pdb new file mode 100644 index 0000000..e9bf580 Binary files /dev/null and b/Common/99DataBaseAccess2/Common/dll/DataBaseAccess.pdb differ diff --git a/Common/99DataBaseAccess2/Common/dll/DoWhatPlc.dll b/Common/99DataBaseAccess2/Common/dll/DoWhatPlc.dll new file mode 100644 index 0000000..34ab0bb Binary files /dev/null and b/Common/99DataBaseAccess2/Common/dll/DoWhatPlc.dll differ diff --git a/Common/99DataBaseAccess2/Common/dll/DoWhatPlc.pdb b/Common/99DataBaseAccess2/Common/dll/DoWhatPlc.pdb new file mode 100644 index 0000000..e75a71b Binary files /dev/null and b/Common/99DataBaseAccess2/Common/dll/DoWhatPlc.pdb differ diff --git a/Common/99DataBaseAccess2/Common/dll/MQTTnet.Extensions.ManagedClient.dll b/Common/99DataBaseAccess2/Common/dll/MQTTnet.Extensions.ManagedClient.dll new file mode 100644 index 0000000..99035f6 Binary files /dev/null and b/Common/99DataBaseAccess2/Common/dll/MQTTnet.Extensions.ManagedClient.dll differ diff --git a/Common/99DataBaseAccess2/Common/dll/MQTTnet.dll b/Common/99DataBaseAccess2/Common/dll/MQTTnet.dll new file mode 100644 index 0000000..2951433 Binary files /dev/null and b/Common/99DataBaseAccess2/Common/dll/MQTTnet.dll differ diff --git a/Common/99DataBaseAccess2/Common/dll/MesWorkMqtt.dll b/Common/99DataBaseAccess2/Common/dll/MesWorkMqtt.dll new file mode 100644 index 0000000..4834574 Binary files /dev/null and b/Common/99DataBaseAccess2/Common/dll/MesWorkMqtt.dll differ diff --git a/Common/99DataBaseAccess2/Common/dll/MesWorkMqtt.pdb b/Common/99DataBaseAccess2/Common/dll/MesWorkMqtt.pdb new file mode 100644 index 0000000..fb10624 Binary files /dev/null and b/Common/99DataBaseAccess2/Common/dll/MesWorkMqtt.pdb differ diff --git a/Common/99DataBaseAccess2/Common/dll/Newtonsoft.Json.dll b/Common/99DataBaseAccess2/Common/dll/Newtonsoft.Json.dll new file mode 100644 index 0000000..597a1ce Binary files /dev/null and b/Common/99DataBaseAccess2/Common/dll/Newtonsoft.Json.dll differ diff --git a/Common/99DataBaseAccess2/Common/dll/WebApiCall.dll b/Common/99DataBaseAccess2/Common/dll/WebApiCall.dll new file mode 100644 index 0000000..a519e2a Binary files /dev/null and b/Common/99DataBaseAccess2/Common/dll/WebApiCall.dll differ diff --git a/Common/99DataBaseAccess2/Common/dll/WebApiCall.dll.config b/Common/99DataBaseAccess2/Common/dll/WebApiCall.dll.config new file mode 100644 index 0000000..6035ea8 --- /dev/null +++ b/Common/99DataBaseAccess2/Common/dll/WebApiCall.dll.config @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/Common/99DataBaseAccess2/Common/dll/WebApiCall.pdb b/Common/99DataBaseAccess2/Common/dll/WebApiCall.pdb new file mode 100644 index 0000000..16b7902 Binary files /dev/null and b/Common/99DataBaseAccess2/Common/dll/WebApiCall.pdb differ diff --git a/Common/99DataBaseAccess2/DataBaseAccess.sln b/Common/99DataBaseAccess2/DataBaseAccess.sln new file mode 100644 index 0000000..87a94f3 --- /dev/null +++ b/Common/99DataBaseAccess2/DataBaseAccess.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.32901.82 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "04-DataBaseAccess", "DataBaseAccess\04-DataBaseAccess.csproj", "{F434E066-4C59-47C8-AA82-6F48CC84501A}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {F434E066-4C59-47C8-AA82-6F48CC84501A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F434E066-4C59-47C8-AA82-6F48CC84501A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F434E066-4C59-47C8-AA82-6F48CC84501A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F434E066-4C59-47C8-AA82-6F48CC84501A}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {CB4AAB51-C433-4A0B-B835-FF7E3CB86238} + EndGlobalSection +EndGlobal diff --git a/Common/99DataBaseAccess2/DataBaseAccess/99-DataBaseAccess2.csproj b/Common/99DataBaseAccess2/DataBaseAccess/99-DataBaseAccess2.csproj new file mode 100644 index 0000000..9616abb --- /dev/null +++ b/Common/99DataBaseAccess2/DataBaseAccess/99-DataBaseAccess2.csproj @@ -0,0 +1,54 @@ + + + + + Debug + AnyCPU + {5C0C572B-F8F1-41DE-B049-4D40AE29CD21} + Library + Properties + DataBaseAccess2 + 99DataBaseAccess2 + v4.8 + 512 + true + + + + true + full + false + ..\..\dll\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Common/99DataBaseAccess2/DataBaseAccess/DataAccess.cs b/Common/99DataBaseAccess2/DataBaseAccess/DataAccess.cs new file mode 100644 index 0000000..77d8a54 --- /dev/null +++ b/Common/99DataBaseAccess2/DataBaseAccess/DataAccess.cs @@ -0,0 +1,611 @@ +using System; +using System.Collections.Generic; +using System.Collections.Specialized; +using System.Configuration; +using System.Data; +using System.Data.SqlClient; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace DataLinkMesWork2 +{ + public class DataAccess2 + { + public static string ConnectionString_MES = ConfigurationManager.AppSettings["ConnectionString_MES"]; + public static bool ExecuteNonQuery(string sql, string connectionString, out string errorMessage) + { + bool result = false; + errorMessage = ""; + using (SqlConnection conn = new SqlConnection(connectionString)) + { + try + { + using (SqlCommand cmd = new SqlCommand(sql, conn)) + { + //if (!SqlServerConnectionStatus) return false; + conn.Open(); + cmd.ExecuteNonQuery(); + } + //SqlServerConnectionStatus = true; + result = true; + } + catch (Exception e) + { + errorMessage = e.ToString(); + //TestConnection(); + //ApplicationLog.WriteLog(e, "\r\nExecuteNonQuery\r\nSQL��䣺\r\n" + sql + "\r\n�����ַ�����\r\n" + connectionString); + } + finally + { + if (conn.State == ConnectionState.Open) + conn.Close(); + } + } + return result; + + } + public static bool ExecuteDataset(string sql, string connectionString, out DataSet ds, out string errorMessage) + { + errorMessage = ""; + bool result = true; + errorMessage = ""; + ds = new DataSet(); + + /// SQLSERVER + /// SQLiteDB + try + { + //bool result = false; + errorMessage = ""; + ds = new DataSet(); + using (SqlConnection conn = new SqlConnection(connectionString)) + { + try + { + //if (!SqlServerConnectionStatus) return false; + conn.Open(); + using (SqlDataAdapter dsCommand = new SqlDataAdapter()) + { + dsCommand.SelectCommand = new SqlCommand(sql, conn); + dsCommand.Fill(ds); + } + //SqlServerConnectionStatus = true; + result = true; + } + catch (Exception e) + { + errorMessage = e.ToString(); + //TestConnection(); + //ApplicationLog.WriteLog(e, "\r\nExecuteNonQuery\r\nSQL��䣺\r\n" + sql + "\r\n�����ַ�����\r\n" + connectionString); + } + finally + { + if (conn.State == ConnectionState.Open) + conn.Close(); + } + } + return result; + } + catch (Exception err) + { + + } + + return result; + + + } + /// + /// 增 删 改 + /// + /// + /// + /// + public static bool ExecuteStoredProcedure(string procedureName, ref SqlParameter[] sqlParameters) + { + string connectionString = ConnectionString_MES; + string errorMessage; + bool result = false; + errorMessage = ""; + using (SqlConnection conn = new SqlConnection(connectionString)) + { + try + { + //if (!SqlServerConnectionStatus) return false; + conn.Open(); + using (SqlCommand cmd = new SqlCommand(procedureName, conn)) + { + cmd.CommandTimeout = 0; + cmd.CommandType = CommandType.StoredProcedure; + if (sqlParameters != null) + { + for (int i = 0; i < sqlParameters.Length; i++) + { + cmd.Parameters.Add(sqlParameters[i]); + } + } + cmd.ExecuteNonQuery(); + } + //SqlServerConnectionStatus = true; + result = true; + } + catch (Exception e) + { + errorMessage = e.ToString(); + if (conn.State == ConnectionState.Open) + conn.Close(); + //TestConnection(); + ////ApplicationLog.WriteLog(e, "\r\nExecuteStoredProcedure\r\n�洢���̣�\r\n" + procedureName + "\r\n�����ַ�����\r\n" + connectionString); + } + finally + { + if (conn.State == ConnectionState.Open) + conn.Close(); + } + } + return result; + } + public static bool ExecuteStoredProcedure(string procedureName, ref SqlParameter[] sqlParameters,out DataTable dt) + { + string connectionString = ConnectionString_MES; + string errorMessage; + bool result = false; + errorMessage = ""; + //ds = new DataSet(); + dt = new DataTable(); + using (SqlConnection conn = new SqlConnection(connectionString)) + { + try + { + //if (!SqlServerConnectionStatus) return false; + conn.Open(); + using (SqlDataAdapter dsCommand = new SqlDataAdapter()) + { + dsCommand.SelectCommand = new SqlCommand(procedureName, conn); + dsCommand.SelectCommand.CommandType = CommandType.StoredProcedure; + dsCommand.SelectCommand.CommandTimeout = 0; + if (sqlParameters != null) + { + for (int i = 0; i < sqlParameters.Length; i++) + { + dsCommand.SelectCommand.Parameters.Add(sqlParameters[i]); + } + } + + dsCommand.Fill(dt); + } + //SqlServerConnectionStatus = true; + result = true; + } + catch (Exception e) + { + errorMessage = e.ToString(); + //TestConnection(); + ////ApplicationLog.WriteLog(e, "\r\nExecuteStoredProcedure\r\n�洢���̣�\r\n" + procedureName + "\r\n�����ַ�����\r\n" + connectionString); + } + finally + { + if (conn.State == ConnectionState.Open) + conn.Close(); + } + } + return result; + } + public static bool ExecuteStoredProcedure(string procedureName, ref SqlParameter[] sqlParameters, out DataSet ds) + { + string connectionString = ConnectionString_MES; + string errorMessage; + bool result = false; + errorMessage = ""; + ds = new DataSet(); + using (SqlConnection conn = new SqlConnection(connectionString)) + { + try + { + //if (!SqlServerConnectionStatus) return false; + conn.Open(); + using (SqlDataAdapter dsCommand = new SqlDataAdapter()) + { + dsCommand.SelectCommand = new SqlCommand(procedureName, conn); + dsCommand.SelectCommand.CommandType = CommandType.StoredProcedure; + dsCommand.SelectCommand.CommandTimeout = 0; + if (sqlParameters != null) + { + for (int i = 0; i < sqlParameters.Length; i++) + { + dsCommand.SelectCommand.Parameters.Add(sqlParameters[i]); + } + } + + dsCommand.Fill(ds); + } + //SqlServerConnectionStatus = true; + result = true; + } + catch (Exception e) + { + errorMessage = e.ToString(); + //TestConnection(); + ////ApplicationLog.WriteLog(e, "\r\nExecuteStoredProcedure\r\n�洢���̣�\r\n" + procedureName + "\r\n�����ַ�����\r\n" + connectionString); + } + finally + { + if (conn.State == ConnectionState.Open) + conn.Close(); + } + } + return result; + } + public static bool ExecuteDataset(string sql, out DataSet ds) + { + string errorMessage; + string connectionString = ConnectionString_MES; + bool result = false; + errorMessage = ""; + ds = new DataSet(); + using (SqlConnection conn = new SqlConnection(connectionString)) + { + try + { + //if (!SqlServerConnectionStatus) return false; + conn.Open(); + using (SqlDataAdapter dsCommand = new SqlDataAdapter()) + { + dsCommand.SelectCommand = new SqlCommand(sql, conn); + dsCommand.Fill(ds); + } + //SqlServerConnectionStatus = true; + result = true; + } + catch (Exception e) + { + errorMessage = e.ToString(); + //TestConnection(); + ////ApplicationLog.WriteLog(e, "\r\nExecuteNonQuery\r\nSQL��䣺\r\n" + sql + "\r\n�����ַ�����\r\n" + connectionString); + } + finally + { + if (conn.State == ConnectionState.Open) + conn.Close(); + } + } + return result; + } + + public static bool ExecuteDataTable(string sql, out DataTable dt) + { + //public static bool ExecuteDataTable(string sql, string connectionString, out DataTable dt, out string errorMessage) + string errorMessage; + string connectionString = ConnectionString_MES; + bool result = false; + errorMessage = ""; + dt = new DataTable(); + using (SqlConnection conn = new SqlConnection(connectionString)) + { + try + { + //if (!SqlServerConnectionStatus) return false; + conn.Open(); + using (SqlDataAdapter dsCommand = new SqlDataAdapter()) + { + dsCommand.SelectCommand = new SqlCommand(sql, conn); + dsCommand.Fill(dt); + } + //SqlServerConnectionStatus = true; + result = true; + } + catch (Exception e) + { + errorMessage = e.ToString(); + //TestConnection(); + ////ApplicationLog.WriteLog(e, "\r\nExecuteNonQuery\r\nSQL��䣺\r\n" + sql + "\r\n�����ַ�����\r\n" + connectionString); + } + finally + { + if (conn.State == ConnectionState.Open) + conn.Close(); + } + } + return result; + } + + public static DataTable ExecuteSQL(string sql, ref SqlParameter[] sqlParameters) + { + string connectionString = ConnectionString_MES; + string err; + bool result = false; + err = ""; + DataTable dt = new DataTable(); + using (SqlConnection conn = new SqlConnection(connectionString)) + { + try + { + //if (!SqlServerConnectionStatus) return false; + conn.Open(); + using (SqlDataAdapter dsCommand = new SqlDataAdapter(sql, conn)) + { + if (sqlParameters != null) + { + for (int i = 0; i < sqlParameters.Length; i++) + { + dsCommand.SelectCommand.Parameters.Add(sqlParameters[i]); + } + } + dsCommand.Fill(dt); + } + result = true; + } + catch (Exception e) + { + err = e.ToString(); + ////ApplicationLog.WriteLog(e, "\r\nExecuteSelectMesWork\r\n" + sql + "\r\n" + connectionString); + } + finally + { + if (conn.State == ConnectionState.Open) + conn.Close(); + } + } + return dt; + } + + public static bool ExecuteSQL(string sql) + { + string connectionString = ConnectionString_MES; + string errorMessage; + bool result = false; + errorMessage = ""; + using (SqlConnection conn = new SqlConnection(connectionString)) + { + try + { + using (SqlCommand cmd = new SqlCommand(sql, conn)) + { + //if (!SqlServerConnectionStatus) return false; + conn.Open(); + cmd.ExecuteNonQuery(); + } + //SqlServerConnectionStatus = true; + result = true; + } + catch (Exception e) + { + errorMessage = e.ToString(); + //TestConnection(); + ////ApplicationLog.WriteLog(e, "\r\nExecuteNonQuery\r\nSQL��䣺\r\n" + sql + "\r\n�����ַ�����\r\n" + connectionString); + } + finally + { + if (conn.State == ConnectionState.Open) + conn.Close(); + } + } + return result; + } + + /// + /// 提供通用的调用存储过程的方法(增加数据的数据表的到数据库的调用) + /// + /// 存储过程名称 + /// 存储过程参数数组 + /// 增加数据的数据表 + /// + public static bool ExecuteStoredProcedure(string procedureName, ref SqlParameter[] sqlParameters, DataTable dt) + { + string connectionString = ConnectionString_MES; + string errorMessage; + bool result = false; + errorMessage = ""; + using (SqlConnection conn = new SqlConnection(connectionString)) + { + try + { + // if (!SqlServerConnectionStatus) return false; + conn.Open(); + using (SqlDataAdapter dsCommand = new SqlDataAdapter()) + { + dsCommand.InsertCommand = new SqlCommand(procedureName, conn); + dsCommand.InsertCommand.CommandType = CommandType.StoredProcedure; + for (int i = 0; i < sqlParameters.Length; i++) + { + dsCommand.InsertCommand.Parameters.Add(sqlParameters[i]); + } + if (dt == null) return false; + dt.AcceptChanges(); + for (int i = 0; i < dt.Rows.Count; i++) + { + dt.Rows[i].SetAdded(); + } + dsCommand.Update(dt); + } + //SqlServerConnectionStatus = true; + result = true; + } + catch (Exception e) + { + errorMessage = e.ToString(); + //TestConnection(); + ////ApplicationLog.WriteLog(e, "\r\nExecuteStoredProcedure\r\n�洢���̣�\r\n" + procedureName + "\r\n�����ַ�����\r\n" + connectionString); + } + finally + { + if (conn.State == ConnectionState.Open) + conn.Close(); + } + } + return result; + } + + /// + /// 提供通用的调用存储过程的方法(增加数据的数据表的到数据库的调用) + /// + /// + /// + /// + public static bool ExecuteStoredProcedure(string procedureName, out DataTable dt) + { + string connectionString = ConnectionString_MES; + string errorMessage; + bool result = false; + errorMessage = ""; + dt = new DataTable(); + using (SqlConnection conn = new SqlConnection(connectionString)) + { + try + { + + //if (!SqlServerConnectionStatus) return false; + conn.Open(); + using (SqlDataAdapter dsCommand = new SqlDataAdapter()) + { + dsCommand.SelectCommand = new SqlCommand(procedureName, conn); + dsCommand.SelectCommand.CommandType = CommandType.StoredProcedure; + + dsCommand.Fill(dt); + } + //SqlServerConnectionStatus = true; + result = true; + } + catch (Exception e) + { + errorMessage = e.ToString(); + //TestConnection(); + ////ApplicationLog.WriteLog(e, "\r\nExecuteStoredProcedure\r\n�洢���̣�\r\n" + procedureName + "\r\n�����ַ�����\r\n" + connectionString); + } + finally + { + if (conn.State == ConnectionState.Open) + conn.Close(); + } + } + return result; + } + + /// + /// + /// + /// + /// + /// + /// + public static bool ExecuteSQL(string sql, ref SqlParameter[] sqlParameters, DataTable dt) + { + string connectionString = ConnectionString_MES; + string errorMessage; + bool result = false; + errorMessage = ""; + using (SqlConnection conn = new SqlConnection(connectionString)) + { + + + try + { + // if (!SqlServerConnectionStatus) return false; + conn.Open(); + using (SqlDataAdapter dsCommand = new SqlDataAdapter()) + { + dsCommand.InsertCommand = new SqlCommand(sql, conn); + + for (int i = 0; i < sqlParameters.Length; i++) + { + sqlParameters[i].IsNullable = true; + dsCommand.InsertCommand.Parameters.Add(sqlParameters[i]); + } + if (dt == null) return false; + dt.AcceptChanges(); + for (int i = 0; i < dt.Rows.Count; i++) + { + dt.Rows[i].SetAdded(); + } + dsCommand.Update(dt); + } + //SqlServerConnectionStatus = true; + result = true; + } + catch (Exception e) + { + //ApplicationConfig.ConnectionStringPIS_NEW_Value = "0"; + //TestConnection(); + //errorMessage = e.ToString(); + ////ApplicationLog.WriteLog(e, "\r\nExecuteSQL\r\nSQL��䣺\r\n" + sql + "\r\n�����ַ�����\r\n" + connectionString); + } + finally + { + if (conn.State == ConnectionState.Open) + conn.Close(); + } + } + return result; + } + + public static bool ExecuteNonQuery_newID(string sql, out long newID) + { + sql += ";select @@identity"; + string connectionString; + connectionString = ConnectionString_MES; + using (SqlConnection conn = new SqlConnection(connectionString)) + { + try + { + using (SqlCommand cmd = new SqlCommand(sql, conn)) + { + conn.Open(); + newID = Convert.ToInt64(cmd.ExecuteScalar()); + } + return true; + } + catch (Exception e) + { + newID = 0; + //TestConnection(); + ////ApplicationLog.WriteLog(e, "\r\n ExecuteNonQuery_newID\r\n�洢���̣�\r\n" + sql + "\r\n�����ַ�����\r\n" + connectionString); + return false; + } + finally + { + if (conn.State == ConnectionState.Open) + conn.Close(); + } + } + } + + public static bool ExecuteOutNum(string sql, out int count) + { + string connectionString; + connectionString = ConnectionString_MES; + string errorMessage; + bool result = false; + errorMessage = ""; + using (SqlConnection conn = new SqlConnection(connectionString)) + { + count = 0; + try + { + using (SqlCommand cmd = new SqlCommand(sql, conn)) + { + //if (!SqlServerConnectionStatus) return false; + conn.Open(); + count = Convert.ToInt32(cmd.ExecuteScalar().ToString()); + } + //SqlServerConnectionStatus = true; + result = true; + } + catch (Exception e) + { + errorMessage = e.ToString(); + //TestConnection(); + ////ApplicationLog.WriteLog(e, "\r\nExecuteNonQuery\r\nSQL��䣺\r\n" + sql + "\r\n�����ַ�����\r\n" + connectionString); + } + finally + { + if (conn.State == ConnectionState.Open) + conn.Close(); + } + } + return result; + } + } + + +} diff --git a/Common/99DataBaseAccess2/DataBaseAccess/JsonHelper.cs b/Common/99DataBaseAccess2/DataBaseAccess/JsonHelper.cs new file mode 100644 index 0000000..5ec9f9c --- /dev/null +++ b/Common/99DataBaseAccess2/DataBaseAccess/JsonHelper.cs @@ -0,0 +1,336 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Data; +using System.Runtime.Serialization.Json; +using System.Web.Script.Serialization; +//using System.Runtime.Serialization.Json; + +//using System.Runtime.Serialization.Json; + +public class JsonHelper +{ + #region 序列化和反序列化 + // 序列化 + public static string JsonSerializer(T t) + { + // 使用 DataContractJsonSerializer 将 T 对象序列化为内存流。 + DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(T)); + MemoryStream ms = new MemoryStream(); + // 使用 WriteObject 方法将 JSON 数据写入到流中。 + jsonSerializer.WriteObject(ms, t); + // 流转字符串 + string jsonString = Encoding.UTF8.GetString(ms.ToArray()); + ms.Close(); + //替换Json的Date字符串 + string p = @"\\/Date\((\d+)\+\d+\)\\/"; + MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertJsonDateToDateString); + Regex reg = new Regex(p); + jsonString = reg.Replace(jsonString, matchEvaluator); + return jsonString; + } + public static T JsonDeserialize(string jsonString) + { + //将"yyyy-MM-dd HH:mm:ss"格式的字符串转为"\/Date(1294499956278+0800)\/"格式 + string p = @"\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}"; + MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertDateStringToJsonDate); + Regex reg = new Regex(p); + jsonString = reg.Replace(jsonString, matchEvaluator); + DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(T)); + // 字符串转流 + MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)); + // 通过使用 DataContractJsonSerializer 的 ReadObject 方法,将 JSON 编码数据反序列化为T + T obj = (T)jsonSerializer.ReadObject(ms); + return obj; + } + public static string ConvertJsonDateToDateString(Match match) + { + string result = string.Empty; + DateTime dateTime = new DateTime(1970, 1, 1); + dateTime = dateTime.AddMilliseconds(long.Parse(match.Groups[1].Value)); + dateTime = dateTime.ToLocalTime(); + result = dateTime.ToString("yyyy-MM-dd HH:mm:ss"); + return result; + } + private static string ConvertDateStringToJsonDate(Match m) + { + string result = string.Empty; + DateTime dt = DateTime.Parse(m.Groups[0].Value); + dt = dt.ToUniversalTime(); + TimeSpan ts = dt - DateTime.Parse("1970-01-01"); + result = string.Format("\\/Date({0}+0800)\\/", ts.TotalMilliseconds); + return result; + } + #endregion + + // 对象转换为Json + public static string ObjectToJson(object obj) + { + JavaScriptSerializer js = new JavaScriptSerializer(); + js.MaxJsonLength = Int32.MaxValue; // 定义JavaScriptSerializer接受字符串的最大长度 hdk 20180524 + try + { + return js.Serialize(obj); + } + catch (Exception exception) + { + + throw new Exception(exception.Message); + } + } + // 数据表转化为集合 + public static List> DataTableToList(DataTable dt) + { + List> list = new List>(); + foreach (DataRow dataRow in dt.Rows) + { + Dictionary dic = new Dictionary(); + + + foreach (DataColumn dc in dt.Columns) + { + if (dataRow[dc.ColumnName].GetType() == typeof(DateTime)) + { + string str = Convert.ToDateTime(dataRow[dc.ColumnName]).ToString("yyyy-MM-dd HH:mm:ss"); + dic.Add(dc.ColumnName, str); + } + else if + (dataRow[dc.ColumnName].GetType() == typeof(byte[])) + { + string str = Convert.ToBase64String((byte[])dataRow[dc.ColumnName]); + dic.Add(dc.ColumnName, str); + } + else + { + dic.Add(dc.ColumnName, dataRow[dc.ColumnName]); + } + + //Type type1 = dt.Rows[0]["产品图片"].GetType(); + //Type type2 = typeof(byte[]); + + } + list.Add(dic); + } + return list; + } + /// + /// 表转换为Json + /// + /// + /// + public static string DataTableToJson(DataTable dt) + { + return ObjectToJson(DataTableToList(dt)); + } + /// + /// 将DataTable中的数据转换成JSON格式 + /// + /// 数据源DataTable + /// 是否输出数据总条数 + /// JSON中显示的数据总条数 + /// + public static string CreateJsonParameters(DataTable dt, bool displayCount, int totalcount) + { + StringBuilder JsonString = new StringBuilder(); + //Exception Handling + + if (dt != null) + { + JsonString.Append("{ "); + JsonString.Append("\"rows\":[ "); + for (int i = 0; i < dt.Rows.Count; i++) + { + JsonString.Append("{ "); + for (int j = 0; j < dt.Columns.Count; j++) + { + if (j < dt.Columns.Count - 1) + { + //if (dt.Rows[i][j] == DBNull.Value) continue; + if (dt.Columns[j].DataType == typeof(bool)) + { + JsonString.Append("\"" + dt.Columns[j].ColumnName.ToLower() + "\":" + + dt.Rows[i][j].ToString().ToLower() + ","); + } + else if (dt.Columns[j].DataType == typeof(string)) + { + JsonString.Append("\"" + dt.Columns[j].ColumnName.ToLower() + "\":" + + ObjectToJson(dt.Rows[i][j]).ToString() + ","); + //JsonString.Append("\"" + dt.Columns[j].ColumnName.ToLower() + "\":" + "\"" + + // dt.Rows[i][j].ToString().Replace("\"", "\\\"") + "\","); + } + else + { + JsonString.Append("\"" + dt.Columns[j].ColumnName.ToLower() + "\":" + "\"" + dt.Rows[i][j] + "\","); + } + } + else if (j == dt.Columns.Count - 1) + { + //if (dt.Rows[i][j] == DBNull.Value) continue; + if (dt.Columns[j].DataType == typeof(bool)) + { + JsonString.Append("\"" + dt.Columns[j].ColumnName.ToLower() + "\":" + + dt.Rows[i][j].ToString().ToLower()); + } + else if (dt.Columns[j].DataType == typeof(string)) + { + JsonString.Append("\"" + dt.Columns[j].ColumnName.ToLower() + "\":" + + ObjectToJson(dt.Rows[i][j]).ToString()); + //JsonString.Append("\"" + dt.Columns[j].ColumnName.ToLower() + "\":" + "\"" + + // dt.Rows[i][j].ToString().Replace("\"", "\\\"") + "\""); + } + else + { + JsonString.Append("\"" + dt.Columns[j].ColumnName.ToLower() + "\":" + "\"" + dt.Rows[i][j] + "\""); + } + } + } + /*end Of String*/ + if (i == dt.Rows.Count - 1) + { + JsonString.Append("} "); + } + else + { + JsonString.Append("}, "); + } + } + JsonString.Append("]"); + + if (displayCount) + { + JsonString.Append(","); + + JsonString.Append("\"total\":"); + JsonString.Append(totalcount); + } + + JsonString.Append("}"); + return JsonString.ToString().Replace("\n", ""); + } + else + { + return null; + } + } + public static string CreateJsonParameters(DataTable dt) + { + StringBuilder JsonString = new StringBuilder(); + //Exception Handling + + if (dt != null) + { + JsonString.Append("{ "); + JsonString.Append("\"rows\":[ "); + for (int i = 0; i < dt.Rows.Count; i++) + { + JsonString.Append("{ "); + for (int j = 0; j < dt.Columns.Count; j++) + { + if (j < dt.Columns.Count - 1) + { + //if (dt.Rows[i][j] == DBNull.Value) continue; + if (dt.Columns[j].DataType == typeof(bool)) + { + JsonString.Append("\"" + dt.Columns[j].ColumnName.ToLower() + "\":" + + dt.Rows[i][j].ToString().ToLower() + ","); + } + else if (dt.Columns[j].DataType == typeof(string)) + { + JsonString.Append("\"" + dt.Columns[j].ColumnName.ToLower() + "\":" + + ObjectToJson(dt.Rows[i][j]).ToString() + ","); + //JsonString.Append("\"" + dt.Columns[j].ColumnName.ToLower() + "\":" + "\"" + + // dt.Rows[i][j].ToString().Replace("\"", "\\\"") + "\","); + } + else + { + JsonString.Append("\"" + dt.Columns[j].ColumnName.ToLower() + "\":" + "\"" + dt.Rows[i][j] + "\","); + } + } + else if (j == dt.Columns.Count - 1) + { + //if (dt.Rows[i][j] == DBNull.Value) continue; + if (dt.Columns[j].DataType == typeof(bool)) + { + JsonString.Append("\"" + dt.Columns[j].ColumnName.ToLower() + "\":" + + dt.Rows[i][j].ToString().ToLower()); + } + else if (dt.Columns[j].DataType == typeof(string)) + { + JsonString.Append("\"" + dt.Columns[j].ColumnName.ToLower() + "\":" + + ObjectToJson(dt.Rows[i][j]).ToString()); + //JsonString.Append("\"" + dt.Columns[j].ColumnName.ToLower() + "\":" + "\"" + + // dt.Rows[i][j].ToString().Replace("\"", "\\\"") + "\""); + } + else + { + JsonString.Append("\"" + dt.Columns[j].ColumnName.ToLower() + "\":" + "\"" + dt.Rows[i][j] + "\""); + } + } + } + /*end Of String*/ + if (i == dt.Rows.Count - 1) + { + JsonString.Append("} "); + } + else + { + JsonString.Append("}, "); + } + } + JsonString.Append("]"); + + JsonString.Append("}"); + return JsonString.ToString().Replace("\n", ""); + } + else + { + return null; + } + } + StringBuilder result = new StringBuilder(); + StringBuilder sb = new StringBuilder(); + /// + /// 根据DataTable生成EasyUI Tree Json树结构 + /// + /// 数据源 + /// ID列 + /// Text列 + /// 节点Url + /// 关系字段 + /// 父ID + public string GetTreeJsonByTable(DataTable tabel, string idCol, string txtCol, string url, string rela, object pId) + { + result.Append(sb.ToString()); + sb.Clear(); + if (tabel.Rows.Count > 0) + { + sb.Append("["); + string filer = string.Format("{0}='{1}'", rela, pId); + DataRow[] rows = tabel.Select(filer); + if (rows.Length > 0) + { + foreach (DataRow row in rows) + { + sb.Append("{\"id\":\"" + row[idCol] + "\",\"text\":\"" + row[txtCol] + "\",\"attributes\":\"" + row[url] + "\",\"state\":\"open\""); + if (tabel.Select(string.Format("{0}='{1}'", rela, row[idCol])).Length > 0) + { + sb.Append(",\"children\":"); + GetTreeJsonByTable(tabel, idCol, txtCol, url, rela, row[idCol]); + result.Append(sb.ToString()); + sb.Clear(); + } + result.Append(sb.ToString()); + sb.Clear(); + sb.Append("},"); + } + sb = sb.Remove(sb.Length - 1, 1); + } + sb.Append("]"); + result.Append(sb.ToString()); + sb.Clear(); + } + return result.ToString(); + } +} \ No newline at end of file diff --git a/Common/99DataBaseAccess2/DataBaseAccess/Properties/AssemblyInfo.cs b/Common/99DataBaseAccess2/DataBaseAccess/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..34eb61c --- /dev/null +++ b/Common/99DataBaseAccess2/DataBaseAccess/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// 有关程序集的一般信息由以下 +// 控制。更改这些特性值可修改 +// 与程序集关联的信息。 +[assembly: AssemblyTitle("DataBaseAccess")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("DataBaseAccess")] +[assembly: AssemblyCopyright("Copyright © 2022")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// 将 ComVisible 设置为 false 会使此程序集中的类型 +//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型 +//请将此类型的 ComVisible 特性设置为 true。 +[assembly: ComVisible(false)] + +// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID +[assembly: Guid("f434e066-4c59-47c8-aa82-6f48cc84501a")] + +// 程序集的版本信息由下列四个值组成: +// +// 主版本 +// 次版本 +// 生成号 +// 修订号 +// +//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值 +//通过使用 "*",如下所示: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Common/DoWhatPlc/01_01DoWhatPlc.csproj b/Common/DoWhatPlc/01_01DoWhatPlc.csproj new file mode 100644 index 0000000..afaaaf8 --- /dev/null +++ b/Common/DoWhatPlc/01_01DoWhatPlc.csproj @@ -0,0 +1,56 @@ + + + + + Debug + AnyCPU + {0D1AF432-439A-4920-8692-43AE139F5530} + Library + Properties + DoWhatPlc + DoWhatPlc + v4.5.1 + 512 + true + + + + true + full + false + ..\WebApiDll\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + ..\MisData_3.0_2022.08.23.1622.LLX\packages\Newtonsoft.Json.13.0.1\lib\net45\Newtonsoft.Json.dll + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Common/DoWhatPlc/DoWhat.cs b/Common/DoWhatPlc/DoWhat.cs new file mode 100644 index 0000000..56a40a0 --- /dev/null +++ b/Common/DoWhatPlc/DoWhat.cs @@ -0,0 +1,1299 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Data; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + + +namespace DoWhatPlc +{ + public class EngineValue + { + public string OpName { set; get; } + public string EngineID { set; get; } + public string EngineType { set; get; } + public int EngineTypeID { set; get; } + public int PalletCode { set; get; } + public int ProcessCode { set; get; } + public int PartPalletCode { set; get; } + public string PalletInfo { set; get; } + /// + /// 显示返修标志 + /// + public int RepairPartStatusPLC { set; get; } + /// + /// 1 合格;2 不合格 + /// + public int QualityMask { set; get; } + + public string OrderForm { set; get; } + } + public class DoWhat + { + public const string ReadPLC_TagID = "ReadPLC_TagID"; + public const string WritePLC_TagID = "WritePLC_TagID"; + public const string ReadPLC_TagTypeCodeID = "ReadPLC_TagTypeCodeID"; + public const string WritePLC_TagTypeCodeID = "WritePLC_TagTypeCodeID"; + public const string ReadPLC_Cmd = "ReadPLC_Cmd"; + public const string WritePLC_Cmd = "WritePLC_Cmd"; + public const string ReadPLC_GroupData = "ReadPLC_GroupData"; + public const string ReadPLC_GroupMonitor = "ReadPLC_GroupMonitor"; + public const string ReadPLC_IpTag = "ReadPLC_IpTag"; + public const string ReadPLC_IpMonitorTag = "ReadPLC_IpMonitorTag"; + public const string ReadQualityDataList = "ReadQualityDataList"; + public const string ReadByteData_Op = "ReadByteData_Op"; + public const string ReadByteData_Ip = "ReadByteData_Ip"; + public const string WritePLC_Bytes_Op = "WritePLC_Bytes_Op"; + public const string WritePLC_Bytes_Ip = "WritePLC_Bytes_Ip"; + public const string IpAllTag = "IpAllTag"; + public const string IpMonitorTag = "IpMonitorTag"; + public const string RegionRead = "RegionRead"; + public const string ReadBytes = "ReadBytes"; + public const string WriteBytes = "WriteBytes"; + } + /// + /// object 类型数据转换成字符串变量表达 + /// + public class ReturnValueString + { + public string TagID { set; get; } + public string TagValue { set; get; } + public string ValueType { set; get; } + public string OpName { set; get; } + public string TimeStamp { set; get; } + public string TagTypeCodeID { set; get; } + public string TagTypeID { set; get; } + /// + /// 测量项目 TEXT2 报警的 工步内容 + /// + public string ItemName { set; get; } + /// + /// 测量位置 TEXT1 报警的 工步号 + /// + public string ShaftID { set; get; } + /// + /// 列位置 工步 工位工步分类 + /// + public string TagOrderBy { set; get; } + + + public string TagValueBefore { get; set; } + public string TimeStampBefore { get; set; } + public string TagName { get; set; } + + + /// + /// 变量变化的持续时间,单位 毫秒 + /// + public string TagKeepTime; + public string FunName; + public string FunCmd; + public string MesServerCode; + public string CmdPlcReadWrite; + public ReturnValueString() + { + + } + public ReturnValueString(string tagID, object tagValue, string opName = "", string tagTypeCodeID = "", string tagTypeID = "", string tagKeepTime = "", + string funName = "", string funCmd = "", string mesServerCode = "", string timeStamp = "", + string timeStampBefore = "", string tagValueBefore = "", string tagName = "",string itemName="", + string shaftID = "", string tagOrderBy = "") + { + TagTypeCodeID = tagTypeCodeID; + TagTypeID = tagTypeID; + TagValue = tagValue.ToString(); + ValueType = tagValue.GetType().Name; + TagID = tagID; + OpName = opName; + TagKeepTime = tagKeepTime; + FunName = funName; + FunCmd = funCmd; + MesServerCode = mesServerCode; + TimeStamp = timeStamp; + TimeStampBefore = timeStampBefore; + TagName = tagName; + TagValueBefore = tagValueBefore; + ItemName = itemName; + ShaftID = shaftID; + TagOrderBy = tagOrderBy; + } + + public ReturnValueObject ReturnValueToObject() + { + ReturnValueObject ro = new ReturnValueObject(TagID, TagValue, OpName, TagTypeCodeID, ValueType, TimeStamp, TimeStampBefore, TagValueBefore, TagName, ItemName, ShaftID); + + return ro; + } + + } + /// + /// 字符串变量转变成object类型变量 + /// + public class ReturnValueObject + { + public string TagID { set; get; } + public object TagValue { set; get; } + public string ValueType { set; get; } + public string OpName { set; get; } + public DateTime TimeStamp { set; get; } + public string TagTypeCodeID { set; get; } + /// + /// 变量变化的持续时间,单位 毫秒 + /// + public int TagKeepTime; + + public object TagValueBefore { get; set; } + public DateTime TimeStampBefore { get; set; } + public string TagName { get; set; } + public string ItemName { set; get; } + public string ShaftID { set; get; } + public string TagOrderBy { set; get; } + public ReturnValueObject(string tagID, string tagValue, string opName = "", string tagTypeCodeID = "", string valueType = "", + string timeStamp = "", string timeStampBefore = "", string tagValueBefore = "", + string tagName = "", string itemName = "", string shaftID = "", string tagOrderBy = "") + { + TagValue = GetTypeValue(valueType, tagValue); + if (tagValueBefore != null) + { + TagValueBefore = GetTypeValue(valueType, tagValueBefore); + } + ValueType = valueType; + TagID = tagID; + OpName = opName; + try + { + TimeStamp = Convert.ToDateTime(timeStamp); + } + catch + { + TimeStamp = DateTime.Now; + + } + try + { + TimeStampBefore = Convert.ToDateTime(timeStampBefore); + } + catch + { + TimeStampBefore = DateTime.Now; + + } + TagTypeCodeID = tagTypeCodeID; + TagName = tagName; + ItemName = itemName; + ShaftID = shaftID; + TagOrderBy = tagOrderBy; + + } + + + public ReturnValueString ReturnValueToString() + { + ReturnValueString rs = new ReturnValueString(TagID, TagValue, OpName, TagTypeCodeID); + return rs; + } + public static object GetTypeValue(string type, string tagValue) + { + object tagV = "-1"; + if (type == null) + { + tagV = tagValue; + } + switch (type.ToLower()) + { + case "bool": + case "boolean": + tagV = false; + switch (tagValue.ToLower()) + { + case "1": + case "true": + tagV = true; + break; + case "0": + case "false": + tagV = false; + break; + } + return tagV; + //return Type.GetType(" System.Boolean ", true, true); + case "byte ": + return Convert.ToByte(tagValue); + case "sbyte": + return Convert.ToSByte(tagValue); + case "char": + return Convert.ToChar(tagValue); + case "decimal": + return Convert.ToDecimal(tagValue); + case "double": + return Convert.ToDouble(tagValue); + case "float": + return Convert.ToSingle(tagValue); + case "int": + return Convert.ToInt32(tagValue); + case "int16": + return Convert.ToInt32(tagValue); + case "uint": + return Convert.ToUInt32(tagValue); + case "long": + return Convert.ToInt64(tagValue); + case "ulong": + return Convert.ToUInt64(tagValue); + case "object": + return tagValue; + case "short": + return Convert.ToInt16(tagValue); + case "ushort": + return Convert.ToUInt16(tagValue); + case "string": + return tagValue; + case "date": + case "datetime": + return Convert.ToDateTime(tagValue); + case "guid": + return tagValue; + default: + return tagValue; + } + } + + + } + + public class TagIDTagFormat + { + public string TagID; + public TagFormat TF; + + public TagIDTagFormat(string tagID, TagFormat tF) + { + TagID = tagID; + TF = tF; + } + } + + + public class QualityDataSaveList + { + public Hashtable valuList; + public DataTable BasicDataTagValue; + public DataTable BasicDataTagValueUpDown; + public Hashtable hashtable_EngineTypeID; + public Hashtable hashtable_tagTable_OpName_SaveData; + } + + + + public struct ControlData + { + public int TagType; + public string opName; + public Control btn; public ControlData(Control Ctrl, string OpName) + { + string[] Array_NameSplit; + Array_NameSplit = Ctrl.Name.Split('_'); + TagType = Convert.ToInt32(Array_NameSplit[2]); + opName = OpName; + btn = Ctrl; + + } + } + public struct ControlChangeByTagType + { + public ControlChangeByTagType(int tagType, string value) + { + TagType = tagType; + Value = value; + } + + public int TagType; + public string Value; + } + /// + /// tag格式化结构 + /// + public struct TagFormat + { + /// + /// TagID + /// + public string TagID; + /// + /// TagID + /// + public string TagName; + /// + /// 工位号 + /// + public string OpName; + /// + /// 数据来源 + /// + public string DataSources; + /// + /// IP + /// + public string IP; + /// + /// OPC的URL + /// + public string OpcIpPort; + /// + /// 组 + /// + public string Group; + /// + /// 监控时间间隔 + /// + public string MonitorInterval; + /// + /// DB号加起始地址,DB1001.30 + /// + public string TagDbAndStartAdr; + /// + /// DB号加起始地址,DB1001.30.1,为了bool写入专用 + /// + public string TagDbAndStartAdrWrite; + /// + /// OPC协议地址 + /// 例如:S7:[192.168.1.211|VFD1|S7ONLINE|01.00,192.168.1.211,02.02,1]DB1001,DINT154 + /// + public string TagOPCAdrStr; + /// + /// DB地址位置 + /// 变量起始地址,例如 0,1,2,56,80... + /// + public int Index; + /// + /// 变量字节长度 + /// 变量字节长度,l例如 1,2,4... + /// + public int Length; + /// + /// X 0,1,2,3,4,5,6,7 + /// 例如 X 0,1,2,3,4,5,6,7 + /// + public int BitIndex; + /// + /// 以连续Byte数组方式读取的DB地址实际位置 + /// 变量起始地址,例如 0,1,2,56,80... + /// + public int IndexBytes; + /// + /// 绝对地址差分,应用区域读取的拆分20200101_LLX + /// + public int AbsAddrDiff; + + + + /// + /// 点类型代码 + /// 比如bool是11,String是8 + /// + public int TagTypeID; + /// + /// 点类型 + /// 比如Bool,INT,STRING等 + /// + public string TagType; + /// + /// 变量类型代码 + /// 比如:允许保存是19 + /// + public int TagTypeCodeID; + /// + /// Value + /// + public object TagValue; + /// + /// 是否监控 + /// + public int IsMonitor; + + + + + + /// + /// 时间戳 + /// + public DateTime TimeStamp; + /// + /// 标签质量 192 , -1 + /// + public string TagQuality; + /// + /// 测量位置 + /// + public string ShaftID; + /// + /// 测量项目 + /// + public string ItemName; + /// + /// 测量单位 + /// + public string Unit; + /// + /// 上限值 + /// + public string TagValueUp; + /// + /// 下限值 + /// + public string TagValueDown; + /// + /// 理论值 + /// + public string TagValeNormal; + /// + /// 合格标志 + /// + public string IsGoodBad; + /// + /// 列位置 + /// + public string TagOrderBy; + /// + /// 变量排序 + /// + public string TagItemOrderBy; + /// + /// 是保存到数据库 + /// + public int IsSaveToSql; + /// + /// 是发送到WebSocket + /// + public int IsWebSocket; + /// + /// 是程序启动时候的值 + /// + public int IsFirstValue; + /// + /// 变量特点 + /// + public int TagProperty; + /// + /// 变量变化的持续时间,单位 毫秒 + /// + public int TagKeepTime; + /// + /// 变量变化前的值 + /// + public object TagValueBefore; + + } + + public class CustomeEvetnArgs : EventArgs + { + public int TagKeepTime { get; set; } + public object TagProperty { get; set; } + public object TagItemOrderBy { get; set; } + public object TagOrderBy { get; set; } + public object IsGoodBad { get; set; } + public object TagValeNormal { get; set; } + public object TagValueDown { get; set; } + public object TagValueUp { get; set; } + public object Unit { get; set; } + public object ItemName { get; set; } + public object ShaftID { get; set; } + public object IsMonitor { get; set; } + public object TagTypeActual { get; set; } + public object TagValueBefore { get; set; } + public object IsFirstValue { get; set; } + public object IsSaveToSql { get; set; } + public object DataDources { get; set; } + public object TagTypeID { get; set; } + public object TagTypeCodeID { get; set; } + public object TagID { get; set; } + public string TimeStamp { get; set; } + public object TagQuality { get; set; } + public object OpName { get; set; } + public object TagValue { get; set; } + public object TagValueType { get; set; } + public object TagType { get; set; } + public object TagName { get; set; } + public object TagKey { get; set; } + public object IsWebSocket { get; set; } + public string TimeStampBefore { get; set; } + } + + public class QualityDataType + { + public int tagValueType; + public int tagTypeID; + public string opName; + public string tagID; + public object tagValue; + public int tagQuality; + public int tagOrderBy; + public int tagItemOrderBy; + public int tagProperty; + public int isGoodBad; + } + + public class HashtableList + { + /// + /// MesServerCode + /// + static public Hashtable hashtable_MesServerCode_Temp; + /// + /// MesDll + /// + static public Hashtable hashtable_MesDll_Temp; + static public Hashtable hashtable_TagTypeDataType_Temp; + static public Hashtable hashtable_TagType_Temp; + + static public Hashtable hashtable_EngineGetOver_EngineTypeID_Temp; + static public Hashtable hashtable_EngineGetOver_EngineType_Temp; + static public Hashtable hashtable_EngineGetOver_EngineID_Temp; + static public Hashtable hashtable_EngineGetOver_OrderForm_Temp; + + static public Hashtable hashtable_OpNameRepair_Temp; + + static public Hashtable hashtable_WorkGroupIndex_Temp; + static public Hashtable hashtable_workStepProperty_Temp; + static public Hashtable hashtable_QualityMesRead_Temp; + static public Hashtable hashtable_IsAllowWork_Temp; + /// + /// 工位号与工位上下线类型 + /// (0普通工位)(1正常上线)(2正常下线)(3返修上线)(4返修下线) + /// 5 分线上线(总线) 6 分线上线(分线) + /// + static public Hashtable hashtableOpName_OpType_Temp; + + /// + /// + /// 工位号与工位上下线类型 + /// (0普通工位)(1正常上线)(2正常下线)(3返修上线)(4返修下线) + /// 5 分线上线(总线) 6 分线上线(分线) + /// + public Hashtable hashtableOpName_OpType; + public Hashtable hashtable_IsAllowWork; + public Hashtable hashtable_QualityMesRead; + public Hashtable hashtable_workStepProperty; + public Hashtable hashtable_OpNameRepair; + /// + /// MesServerCode + /// + public Hashtable hashtable_MesServerCode; + /// + /// MesDll + /// + public Hashtable hashtable_MesDll; + public Hashtable hashtable_TagTypeDataType; + public Hashtable hashtable_TagType; + + + public Hashtable hashtable_EngineGetOver_EngineTypeID; + public Hashtable hashtable_EngineGetOver_EngineType; + public Hashtable hashtable_EngineGetOver_EngineID; + public Hashtable hashtable_EngineGetOver_OrderForm; + + public Hashtable hashtable_WorkGroupIndex; + } + + public struct QualityDataQueryStruct + { + + public QualityDataQueryStruct(string opName, Control ctrl) + { + OpName = opName; + Ctrl = ctrl; + tagType = 0; + tagValue = ""; + tagID = ""; + tagTypeID = 0; + tempForm = null; + tagValue2 = null; + + } + + public QualityDataQueryStruct(string opName, int TagType) + { + + OpName = opName; + Ctrl = null; + tagType = TagType; + tagValue = ""; + tagID = ""; + tagTypeID = 0; + tempForm = null; + tagValue2 = null; + } + + public QualityDataQueryStruct(string opName, int TagType, Control ctrl) + { + + OpName = opName; + Ctrl = ctrl; + tagType = TagType; + tagValue = ""; + tagID = ""; + tagTypeID = 0; + tempForm = null; + tagValue2 = null; + } + public QualityDataQueryStruct(string opName, int TagType, object TagValue) + { + + OpName = opName; + Ctrl = null; + tagType = TagType; + tagValue = TagValue; + tagID = ""; + tagTypeID = 0; + tempForm = null; + tagValue2 = null; + } + public QualityDataQueryStruct(string TagID, int TagTypeID, object TagValue, object TagValue2, Form TempForm) + { + + OpName = ""; + Ctrl = null; + tagType = 0; + tagValue = TagValue; + tagID = TagID; + tagTypeID = TagTypeID; + tempForm = TempForm; + tagValue2 = TagValue2; + } + + + public string OpName; + public Control Ctrl; + public int tagType; + public object tagValue; + public object tagValue2; + public string tagID; + public int tagTypeID; + public Form tempForm; + + + } +} + + + +namespace DoWhatPlc1 +{ + public class EngineValue + { + public string OpName { set; get; } + public string EngineID { set; get; } + public string EngineType { set; get; } + public int EngineTypeID { set; get; } + public int PalletCode { set; get; } + public int ProcessCode { set; get; } + public int PartPalletCode { set; get; } + public string PalletInfo { set; get; } + /// + /// 显示返修标志 + /// + public int RepairPartStatusPLC { set; get; } + /// + /// 1 合格;2 不合格 + /// + public int QualityMask { set; get; } + + public string OrderForm { set; get; } + } + public class DoWhat + { + public const string ReadPLC_TagID = "ReadPLC_TagID"; + public const string WritePLC_TagID = "WritePLC_TagID"; + public const string ReadPLC_TagTypeCodeID = "ReadPLC_TagTypeCodeID"; + public const string WritePLC_TagTypeCodeID = "WritePLC_TagTypeCodeID"; + public const string ReadPLC_Cmd = "ReadPLC_Cmd"; + public const string WritePLC_Cmd = "WritePLC_Cmd"; + public const string ReadPLC_GroupData = "ReadPLC_GroupData"; + public const string ReadPLC_GroupMonitor = "ReadPLC_GroupMonitor"; + public const string ReadPLC_IpTag = "ReadPLC_IpTag"; + public const string ReadPLC_IpMonitorTag = "ReadPLC_IpMonitorTag"; + public const string ReadQualityDataList = "ReadQualityDataList"; + public const string ReadByteData_Op = "ReadByteData_Op"; + public const string ReadByteData_Ip = "ReadByteData_Ip"; + public const string WritePLC_Bytes_Op = "WritePLC_Bytes_Op"; + public const string WritePLC_Bytes_Ip = "WritePLC_Bytes_Ip"; + public const string IpAllTag = "IpAllTag"; + public const string IpMonitorTag = "IpMonitorTag"; + public const string RegionRead = "RegionRead"; + public const string ReadBytes = "ReadBytes"; + public const string WriteBytes = "WriteBytes"; + } + /// + /// object 类型数据转换成字符串变量表达 + /// + public class ReturnValueString + { + public string TagID { set; get; } + public string TagValue { set; get; } + public string ValueType { set; get; } + public string OpName { set; get; } + public string TimeStamp { set; get; } + public string TagTypeCodeID { set; get; } + public string TagTypeID { set; get; } + /// + /// 变量变化的持续时间,单位 毫秒 + /// + public string TagKeepTime; + public string FunName; + public string FunCmd; + public string MesServerCode; + public string CmdPlcReadWrite; + public ReturnValueString() + { + + } + public ReturnValueString(string tagID, object tagValue, string opName = "", string tagTypeCodeID = "", string tagTypeID = "", string tagKeepTime = "", string funName = "", string funCmd = "", string mesServerCode = "") + { + TagTypeCodeID = tagTypeCodeID; + TagTypeID = tagTypeID; + TagValue = tagValue.ToString(); + ValueType = tagValue.GetType().Name; + TagID = tagID; + OpName = opName; + TagKeepTime = tagKeepTime; + FunName = funName; + FunCmd = funCmd; + MesServerCode = mesServerCode; + TimeStamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff"); + } + + public ReturnValueObject ReturnValueToObject() + { + ReturnValueObject ro = new ReturnValueObject(TagID, TagValue, OpName, TagTypeCodeID, ValueType, TimeStamp); + + return ro; + } + + } + /// + /// 字符串变量转变成object类型变量 + /// + public class ReturnValueObject + { + public string TagID { set; get; } + public object TagValue { set; get; } + public string ValueType { set; get; } + public string OpName { set; get; } + public DateTime TimeStamp { set; get; } + public string TagTypeCodeID { set; get; } + /// + /// 变量变化的持续时间,单位 毫秒 + /// + public int TagKeepTime; + + public ReturnValueObject(string tagID, string tagValue, string opName = "", string tagTypeCodeID = "", string valueType = "", string timeStamp = "") + { + TagValue = GetTypeValue(valueType, tagValue); + ValueType = valueType; + TagID = tagID; + OpName = opName; + try + { + TimeStamp = Convert.ToDateTime(timeStamp); + } + catch + { + TimeStamp = DateTime.Now; + + } + TagTypeCodeID = tagTypeCodeID; + + } + + public ReturnValueString ReturnValueToString() + { + ReturnValueString rs = new ReturnValueString(TagID, TagValue, OpName, TagTypeCodeID); + return rs; + } + public static object GetTypeValue(string type, string tagValue) + { + object tagV = "-1"; + if (type == null) + { + tagV = tagValue; + } + switch (type.ToLower()) + { + case "bool": + case "boolean": + tagV = false; + switch (tagValue.ToLower()) + { + case "1": + case "true": + tagV = true; + break; + case "0": + case "false": + tagV = false; + break; + } + return tagV; + //return Type.GetType(" System.Boolean ", true, true); + case "byte ": + return Convert.ToByte(tagValue); + case "sbyte": + return Convert.ToSByte(tagValue); + case "char": + return Convert.ToChar(tagValue); + case "decimal": + return Convert.ToDecimal(tagValue); + case "double": + return Convert.ToDouble(tagValue); + case "float": + return Convert.ToSingle(tagValue); + case "int": + return Convert.ToInt32(tagValue); + case "int16": + return Convert.ToInt32(tagValue); + case "uint": + return Convert.ToUInt32(tagValue); + case "long": + return Convert.ToInt64(tagValue); + case "ulong": + return Convert.ToUInt64(tagValue); + case "object": + return tagValue; + case "short": + return Convert.ToInt16(tagValue); + case "ushort": + return Convert.ToUInt16(tagValue); + case "string": + return tagValue; + case "date": + case "datetime": + return Convert.ToDateTime(tagValue); + case "guid": + return tagValue; + default: + return tagValue; + } + } + + + } + + public class TagIDTagFormat + { + public string TagID; + public TagFormat TF; + + public TagIDTagFormat(string tagID, TagFormat tF) + { + TagID = tagID; + TF = tF; + } + } + + + public class QualityDataSaveList + { + public Hashtable valuList; + public DataTable BasicDataTagValue; + public DataTable BasicDataTagValueUpDown; + public Hashtable hashtable_EngineTypeID; + public Hashtable hashtable_tagTable_OpName_SaveData; + } + + + + public struct ControlData + { + public int TagType; + public string opName; + public Control btn; public ControlData(Control Ctrl, string OpName) + { + string[] Array_NameSplit; + Array_NameSplit = Ctrl.Name.Split('_'); + TagType = Convert.ToInt32(Array_NameSplit[2]); + opName = OpName; + btn = Ctrl; + + } + } + public struct ControlChangeByTagType + { + public ControlChangeByTagType(int tagType, string value) + { + TagType = tagType; + Value = value; + } + + public int TagType; + public string Value; + } + /// + /// tag格式化结构 + /// + public struct TagFormat + { + /// + /// TagID + /// + public string TagID; + /// + /// TagID + /// + public string TagName; + /// + /// 工位号 + /// + public string OpName; + /// + /// 数据来源 + /// + public string DataSources; + /// + /// IP + /// + public string IP; + /// + /// OPC的URL + /// + public string OpcIpPort; + /// + /// 组 + /// + public string Group; + /// + /// 监控时间间隔 + /// + public string MonitorInterval; + /// + /// DB号加起始地址,DB1001.30 + /// + public string TagDbAndStartAdr; + /// + /// DB号加起始地址,DB1001.30.1,为了bool写入专用 + /// + public string TagDbAndStartAdrWrite; + /// + /// OPC协议地址 + /// 例如:S7:[192.168.1.211|VFD1|S7ONLINE|01.00,192.168.1.211,02.02,1]DB1001,DINT154 + /// + public string TagOPCAdrStr; + /// + /// DB地址位置 + /// 变量起始地址,例如 0,1,2,56,80... + /// + public int Index; + /// + /// 变量字节长度 + /// 变量字节长度,l例如 1,2,4... + /// + public int Length; + /// + /// X 0,1,2,3,4,5,6,7 + /// 例如 X 0,1,2,3,4,5,6,7 + /// + public int BitIndex; + /// + /// 以连续Byte数组方式读取的DB地址实际位置 + /// 变量起始地址,例如 0,1,2,56,80... + /// + public int IndexBytes; + /// + /// 绝对地址差分,应用区域读取的拆分20200101_LLX + /// + public int AbsAddrDiff; + + + + /// + /// 点类型代码 + /// 比如bool是11,String是8 + /// + public int TagTypeID; + /// + /// 点类型 + /// 比如Bool,INT,STRING等 + /// + public string TagType; + /// + /// 变量类型代码 + /// 比如:允许保存是19 + /// + public int TagTypeCodeID; + /// + /// Value + /// + public object TagValue; + /// + /// 是否监控 + /// + public int IsMonitor; + + + + + + /// + /// 时间戳 + /// + public DateTime TimeStamp; + /// + /// 标签质量 192 , -1 + /// + public string TagQuality; + /// + /// 测量位置 + /// + public string ShaftID; + /// + /// 测量项目 + /// + public string ItemName; + /// + /// 测量单位 + /// + public string Unit; + /// + /// 上限值 + /// + public string TagValueUp; + /// + /// 下限值 + /// + public string TagValueDown; + /// + /// 理论值 + /// + public string TagValeNormal; + /// + /// 合格标志 + /// + public string IsGoodBad; + /// + /// 列位置 + /// + public string TagOrderBy; + /// + /// 变量排序 + /// + public string TagItemOrderBy; + /// + /// 是保存到数据库 + /// + public int IsSaveToSql; + /// + /// 是发送到WebSocket + /// + public int IsWebSocket; + /// + /// 是程序启动时候的值 + /// + public int IsFirstValue; + /// + /// 变量特点 + /// + public int TagProperty; + /// + /// 变量变化的持续时间,单位 毫秒 + /// + public int TagKeepTime; + /// + /// 变量变化前的值 + /// + public object TagValueBefore; + + } + + public class CustomeEvetnArgs : EventArgs + { + public int TagKeepTime { get; set; } + public object TagProperty { get; set; } + public object TagItemOrderBy { get; set; } + public object TagOrderBy { get; set; } + public object IsGoodBad { get; set; } + public object TagValeNormal { get; set; } + public object TagValueDown { get; set; } + public object TagValueUp { get; set; } + public object Unit { get; set; } + public object ItemName { get; set; } + public object ShaftID { get; set; } + public object IsMonitor { get; set; } + public object TagTypeActual { get; set; } + public object TagValueBefore { get; set; } + public object IsFirstValue { get; set; } + public object IsSaveToSql { get; set; } + public object DataDources { get; set; } + public object TagTypeID { get; set; } + public object TagTypeCodeID { get; set; } + public object TagID { get; set; } + public string TimeStamp { get; set; } + public object TagQuality { get; set; } + public object OpName { get; set; } + public object TagValue { get; set; } + public object TagValueType { get; set; } + public object TagType { get; set; } + public object TagName { get; set; } + public object TagKey { get; set; } + public object IsWebSocket { get; set; } + public string TimeStampBefore { get; set; } + } + + public class QualityDataType + { + public int tagValueType; + public int tagTypeID; + public string opName; + public string tagID; + public object tagValue; + public int tagQuality; + public int tagOrderBy; + public int tagItemOrderBy; + public int tagProperty; + public int isGoodBad; + } + + public class HashtableList + { + /// + /// MesServerCode + /// + static public Hashtable hashtable_MesServerCode_Temp; + /// + /// MesDll + /// + static public Hashtable hashtable_MesDll_Temp; + static public Hashtable hashtable_TagTypeDataType_Temp; + static public Hashtable hashtable_TagType_Temp; + + static public Hashtable hashtable_EngineGetOver_EngineTypeID_Temp; + static public Hashtable hashtable_EngineGetOver_EngineType_Temp; + static public Hashtable hashtable_EngineGetOver_EngineID_Temp; + static public Hashtable hashtable_EngineGetOver_OrderForm_Temp; + + static public Hashtable hashtable_OpNameRepair_Temp; + + static public Hashtable hashtable_WorkGroupIndex_Temp; + static public Hashtable hashtable_workStepProperty_Temp; + static public Hashtable hashtable_QualityMesRead_Temp; + static public Hashtable hashtable_IsAllowWork_Temp; + /// + /// 工位号与工位上下线类型 + /// (0普通工位)(1正常上线)(2正常下线)(3返修上线)(4返修下线) + /// 5 分线上线(总线) 6 分线上线(分线) + /// + static public Hashtable hashtableOpName_OpType_Temp; + + /// + /// + /// 工位号与工位上下线类型 + /// (0普通工位)(1正常上线)(2正常下线)(3返修上线)(4返修下线) + /// 5 分线上线(总线) 6 分线上线(分线) + /// + public Hashtable hashtableOpName_OpType; + public Hashtable hashtable_IsAllowWork; + public Hashtable hashtable_QualityMesRead; + public Hashtable hashtable_workStepProperty; + public Hashtable hashtable_OpNameRepair; + /// + /// MesServerCode + /// + public Hashtable hashtable_MesServerCode; + /// + /// MesDll + /// + public Hashtable hashtable_MesDll; + public Hashtable hashtable_TagTypeDataType; + public Hashtable hashtable_TagType; + + + public Hashtable hashtable_EngineGetOver_EngineTypeID; + public Hashtable hashtable_EngineGetOver_EngineType; + public Hashtable hashtable_EngineGetOver_EngineID; + public Hashtable hashtable_EngineGetOver_OrderForm; + + public Hashtable hashtable_WorkGroupIndex; + } + + public struct QualityDataQueryStruct + { + + public QualityDataQueryStruct(string opName, Control ctrl) + { + OpName = opName; + Ctrl = ctrl; + tagType = 0; + tagValue = ""; + tagID = ""; + tagTypeID = 0; + tempForm = null; + tagValue2 = null; + + } + + public QualityDataQueryStruct(string opName, int TagType) + { + + OpName = opName; + Ctrl = null; + tagType = TagType; + tagValue = ""; + tagID = ""; + tagTypeID = 0; + tempForm = null; + tagValue2 = null; + } + + public QualityDataQueryStruct(string opName, int TagType, Control ctrl) + { + + OpName = opName; + Ctrl = ctrl; + tagType = TagType; + tagValue = ""; + tagID = ""; + tagTypeID = 0; + tempForm = null; + tagValue2 = null; + } + public QualityDataQueryStruct(string opName, int TagType, object TagValue) + { + + OpName = opName; + Ctrl = null; + tagType = TagType; + tagValue = TagValue; + tagID = ""; + tagTypeID = 0; + tempForm = null; + tagValue2 = null; + } + public QualityDataQueryStruct(string TagID, int TagTypeID, object TagValue, object TagValue2, Form TempForm) + { + + OpName = ""; + Ctrl = null; + tagType = 0; + tagValue = TagValue; + tagID = TagID; + tagTypeID = TagTypeID; + tempForm = TempForm; + tagValue2 = TagValue2; + } + + + public string OpName; + public Control Ctrl; + public int tagType; + public object tagValue; + public object tagValue2; + public string tagID; + public int tagTypeID; + public Form tempForm; + + + } +} + + diff --git a/Common/DoWhatPlc/Properties/AssemblyInfo.cs b/Common/DoWhatPlc/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..d89ceef --- /dev/null +++ b/Common/DoWhatPlc/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// 有关程序集的一般信息由以下 +// 控制。更改这些特性值可修改 +// 与程序集关联的信息。 +[assembly: AssemblyTitle("DoWhatPlc")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("DoWhatPlc")] +[assembly: AssemblyCopyright("Copyright © 2022")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// 将 ComVisible 设置为 false 会使此程序集中的类型 +//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型 +//请将此类型的 ComVisible 特性设置为 true。 +[assembly: ComVisible(false)] + +// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID +[assembly: Guid("0d1af432-439a-4920-8692-43ae139f5530")] + +// 程序集的版本信息由下列四个值组成: +// +// 主版本 +// 次版本 +// 生成号 +// 修订号 +// +//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值 +//通过使用 "*",如下所示: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Common/DoWhatPlc/TagTypeCodeID.cs b/Common/DoWhatPlc/TagTypeCodeID.cs new file mode 100644 index 0000000..292e5c4 --- /dev/null +++ b/Common/DoWhatPlc/TagTypeCodeID.cs @@ -0,0 +1,463 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +///1 X WorkStart 2 工件到位(PLC) 工件到位。托盘到达工位,并且托盘上有工件。 +///2 X RepairPartStatusPLC 3 RepairPartStatusPLC 备用 +///3 STRING RepairPathString 4 RepairPathString "工位返修字符串(121211112222111),前2位是西门子字符串格式,第一位是总长度,第二位是实际长度" +///4 X EngineTypeGetOverMES 5 传递机型(MES) MES传递总成信息给PLC(上线工位) +///5 X PartPalletGoOver 6 PartPalletGoOver 上线工位。0:正常工作;1:空托盘放行,PLC读取到此标志不走申请上线逻辑。 +///6 X MaterialVerifyOver 7 MaterialVerifyOver MES保存完质量数据,物料数据等与PLC信号交互完成后通知PLC,所以工步都完成,才可以放行工件,正常工作时工件放行的必要条件。 +///7 X FalseGo 8 FalseGo 按MES界面[不合格放行]按钮,MES发送此信号。操作者判断工件不合格,通知设备,按不合格方式放行工件,工件流转到返修下线工位后,返修下线。MES工作完成MES0.3=1,MES合格放行MES0.5=0,MES0.4=1 +///8 INT EngineTypeID 9 EngineTypeID MES发动机机型标志(必须PLC) +///9 STRING EngineID 10 EngineID MES发动机编号(必须PLC) +///10 STRING EngineType 11 机型(MES) MES发动机机型(必须PLC) +///11 X PartPalletStatus 13 PartPalletStatus MES激发变量托盘到位离开(必须PLC) +///12 X HeartBeatPLC 14 HeartBeatPLC 心跳处理:PLC收到MES心跳信号后,PLC延时5秒后,数值取反再写回PLC,写回PLC开始计时,如果5秒钟MES无反馈报通讯故障。 +///13 X HeartBeatMIS 15 HeartBeatMIS 间隔时间5S,心跳处理。收到PLC心跳信号后,MES按原值回写。PLC收到MES信号后延时5秒,取反写入,以此循环。 +///14 X TargetTimeRead 16 TargetTimeRead MES允许可读工位运行时间 +///15 Int MachineTargetTime 17 MachineTargetTime 目标运行时间 +///16 Int MachineActualTime 18 MachineActualTime 实际运行时间 +///17 X MesRead 19 允许保存(PLC) 质量数据可以读数据 +///18 X MesReadOver 20 保存完成(MES) MES保存完数据(必须MIS) +///19 INT QualityMask 21 合格标志(PLC) 质量数据工位合格标志0:没有工作;1:合格 ;2 :不合格(必须PLC) +///20 B PalletInfo 22 PalletInfo 0空托盘,1合格件,2不合格件 +///21 INT RepairStatusPLC 23 RepairStatusPLC 0正常件,1返修件 +///22 INT OrderNo 24 订单号(MES) 订单号(MES) +///23 X StorageNo 25 库位号(MES) 库位号(MES) +///24 X AllowPass 26 允许放行(MES) 允许放行 +///25 X PartLoadFinish 27 PartLoadFinish PartLoadFinish +///26 X Reserved_7 28 Reserved_7 备用 +///27 X Reserved_8 29 Reserved_8 备用 +///28 X Reserved_9 30 Reserved_9 备用 +///29 X Reserved_10 31 Reserved_10 备用 +///30 X Reserved_11 32 Reserved_11 备用 +///31 X Reserved_12 33 Reserved_12 备用 +///32 X Reserved_13 34 Reserved_13 备用 +///33 X Reserved_14 35 Reserved_14 备用 +///34 Int PLCSPareint1 36 PLCSPareint1 备用 +///35 Int PLCSPareint2 37 PLCSPareint2 备用 +///36 Int PLCSPareint3 38 PLCSPareint3 备用 +///37 STRING PLCSarestring1 39 PLCSarestring1 备用 +///38 STRING PLCSarestring2 40 PLCSarestring2 备用 +///39 STRING MarkID 42 MarkID 机体打标号(MES)前2位是西门子字符串格式,第一位是总长度,第二位是实际长度 +///40 X PartLoad 43 PartLoad 上线工位,PLC向MES申请总成编号。收到该信号后,MES将机型标志(DBB22 ~23)、总成号(DBB24 ~63)、总成机型DBB64 ~103写入PLC。之后MES通过信号“传递机型(DBX0.1)”通知PLC。 +///41 X EngineTypeGetOverPLC 44 传递机型(PLC) PLC将机型标志(DBB50…51)、工件编号(DBB52…101)、产品型号(DBB102…187)、托盘编号(DBB188…189)准备完毕后,通知MES。 +///42 X PartLoadOK 48 PartLoadOK 备用 +///43 X Reserved_18 49 Reserved_18 备用 +///44 X PalletDown 50 PalletDown 暂时保留,项目未使用 +///45 X ConfirmOkGo 51 ConfirmOkGo 按MES界面[合格放行]按钮,MES发送此信号。操作者判断工件合格,通知设备,工件按合格方式放行工件。MES工作完成MES0.3=1,MES合格放行MES0.5=1,MES0.4=0 +///46 X ResetDevice 52 ResetDevice 针对手动工位,无HMI,需要复位设备在MES页面操作。 +///47 X UnloadCompleted 53 UnloadCompleted 暂时保留,项目未使用 +///48 X MachineTime_ReadOver 54 MachineTime_ReadOver 备用 +///49 X Reserved_19 58 Reserved_19 备用 +///50 X FixOK 59 FixOK 手动拧紧工位,单工步螺栓拧紧完成,通知PC读取数据。 +///51 X Reserved_21 61 Reserved_21 备用 +///52 X Reserved_22 62 Reserved_22 备用 +///53 X Reserved_23 63 Reserved_23 备用 +///54 X Reserved_24 64 Reserved_24 备用 +///55 X Reserved_25 65 Reserved_25 备用 +///56 X FixAllow 66 FixAllow "设备工作的必须信号,对于有物料验证的工位,MES验证完成给出此信号,对于无物料验证工位,MES直接给出此信号。" +///57 X FixOver 67 FixOver 用于手动拧紧且有质量数据工位。通知设备当前工步拧紧螺钉工作结束。 +///58 X MatchingCompleted 68 MatchingCompleted 分线上总线,匹配成功是1;不成功是0。 +///59 X Match 69 Match 分线上总线,匹配成功是1;不成功是0。 +///60 X Reserved_2 70 Reserved_2 备用 +///61 X IsAutoGetEngineID 71 IsAutoGetEngineID 自动手动申请工件编号。0是自动方式;1:手动方式。暂时保留,生成流水号方式是在数据库中实现的 +///62 X RepairUplineMES 72 RepairUplineMES 上线清空MOBY(针对上线工位):通知PLC从新开始申请上线流程 +///63 INT EngineTypeID_MES 73 机型代码(MES) MES发动机机型标志(必须MES) +///64 STRING EngineID_MES 74 工件编号(MES) MES发动机编号(必须MES) +///65 STRING EngineType_MES 75 EngineType_MES MES发动机机型(必须MES) +///66 X Reserved_20 76 Reserved_20 备用 +///67 INT ProcessCode 77 ProcessCode 手动拧紧工位:由MES通知PLC拧紧序号 +///68 B OnLineState 79 OnLineState 通过线体工位PC实现下达工位工作状态:工位有三种状态:在线、离线、屏蔽。在线:0正常状态,实现正常功能。1离线:设备脱离MES工作,进入不交互模式。 +///69 INT PartPalletCode 80 托盘号(MES) 托盘编号(B5A) +///70 INT BoltCode 88 BoltCode 手动拧紧工位:指导PLC所用套筒 +///71 INT RepairStatus 93 RepairStatus "0正常件,1返修件。对于上线工位MES给出是正常上线还是返修上线,返修路径" +///72 DInt Reserved_15 110 Reserved_15 备用 +///73 DInt Reserved_16 111 Reserved_16 备用 +///74 B Reserved_17 112 Reserved_17 备用 +///75 INT SPareint1 113 SPareint1 备用int1 +///76 INT SPareint2 114 SPareint2 备用int2 +///77 INT SPareint3 115 SPareint3 备用int3 +///78 STRING Sparestring1 116 Sparestring1 备用字符串1 +///79 STRING Sparestring2 117 Sparestring2 备用字符串2 +///80 X MachineStatusPutOn 1000 机床上电(PLC) 机床上电(必须PLC) +///81 X MachineStatusWorkOn 1001 循环开始(PLC) 循环开始(必须PLC) +///82 X MachineStatusAlarm 1002 设备报警(PLC) 机床故障(必须PLC) +///83 X MachineStatusNoPart 1003 MachineStatusNoPart 上料无件(必须PLC) +///84 X MachineStatusBlock 1004 MachineStatusBlock 下料堵塞(必须PLC) + + +namespace MesWork +{ + /// + /// 这是变量类型代码的配置,几乎是不变的 + /// 请不要随意修改,为了保证变量版本同一,并且方便维护,请联系发行人修改! + /// 请注意,此修改为全局修改! + /// + public enum EnumTagTypeCodeID + { + /// + /// 工件到位(PLC) + /// 变量类型:Bool + /// 解释:托盘到达工位,并且托盘上有工件。 + /// + WorkStart = 2, + /// + /// + /// + RepairPartStatusPLC = 3, + /// + /// 工位返修字符串 + /// 变量类型:String + /// 解释:工位返修字符串 + /// + RepairPathString = 4, + /// + /// 传递机型(MES) + /// 变量类型:Bool + /// 解释:MES传递总成信息给PLC(上线工位) + /// + EngineTypeGetOverMES = 5, + /// + /// + /// + PartPalletGoOver = 6, + /// + /// + /// + MaterialVerifyOver = 7, + /// + /// + /// + FalseGo = 8, + /// + /// + /// + EngineTypeID = 9, + /// + /// + /// + EngineID = 10, + /// + /// 机型(MES) + /// 变量类型:String + /// + EngineType = 11, + /// + /// + /// + PartPalletStatus = 13, + /// + /// + /// + HeartBeatPLC = 14, + /// + /// + /// + HeartBeatMIS = 15, + /// + /// + /// + TargetTimeRead = 16, + /// + /// + /// + MachineTargetTime = 17, + /// + /// + /// + MachineActualTime = 18, + /// + /// 允许保存(PLC) + /// 变量类型:Bool + /// + MesRead = 19, + /// + /// 保存完成(MES) + /// 变量类型:Bool + /// + MesReadOver = 20, + /// + /// 合格标志(PLC) + /// 变量类型:Int + /// + QualityMask = 21, + /// + /// + /// + PalletInfo = 22, + /// + /// + /// + RepairStatusPLC = 23, + /// + /// 订单号(MES) + /// 变量类型:Int + /// + OrderNo = 24, + /// + /// 库位号(MES) + /// 变量类型:Bool + /// + StorageNo = 25, + /// + /// 允许放行(MES) + /// 变量类型:Bool + /// + AllowPass = 26, + /// + /// + /// + PartLoadFinish = 27, + /// + /// + /// + Reserved_7 = 28, + /// + /// + /// + Reserved_8 = 29, + /// + /// + /// + Reserved_9 = 30, + /// + /// + /// + Reserved_10 = 31, + /// + /// + /// + Reserved_11 = 32, + /// + /// + /// + Reserved_12 = 33, + /// + /// + /// + Reserved_13 = 34, + /// + /// + /// + Reserved_14 = 35, + /// + /// + /// + PLCSPareint1 = 36, + /// + /// + /// + PLCSPareint2 = 37, + /// + /// + /// + PLCSPareint3 = 38, + /// + /// + /// + PLCSarestring1 = 39, + /// + /// + /// + PLCSarestring2 = 40, + /// + /// + /// + MarkID = 42, + /// + /// + /// + PartLoad = 43, + /// + /// 传递机型(PLC) + /// 变量类型:Bool + /// + EngineTypeGetOverPLC = 44, + /// + /// + /// + PartLoadOK = 48, + /// + /// + /// + Reserved_18 = 49, + /// + /// + /// + PalletDown = 50, + /// + /// + /// + ConfirmOkGo = 51, + /// + /// + /// + ResetDevice = 52, + /// + /// + /// + UnloadCompleted = 53, + /// + /// + /// + MachineTime_ReadOver = 54, + /// + /// + /// + Reserved_19 = 58, + /// + /// + /// + FixOK = 59, + /// + /// + /// + Reserved_21 = 61, + /// + /// + /// + Reserved_22 = 62, + /// + /// + /// + Reserved_23 = 63, + /// + /// + /// + Reserved_24 = 64, + /// + /// + /// + Reserved_25 = 65, + /// + /// + /// + FixAllow = 66, + /// + /// + /// + FixOver = 67, + /// + /// + /// + MatchingCompleted = 68, + /// + /// + /// + Match = 69, + /// + /// + /// + Reserved_2 = 70, + /// + /// + /// + IsAutoGetEngineID = 71, + /// + /// + /// + RepairUplineMES = 72, + /// + /// 机型代码(MES) + /// 变量类型:Int + /// + EngineTypeID_MES = 73, + /// + /// 工件编号(MES) + /// 变量类型:String + /// + EngineID_MES = 74, + /// + /// + /// + EngineType_MES = 75, + /// + /// + /// + Reserved_20 = 76, + /// + /// + /// + ProcessCode = 77, + /// + /// + /// + OnLineState = 79, + /// + /// 托盘号(MES) + /// 变量类型:Int + /// + PartPalletCode = 80, + /// + /// + /// + BoltCode = 88, + /// + /// + /// + RepairStatus = 93, + /// + /// + /// + Reserved_15 = 110, + /// + /// + /// + Reserved_16 = 111, + /// + /// + /// + Reserved_17 = 112, + /// + /// + /// + SPareint1 = 113, + /// + /// + /// + SPareint2 = 114, + /// + /// + /// + SPareint3 = 115, + /// + /// + /// + Sparestring1 = 116, + /// + /// + /// + Sparestring2 = 117, + /// + /// 机床上电(PLC) + /// 变量类型:Bool + /// + MachineStatusPutOn = 1000, + /// + /// 循环开始(PLC) + /// 变量类型:Bool + /// + MachineStatusWorkOn = 1001, + /// + /// 设备报警(PLC) + /// 变量类型:Bool + /// + MachineStatusAlarm = 1002, + /// + /// 上料无件(PLC) + /// 变量类型:Bool + /// + MachineStatusNoPart = 1003, + /// + /// 下料堵塞(PLC) + /// 变量类型:Bool + /// + MachineStatusBlock = 1004, + + + } +} diff --git a/Common/DoWhatPlc/TagTypeID.cs b/Common/DoWhatPlc/TagTypeID.cs new file mode 100644 index 0000000..b8800ac --- /dev/null +++ b/Common/DoWhatPlc/TagTypeID.cs @@ -0,0 +1,28 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MesWork +{ + /// + /// 这是信号点类型代码的配置 + /// 这里是不变的,请不要随意修改!!! + /// 请注意,此修改为全局修改! + /// + public enum EnumTagTypeID + { + Int16 = 2, + Int32 = 3, + Float = 4, + UInt64 = 7, + String = 8, + Bool = 11, + Byte = 17, + UInt16 = 18, + Double = 19, + Bytes = 21, + + } +} diff --git a/Common/DoWhatPlc/packages.config b/Common/DoWhatPlc/packages.config new file mode 100644 index 0000000..376abb5 --- /dev/null +++ b/Common/DoWhatPlc/packages.config @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/Common/MesControl/MesBoolSignal.Designer.cs b/Common/MesControl/MesBoolSignal.Designer.cs new file mode 100644 index 0000000..2989846 --- /dev/null +++ b/Common/MesControl/MesBoolSignal.Designer.cs @@ -0,0 +1,79 @@ +namespace MesControl +{ + partial class MesBoolSignal + { + /// + /// 必需的设计器变量。 + /// + private System.ComponentModel.IContainer components = null; + + /// + /// 清理所有正在使用的资源。 + /// + /// 如果应释放托管资源,为 true;否则为 false。 + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region 组件设计器生成的代码 + + /// + /// 设计器支持所需的方法 - 不要修改 + /// 使用代码编辑器修改此方法的内容。 + /// + private void InitializeComponent() + { + this.pictureBox_Signal = new System.Windows.Forms.PictureBox(); + this.label_SignalName = new System.Windows.Forms.Label(); + ((System.ComponentModel.ISupportInitialize)(this.pictureBox_Signal)).BeginInit(); + this.SuspendLayout(); + // + // pictureBox_Signal + // + this.pictureBox_Signal.BackgroundImage = global::MesControl.Properties.Resources.none; + this.pictureBox_Signal.Location = new System.Drawing.Point(3, 1); + this.pictureBox_Signal.Name = "pictureBox_Signal"; + this.pictureBox_Signal.Size = new System.Drawing.Size(20, 20); + this.pictureBox_Signal.TabIndex = 0; + this.pictureBox_Signal.TabStop = false; + // + // label_SignalName + // + this.label_SignalName.AutoSize = true; + this.label_SignalName.Font = new System.Drawing.Font("宋体", 12F); + this.label_SignalName.Location = new System.Drawing.Point(32, 3); + this.label_SignalName.MaximumSize = new System.Drawing.Size(72, 16); + this.label_SignalName.MinimumSize = new System.Drawing.Size(72, 16); + this.label_SignalName.Name = "label_SignalName"; + this.label_SignalName.Size = new System.Drawing.Size(72, 16); + this.label_SignalName.TabIndex = 1; + this.label_SignalName.Text = "心跳信号"; + // + // MesBoolSignal + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.BackColor = System.Drawing.Color.Transparent; + this.Controls.Add(this.label_SignalName); + this.Controls.Add(this.pictureBox_Signal); + this.MaximumSize = new System.Drawing.Size(110, 22); + this.MinimumSize = new System.Drawing.Size(110, 22); + this.Name = "MesBoolSignal"; + this.Size = new System.Drawing.Size(110, 22); + ((System.ComponentModel.ISupportInitialize)(this.pictureBox_Signal)).EndInit(); + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private System.Windows.Forms.PictureBox pictureBox_Signal; + private System.Windows.Forms.Label label_SignalName; + } +} diff --git a/Common/MesControl/MesBoolSignal.cs b/Common/MesControl/MesBoolSignal.cs new file mode 100644 index 0000000..c3e1d98 --- /dev/null +++ b/Common/MesControl/MesBoolSignal.cs @@ -0,0 +1,111 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Drawing; +using System.Data; +using System.Linq; +using System.Text; +using System.Windows.Forms; + +namespace MesControl +{ + public partial class MesBoolSignal : UserControl + { + public MesBoolSignal() + { + InitializeComponent(); + } + + /// + /// 外部调用控件触发的信号 + /// + /// + public void InputBoolSignal(bool Signal) + { + + if (Signal) + { + + pictureBox_Signal.BackgroundImage = Properties.Resources.green; + } + else + { + pictureBox_Signal.BackgroundImage = Properties.Resources.init; + } + + } + + [Browsable(true)] + [Description("控件中显示的文本内容"), Category("SignalText"), DefaultValue("")] + public string SignalText + { + get + { + return label_SignalName.Text; + } + + set + { + label_SignalName.Text = value; + } + + } + + SignalImage_Enum enum1; + + [Browsable(true)] + [Description("控件用于显示状态的图片"), Category("SignalImage"), DefaultValue("none")] + public SignalImage_Enum SignalImage + { + get + { + return enum1; + } + set + { + SetSignalImage(value); + enum1 = value; + + + + } + + + } + + + + public enum SignalImage_Enum + { + + none, init, green, yellow, red + + } + + void SetSignalImage(SignalImage_Enum Image) + { + switch (Image) + { + case SignalImage_Enum.none: + pictureBox_Signal.BackgroundImage = Properties.Resources.none; + break; + case SignalImage_Enum.init: + pictureBox_Signal.BackgroundImage = Properties.Resources.init; + break; + case SignalImage_Enum.green: + pictureBox_Signal.BackgroundImage = Properties.Resources.green; + break; + case SignalImage_Enum.yellow: + pictureBox_Signal.BackgroundImage = Properties.Resources.yellow; + break; + case SignalImage_Enum.red: + pictureBox_Signal.BackgroundImage = Properties.Resources.red; + break; + + } + + } + + + } +} diff --git a/Common/MesControl/MesBoolSignal.resx b/Common/MesControl/MesBoolSignal.resx new file mode 100644 index 0000000..1810bb4 --- /dev/null +++ b/Common/MesControl/MesBoolSignal.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 + + + True + + + True + + \ No newline at end of file diff --git a/Common/MesControl/MesControl.csproj b/Common/MesControl/MesControl.csproj new file mode 100644 index 0000000..624392c --- /dev/null +++ b/Common/MesControl/MesControl.csproj @@ -0,0 +1,139 @@ + + + + + Debug + AnyCPU + {FAB322CC-531D-4AEA-986A-B921B64D8D3F} + Library + Properties + MesControl + MesControl + v4.6.1 + 512 + + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + false + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + false + + + + + + + + + + + + + + + UserControl + + + MesBoolSignal.cs + + + UserControl + + + PlcWorkStationSignal.cs + + + UserControl + + + PlcConnect.cs + + + + True + True + Resources.resx + + + UserControl + + + + + + MesBoolSignal.cs + + + PlcWorkStationSignal.cs + + + ResXFileCodeGenerator + Designer + Resources.Designer.cs + + + PlcConnect.cs + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Common/MesControl/PlcConnect.Designer.cs b/Common/MesControl/PlcConnect.Designer.cs new file mode 100644 index 0000000..5e44fd1 --- /dev/null +++ b/Common/MesControl/PlcConnect.Designer.cs @@ -0,0 +1,81 @@ +namespace MesControl +{ + partial class PlcConnect + { + /// + /// 必需的设计器变量。 + /// + private System.ComponentModel.IContainer components = null; + + /// + /// 清理所有正在使用的资源。 + /// + /// 如果应释放托管资源,为 true;否则为 false。 + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region 组件设计器生成的代码 + + /// + /// 设计器支持所需的方法 - 不要修改 + /// 使用代码编辑器修改此方法的内容。 + /// + private void InitializeComponent() + { + this.pictureBox_OpName = new System.Windows.Forms.PictureBox(); + this.label_OpName = new System.Windows.Forms.Label(); + ((System.ComponentModel.ISupportInitialize)(this.pictureBox_OpName)).BeginInit(); + this.SuspendLayout(); + // + // pictureBox_OpName + // + this.pictureBox_OpName.BackgroundImage = global::MesControl.Properties.Resources.BreakPLC; + this.pictureBox_OpName.Location = new System.Drawing.Point(3, 1); + this.pictureBox_OpName.MaximumSize = new System.Drawing.Size(20, 20); + this.pictureBox_OpName.MinimumSize = new System.Drawing.Size(20, 20); + this.pictureBox_OpName.Name = "pictureBox_OpName"; + this.pictureBox_OpName.Size = new System.Drawing.Size(20, 20); + this.pictureBox_OpName.TabIndex = 0; + this.pictureBox_OpName.TabStop = false; + // + // label_OpName + // + this.label_OpName.AutoSize = true; + this.label_OpName.Font = new System.Drawing.Font("宋体", 12F); + this.label_OpName.Location = new System.Drawing.Point(32, 3); + this.label_OpName.MaximumSize = new System.Drawing.Size(72, 16); + this.label_OpName.MinimumSize = new System.Drawing.Size(72, 16); + this.label_OpName.Name = "label_OpName"; + this.label_OpName.Size = new System.Drawing.Size(72, 16); + this.label_OpName.TabIndex = 1; + this.label_OpName.Text = "通讯状态"; + // + // PlcConnect + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.BackColor = System.Drawing.Color.Transparent; + this.Controls.Add(this.label_OpName); + this.Controls.Add(this.pictureBox_OpName); + this.MaximumSize = new System.Drawing.Size(110, 22); + this.MinimumSize = new System.Drawing.Size(110, 22); + this.Name = "PlcConnect"; + this.Size = new System.Drawing.Size(110, 22); + ((System.ComponentModel.ISupportInitialize)(this.pictureBox_OpName)).EndInit(); + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private System.Windows.Forms.PictureBox pictureBox_OpName; + private System.Windows.Forms.Label label_OpName; + } +} diff --git a/Common/MesControl/PlcConnect.cs b/Common/MesControl/PlcConnect.cs new file mode 100644 index 0000000..6bbf2e1 --- /dev/null +++ b/Common/MesControl/PlcConnect.cs @@ -0,0 +1,221 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Drawing; +using System.Data; +using System.Linq; +using System.Text; +using System.Windows.Forms; + +namespace MesControl +{ + public delegate void PlcStatusHandle(); + public partial class PlcConnect: UserControl + { + public PlcConnect() + { + InitializeComponent(); + + } + public static PlcStatusHandle PlcBreakChange,PlcConnectChange; + + + #region 内部变量 + int externalTimerTimes =0; + + int testPlcBreakInterval=10000; + + int testPlcBreakTime=0; + + int externalTimerInterval = 200; + + bool isBreakPLC = true; + + bool plcTestEnable; + + bool plcBreakIsChanged=false; + bool plcConnectIsChanged = false; + + #endregion + #region 内部方法 + + void TimerTimeChange() + { + if (externalTimerTimes == 999) + { + externalTimerTimes = 0; + } + else + { + externalTimerTimes++; + } + + if (testPlcBreakTime > 0) + { + testPlcBreakTime--; + plcBreakIsChanged = false; + + if (PlcConnectChange!=null&&!plcConnectIsChanged) + { + PlcConnectChange(); + plcConnectIsChanged = true; + } + } + else + { + if (plcTestEnable) + { + if(PlcBreakChange != null&& !plcBreakIsChanged) + { + PlcBreakChange(); + plcBreakIsChanged = true; + } + plcConnectIsChanged = false; + } + isBreakPLC = true; + } + + } + #endregion + + #region 外部方法 + public void ExternalTimer() + { + + if (!isBreakPLC) + { + switch (externalTimerTimes % 5) + { + case 0: + pictureBox_OpName.BackgroundImage = Properties.Resources.PlcConnect0; + break; + case 1: + pictureBox_OpName.BackgroundImage = Properties.Resources.PlcConnect1; + break; + case 2: + pictureBox_OpName.BackgroundImage = Properties.Resources.PlcConnect2; + break; + case 3: + pictureBox_OpName.BackgroundImage = Properties.Resources.PlcConnect3; + break; + case 4: + pictureBox_OpName.BackgroundImage = Properties.Resources.PlcConnect4; + break; + + } + } + else + { + pictureBox_OpName.BackgroundImage = Properties.Resources.BreakPLC; + } + + + TimerTimeChange(); + } + + + + + public void ExternalPlcConnect() + { + testPlcBreakTime = (testPlcBreakInterval / externalTimerInterval) + 1; + isBreakPLC = false; + + } + + public void PlcBreak() + { + pictureBox_OpName.BackgroundImage = Properties.Resources.BreakPLC; + isBreakPLC = true; + } + + #endregion + + #region 属性 + + [Browsable(true)] + [Description("控件中显示的文本内容"), Category("外观"), DefaultValue("OP0000")] + public string LabelText + { + get + { + return label_OpName.Text; + } + + set + { + label_OpName.Text = value; + } + + } + + + [Browsable(true)] + [Description("外部定时器周期"), Category("行为"), DefaultValue("200")] + public int ExternalTimerInterval + { + get + { + return externalTimerInterval; + } + + set + { + externalTimerInterval = value; + } + + } + + [Browsable(true)] + [Description("检测PLC在线状态超时,超过此时间,PLC为离线状态"), Category("行为"), DefaultValue("200")] + public int TestPlcBreakInterval + { + get + { + return testPlcBreakInterval; + } + + set + { + testPlcBreakInterval = value; + } + + } + + [Browsable(true)] + [Description("指示PLC是否为断开状态"), Category("行为"), DefaultValue("True")] + public bool IsBreakPLC + { + get + { + return isBreakPLC; + } + + set + { + isBreakPLC = value; + } + + } + + [Browsable(true)] + [Description("是否启用检测PLC在线状态功能"), Category("行为"), DefaultValue("True")] + public bool PlcTestEnable + { + get + { + return plcTestEnable; + } + + set + { + plcTestEnable = value; + } + + } + + #endregion + + + } +} diff --git a/Common/MesControl/PlcConnect.resx b/Common/MesControl/PlcConnect.resx new file mode 100644 index 0000000..0abf881 --- /dev/null +++ b/Common/MesControl/PlcConnect.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/Common/MesControl/PlcWorkStationSignal.Designer.cs b/Common/MesControl/PlcWorkStationSignal.Designer.cs new file mode 100644 index 0000000..e4e1488 --- /dev/null +++ b/Common/MesControl/PlcWorkStationSignal.Designer.cs @@ -0,0 +1,80 @@ +namespace MesControl +{ + partial class PlcWorkStationSignal + { + /// + /// 必需的设计器变量。 + /// + private System.ComponentModel.IContainer components = null; + + /// + /// 清理所有正在使用的资源。 + /// + /// 如果应释放托管资源,为 true;否则为 false。 + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region 组件设计器生成的代码 + + /// + /// 设计器支持所需的方法 - 不要修改 + /// 使用代码编辑器修改此方法的内容。 + /// + private void InitializeComponent() + { + this.groupBox_WorkStationGrp = new System.Windows.Forms.GroupBox(); + this.plcConnect_WorkStation = new MesControl.PlcConnect(); + this.groupBox_WorkStationGrp.SuspendLayout(); + this.SuspendLayout(); + // + // groupBox_WorkStationGrp + // + this.groupBox_WorkStationGrp.BackColor = System.Drawing.Color.Transparent; + this.groupBox_WorkStationGrp.Controls.Add(this.plcConnect_WorkStation); + this.groupBox_WorkStationGrp.Location = new System.Drawing.Point(4, 4); + this.groupBox_WorkStationGrp.Name = "groupBox_WorkStationGrp"; + this.groupBox_WorkStationGrp.Size = new System.Drawing.Size(125, 50); + this.groupBox_WorkStationGrp.TabIndex = 0; + this.groupBox_WorkStationGrp.TabStop = false; + this.groupBox_WorkStationGrp.Text = "OP0000"; + // + // plcConnect_WorkStation + // + this.plcConnect_WorkStation.BackColor = System.Drawing.Color.Transparent; + this.plcConnect_WorkStation.ExternalTimerInterval = 200; + this.plcConnect_WorkStation.IsBreakPLC = false; + this.plcConnect_WorkStation.LabelText = "通讯状态"; + this.plcConnect_WorkStation.Location = new System.Drawing.Point(7, 21); + this.plcConnect_WorkStation.MaximumSize = new System.Drawing.Size(110, 22); + this.plcConnect_WorkStation.MinimumSize = new System.Drawing.Size(110, 22); + this.plcConnect_WorkStation.Name = "plcConnect_WorkStation"; + this.plcConnect_WorkStation.PlcTestEnable = false; + this.plcConnect_WorkStation.Size = new System.Drawing.Size(110, 22); + this.plcConnect_WorkStation.TabIndex = 0; + this.plcConnect_WorkStation.TestPlcBreakInterval = 0; + // + // PlcWorkStationSignal + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.BackColor = System.Drawing.Color.Transparent; + this.Controls.Add(this.groupBox_WorkStationGrp); + this.Name = "PlcWorkStationSignal"; + this.Size = new System.Drawing.Size(136, 60); + this.groupBox_WorkStationGrp.ResumeLayout(false); + this.ResumeLayout(false); + + } + + #endregion + + private System.Windows.Forms.GroupBox groupBox_WorkStationGrp; + private PlcConnect plcConnect_WorkStation; + } +} diff --git a/Common/MesControl/PlcWorkStationSignal.cs b/Common/MesControl/PlcWorkStationSignal.cs new file mode 100644 index 0000000..eb47a8c --- /dev/null +++ b/Common/MesControl/PlcWorkStationSignal.cs @@ -0,0 +1,225 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Drawing; +using System.Data; +using System.Linq; +using System.Text; +using System.Windows.Forms; + +namespace MesControl +{ + public delegate void WorkStationPlcBreakChanged(); + public partial class PlcWorkStationSignal : UserControl + { + public PlcWorkStationSignal() + { + InitializeComponent(); + PlcConnect.PlcBreakChange = new PlcStatusHandle(internalPlcBreak); + PlcConnect.PlcConnectChange = new PlcStatusHandle(internalPlcConnect); + + } + + public EventHandler WorkStationPlcStatusChange; + + #region 工位信号方法与属性 + + public void InitSignalControl() + { + + + for (int i = 0; i < SignalItems.Count; i++) + { + + MesBoolSignal mesBoolSignalNew = new MesBoolSignal(); + this.groupBox_WorkStationGrp.Controls.Add(mesBoolSignalNew);//扩展GroupBox + mesBoolSignalNew.BackColor = System.Drawing.Color.Transparent; + mesBoolSignalNew.Location = new System.Drawing.Point(7, 46 + (25 * i)); + mesBoolSignalNew.Name = SignalItems[i].Name; + mesBoolSignalNew.SignalImage = MesBoolSignal.SignalImage_Enum.none; + mesBoolSignalNew.SignalText = SignalItems[i].SignalText; + mesBoolSignalNew.Size = new System.Drawing.Size(110, 22); + mesBoolSignalNew.TabIndex = i; + + } + + //groupbox大小 + groupBox_WorkStationGrp.Size = new Size(125, 50 + (SignalItems.Count * 25)); + //控件大小 + this.Size = new Size(136, 60 + (SignalItems.Count * 25)); + + } + + private List signalItems = new List(); + [Browsable(true)] + [Description("MES信号控件集合"), Category("数据")] + [TypeConverter(typeof(System.ComponentModel.CollectionConverter))] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] + public List SignalItems + { + get + { + return signalItems; + } + + set + { + signalItems = value; + InitSignalControl(); + } + } + + /// + ///更改工位各个信号状态(默认) + /// + /// + /// + public void SignalChange(string SignalName, bool Value) + { + MesBoolSignal thisControl = (MesBoolSignal)Controls.Find(SignalName, true)[0]; + if (thisControl != null) + thisControl.SignalImage = Value ? MesBoolSignal.SignalImage_Enum.green : MesBoolSignal.SignalImage_Enum.init; + + } + + #endregion + + #region PLC在线状态属性与方法 + + ///////////////////////////////////////////////方法/////////////////////////////////////////////////// + + public void PlcConnectStatusChange(bool value) + { + plcConnect_WorkStation.ExternalPlcConnect(); + + } + public void ExternalTimerExcute() + { + plcConnect_WorkStation.ExternalTimer(); + } + + public void PlcBreak() + { + plcConnect_WorkStation.PlcBreak(); + } + + void internalPlcBreak() + { + if (WorkStationPlcStatusChange != null) + { + WorkStationPlcStatusChange(groupBox_WorkStationGrp.Text+"&Breaked",null); + } + + } + + void internalPlcConnect() + { + if (WorkStationPlcStatusChange != null) + { + WorkStationPlcStatusChange(groupBox_WorkStationGrp.Text + "&Connected", null); + } + } + + + //////////////////////////////////////////////////////////////属性/////////////////////////////////////////////// + + [Browsable(true)] + [Description("检测PLC在线状态开关"), Category("行为"), DefaultValue(true)] + public bool TestPLC_Enable + { + get + { + return plcConnect_WorkStation.PlcTestEnable; + } + set + { + plcConnect_WorkStation.PlcTestEnable = value; + } + } + + [Browsable(true)] + [Description("PLC心跳超时(超过此时间认为PLC离线)"), Category("行为"), DefaultValue(10000)] + public int TestPLC_Interval + { + get + { + return plcConnect_WorkStation.TestPlcBreakInterval; + } + set + { + + plcConnect_WorkStation.TestPlcBreakInterval = value; + + } + } + + + [Browsable(true)] + [Description("外部定时器循环时间"), Category("行为"), DefaultValue(200)] + public int ExternalTimerInterval + { + get + { + return plcConnect_WorkStation.ExternalTimerInterval; + } + set + { + plcConnect_WorkStation.ExternalTimerInterval = value; + } + } + + [Browsable(true)] + [Description("PLC在线状态"), Category("行为"), DefaultValue(false)] + public bool PLC_ConnectStatus + { + get + { + return plcConnect_WorkStation.IsBreakPLC; + } + set + { + plcConnect_WorkStation.IsBreakPLC = value; + } + } + + #endregion + + #region 当前控件方法与属性 + + [Browsable(true)] + [Description("控件显示的工位号"), Category("外观"), DefaultValue("OP0000")] + public string WorkStationNameText + { + get + { + return groupBox_WorkStationGrp.Text; + } + set + { + groupBox_WorkStationGrp.Text = value; + + } + + } + + [Browsable(true)] + [Description("控件中plc通讯显示的文本内容"), Category("外观"), DefaultValue("PLC连接")] + public string WS_PlcLabelText + { + get + { + return plcConnect_WorkStation.LabelText ; + } + + set + { + plcConnect_WorkStation.LabelText = value; + } + + } + + + #endregion + + } +} diff --git a/Common/MesControl/PlcWorkStationSignal.resx b/Common/MesControl/PlcWorkStationSignal.resx new file mode 100644 index 0000000..48f62a6 --- /dev/null +++ b/Common/MesControl/PlcWorkStationSignal.resx @@ -0,0 +1,123 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + \ No newline at end of file diff --git a/Common/MesControl/Properties/AssemblyInfo.cs b/Common/MesControl/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..68d5529 --- /dev/null +++ b/Common/MesControl/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// 有关程序集的一般信息由以下 +// 控制。更改这些特性值可修改 +// 与程序集关联的信息。 +[assembly: AssemblyTitle("MesControl")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("MesControl")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +//将 ComVisible 设置为 false 将使此程序集中的类型 +//对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型, +//请将此类型的 ComVisible 特性设置为 true。 +[assembly: ComVisible(false)] + +// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID +[assembly: Guid("fab322cc-531d-4aea-986a-b921b64d8d3f")] + +// 程序集的版本信息由下列四个值组成: +// +// 主版本 +// 次版本 +// 生成号 +// 修订号 +// +//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, +// 方法是按如下所示使用“*”: : +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Common/MesControl/Properties/Resources.Designer.cs b/Common/MesControl/Properties/Resources.Designer.cs new file mode 100644 index 0000000..543a51e --- /dev/null +++ b/Common/MesControl/Properties/Resources.Designer.cs @@ -0,0 +1,193 @@ +//------------------------------------------------------------------------------ +// +// 此代码由工具生成。 +// 运行时版本:4.0.30319.42000 +// +// 对此文件的更改可能会导致不正确的行为,并且如果 +// 重新生成代码,这些更改将会丢失。 +// +//------------------------------------------------------------------------------ + +namespace MesControl.Properties { + using System; + + + /// + /// 一个强类型的资源类,用于查找本地化的字符串等。 + /// + // 此类是由 StronglyTypedResourceBuilder + // 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。 + // 若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen + // (以 /str 作为命令选项),或重新生成 VS 项目。 + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.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 (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("MesControl.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// 重写当前线程的 CurrentUICulture 属性 + /// 重写当前线程的 CurrentUICulture 属性。 + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + + /// + /// 查找 System.Drawing.Bitmap 类型的本地化资源。 + /// + internal static System.Drawing.Bitmap BreakPLC { + get { + object obj = ResourceManager.GetObject("BreakPLC", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// 查找 System.Drawing.Bitmap 类型的本地化资源。 + /// + internal static System.Drawing.Bitmap green { + get { + object obj = ResourceManager.GetObject("green", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// 查找 System.Drawing.Bitmap 类型的本地化资源。 + /// + internal static System.Drawing.Bitmap init { + get { + object obj = ResourceManager.GetObject("init", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// 查找 System.Drawing.Bitmap 类型的本地化资源。 + /// + internal static System.Drawing.Bitmap none { + get { + object obj = ResourceManager.GetObject("none", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// 查找 System.Drawing.Bitmap 类型的本地化资源。 + /// + internal static System.Drawing.Bitmap PlcConnect0 { + get { + object obj = ResourceManager.GetObject("PlcConnect0", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// 查找 System.Drawing.Bitmap 类型的本地化资源。 + /// + internal static System.Drawing.Bitmap PlcConnect1 { + get { + object obj = ResourceManager.GetObject("PlcConnect1", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// 查找 System.Drawing.Bitmap 类型的本地化资源。 + /// + internal static System.Drawing.Bitmap PlcConnect2 { + get { + object obj = ResourceManager.GetObject("PlcConnect2", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// 查找 System.Drawing.Bitmap 类型的本地化资源。 + /// + internal static System.Drawing.Bitmap PlcConnect3 { + get { + object obj = ResourceManager.GetObject("PlcConnect3", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// 查找 System.Drawing.Bitmap 类型的本地化资源。 + /// + internal static System.Drawing.Bitmap PlcConnect4 { + get { + object obj = ResourceManager.GetObject("PlcConnect4", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// 查找 System.Drawing.Bitmap 类型的本地化资源。 + /// + internal static System.Drawing.Bitmap PlcConnectBig { + get { + object obj = ResourceManager.GetObject("PlcConnectBig", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// 查找 System.Drawing.Bitmap 类型的本地化资源。 + /// + internal static System.Drawing.Bitmap PlcConnectSmall { + get { + object obj = ResourceManager.GetObject("PlcConnectSmall", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// 查找 System.Drawing.Bitmap 类型的本地化资源。 + /// + internal static System.Drawing.Bitmap red { + get { + object obj = ResourceManager.GetObject("red", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// 查找 System.Drawing.Bitmap 类型的本地化资源。 + /// + internal static System.Drawing.Bitmap yellow { + get { + object obj = ResourceManager.GetObject("yellow", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + } +} diff --git a/Common/MesControl/Properties/Resources.resx b/Common/MesControl/Properties/Resources.resx new file mode 100644 index 0000000..e9eebfc --- /dev/null +++ b/Common/MesControl/Properties/Resources.resx @@ -0,0 +1,160 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + + ..\Resources\red.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\yellow.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\PlcConnect1.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\PlcConnect0.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\PlcConnect3.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\none.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\PlcConnectSmall.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\PlcConnect2.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\init.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\PlcConnectBig.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\BreakPLC.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\green.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\PlcConnect4.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + \ No newline at end of file diff --git a/Common/MesControl/Properties/_system~.ini b/Common/MesControl/Properties/_system~.ini new file mode 100644 index 0000000..e69de29 diff --git a/Common/MesControl/Resources/BreakPLC.png b/Common/MesControl/Resources/BreakPLC.png new file mode 100644 index 0000000..4873366 Binary files /dev/null and b/Common/MesControl/Resources/BreakPLC.png differ diff --git a/Common/MesControl/Resources/PlcConnect0.png b/Common/MesControl/Resources/PlcConnect0.png new file mode 100644 index 0000000..73e71bd Binary files /dev/null and b/Common/MesControl/Resources/PlcConnect0.png differ diff --git a/Common/MesControl/Resources/PlcConnect1.png b/Common/MesControl/Resources/PlcConnect1.png new file mode 100644 index 0000000..8c0a417 Binary files /dev/null and b/Common/MesControl/Resources/PlcConnect1.png differ diff --git a/Common/MesControl/Resources/PlcConnect2.png b/Common/MesControl/Resources/PlcConnect2.png new file mode 100644 index 0000000..671a278 Binary files /dev/null and b/Common/MesControl/Resources/PlcConnect2.png differ diff --git a/Common/MesControl/Resources/PlcConnect3.png b/Common/MesControl/Resources/PlcConnect3.png new file mode 100644 index 0000000..165eaeb Binary files /dev/null and b/Common/MesControl/Resources/PlcConnect3.png differ diff --git a/Common/MesControl/Resources/PlcConnect4.png b/Common/MesControl/Resources/PlcConnect4.png new file mode 100644 index 0000000..9fc042d Binary files /dev/null and b/Common/MesControl/Resources/PlcConnect4.png differ diff --git a/Common/MesControl/Resources/PlcConnectBig.png b/Common/MesControl/Resources/PlcConnectBig.png new file mode 100644 index 0000000..f2a21c0 Binary files /dev/null and b/Common/MesControl/Resources/PlcConnectBig.png differ diff --git a/Common/MesControl/Resources/PlcConnectSmall.png b/Common/MesControl/Resources/PlcConnectSmall.png new file mode 100644 index 0000000..8f43514 Binary files /dev/null and b/Common/MesControl/Resources/PlcConnectSmall.png differ diff --git a/Common/MesControl/Resources/_system~.ini b/Common/MesControl/Resources/_system~.ini new file mode 100644 index 0000000..e69de29 diff --git a/Common/MesControl/Resources/green.png b/Common/MesControl/Resources/green.png new file mode 100644 index 0000000..c4b463e Binary files /dev/null and b/Common/MesControl/Resources/green.png differ diff --git a/Common/MesControl/Resources/init.png b/Common/MesControl/Resources/init.png new file mode 100644 index 0000000..c148366 Binary files /dev/null and b/Common/MesControl/Resources/init.png differ diff --git a/Common/MesControl/Resources/none.png b/Common/MesControl/Resources/none.png new file mode 100644 index 0000000..8ec6c8d Binary files /dev/null and b/Common/MesControl/Resources/none.png differ diff --git a/Common/MesControl/Resources/red.png b/Common/MesControl/Resources/red.png new file mode 100644 index 0000000..26a05cb Binary files /dev/null and b/Common/MesControl/Resources/red.png differ diff --git a/Common/MesControl/Resources/yellow.png b/Common/MesControl/Resources/yellow.png new file mode 100644 index 0000000..ee71881 Binary files /dev/null and b/Common/MesControl/Resources/yellow.png differ diff --git a/Common/MesControl/SignalInit.cs b/Common/MesControl/SignalInit.cs new file mode 100644 index 0000000..3b5b0a8 --- /dev/null +++ b/Common/MesControl/SignalInit.cs @@ -0,0 +1,37 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace MesControl +{ + public partial class PlcWorkStationSignal + { + void initsignal() + { + //private PlcConnect plcConnect_WorkStation; + //this.plcConnect_WorkStation = new MesControl.PlcConnect(); + //this.groupBox_WorkStationGrp.Controls.Add(this.plcConnect_WorkStation); + + //// + //// plcConnect_WorkStation + //// + //this.plcConnect_WorkStation.BackColor = System.Drawing.Color.Transparent; + //this.plcConnect_WorkStation.ExternalTimerInterval = 200; + //this.plcConnect_WorkStation.IsBreakPLC = false; + //this.plcConnect_WorkStation.LabelText = "通讯状态"; + //this.plcConnect_WorkStation.Location = new System.Drawing.Point(7, 21); + //this.plcConnect_WorkStation.MaximumSize = new System.Drawing.Size(110, 22); + //this.plcConnect_WorkStation.MinimumSize = new System.Drawing.Size(110, 22); + //this.plcConnect_WorkStation.Name = "plcConnect_WorkStation"; + //this.plcConnect_WorkStation.PlcTestEnable = false; + //this.plcConnect_WorkStation.Size = new System.Drawing.Size(110, 22); + //this.plcConnect_WorkStation.TabIndex = 0; + //this.plcConnect_WorkStation.TestPlcBreakInterval = 0; + + } + + + + } +} diff --git a/Common/MesControl/_system~.ini b/Common/MesControl/_system~.ini new file mode 100644 index 0000000..e69de29 diff --git a/Common/MyLog4Net/00_MyLog4Net.csproj b/Common/MyLog4Net/00_MyLog4Net.csproj new file mode 100644 index 0000000..1c1c6ad --- /dev/null +++ b/Common/MyLog4Net/00_MyLog4Net.csproj @@ -0,0 +1,61 @@ + + + + + Debug + AnyCPU + {1DC48C83-1842-4DE8-ACAF-26E1E7F7C58F} + Library + Properties + MyLog4Net + MyLog4Net + v4.8 + 512 + true + + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + ..\packages\log4net.2.0.14\lib\net45\log4net.dll + + + + + + + + + + + + + + + + + + + + + Always + + + + \ No newline at end of file diff --git a/Common/MyLog4Net/MyLogEventArgs.cs b/Common/MyLog4Net/MyLogEventArgs.cs new file mode 100644 index 0000000..a913363 --- /dev/null +++ b/Common/MyLog4Net/MyLogEventArgs.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MyLog4Net +{ + public class MyLogEventArgs : EventArgs + { + public string Message { get; set; } + public string Module { get; set; } + } +} diff --git a/Common/MyLog4Net/MyLogHelper.cs b/Common/MyLog4Net/MyLogHelper.cs new file mode 100644 index 0000000..cb446e4 --- /dev/null +++ b/Common/MyLog4Net/MyLogHelper.cs @@ -0,0 +1,65 @@ +using log4net; +using System; + +namespace MyLog4Net +{ + public class MyLogHelper + { + public delegate void MyLogEventHandler(object sender, MyLogEventArgs e); + public static event MyLogEventHandler LogCommit; + + /// + /// 普通日志 + /// + /// 日志内容 + public static void Info(string module, string message) + { + ILog log = LogManager.GetLogger(module); + if (log.IsInfoEnabled) + { + log.Info(message); + + var e = new MyLogEventArgs(); + e.Module = module; + e.Message = message; + LogCommit?.Invoke(null, e); + } + } + /// + /// 错误日志带异常 + /// + /// 错误日志 + public static void Error(string module, string message, Exception ex) + { + ILog log = LogManager.GetLogger(module); + if (log.IsErrorEnabled) + { + log.Error(message, ex); + + var e = new MyLogEventArgs(); + e.Module = module; + e.Message = message; + LogCommit?.Invoke(null, e); + } + } + + /// + /// 错误日志不带异常 + /// + /// 错误日志 + public static void Error(string module, string message) + { + ILog log = LogManager.GetLogger(module); + if (log.IsErrorEnabled) + { + log.Error(message); + + var e = new MyLogEventArgs(); + e.Module = module; + e.Message = message; + LogCommit?.Invoke(null, e); + } + } + } + +} diff --git a/Common/MyLog4Net/Properties/AssemblyInfo.cs b/Common/MyLog4Net/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..1228254 --- /dev/null +++ b/Common/MyLog4Net/Properties/AssemblyInfo.cs @@ -0,0 +1,37 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Log4Net")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("Log4Net")] +[assembly: AssemblyCopyright("Copyright © 2022")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("1dc48c83-1842-4de8-acaf-26e1e7f7c58f")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] +[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)] diff --git a/Common/MyLog4Net/log4net.config b/Common/MyLog4Net/log4net.config new file mode 100644 index 0000000..92f4d40 --- /dev/null +++ b/Common/MyLog4Net/log4net.config @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Common/MyLog4Net/packages.config b/Common/MyLog4Net/packages.config new file mode 100644 index 0000000..a0798f9 --- /dev/null +++ b/Common/MyLog4Net/packages.config @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/Common/WebApiDll/DoWhatPlc.dll b/Common/WebApiDll/DoWhatPlc.dll new file mode 100644 index 0000000..8f218b4 Binary files /dev/null and b/Common/WebApiDll/DoWhatPlc.dll differ diff --git a/Common/WebApiDll/DoWhatPlc.pdb b/Common/WebApiDll/DoWhatPlc.pdb new file mode 100644 index 0000000..5f70e79 Binary files /dev/null and b/Common/WebApiDll/DoWhatPlc.pdb differ diff --git a/Common/WebApiDll/Newtonsoft.Json.dll b/Common/WebApiDll/Newtonsoft.Json.dll new file mode 100644 index 0000000..55d537f Binary files /dev/null and b/Common/WebApiDll/Newtonsoft.Json.dll differ diff --git a/Common/dll/00.1Newtonsoft.Json.dll b/Common/dll/00.1Newtonsoft.Json.dll new file mode 100644 index 0000000..fe004fd Binary files /dev/null and b/Common/dll/00.1Newtonsoft.Json.dll differ diff --git a/Common/dll/00.1Newtonsoft.Json.pdb b/Common/dll/00.1Newtonsoft.Json.pdb new file mode 100644 index 0000000..b9b7b33 Binary files /dev/null and b/Common/dll/00.1Newtonsoft.Json.pdb differ diff --git a/Common/dll/00MesWorkMqtt.dll b/Common/dll/00MesWorkMqtt.dll new file mode 100644 index 0000000..a480e9f Binary files /dev/null and b/Common/dll/00MesWorkMqtt.dll differ diff --git a/Common/dll/00MesWorkMqtt.pdb b/Common/dll/00MesWorkMqtt.pdb new file mode 100644 index 0000000..03a50bf Binary files /dev/null and b/Common/dll/00MesWorkMqtt.pdb differ diff --git a/Common/dll/01DoWhatPlc.dll b/Common/dll/01DoWhatPlc.dll new file mode 100644 index 0000000..9bd5bc9 Binary files /dev/null and b/Common/dll/01DoWhatPlc.dll differ diff --git a/Common/dll/01DoWhatPlc.pdb b/Common/dll/01DoWhatPlc.pdb new file mode 100644 index 0000000..1bcb207 Binary files /dev/null and b/Common/dll/01DoWhatPlc.pdb differ diff --git a/Common/dll/02WebApiCall.dll b/Common/dll/02WebApiCall.dll new file mode 100644 index 0000000..c6c9aa8 Binary files /dev/null and b/Common/dll/02WebApiCall.dll differ diff --git a/Common/dll/02WebApiCall.dll.config b/Common/dll/02WebApiCall.dll.config new file mode 100644 index 0000000..b740b86 --- /dev/null +++ b/Common/dll/02WebApiCall.dll.config @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/Common/dll/02WebApiCall.pdb b/Common/dll/02WebApiCall.pdb new file mode 100644 index 0000000..ea8e015 Binary files /dev/null and b/Common/dll/02WebApiCall.pdb differ diff --git a/Common/dll/04DataBaseAccess.dll b/Common/dll/04DataBaseAccess.dll new file mode 100644 index 0000000..74ebd53 Binary files /dev/null and b/Common/dll/04DataBaseAccess.dll differ diff --git a/Common/dll/04DataBaseAccess.pdb b/Common/dll/04DataBaseAccess.pdb new file mode 100644 index 0000000..ccbde38 Binary files /dev/null and b/Common/dll/04DataBaseAccess.pdb differ diff --git a/Common/dll/07BusinessFacade.dll b/Common/dll/07BusinessFacade.dll new file mode 100644 index 0000000..a881932 Binary files /dev/null and b/Common/dll/07BusinessFacade.dll differ diff --git a/Common/dll/07BusinessFacade.pdb b/Common/dll/07BusinessFacade.pdb new file mode 100644 index 0000000..bec0dfb Binary files /dev/null and b/Common/dll/07BusinessFacade.pdb differ diff --git a/Common/dll/08WebFun_base.dll b/Common/dll/08WebFun_base.dll new file mode 100644 index 0000000..aa1cbe6 Binary files /dev/null and b/Common/dll/08WebFun_base.dll differ diff --git a/Common/dll/08WebFun_base.pdb b/Common/dll/08WebFun_base.pdb new file mode 100644 index 0000000..4c7e173 Binary files /dev/null and b/Common/dll/08WebFun_base.pdb differ diff --git a/Common/dll/09MesDataFunction.dll b/Common/dll/09MesDataFunction.dll new file mode 100644 index 0000000..0bc974a Binary files /dev/null and b/Common/dll/09MesDataFunction.dll differ diff --git a/Common/dll/09MesDataFunction.pdb b/Common/dll/09MesDataFunction.pdb new file mode 100644 index 0000000..716b2df Binary files /dev/null and b/Common/dll/09MesDataFunction.pdb differ diff --git a/Common/dll/99DataBaseAccess2.dll b/Common/dll/99DataBaseAccess2.dll new file mode 100644 index 0000000..ac680ff Binary files /dev/null and b/Common/dll/99DataBaseAccess2.dll differ diff --git a/Common/dll/99DataBaseAccess2.pdb b/Common/dll/99DataBaseAccess2.pdb new file mode 100644 index 0000000..e013850 Binary files /dev/null and b/Common/dll/99DataBaseAccess2.pdb differ diff --git a/Common/dll/BasicData.dll b/Common/dll/BasicData.dll new file mode 100644 index 0000000..8dfe09b Binary files /dev/null and b/Common/dll/BasicData.dll differ diff --git a/Common/dll/BasicData.pdb b/Common/dll/BasicData.pdb new file mode 100644 index 0000000..e432017 Binary files /dev/null and b/Common/dll/BasicData.pdb differ diff --git a/Common/dll/BouncyCastle.Crypto.dll b/Common/dll/BouncyCastle.Crypto.dll new file mode 100644 index 0000000..0310983 Binary files /dev/null and b/Common/dll/BouncyCastle.Crypto.dll differ diff --git a/Common/dll/BusinessFacade.pdb b/Common/dll/BusinessFacade.pdb new file mode 100644 index 0000000..2e1bfcb Binary files /dev/null and b/Common/dll/BusinessFacade.pdb differ diff --git a/Common/dll/ConLink.dll b/Common/dll/ConLink.dll new file mode 100644 index 0000000..6ccb558 Binary files /dev/null and b/Common/dll/ConLink.dll differ diff --git a/Common/dll/DataLinkMesWork.dll b/Common/dll/DataLinkMesWork.dll new file mode 100644 index 0000000..57fcd25 Binary files /dev/null and b/Common/dll/DataLinkMesWork.dll differ diff --git a/Common/dll/DoWhatPlc.dll b/Common/dll/DoWhatPlc.dll new file mode 100644 index 0000000..8f218b4 Binary files /dev/null and b/Common/dll/DoWhatPlc.dll differ diff --git a/Common/dll/DoWhatPlc.pdb b/Common/dll/DoWhatPlc.pdb new file mode 100644 index 0000000..5f70e79 Binary files /dev/null and b/Common/dll/DoWhatPlc.pdb differ diff --git a/Common/dll/ICSharpCode.SharpZipLib.dll b/Common/dll/ICSharpCode.SharpZipLib.dll new file mode 100644 index 0000000..84e8c68 Binary files /dev/null and b/Common/dll/ICSharpCode.SharpZipLib.dll differ diff --git a/Common/dll/MQTTnet.Extensions.ManagedClient.dll b/Common/dll/MQTTnet.Extensions.ManagedClient.dll new file mode 100644 index 0000000..99035f6 Binary files /dev/null and b/Common/dll/MQTTnet.Extensions.ManagedClient.dll differ diff --git a/Common/dll/MQTTnet.dll b/Common/dll/MQTTnet.dll new file mode 100644 index 0000000..2951433 Binary files /dev/null and b/Common/dll/MQTTnet.dll differ diff --git a/Common/dll/MesWork.DeviceDriver.dll b/Common/dll/MesWork.DeviceDriver.dll new file mode 100644 index 0000000..a6ec60f Binary files /dev/null and b/Common/dll/MesWork.DeviceDriver.dll differ diff --git a/Common/dll/MesWork.DeviceDriver.pdb b/Common/dll/MesWork.DeviceDriver.pdb new file mode 100644 index 0000000..6ebff64 Binary files /dev/null and b/Common/dll/MesWork.DeviceDriver.pdb differ diff --git a/Common/dll/MesWork.PLC.dll b/Common/dll/MesWork.PLC.dll new file mode 100644 index 0000000..3399040 Binary files /dev/null and b/Common/dll/MesWork.PLC.dll differ diff --git a/Common/dll/MesWork.PLC.pdb b/Common/dll/MesWork.PLC.pdb new file mode 100644 index 0000000..af5273f Binary files /dev/null and b/Common/dll/MesWork.PLC.pdb differ diff --git a/Common/dll/Monitor.MesWork.dll b/Common/dll/Monitor.MesWork.dll new file mode 100644 index 0000000..1874ca5 Binary files /dev/null and b/Common/dll/Monitor.MesWork.dll differ diff --git a/Common/dll/Monitor.MesWork.pdb b/Common/dll/Monitor.MesWork.pdb new file mode 100644 index 0000000..a2c1b3f Binary files /dev/null and b/Common/dll/Monitor.MesWork.pdb differ diff --git a/Common/dll/Monitor.MesWork.xml b/Common/dll/Monitor.MesWork.xml new file mode 100644 index 0000000..f978604 --- /dev/null +++ b/Common/dll/Monitor.MesWork.xml @@ -0,0 +1,2860 @@ + + + + Monitor.MesWork + + + + + AlarmListView 的摘要说明。 + + + + + 从OnDataChange发送int tagID, int tagValue到处理程序 + private void OnDataChange(int tagID, int tagValue) + + + + + + + 从OnDataChange发送int tagID, int tagValue到处理程序 + private void OnDataChange(int tagID, int tagValue) + + + + + 必需的设计器变量。 + + + + + 当时发生的报警总行数 + + + + + + + + + + 清理所有正在使用的资源。 + + + + + 设计器支持所需的方法 - 不要使用代码编辑器 + 修改此方法的内容。 + + + + + 报警到达 + + + + + 报警到达 + + + + + 报警解除 + + + + + 报警解除 + + + + + 报警确认 + + + + + 报警确认 + + + + + 报警过滤条件 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 报警过滤条件 + + + + + 从系统获得 + =null 时,初始化时显示全部报警 + =AlarmItemSelect,初始化时显示AlarmItemSelect条件报警 + + + + + + + + + + 报警到达文字颜色 + + + + + 报警到达文本底色 + + + + + 报警解除文字颜色 + + + + + 报警解除文本底色 + + + + + 报警确认文字颜色 + + + + + 报警确认文本底色 + + + + + 初始化报警显示 + + + + + 报警控件,监控值变化时,图形重绘 + + + + + + 增加TagKey + + + + + =true,调Gif;false不调Gif + + + + + Gif图像 + + + + + Gif图像 + + + + + IsRotation =0不调用Gif;=1调用Gif TagValueType + + + + + IsRotation =0不调用Gif;=1调用Gif + + + + + Tag位置0时颜色 1 + + + + + Tag位置1时颜色 2 + + + + + Tag位置2时颜色 4 + + + + + Tag位置3时颜色 8 + + + + + Tag位置4时颜色 16 + + + + + Tag位置5时颜色 32 + + + + + Tag位置6时颜色 64 + + + + + Tag位置7时颜色 128 + + + + + 设置Tag位置0时颜色 + + + + + 设置Tag位置1时颜色 + + + + + 设置Tag位置2时颜色 + + + + + 设置Tag位置3时颜色 + + + + + 设置Tag位置4时颜色 + + + + + 设置Tag位置5时颜色 + + + + + 设置Tag位置6时颜色 + + + + + 设置Tag位置7时颜色 + + + + + TagKey 显示选项 + + + + + TagKey 显示选项 + + + + + OpName + 工位名称 + + + + + OpName + 工位名称 + + + + + 序号 + + + + + 序号 + + + + + 是否保存到数据库 + + + + + LineColor设置外园线颜色 + + + + + Tag位置1时颜色 + + + + + Tag位置0时颜色 + + + + + 变量值 + + + + + 变量值 + + + + + TagBit变量测试位 + + + + + Tag位置1时颜色 + + + + + Tag位置0时颜色 + + + + + TagBit变量测试位 + + + + + LineColor设置外园线颜色 + + + + + 是否保存到数据库 + + + + + + + + + + + + + + + 绘制图形 + + + + + + 正常绘制 + + + + + + 显示Gif + + + + + + 增加TagKey + + + + + =true,调Gif;false不调Gif + + + + + Gif图像 + + + + + IsRotation =0不调用Gif;=1调用Gif TagValueType + + + + + IsRotation =0不调用Gif;=1调用Gif + + + + + Tag位置0时颜色 1 + + + + + Tag位置1时颜色 2 + + + + + Tag位置2时颜色 4 + + + + + Tag位置3时颜色 8 + + + + + Tag位置4时颜色 16 + + + + + Tag位置5时颜色 32 + + + + + Tag位置6时颜色 64 + + + + + Tag位置7时颜色 128 + + + + + 设置Tag位置0时颜色 + + + + + 设置Tag位置1时颜色 + + + + + 设置Tag位置2时颜色 + + + + + 设置Tag位置3时颜色 + + + + + 设置Tag位置4时颜色 + + + + + 设置Tag位置5时颜色 + + + + + 设置Tag位置6时颜色 + + + + + 设置Tag位置7时颜色 + + + + + TagKey 显示选项 + + + + + TagKey 显示选项 + + + + + OpName + 工位名称 + + + + + OpName + 工位名称 + + + + + 序号 + + + + + 序号 + + + + + 是否保存到数据库 + + + + + LineColor设置外园线颜色 + + + + + Tag位置1时颜色 + + + + + Tag位置0时颜色 + + + + + 变量值 + + + + + 变量值 + + + + + TagBit变量测试位 + + + + + Tag位置1时颜色 + + + + + Tag位置0时颜色 + + + + + TagBit变量测试位 + + + + + LineColor设置外园线颜色 + + + + + 是否保存到数据库 + + + + + + + + + + + + + + + 绘制图形 + + + + + + 正常绘制 + + + + + + 显示Gif + + + + + + PlcLinkStatus 的摘要说明。 + + + + + 显示PLC连接状态 + + + + + + PLC连接正常时图形 + + + + + PLC连接正常时图形 + + + + + PLC连接不正常时图形 + + + + + PLC连接不正常时图形 + + + + + + + + + + 清理所有正在使用的资源。 + + + + + 设计器支持所需的方法 - 不要使用代码编辑器 + 修改此方法的内容。 + + + + + PlcLinkStatusWork 的摘要说明。 + + + + + OpName + 工位名称 + + + + + OpName + 工位名称 + + + + + + + + + + 根据变量是否正确,显示通讯状态 通讯数据交换 + + + + + + 通讯正常 + + + + + 通讯失败 + + + + + 清理所有正在使用的资源。 + + + + + 设计器支持所需的方法 - 不要使用代码编辑器 + 修改此方法的内容。 + + + + + PlcLinkStatusWork 的摘要说明。 + + + + + OpName + 工位名称 + + + + + OpName + 工位名称 + + + + + + + + + + 根据变量是否正确,显示通讯状态 通讯数据交换 + + + + + + 通讯正常 + + + + + 通讯失败 + + + + + 清理所有正在使用的资源。 + + + + + 设计器支持所需的方法 - 不要使用代码编辑器 + 修改此方法的内容。 + + + + + Tag位置1时颜色 + + + + + OpName + 工位名称 + + + + + OpName + 工位名称 + + + + + 变量类型 + + + + + 变量类型 + + + + + 是否保存到数据库 + + + + + LineColor设置外园线颜色 + + + + + Tag位置1时颜色 + + + + + Tag位置0时颜色 + + + + + 变量值 + + + + + 变量值 + + + + + TagBit变量测试位 + + + + + Tag位置1时颜色 + + + + + Tag位置0时颜色 + + + + + TagBit变量测试位 + + + + + LineColor设置外园线颜色 + + + + + 是否保存到数据库 + + + + + + + + + + 显示机床状态 + + + + + + 绘制图形 + + + + + + Tag位置1时颜色 + + + + + OpName + 工位名称 + + + + + OpName + 工位名称 + + + + + 是否保存到数据库 + + + + + LineColor设置外园线颜色 + + + + + Tag位置1时颜色 + + + + + Tag位置0时颜色 + + + + + 变量值 + + + + + 变量值 + + + + + TagBit变量测试位 + + + + + Tag位置1时颜色 + + + + + Tag位置0时颜色 + + + + + TagBit变量测试位 + + + + + LineColor设置外园线颜色 + + + + + 是否保存到数据库 + + + + + + + + + + 显示机床状态 + + + + + + 绘制图形 + + + + + + 增加TagKey + + + + + TagKey 显示选项 + + + + + TagKey 显示选项 + + + + + OpName + 工位名称 + + + + + OpName + 工位名称 + + + + + 是否保存到数据库 + + + + + LineColor设置外园线颜色 + + + + + Tag位置1时颜色 + + + + + Tag位置0时颜色 + + + + + 变量值 + + + + + 变量值 + + + + + TagBit变量测试位 + + + + + Tag位置1时颜色 + + + + + Tag位置0时颜色 + + + + + TagBit变量测试位 + + + + + LineColor设置外园线颜色 + + + + + 是否保存到数据库 + + + + + + + + + + 显示到位信号 + + + + + + 绘制图形 + + + + + + 发动机工位在线显示 + + + + + OpName + 工位名称 + + + + + 是否保存到数据库 + + + + + LineColor设置外园线颜色 + + + + + Tag位置1时颜色 + + + + + Tag位置0时颜色 + + + + + + + + + + 显示托盘状态 + 1 有托盘(黄色) + 0 无托盘(灰色) + + + + + 显示托盘状态 + 1 有托盘(黄色) + 0 无托盘(灰色) + + + + + 发动机号 + + + + + 发动机号 + + + + + Tag位置1时颜色 + + + + + Tag位置0时颜色 + + + + + LineColor设置外园线颜色 + + + + + 是否保存到数据库 + + + + + OpName + 工位名称 + + + + + 是否进行具体发动机号追踪 + + + + + 是否进行具体发动机号追踪 + + + + + 具体发动机号追踪发动机号 + 发动机号 + + + + + 具体发动机号追踪 + 发动机号 + + + + + 具体发动机号追踪 + Tag位置0时颜色 + + + + + 具体发动机号追踪 + Tag位置1时颜色 + + + + + + + + + + 发动机号的变化,给本控件的发动机号赋值 + 确定被追踪的发动机号 + + + + + + + 发动机号动态追踪设定 + + + + + + + 显示被追踪的发动机 + + + + + 显示托盘状态 + 1 有托盘(黄色) + 0 无托盘(灰色) + + + + + + 显示托盘状态 + 1 有托盘(黄色) + 0 无托盘(灰色) + + + + + 托盘到位 + + + + + + + 绘制图形 + + + + + + 发动机工位在线显示 + + + + + 当鼠标在上方时出现工件编号 + + + + + Tag位置0时颜色 1 + + + + + Tag位置1时颜色 2 + + + + + Tag位置2时颜色 4 + + + + + Tag位置3时颜色 8 + + + + + Tag位置4时颜色 16 + + + + + Tag位置5时颜色 32 + + + + + Tag位置6时颜色 64 + + + + + Tag位置7时颜色 128 + + + + + 设置Tag位置0时颜色 + + + + + 设置Tag位置1时颜色 + + + + + 设置Tag位置2时颜色 + + + + + 设置Tag位置3时颜色 + + + + + 设置Tag位置4时颜色 + + + + + 设置Tag位置5时颜色 + + + + + 设置Tag位置6时颜色 + + + + + 设置Tag位置7时颜色 + + + + + 变量值 + + + + + 变量值 + + + + + OpName + 工位名称 + + + + + 是否保存到数据库 + + + + + LineColor设置外园线颜色 + + + + + Tag位置1时颜色 + + + + + Tag位置0时颜色 + + + + + + + + + + 显示托盘状态 + 1 有托盘(黄色) + 0 无托盘(灰色) + + + + + 显示托盘状态 + 1 有托盘(黄色) + 0 无托盘(灰色) + + + + + 发动机号 + + + + + 发动机号 + + + + + Tag位置1时颜色 + + + + + Tag位置0时颜色 + + + + + LineColor设置外园线颜色 + + + + + 是否保存到数据库 + + + + + OpName + 工位名称 + + + + + 是否进行具体发动机号追踪 + + + + + 是否进行具体发动机号追踪 + + + + + 具体发动机号追踪发动机号 + 发动机号 + + + + + 具体发动机号追踪 + 发动机号 + + + + + 具体发动机号追踪 + Tag位置0时颜色 + + + + + 具体发动机号追踪 + Tag位置1时颜色 + + + + + + + + + + 发动机号的变化,给本控件的发动机号赋值 + 确定被追踪的发动机号 + + + + + + + 发动机号动态追踪设定 + + + + + + + 显示被追踪的发动机 + + + + + 显示托盘状态 + 1 有托盘(黄色) + 0 无托盘(灰色) + + + + + + 显示托盘状态 + 1 有托盘(黄色) + 0 无托盘(灰色) + + + + + 托盘到位 + + + + + + + 绘制图形 + + + + + + UserControlButton 的摘要说明。 + + + + + 发动机号 + + + + + 发动机号 + + + + + 当鼠标在上方时出现发动机号 + + + + + + + + + + Button 文本 + + + + + Button 文本 + + + + + OpName + 工位名称 + + + + + OpName + 工位名称 + + + + + Button 文本 + + + + + Button 文本 + + + + + + + + + + 清理所有正在使用的资源。 + + + + + 设计器支持所需的方法 - 不要使用代码编辑器 + 修改此方法的内容。 + + + + + + + + + + + UserControlButton 的摘要说明。 + + + + + 机床状态 + + + + + 机床状态 + + + + + 工件编号 + + + + + 工件编号 + + + + + 当鼠标在上方时出现工件编号 + + + + + + + + + + Button 文本 + + + + + Button 文本 + + + + + OpName + 工位名称 + + + + + OpName + 工位名称 + + + + + Button 文本 + + + + + Button 文本 + + + + + + + + + + 机床状态 + + + + + + + 清理所有正在使用的资源。 + + + + + 设计器支持所需的方法 - 不要使用代码编辑器 + 修改此方法的内容。 + + + + + + + + + + + UserControlLable11 的摘要说明。 + + + + + 必需的设计器变量。 + + + + + 变量值 + + + + + 变量值 + + + + + 变量类型 + + + + + 变量类型 + + + + + LableText 变量值 + + + + + LableText 变量值 + + + + + + + + + + + + + + + 清理所有正在使用的资源。 + + + + + 设计器支持所需的方法 - 不要使用代码编辑器 + 修改此方法的内容。 + + + + + + + + + + + UserControlLable11 的摘要说明。 + + + + + 必需的设计器变量。 + + + + + TagNameID名称 + + + + + LableText 变量值 + + + + + LableText 变量值 + + + + + + + + + + + + + + + 清理所有正在使用的资源。 + + + + + 设计器支持所需的方法 - 不要使用代码编辑器 + 修改此方法的内容。 + + + + + + + + + + + UserControlButton 的摘要说明。 + + + + + 发动机号 + + + + + 发动机号 + + + + + 当鼠标在上方时出现发动机号 + + + + + + + + + + Button 文本 + + + + + Button 文本 + + + + + OpName + 工位名称 + + + + + OpName + 工位名称 + + + + + Button 文本 + + + + + Button 文本 + + + + + + + + + + 清理所有正在使用的资源。 + + + + + 设计器支持所需的方法 - 不要使用代码编辑器 + 修改此方法的内容。 + + + + + + + + + + + Tag位置1时颜色 + + + + + OpName + 工位名称 + + + + + OpName + 工位名称 + + + + + 是否保存到数据库 + + + + + LineColor设置外园线颜色 + + + + + Tag位置1时颜色 + + + + + Tag位置0时颜色 + + + + + 变量值 + + + + + 变量值 + + + + + TagBit变量测试位 + + + + + Tag位置1时颜色 + + + + + Tag位置0时颜色 + + + + + TagBit变量测试位 + + + + + LineColor设置外园线颜色 + + + + + 是否保存到数据库 + + + + + + + + + + 显示心跳控件 + + + + + + 绘制图形 + + + + + + 增加TagKey + + + + + Tag位置0时颜色 1 + + + + + Tag位置1时颜色 2 + + + + + Tag位置2时颜色 4 + + + + + Tag位置3时颜色 8 + + + + + Tag位置4时颜色 16 + + + + + Tag位置5时颜色 32 + + + + + Tag位置6时颜色 64 + + + + + Tag位置7时颜色 128 + + + + + 设置Tag位置0时颜色 + + + + + 设置Tag位置1时颜色 + + + + + 设置Tag位置2时颜色 + + + + + 设置Tag位置3时颜色 + + + + + 设置Tag位置4时颜色 + + + + + 设置Tag位置5时颜色 + + + + + 设置Tag位置6时颜色 + + + + + 设置Tag位置7时颜色 + + + + + TagKey 显示选项 + + + + + TagKey 显示选项 + + + + + OpName + 工位名称 + + + + + OpName + 工位名称 + + + + + 序号 + + + + + 序号 + + + + + 是否保存到数据库 + + + + + LineColor设置外园线颜色 + + + + + Tag位置1时颜色 + + + + + Tag位置0时颜色 + + + + + 变量值 + + + + + 变量值 + + + + + TagBit变量测试位 + + + + + Tag位置1时颜色 + + + + + Tag位置0时颜色 + + + + + TagBit变量测试位 + + + + + LineColor设置外园线颜色 + + + + + 是否保存到数据库 + + + + + + + + + + 绘制图形 + + + + + + 水平方式显示工件编号。 + + + + + 机床状态 + + + + + 机床状态 + + + + + 工件编号 + + + + + 工件编号 + + + + + 当鼠标在上方时出现工件编号 + + + + + + + + + + Button 文本 + + + + + Button 文本 + + + + + OpName + 工位名称 + + + + + OpName + 工位名称 + + + + + Button 文本 + + + + + Button 文本 + + + + + + + + + + + + + + + + 清理所有正在使用的资源。 + + + + + 设计器支持所需的方法 - 不要使用代码编辑器 + 修改此方法的内容。 + + + + + + + + + + + 垂直方式显示工件编号。 + + + + + Tag位置0时颜色 1 + + + + + Tag位置1时颜色 2 + + + + + Tag位置2时颜色 4 + + + + + Tag位置3时颜色 8 + + + + + Tag位置4时颜色 16 + + + + + Tag位置5时颜色 32 + + + + + Tag位置6时颜色 64 + + + + + Tag位置7时颜色 128 + + + + + 设置Tag位置0时颜色 + + + + + 设置Tag位置1时颜色 + + + + + 设置Tag位置2时颜色 + + + + + 设置Tag位置3时颜色 + + + + + 设置Tag位置4时颜色 + + + + + 设置Tag位置5时颜色 + + + + + 设置Tag位置6时颜色 + + + + + 设置Tag位置7时颜色 + + + + + TagKey 显示选项 + + + + + TagKey 显示选项 + + + + + 变量值 + + + + + 机床状态 + + + + + 机床状态 + + + + + 工件编号 + + + + + 工件编号 + + + + + 当鼠标在上方时出现工件编号 + + + + + + + + + + Button 文本 + + + + + Button 文本 + + + + + OpName + 工位名称 + + + + + OpName + 工位名称 + + + + + Button 文本 + + + + + Button 文本 + + + + + Button 文本颜色代码 + + + + + + + + + + 显示工件编号 + + + + + + 清理所有正在使用的资源。 + + + + + 设计器支持所需的方法 - 不要使用代码编辑器 + 修改此方法的内容。 + + + + + + + + + + + UserControlButton 的摘要说明。 + + + + + Tag位置0时颜色 1 + + + + + Tag位置1时颜色 2 + + + + + Tag位置2时颜色 4 + + + + + Tag位置3时颜色 8 + + + + + Tag位置4时颜色 16 + + + + + Tag位置5时颜色 32 + + + + + Tag位置6时颜色 64 + + + + + Tag位置7时颜色 128 + + + + + 设置Tag位置0时颜色 + + + + + 设置Tag位置1时颜色 + + + + + 设置Tag位置2时颜色 + + + + + 设置Tag位置3时颜色 + + + + + 设置Tag位置4时颜色 + + + + + 设置Tag位置5时颜色 + + + + + 设置Tag位置6时颜色 + + + + + 设置Tag位置7时颜色 + + + + + TagKey 显示选项 + + + + + TagKey 显示选项 + + + + + 变量值 + + + + + 机床状态 + + + + + 机床状态 + + + + + 工件编号 + + + + + 工件编号 + + + + + 当鼠标在上方时出现工件编号 + + + + + + + + + + Button 文本 + + + + + Button 文本 + + + + + OpName + 工位名称 + + + + + OpName + 工位名称 + + + + + Button 文本 + + + + + Button 文本 + + + + + Button 文本颜色代码 + + + + + + + + + + + + + + + + 清理所有正在使用的资源。 + + + + + 设计器支持所需的方法 - 不要使用代码编辑器 + 修改此方法的内容。 + + + + + + + + + + + UserControlLable11 的摘要说明。 + + + + + 必需的设计器变量。 + + + + + TagNameID名称 + + + + + TagNameID名称 + + + + + TagNameID名称 + + + + + TagNameID名称 + + + + + LableText 变量值 + + + + + LableText 变量值 + + + + + + + + + + + + + + + 清理所有正在使用的资源。 + + + + + 设计器支持所需的方法 - 不要使用代码编辑器 + 修改此方法的内容。 + + + + + + + + + + + 增加TagKey + + + + + TagKey 显示选项 + + + + + TagKey 显示选项 + + + + + OpName + 工位名称 + + + + + OpName + 工位名称 + + + + + 是否保存到数据库 + + + + + LineColor设置外园线颜色 + + + + + Tag位置1时颜色 + + + + + Tag位置0时颜色 + + + + + 变量值 + + + + + 变量值 + + + + + TagBit变量测试位 + + + + + Tag位置1时颜色 + + + + + Tag位置0时颜色 + + + + + TagBit变量测试位 + + + + + LineColor设置外园线颜色 + + + + + 是否保存到数据库 + + + + + + + + + + 绘制图形 + + + + + + 一个强类型的资源类,用于查找本地化的字符串等。 + + + + + 返回此类使用的缓存的 ResourceManager 实例。 + + + + + 重写当前线程的 CurrentUICulture 属性 + 重写当前线程的 CurrentUICulture 属性。 + + + + + 查找 System.Drawing.Bitmap 类型的本地化资源。 + + + + + 查找 System.Drawing.Bitmap 类型的本地化资源。 + + + + + 查找 System.Drawing.Bitmap 类型的本地化资源。 + + + + diff --git a/Common/dll/MyLog4Net.dll b/Common/dll/MyLog4Net.dll new file mode 100644 index 0000000..8751171 Binary files /dev/null and b/Common/dll/MyLog4Net.dll differ diff --git a/Common/dll/MyLog4Net.pdb b/Common/dll/MyLog4Net.pdb new file mode 100644 index 0000000..8368c86 Binary files /dev/null and b/Common/dll/MyLog4Net.pdb differ diff --git a/Common/dll/NPOI.OOXML.dll b/Common/dll/NPOI.OOXML.dll new file mode 100644 index 0000000..031d41d Binary files /dev/null and b/Common/dll/NPOI.OOXML.dll differ diff --git a/Common/dll/NPOI.OpenXml4Net.dll b/Common/dll/NPOI.OpenXml4Net.dll new file mode 100644 index 0000000..8da4ac2 Binary files /dev/null and b/Common/dll/NPOI.OpenXml4Net.dll differ diff --git a/Common/dll/NPOI.OpenXmlFormats.dll b/Common/dll/NPOI.OpenXmlFormats.dll new file mode 100644 index 0000000..4a8f87b Binary files /dev/null and b/Common/dll/NPOI.OpenXmlFormats.dll differ diff --git a/Common/dll/NPOI.dll b/Common/dll/NPOI.dll new file mode 100644 index 0000000..1a500e9 Binary files /dev/null and b/Common/dll/NPOI.dll differ diff --git a/Common/dll/Newtonsoft.Json.dll b/Common/dll/Newtonsoft.Json.dll new file mode 100644 index 0000000..7af125a Binary files /dev/null and b/Common/dll/Newtonsoft.Json.dll differ diff --git a/Common/dll/Opc.Ua.Client.dll b/Common/dll/Opc.Ua.Client.dll new file mode 100644 index 0000000..8874d8f Binary files /dev/null and b/Common/dll/Opc.Ua.Client.dll differ diff --git a/Common/dll/Opc.Ua.Configuration.dll b/Common/dll/Opc.Ua.Configuration.dll new file mode 100644 index 0000000..b3f3970 Binary files /dev/null and b/Common/dll/Opc.Ua.Configuration.dll differ diff --git a/Common/dll/Opc.Ua.Core.dll b/Common/dll/Opc.Ua.Core.dll new file mode 100644 index 0000000..ee01d0d Binary files /dev/null and b/Common/dll/Opc.Ua.Core.dll differ diff --git a/Common/dll/OpcUaHelper.dll b/Common/dll/OpcUaHelper.dll new file mode 100644 index 0000000..e95e509 Binary files /dev/null and b/Common/dll/OpcUaHelper.dll differ diff --git a/Common/dll/OpcUaHelper.pdb b/Common/dll/OpcUaHelper.pdb new file mode 100644 index 0000000..dee6394 Binary files /dev/null and b/Common/dll/OpcUaHelper.pdb differ diff --git a/Common/dll/OpcUaHelper.xml b/Common/dll/OpcUaHelper.xml new file mode 100644 index 0000000..a7977ad --- /dev/null +++ b/Common/dll/OpcUaHelper.xml @@ -0,0 +1,1281 @@ + + + + OpcUaHelper + + + + + Defines numerous re-useable utility functions. + + + + + Handles an exception. + + + + + Returns the application icon. + + + + + Gets the display text for the access level attribute. + + The access level. + The access level formatted as a string. + + + + Gets the display text for the event notifier attribute. + + The event notifier. + The event notifier formatted as a string. + + + + Gets the display text for the value rank attribute. + + The value rank. + The value rank formatted as a string. + + + + Gets the display text for the specified attribute. + + The currently active session. + The id of the attribute. + The value of the attribute. + The attribute formatted as a string. + + + + Browses the address space and returns the references found. + + The session. + The set of browse operations to perform. + if set to true a exception will be thrown on an error. + + The references found. Null if an error occurred. + + + + + Browses the address space and returns the references found. + + + + + Browses the address space and returns the references found. + + The session. + The NodeId for the starting node. + if set to true a exception will be thrown on an error. + + The references found. Null if an error occurred. + + + + + Browses the address space and returns the references found. + + + + + Browses the address space and returns all of the supertypes of the specified type node. + + The session. + The NodeId for a type node in the address space. + if set to true a exception will be thrown on an error. + + The references found. Null if an error occurred. + + + + + Returns the node ids for a set of relative paths. + + An open session with the server to use. + The starting node for the relative paths. + The namespace URIs referenced by the relative paths. + The relative paths. + A collection of local nodes. + + + + Finds the type of the event for the notification. + + The monitored item. + The notification. + The NodeId of the EventType. + + + + Constructs an event object from a notification. + + The session. + The monitored item that produced the notification. + The notification. + The known event types. + Mapping between event types and known event types. + + The event object. Null if the notification is not a valid event type. + + + + + Collects the instance declarations for a type. + + + + + Collects the instance declarations for a type. + + + + + Collects the fields for the instance node. + + + + + Finds the targets for the specified reference. + + + + + Finds the targets for the specified reference. + + + + + Collects the fields for the type. + + The session. + The type id. + The fields. + The node id for the declaration of the field. + + + + Collects the fields for the instance. + + The session. + The instance id. + The fields. + The node id for the declaration of the field. + + + + Collects the fields for the instance node. + + The session. + The node id. + The parent path. + The event fields. + The node id for the declaration of the field. + The table of found nodes. + + + + Determines whether the specified select clause contains the browse path. + + The select clause. + The browse path. + + true if the specified select clause contains path; otherwise, false. + + + + + Prompts the user to specify a host name and discovers the servers. + + + + + Creates an empty form. + + + + + Shows the dialog. + + The client applicatio configuration. + The selected endpoint url + + + + Shows the dialog. + + The client applicatio configuration. + The default host name. + The selected endpoint url + + + + Gets the endpoints for the host. + + Name of the host. + + + + Required designer variable. + + + + + Clean up any resources being used. + + true if managed resources should be disposed; otherwise, false. + + + + Required method for Designer support - do not modify + the contents of this method with the code editor. + + + + + 一个浏览OPC服务器节点的窗口类 + + + + + 允许自己输入服务器地址的实例化 + + + + + 固定地址且不允许更改的实例化 + + + + + Opc客户端的核心类 + + + + + 初始化 + + + + + 连接服务器结束后马上浏览根节点 + + + + + + + OPC 客户端的状态变化后的消息提醒 + + + + + + + 0:NodeClass 1:Value 2:AccessLevel 3:DisplayName 4:Description + + + + + + + 读取一个节点的指定属性 + + + + + + + + Populates the branch in the tree view. + + The NodeId of the Node to browse. + The node collect to populate. + + + + 点击了节点名称前的内容进行复制 + + + + + + + Required designer variable. + + + + + Clean up any resources being used. + + true if managed resources should be disposed; otherwise, false. + + + + Required method for Designer support - do not modify + the contents of this method with the code editor. + + + + + Required designer variable. + + + + + Clean up any resources being used. + + true if managed resources should be disposed; otherwise, false. + + + + Required method for Designer support - do not modify + the contents of this method with the code editor. + + + + + 无闪烁的树节点控件,结果还是没有实现 + + + + + 实例化一个新的控件 + + + + + 通知 + + + + + + A dialog that displays an exception trace in an HTML page. + + + + + Initializes a new instance of the class. + + + + + Replaces all special characters in the message. + + + + + Displays the exception in a dialog. + + + + + Display the exception in the dialog. + + + + + Required designer variable. + + + + + Clean up any resources being used. + + true if managed resources should be disposed; otherwise, false. + + + + Required method for Designer support - do not modify + the contents of this method with the code editor. + + + + + Stores a type declaration retrieved from a server. + + + + + The node if for the type. + + + + + The fully inhierited list of instance declarations for the type. + + + + + Stores an instance declaration fetched from the server. + + + + + The type that the declaration belongs to. + + + + + The browse path to the instance declaration. + + + + + The browse path to the instance declaration. + + + + + A localized path to the instance declaration. + + + + + The node id for the instance declaration. + + + + + The node class of the instance declaration. + + + + + The browse name for the instance declaration. + + + + + The display name for the instance declaration. + + + + + The description for the instance declaration. + + + + + The modelling rule for the instance declaration (i.e. Mandatory or Optional). + + + + + The data type for the instance declaration. + + + + + The value rank for the instance declaration. + + + + + The built-in type parent for the data type. + + + + + A localized name for the data type. + + + + + An instance declaration that has been overridden by the current instance. + + + + + A field in a filter declaration. + + + + + Creates a new instance of a FilterDeclarationField. + + + + + Creates a new instance of a FilterDeclarationField. + + + + + Creates a new instance of a FilterDeclarationField. + + + + + Whether the field is returned as part of the event notification. + + + + + Whether the field is displayed in the list view. + + + + + Whether the filter is enabled. + + + + + The filter operator to use in the where clause. + + + + + The filter value to use in the where clause. + + + + + The instance declaration associated with the field. + + + + + A declararion of an event filter. + + + + + Creates a new instance of a FilterDeclaration. + + + + + Creates a new instance of a FilterDeclaration. + + + + + Creates a new instance of a FilterDeclaration. + + + + + Returns the event filter defined by the filter declaration. + + + + + Adds a simple field to the declaration. + + + + + Adds a simple field to the declaration. + + + + + Adds a simple field to the declaration. + + + + + Adds a simple field to the declaration. + + + + + Returns the select clause defined by the filter declaration. + + + + + Returns the where clause defined by the filter declaration. + + + + + Returns the value for the specified browse name. + + + + + The type of event. + + + + + The list of declarations for the fields. + + + + + 用NodeId读取 + + + + + + + 关闭程序时候断开连接 + + + + + + + 异步回调执行函数 + + + + + + + + 多个节点的订阅 + + + + + + + 取消多个节点的订阅 + + + + + + + 打开监视 + + + + + + + 建立连接的按钮 + + + + + + + 建立连接 + + + + + + 必需的设计器变量。 + + + + + 清理所有正在使用的资源。 + + 如果应释放托管资源,为 true;否则为 false。 + + + + 设计器支持所需的方法 - 不要修改 + 使用代码编辑器修改此方法的内容。 + + + + + 一个二次封装了的OPC UA库,支持从opc ua服务器读写节点数据,批量读写,订阅,批量订阅,历史数据读取,方法调用操作。 + + + + + 默认的构造函数,实例化一个新的OPC UA类 + + + + + connect to server + + remote url + + + + Creates a new session. + + The new session object. + + + + Disconnects from the server. + + + + + Report the client status + + Whether the status represents an error. + The time associated with the status. + The status message. + Arguments used to format the status message. + + + + Handles a keep alive event from a session. + + + + + Handles a reconnect event complete from the reconnect handler. + + + + + 设置OPC客户端的日志输出 + + 完整的文件路径 + 是否删除原文件 + + + + a name of application name show on server + + + + + Whether to use security when connecting. + + + + + The user identity to use when creating the session. + + + + + The currently active session. + + + + + Indicate the connect status + + + + + The number of seconds between reconnect attempts (0 means reconnect is disabled). + + + + + Raised when a good keep alive from the server arrives. + + + + + Raised when a reconnect operation starts. + + + + + Raised when a reconnect operation completes. + + + + + Raised after successfully connecting to or disconnecing from a server. + + + + + Raised after the client status change + + + + + 配置信息 + + + + + Read a value node from server + + node id + DataValue + + + + Read a value node from server + + type of value + node id + 实际值 + + + + Read a tag asynchronously + + The type of tag to read + tag值 + The value retrieved from the OPC + + + + read several value nodes from server + + all NodeIds + all values + + + + read several value nodes from server + + 所以的节点数组信息 + all values + + + + write a note to server(you should use try catch) + + The type of tag to write on + 节点名称 + 值 + if success True,otherwise False + + + + Write a value on the specified opc tag asynchronously + + The type of tag to write on + The fully-qualified identifier of the tag. You can specify a subfolder by using a comma delimited name. E.g: the tag `foo.bar` writes on the tag `bar` on the folder `foo` + The value for the item to write + + + + 所有的节点都写入成功,返回True,否则返回False + + 节点名称数组 + 节点的值数据 + 所有的是否都写入成功 + + + + 删除一个节点的操作,除非服务器配置允许,否则引发异常,成功返回True,否则返回False + + 节点文本描述 + + + + + 新增一个节点数据 + + 父节点tag名称 + + + + 新增一批订阅,需要指定订阅的关键字,订阅的tag名数组,以及回调方法 + + 关键字 + 节点名称数组 + 回调方法 + + + + 移除订阅消息,如果该订阅消息是批量的,也直接移除 + + 订阅关键值 + + + + 移除所有的订阅消息 + + + + + read History data + + 节点的索引 + 开始时间 + 结束时间 + 读取的个数 + 是否包含边界 + 读取的数据列表 + + + + 读取一连串的历史数据,并将其转化成指定的类型 + + 节点的索引 + 开始时间 + 结束时间 + 读取的个数 + 是否包含边界 + 读取的数据列表 + + + + 浏览一个节点的引用 + + 节点值 + 引用节点描述 + + + + 读取一个节点的所有属性 + + 节点信息 + 节点的特性值 + + + + 读取一个节点的所有属性 + + 节点值 + 所有的数据 + + + + call a server method + + 方法的父节点tag + 方法的节点tag + 传递的参数 + 输出的结果值 + + + + Raises the connect complete event on the main GUI thread. + + + + + OPC UA的状态更新消息 + + + + + 是否异常 + + + + + 时间 + + + + + 文本 + + + + + 转化为字符串 + + + + + + 读取属性过程中用于描述的 + + + + + 属性的名称 + + + + + 属性的类型描述 + + + + + 操作结果状态描述 + + + + + 属性的值,如果读取错误,返回文本描述 + + + + + Gets the display text for the access level attribute. + + The access level. + The access level formatted as a string. + + + + Gets the display text for the event notifier attribute. + + The event notifier. + The event notifier formatted as a string. + + + + Gets the display text for the value rank attribute. + + The value rank. + The value rank formatted as a string. + + + + Gets the display text for the specified attribute. + + The currently active session. + The id of the attribute. + The value of the attribute. + The attribute formatted as a string. + + + + Discovers the servers on the local machine. + + The configuration. + A list of server urls. + + + + Finds the endpoint that best matches the current settings. + + The discovery URL. + if set to true select an endpoint that uses security. + The best available endpoint. + + + + Browses the address space and returns the references found. + + The session. + The set of browse operations to perform. + if set to true a exception will be thrown on an error. + + The references found. Null if an error occurred. + + + + + Finds the type of the event for the notification. + + The monitored item. + The notification. + The NodeId of the EventType. + + + + Browses the address space and returns the references found. + + The session. + The NodeId for the starting node. + if set to true a exception will be thrown on an error. + + The references found. Null if an error occurred. + + + + + Browses the address space and returns all of the supertypes of the specified type node. + + The session. + The NodeId for a type node in the address space. + if set to true a exception will be thrown on an error. + + The references found. Null if an error occurred. + + + + + Constructs an event object from a notification. + + The session. + The monitored item that produced the notification. + The notification. + The known event types. + Mapping between event types and known event types. + + The event object. Null if the notification is not a valid event type. + + + + + Returns the node ids for a set of relative paths. + + An open session with the server to use. + The starting node for the relative paths. + The namespace URIs referenced by the relative paths. + The relative paths. + A collection of local nodes. + + + + Collects the fields for the type. + + The session. + The type id. + The fields. + The node id for the declaration of the field. + + + + Collects the fields for the instance. + + The session. + The instance id. + The fields. + The node id for the declaration of the field. + + + + Collects the fields for the instance node. + + The session. + The node id. + The parent path. + The event fields. + The node id for the declaration of the field. + The table of found nodes. + + + + Determines whether the specified select clause contains the browse path. + + The select clause. + The browse path. + + true if the specified select clause contains path; otherwise, false. + + + + + 一个强类型的资源类,用于查找本地化的字符串等。 + + + + + 返回此类使用的缓存的 ResourceManager 实例。 + + + + + 重写当前线程的 CurrentUICulture 属性 + 重写当前线程的 CurrentUICulture 属性。 + + + + + 查找 System.Drawing.Bitmap 类型的本地化资源。 + + + + + 查找 System.Drawing.Bitmap 类型的本地化资源。 + + + + + 查找 System.Drawing.Bitmap 类型的本地化资源。 + + + + + 查找 System.Drawing.Bitmap 类型的本地化资源。 + + + + + 查找 System.Drawing.Bitmap 类型的本地化资源。 + + + + + 查找 System.Drawing.Bitmap 类型的本地化资源。 + + + + + 查找 System.Drawing.Bitmap 类型的本地化资源。 + + + + + 查找 System.Drawing.Bitmap 类型的本地化资源。 + + + + + 查找 System.Drawing.Bitmap 类型的本地化资源。 + + + + + 查找 System.Drawing.Bitmap 类型的本地化资源。 + + + + + 查找 System.Drawing.Bitmap 类型的本地化资源。 + + + + + 查找 System.Drawing.Bitmap 类型的本地化资源。 + + + + + 查找 System.Drawing.Bitmap 类型的本地化资源。 + + + + + 查找 System.Drawing.Bitmap 类型的本地化资源。 + + + + + 查找 System.Drawing.Bitmap 类型的本地化资源。 + + + + + 查找 System.Drawing.Bitmap 类型的本地化资源。 + + + + + 查找 System.Drawing.Bitmap 类型的本地化资源。 + + + + + 查找 System.Drawing.Bitmap 类型的本地化资源。 + + + + + 查找 System.Drawing.Bitmap 类型的本地化资源。 + + + + + 查找 System.Drawing.Bitmap 类型的本地化资源。 + + + + + 查找 System.Drawing.Bitmap 类型的本地化资源。 + + + + + 查找 System.Drawing.Bitmap 类型的本地化资源。 + + + + + 查找 System.Drawing.Bitmap 类型的本地化资源。 + + + + diff --git a/Common/dll/log4net.config b/Common/dll/log4net.config new file mode 100644 index 0000000..92f4d40 --- /dev/null +++ b/Common/dll/log4net.config @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Common/dll/log4net.dll b/Common/dll/log4net.dll new file mode 100644 index 0000000..84bf5b6 Binary files /dev/null and b/Common/dll/log4net.dll differ diff --git a/MESUploadFileProject.ashx b/MESUploadFileProject.ashx new file mode 100644 index 0000000..04bcbe7 --- /dev/null +++ b/MESUploadFileProject.ashx @@ -0,0 +1,85 @@ +<%@ WebHandler Language="C#" Class="UploadHandler" %> + +using System; +using System.Web; +using System.Data; +using System.Collections.Generic; +using System.Linq; +using System.IO; +using System.Net; +using System.Web.Services; +using System.Text; +//using SystemFrameworks; +using DataLinkMesWork; +using System.Data.SqlClient; + + +public class UploadHandler : IHttpHandler +{ + private static string connectionString = System.Configuration.ConfigurationManager.AppSettings.GetValues("ConnectionString")[0].ToString(); + + public void ProcessRequest(HttpContext context) + { + context.Response.ContentType = "text/plain"; + string filePath = "../webpage/PDF"; + filePath = HttpContext.Current.Server.MapPath(filePath); + string filePath1 = "http://127.0.0.1:8100/webpage/PDF/"; + string engineTypeValue1 = HttpContext.Current.Request["engineTypeValue1"]; + string stationNumberValue = HttpContext.Current.Request["stationNumberValue"]; + string engineTypeValue = HttpContext.Current.Request["engineTypeValue"]; + string tableName = HttpContext.Current.Request["tableName"]; + string result = ""; + bool isOK; + try + { + Guid guid = Guid.NewGuid(); + string uid = guid.ToString().Replace("-", "").ToLower() + HttpFileCollection files = context.Request.Files; + if (files.Count > 0) + { + for (int i = 0; i < files.Count; i++) + { + HttpPostedFile hpFile = files[0]; + if (hpFile.ContentLength > 0) + { + string fileName = System.IO.Path.GetFileName(hpFile.FileName); + int index = fileName.LastIndexOf('.'); + string name = fileName.Substring(0, index); + string suffix = fileName.Substring(index + 1); + string sql = "EXEC [电子看板_工位名称与产品型号工艺卡_保存] '"+stationNumberValue+"' , "+engineTypeValue1+" , '"+uid + ".pdf'"+" , '"+filePath1 + fileName + "'"; + isOK = DataLinkMesWork.DataLink.ExecuteNonQuery(sql); + if (isOK) + { + filePath = filePath + "/" + uid+"."+suffix; + hpFile.SaveAs(filePath); + result = "[{ \"result\":\"1\"}]"; + } + else + { + result = "[{ \"result\":\"0\"}]"; + } + + + } + else + { + context.Response.Write(result); + } + } + } + } + catch (Exception ex) + { + result = "[{ \"result\":\"0\"}]"; + } + context.Response.Write(result); + } + + public bool IsReusable + { + get + { + return false; + } + } +} diff --git a/MES基础数据.xlsx b/MES基础数据.xlsx new file mode 100644 index 0000000..2740181 Binary files /dev/null and b/MES基础数据.xlsx differ diff --git a/MIS_FuntionSaveData/MIS_FuntionSaveData.sln b/MIS_FuntionSaveData/MIS_FuntionSaveData.sln new file mode 100644 index 0000000..0b4d9d7 --- /dev/null +++ b/MIS_FuntionSaveData/MIS_FuntionSaveData.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.32901.82 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MIS_FuntionSaveData", "MIS_FuntionSaveData\MIS_FuntionSaveData.csproj", "{55B510C1-59E9-4BFD-AE84-D76D46F6E365}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {55B510C1-59E9-4BFD-AE84-D76D46F6E365}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {55B510C1-59E9-4BFD-AE84-D76D46F6E365}.Debug|Any CPU.Build.0 = Debug|Any CPU + {55B510C1-59E9-4BFD-AE84-D76D46F6E365}.Release|Any CPU.ActiveCfg = Release|Any CPU + {55B510C1-59E9-4BFD-AE84-D76D46F6E365}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {A8F630BE-FDC2-40FF-8EAE-917E83ABAB6F} + EndGlobalSection +EndGlobal diff --git a/MIS_FuntionSaveData/MIS_FuntionSaveData/13.3MIS_FuntionSaveData.csproj b/MIS_FuntionSaveData/MIS_FuntionSaveData/13.3MIS_FuntionSaveData.csproj new file mode 100644 index 0000000..bd226a2 --- /dev/null +++ b/MIS_FuntionSaveData/MIS_FuntionSaveData/13.3MIS_FuntionSaveData.csproj @@ -0,0 +1,99 @@ + + + + + Debug + AnyCPU + {55B510C1-59E9-4BFD-AE84-D76D46F6E365} + Library + Properties + MIS_FuntionSaveData + MIS_FuntionSaveData + v4.8 + 512 + true + + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + False + ..\..\Common\dll\MQTTnet.dll + + + False + ..\..\Common\dll\MQTTnet.Extensions.ManagedClient.dll + + + ..\..\dll_common\Newtonsoft.Json.dll + + + + + + + + + + + + + + + + + + + + + + {f55da1a0-a982-4479-8c47-0d9a5aaf3e18} + 00MesWorkMqtt + + + {0d1af432-439a-4920-8692-43ae139f5530} + 01_01DoWhatPlc + + + {f434e066-4c59-47c8-aa82-6f48cc84501a} + 04-DataBaseAccess + + + {f0a0c525-03fd-428a-9b17-7f54aa0e4475} + 07BusinessFacade + + + {d98be764-adeb-488d-9714-61e308aa8201} + 08-WebFun_base + + + {90e76fb4-646d-45e2-95db-0b8ab4e465d6} + 09-MesDataFunction + + + {1dc48c83-1842-4de8-acaf-26e1e7f7c58f} + 00_MyLog4Net + + + {E4EB6420-906D-4672-947A-CA33DDCDADFC} + 12SendMessageToWeb + + + + \ No newline at end of file diff --git a/MIS_FuntionSaveData/MIS_FuntionSaveData/Funtion.Alarm.cs b/MIS_FuntionSaveData/MIS_FuntionSaveData/Funtion.Alarm.cs new file mode 100644 index 0000000..8114d73 --- /dev/null +++ b/MIS_FuntionSaveData/MIS_FuntionSaveData/Funtion.Alarm.cs @@ -0,0 +1,274 @@ +using bizFacade; +using DataLinkMesWork; +using DoWhatPlc; +using MesServerFunctions; +using MesServerWork; +using Newtonsoft.Json; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Data; +using System.Data.SqlClient; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MisDataSaveDate +{ + public partial class FuntionMesRead + { + + #region 2023.05.14,新增报警 + + public static Hashtable Base_TagIdList = new Hashtable(); + public static Hashtable Base_ObjList = new Hashtable(); + + + public static void GetAlarmInit() + { + Base_TagIdList.Clear(); + GetTagIdList("", out DataTable dt); + + for (int i = 0; i < dt.Rows.Count; i++) + { + string tagid = dt.Rows[i]["TagID"].ToString(); + + if (tagid[0].ToString() == "9") + { + var opName = dt.Rows[i]["工位号"].ToString(); + var ItemName = dt.Rows[i]["测量项目"].ToString(); + var ShaftID = dt.Rows[i]["测量位置"].ToString(); + + string SendMessage = "MES|PlcAlarm|" + opName + "|" + tagid + "&@TagValue&" + ItemName + "&" + ShaftID; + Base_TagIdList.Add(tagid, SendMessage); + + //在存一份报警对象到键值对中 + Base_ObjList.Add(tagid, dt.Rows[i]); + } + } + } + + public static void Send_AlarmMsg(string tagid, string tagVvalue) + { + var val = Base_TagIdList[tagid]; + if (val != null) + { + //var msg = Base_TagIdList[tagid].ToString(); + //var sendmsg = msg.Replace("@TagValue", tagVvalue); + //SendMessageFun.AsyncSendMessage(sendmsg); + + var msg = Base_TagIdList[tagid].ToString(); + var sendmsg = msg.Replace("@TagValue", tagVvalue); + SendMessageFun.AsyncSendMessage(sendmsg); + // 去存一份记录到数据库 + DataRow errObj = (DataRow)Base_ObjList[tagid]; + + Alarm_Insert2(Convert.ToInt32(errObj["TagID"]), errObj["工位号"].ToString(), errObj["测量项目"].ToString(), Convert.ToInt32(Convert.ToBoolean(tagVvalue)), errObj["测量位置"].ToString()); + } + } + + static public void GetTagIdList(string opName, out DataTable dt) + { + string procedureName; + procedureName = "MES_基本变量_原始数据_根据工位号查询"; + SqlParameter[] thisParms = new SqlParameter[1]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out dt); + } + + + /// + /// 报警工位记录表_新增 + /// + /// + /// + /// + /// + /// + static public void Alarm_Insert2(int TagID, string opName, string Text, int Status, string errType) + { + string procedureName; + procedureName = "报警工位记录表_新增"; + SqlParameter[] thisParms = new SqlParameter[5]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@TagId", TagID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@Text", Text); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@状态", Status); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@报警类型", errType); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } + + + #endregion + + + private static void Alarm_Insert(DoWhatPlc.CustomeEvetnArgs e) + { + string TagID; + string opName; + string tagTypeID; + int TagValue; + + DateTime alarmStartTime; + DateTime alarmEndTime; + int TimeDiff; + string TagOrderBy; + string Text1; + string Text2; + TagID = e.TagID.ToString(); + tagTypeID = e.TagTypeID.ToString(); + opName = e.OpName.ToString(); + TagValue = Convert.ToInt32(e.TagValue); + + alarmStartTime = Convert.ToDateTime(e.TimeStampBefore); + alarmEndTime = Convert.ToDateTime(e.TimeStamp); + TimeDiff = Convert.ToInt32(e.TagKeepTime); + TagOrderBy = e.TagOrderBy.ToString(); + Text1 = e.ItemName.ToString(); + Text2 = e.ShaftID.ToString(); + + Alarm_Insert(TagID, tagTypeID, opName, TagValue, + alarmStartTime, alarmEndTime, TimeDiff, Text1, Text2, TagOrderBy); + } + private static void Alarm_InsertBak(ReturnValueString rv) + { + string TagID; + string opName; + string tagTypeID; + int TagValue; + + DateTime alarmStartTime; + DateTime alarmEndTime; + int TimeDiff; + string TagOrderBy; + string Text1; + string Text2; + TagID = rv.TagID; + tagTypeID = rv.TagTypeID; + opName = rv.OpName; + TagValue = Convert.ToInt32(rv.TagValue); + + alarmStartTime = Convert.ToDateTime(rv.TimeStampBefore); + alarmEndTime = Convert.ToDateTime(rv.TimeStamp); + TimeDiff = Convert.ToInt32(rv.TagKeepTime); + TagOrderBy = rv.TagOrderBy; + Text1 = rv.ItemName; + Text2 = rv.ShaftID; + + Alarm_Insert(TagID, tagTypeID, opName, TagValue, + alarmStartTime, alarmEndTime, TimeDiff, Text1, Text2, TagOrderBy); + } + + public static void Alarm_InitAlarm_Send(string opName, out Hashtable ht) + { + //读取工位全部数据 + var tagValues = MIS_BASE.ReadPLC_OpName(opName); //GetDbAndMaxLengthByOpNameByBytes(opName); + var keyValues = tagValues.OrderBy(x => x.Key).ToDictionary(k => k.Key, v => v.Value); + ht = new Hashtable(); + + + foreach (KeyValuePair _cd in keyValues) + { + var tf = (TagFormat)_cd.Value; + if (tf.TagID[0].ToString() == "9") + { + string tagValue = tf.TagValue.ToString(); + if (tf.TagValue == null) return; + switch (tagValue.ToLower()) + { + case "1": + case "true": + tagValue = "1"; + break; + default: + tagValue = "0"; + break; + } + if (tagValue == "1") + { + ht.Add(tf.TagID, tagValue); + } + } + } + } + public static bool Alarm_Insert(string TagID, string tagTypeID, string opName, int TagValue, + DateTime alarmStartTime, DateTime alarmEndTime, int TimeDiff, + string Text1, string Text2, string TagOrderBy) + { + + + string produceName = "测量数据工位报警全部_增加数据"; + SqlParameter[] thisParms = new SqlParameter[10]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@TagID", TagID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@TagTypeID", tagTypeID); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@opName", opName); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@TagValue", TagValue); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@alarmStartTime", alarmStartTime); + thisParms[5] = new System.Data.SqlClient.SqlParameter("@alarmEndTime", alarmEndTime); + thisParms[6] = new System.Data.SqlClient.SqlParameter("@TimeDiff", TimeDiff); + thisParms[7] = new System.Data.SqlClient.SqlParameter("@Text1", Text1); + thisParms[8] = new System.Data.SqlClient.SqlParameter("@Text2", Text2); + thisParms[9] = new System.Data.SqlClient.SqlParameter("@TagOrderBy", TagOrderBy); + if (DataAccess.ExecuteStoredProcedure(produceName, ref thisParms)) + { + + return true; + } + return false; + } + + /// + /// 报错详细工件记录日志 (有可能报错 所以封装) + /// + /// 1.申请上线 2.传递机型 3.允许保存 4.扫码 + /// + public static void Alarm_SaveFileLog4Error(string errorStep, object e, string FunName, Exception err) + { + try + { + MyLog4Net.MyLogHelper.Error($"{FunName}异常:", $"Message:{err.Message} InnerException: {err.InnerException}"); + string leftErrorStep; + if (errorStep == "PartLoad") + { + leftErrorStep = "申请上线"; + } + else if (errorStep == "EngineGetOver") + { + leftErrorStep = "传递机型"; + } + else if (errorStep == "MesRead") + { + leftErrorStep = "允许保存"; + } + else if (errorStep == "Barcode") + { + leftErrorStep = "扫码"; + } + else + { + leftErrorStep = $"未知类型{errorStep}"; + } + + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + MIS_BASE.GetEngineTypeFromPLC(OpName, out int EngineTypeID, out string EngineType, out string EngineID, out int PartPallet_Code, out string OrderForm); + MyLog4Net.MyLogHelper.Error($"{FunName}{leftErrorStep}操作异常:", $"工位号:{OpName}、总成号:{EngineID}、机型:{EngineType}、机型代码:{EngineTypeID}、订单号:{OrderForm}、托盘号:{PartPallet_Code}"); + + string saveString = $"{FunName}{leftErrorStep}操作异常 Message:{err.Message} InnerException: {err.InnerException}:工位号:{OpName}、总成号:{EngineID}、机型:{EngineType}、机型代码:{EngineTypeID}、订单号:{OrderForm}、托盘号:{PartPallet_Code}"; + var sql = + $"INSERT INTO 合力_系统日志 ([工位号],[日志类型],[日志文本])"+ + $" VALUES('{OpName}', 'system', '{saveString}')"; + DataAccess.ExecuteDataTable(sql, out DataTable dt); + } + catch (Exception ex) + { + MyLog4Net.MyLogHelper.Error($"{FunName}保存错误日志失败:", $"Message:{ex}"); + } + } + + public static void Alarm_SystemError(string FunName, Exception err) + { + MyLog4Net.MyLogHelper.Error($"系统{FunName}方法异常:", $"Message:{err.Message} InnerException:{err.InnerException}"); + } + } +} diff --git a/MIS_FuntionSaveData/MIS_FuntionSaveData/Funtion.EngTypeGetOver.cs b/MIS_FuntionSaveData/MIS_FuntionSaveData/Funtion.EngTypeGetOver.cs new file mode 100644 index 0000000..4eb6e05 --- /dev/null +++ b/MIS_FuntionSaveData/MIS_FuntionSaveData/Funtion.EngTypeGetOver.cs @@ -0,0 +1,107 @@ +using bizFacade; +using DataLinkMesWork; +using DoWhatPlc; +using MesServerWork; +using Newtonsoft.Json; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Data; +using System.Data.SqlClient; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MisDataSaveDateMesRead +{ + public partial class Funtion + { + //private static void EngTypeGetOver(string opName,string tagValue) + //{ + // if (hashtable_EngineGetOver.Contains(opName)) + // { + // hashtable_EngineGetOver.Remove(opName); + // } + // hashtable_EngineGetOver.Add(opName, tagValue); + // if (tagValue == "1") + // { + + // int EngineTypeID; + // string EngineType; + // string EngineID; + // int PartPalletCode; + // // 1 读取机型等信息,保存到监控表 + + // DtWebApi.ReadWritePLC.GetEngineTypeFromPLC(opName, out EngineTypeID, out EngineType, out EngineID, out PartPalletCode); + // string OrderForm; + // MIS_BASE.Read_OrderForm(opName, out OrderForm); + // if (hashtable_EngineGetOver_EngineTypeID.Contains(opName)) + // { + // hashtable_EngineGetOver_EngineTypeID.Remove(opName); + // } + // hashtable_EngineGetOver_EngineTypeID.Add(opName, EngineTypeID); + + // if (hashtable_EngineGetOver_EngineType.Contains(opName)) + // { + // hashtable_EngineGetOver_EngineType.Remove(opName); + // } + // hashtable_EngineGetOver_EngineType.Add(opName, EngineType); + + + // if (hashtable_EngineGetOver_EngineID.Contains(opName)) + // { + // hashtable_EngineGetOver_EngineID.Remove(opName); + // } + // hashtable_EngineGetOver_EngineID.Add(opName, EngineID); + // if (hashtable_PartPalletCode.Contains(opName)) + // { + // hashtable_PartPalletCode.Remove(opName); + // } + // hashtable_PartPalletCode.Add(opName, PartPalletCode); + + // EngTypeGetOverInsert(opName, EngineTypeID, EngineType, EngineID, PartPalletCode, OrderForm); + + + // // 2 保存工件到位信息 + + // } + //} + + // + /// + /// @工位号 nvarchar(50)=null, + ///@产品型号代码 int=1 , + ///@发动机型号 nvarchar(50)=null , + ///@发动机号 nvarchar(50)=null , + ///@托盘号 nvarchar(50)='0' + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + //public static bool EngTypeGetOverInsert(string opName, int EngineTypeID, string EngineType,string EngineID, int PartPalletCode,string OrderForm) + //{ + // string procedureName; + // procedureName = "测量数据工位_监控系统_增加"; + // SqlParameter[] thisParms = new SqlParameter[6]; + // thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + // thisParms[1] = new System.Data.SqlClient.SqlParameter("@产品型号代码", EngineTypeID); + // thisParms[2] = new System.Data.SqlClient.SqlParameter("@发动机型号", EngineType); + // thisParms[3] = new System.Data.SqlClient.SqlParameter("@发动机号", EngineID); + // thisParms[4] = new System.Data.SqlClient.SqlParameter("@托盘编号", PartPalletCode); + // thisParms[6] = new System.Data.SqlClient.SqlParameter("@订单号", OrderForm); + + // if (DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms)) + // { + // return true; + // } + // return false; + // + //} + } +} diff --git a/MIS_FuntionSaveData/MIS_FuntionSaveData/Funtion.MesRead.cs b/MIS_FuntionSaveData/MIS_FuntionSaveData/Funtion.MesRead.cs new file mode 100644 index 0000000..4b4eeef --- /dev/null +++ b/MIS_FuntionSaveData/MIS_FuntionSaveData/Funtion.MesRead.cs @@ -0,0 +1,765 @@ +using bizFacade; +using DataLinkMesWork; +using DoWhatPlc; +using MesServerFunctions; +using MesServerWork; +using MesWork; +using Newtonsoft.Json; +using System; +using System.Collections; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Data; +using System.Data.SqlClient; +using System.Linq; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading.Tasks; + +namespace MisDataSaveDateMesRead +{ + public partial class Funtion + { + + + /// + /// 允许保存(针对半自动和手动压装工位) + /// + /// + /// + public static int MesRead(string opName, string tagValue, string tagid, bool isCheck = false) + { + int qualityMask = 0; + + qualityMask = SaveQualityData(opName, Convert.ToInt32(tagValue), tagid, isCheck); + + + //if (tagValue == "0") + //{ + // MIS_BASE.Write_TagTypeID(20, opName, false); + //} + //else + //{ + // qualityMask = SaveQualityData(opName, Convert.ToInt32(tagValue), tagid, isCheck); + // MIS_BASE.Write_TagTypeID(20, opName, true); + //} + return qualityMask; + } + public static string GetRealTimeQualityData(string opName) + { + string message = ""; + DataTable dt1 = new DataTable(); + DataTable dt_WWW; + DataTable dt_WWW_Copy1; + DataTable dt_WWW_Copy2; + Hashtable valueList; + try + { + //读取工位全部数据 + var rtList = MIS_BASE.ReadPLC_OpName(opName); //GetDbAndMaxLengthByOpNameByBytes(opName); + var pp = JsonConvert.SerializeObject(rtList); + var tagValues = JsonConvert.DeserializeObject>(pp); + //过滤出来质量数据 //获得带合格标志的质量数据 + valueList = ReadPLC_OpName_Qd(tagValues); + + //获得带基本信息的质量数据表 + GetQualityDataTable(valueList, opName, MIS_BASE.BasicDataTagValue, MIS_BASE.BasicDataTagValueUpDown, out dt_WWW); + + dt_WWW_Copy1 = dt_WWW.Copy().Select("变量排序 = 1").CopyToDataTable(); + DataView dv1 = dt_WWW_Copy1.DefaultView; + dv1.Sort = "列位置 DESC"; + dt_WWW_Copy1 = dv1.ToTable(); + + dt_WWW_Copy2 = dt_WWW.Copy().Select("变量排序 = 2").CopyToDataTable(); + DataView dv2 = dt_WWW_Copy2.DefaultView; + dv2.Sort = "列位置 DESC"; + dt_WWW_Copy2 = dv2.ToTable(); + + dt1.Columns.Add("列位置", System.Type.GetType("System.String")); + dt1.Columns.Add("测量项目1", System.Type.GetType("System.String")); + dt1.Columns.Add("测量项目2", System.Type.GetType("System.String")); + dt1.Columns.Add("合格标志", System.Type.GetType("System.String")); + dt1.Columns.Add("名称", System.Type.GetType("System.String")); + + for (int i = 0; i < dt_WWW_Copy1.Rows.Count; i++) + { + if (dt_WWW_Copy1.Rows[i]["TagValue"].ToString() != "0" || dt_WWW_Copy2.Rows[i]["TagValue"].ToString() != "0") + { + var dr = dt1.NewRow(); + dr["列位置"] = dt_WWW_Copy1.Rows[i]["列位置"].ToString(); + dr["测量项目1"] = dt_WWW_Copy1.Rows[i]["TagValue"].ToString(); + dr["测量项目2"] = dt_WWW_Copy2.Rows[i]["TagValue"].ToString(); + dr["合格标志"] = dt_WWW_Copy1.Rows[i]["IsGoodBad"].ToString(); + dr["名称"] = dt_WWW_Copy1.Rows[i]["测量项目"].ToString(); + dt1.Rows.Add(dr); + } + } + } + catch (Exception err) + { + } + message = JsonHelper.CreateJsonParameters(dt1); + + return message; + } + /// + /// 返回合格标志 + /// + /// + /// + /// + /// + private static int SaveQualityData(string opName, int tagValue, string tagID, bool isCheck = false) + { + int id_tagCF; + int qualityMask = 0; + int engineTypeID = 0; + string engineID = ""; + string engineType = ""; + string partPallet = ""; + string orderFormPlc = ""; + DataTable dt_WWW; + Hashtable valueList; + try + { + + //读取工位全部数据 + var rtList = MIS_BASE.ReadPLC_OpName(opName); //GetDbAndMaxLengthByOpNameByBytes(opName); + var pp = JsonConvert.SerializeObject(rtList); + var tagValues = JsonConvert.DeserializeObject>(pp); + //过滤出来质量数据 //获得带合格标志的质量数据 + valueList = ReadPLC_OpName_Qd(tagValues); + + + engineTypeID = Convert.ToInt32(GetValueByTagTypeCodeID(tagValues, Convert.ToInt32(EnumTagTypeCodeID.EngineTypeID))); + engineID = GetValueByTagTypeCodeID(tagValues, Convert.ToInt32(EnumTagTypeCodeID.EngineID)).ToString(); + engineType = GetValueByTagTypeCodeID(tagValues, Convert.ToInt32(EnumTagTypeCodeID.EngineType)).ToString(); + orderFormPlc = GetValueByTagTypeCodeID(tagValues, Convert.ToInt32(EnumTagTypeCodeID.OrderFormPLC)).ToString(); + qualityMask = Convert.ToInt32(GetValueByTagTypeCodeID(tagValues, Convert.ToInt32(EnumTagTypeCodeID.QualityMask))); + + + + //获得带基本信息的质量数据表 + GetQualityDataTable(valueList, opName, MIS_BASE.BasicDataTagValue, + MIS_BASE.BasicDataTagValueUpDown, out dt_WWW); + + DateTime lastupdatetime = DateTime.Now; + //保存质量数 + BaseData_tagTable_QualityData_B5A_IndexInsert(engineID, tagID, engineType, engineTypeID, opName, qualityMask, partPallet, out id_tagCF); + BaseData_tagTable_QualityData_B5A_Insert(id_tagCF, engineTypeID, engineID, opName, dt_WWW, isCheck); + + // } + BaseDataSystemMES.Material_Insert(opName, 1); + + //更新订单完工数量及物料 + SendMessageFun.SendMessage("24", "111", opName); + //回写保存完成数据 + //MIS_BASE.Write_TagTypeID(20, opName, true); + #region + //string orderForm = ""; + //string operatorCode = ""; + //int shiftCode = 1; + //DateTime arrivedTime; + //DateTime leavedTime; + //int TimeDiff; + //int targetTime = 0; + //string lineType = ""; + //string isPass; + //int machineWorkOn = 0; + //int arrivedOrLeaved = 2; + //int cartColorOpName = 0; + //int cartColorConfirm = 0; + //// int partMoveDirection; + //int partGoOver = 0; + //if (qualityMask == 1) + //{ + // isPass = "PASS"; + //} + //else + //{ + // isPass = "FAIL"; + //} + + ////工位上下线类型 + ////(0普通工位)(1正常上线)(2正常下线)(3返修上线)(4返修下线) + //int OpNameUpDownType; + //OpNameUpDownType = Convert.ToInt32(hashtableOpName_OpType[opName]); + //arrivedTime = (DateTime)m_WorkStart_OpName_Time[opName]; + //leavedTime = DateTime.Now; + //TimeDiff = Convert.ToInt32(leavedTime.Subtract(arrivedTime).TotalSeconds); + + //lineType = hashtableOpName_LineType[opName].ToString(); + + //string isHaveComputer = hashtableOpName_IsHaveComputer[opName].ToString(); + ////isHaveComputer = MIS_BASE.hashtable_tagTable_OpName_SaveData[opName].ToString(); + ////有计算机的工位,通过工位计算机保存[测量数据发动机在线状态]。 + //if (Convert.ToInt32(isHaveComputer) == 0) + //{ + // //1->0 工件离开 工件刚刚离开 + // if (Convert.ToInt32(m_WorkStart_OpName[opName]) == 1) + // { + + // //[测量数据发动机在线状态] + // QualityDataSystem.WorkStartInsert + // (opName, orderForm, engineTypeID, engineType, engineID, partPallet.ToString(), operatorCode, shiftCode, + // arrivedTime, leavedTime, TimeDiff, targetTime, lineType, isPass, machineWorkOn, + // arrivedOrLeaved, cartColorOpName, cartColorConfirm, partMoveDirection, partGoOver, mes_MustTest, onLineState, OpNameUpDownType); + // } + //} + #endregion + } + catch (Exception err) + { + //MIS_BASE.Write_TagTypeID(20, opName, true); + ////ApplicationLog.WriteLog(err, err.Message); + } + return qualityMask; + } + static public void GetQualityDataTable(Hashtable valuList, string opName, DataTable BasicDataTagValue, DataTable BasicDataTagValueUpDown, out DataTable dt) + { + //78 0:屏蔽MES;1:启用MES(必须MIS) + //79 通过线体工位PC实现下达工位工作状态:工位有三种状态:在线、离线、屏蔽。在线;0正常状态,实现正常功能。1离线:2屏蔽。(必须MIS) + //41 机体流向标志(1 BYTE):0普通工位:1:上线(发动机上线);2:下线(发动机下线);(必须PLC) + //51 返修工位,修改后的数据MES将数据写入PLC ,MES通知PLC数据修改完成。(YN) + //8 只要返修,必须由mes发送此信号,plc接收此信号后才能放行 + //(暂时没用)用于有扳手拧紧工位。通知设备螺钉拧紧完成。PC已经将数据保存到数据库中。(B5A) + + QualityDataType qualityData; + //是否有数据 + //bool isUsing; + + DataRow dr; + DataRow[] dr_WWW; + //MES_基本数据_测量范围 + DataRow[] dr_WWW_UpDown; + + dt = BaseDataSystemMES.BuildDataTables_WWW(); + + //测量位置 + string shaftID; + //测量项目 + string item; + //测量单位 + string unit; + //机体类型 + //原始数据中的机型代码 + int engineTypeID_Source; + //上限值 + string tagValueUp; + //下限值 + string tagValueDown; + //理论值 + string tagValeNormal; + //TagValue + // 合格标志 + //string IsGoodBad; + + foreach (DictionaryEntry valueItem in valuList) //ht为一个Hashtable实例 + { + try + { + qualityData = (QualityDataType)valueItem.Value; + + + //if ((qualityData.tagProperty != 2) || (qualityData.tagProperty != 6)) + //{ + // continue ; + //} + //if ((qualityData.tagProperty == 2) || (qualityData.tagProperty == 6)) + { + //if (engineTypeID == 0) + //{ + // engineTypeID = 1; + //} + dr_WWW = BasicDataTagValue.Select("TagID = " + qualityData.tagID); + try + { + dr_WWW_UpDown = BasicDataTagValueUpDown.Select("TagID = " + qualityData.tagID); + } + catch { dr_WWW_UpDown = null; } + + + //if (dr_WWW.Length > 0) + //{ + // { + // engineTypeID_Source = Convert.ToInt32(dr_WWW[0]["机体类型"]); + // int temp; + // temp = engineTypeID_Source & engineTypeID; + // if (temp == 0) + // { + // continue; + // } + // if (qualityData.isGoodBad == -1) + // { + // continue; + // } + // } + //} + //else + //{ + // continue; + + //} + + try + { + shaftID = dr_WWW[0]["测量位置"].ToString(); + } + catch + { + shaftID = ""; + } + try + { + item = dr_WWW[0]["测量项目"].ToString(); + } + catch + { + item = ""; + } + try + { + unit = dr_WWW[0]["测量单位"].ToString(); + } + catch + { + unit = ""; + } + try + { + tagValueUp = ""; + if (dr_WWW_UpDown != null && dr_WWW_UpDown.Length > 0) + { + tagValueUp = dr_WWW_UpDown[0]["值上限"].ToString(); + } + else + { + tagValueUp = ""; + } + } + catch + { + tagValueUp = ""; + } + try + { + tagValueDown = ""; + if (dr_WWW_UpDown != null && dr_WWW_UpDown.Length > 0) + { + tagValueDown = dr_WWW_UpDown[0]["值下限"].ToString(); + } + } + catch + { + tagValueDown = ""; + } + try + { + tagValeNormal = ""; + if (dr_WWW_UpDown != null && dr_WWW_UpDown.Length > 0) + { + tagValeNormal = dr_WWW_UpDown[0]["理论值"].ToString(); + } + + } + catch + { + tagValeNormal = ""; + } + + dr = dt.NewRow(); + + dr["TagID"] = qualityData.tagID; + dr["测量位置"] = shaftID; + dr["测量项目"] = item; + dr["测量单位"] = unit; + dr["上限值"] = tagValueUp; + dr["下限值"] = tagValueDown; + dr["理论值"] = tagValeNormal; + dr["工位号"] = opName; + dr["列位置"] = qualityData.tagOrderBy; + dr["变量排序"] = qualityData.tagItemOrderBy; + + dr["IsGoodBad"] = qualityData.isGoodBad; + + switch (qualityData.tagTypeID)// + { + //合格标志数组 + case 8203: + dr["TagValue"] = BaseDataSystemMES.GetQualityData_GoodBad_String((bool[])qualityData.tagValue); + break; + case 8209: + dr["TagValue"] = ""; + break; + //非标准REAL + case 8210: + dr["TagValue"] = BaseDataSystemMES.GetNoNormalReal(qualityData.tagValue); + dt.Rows.Add(dr); + break; + default: + dr["TagValue"] = Convert.ToString(qualityData.tagValue); + dt.Rows.Add(dr); + break; + } + + //福田对质量数据特殊处理,MA20保留4位小数点,其余保留两位 + if (opName == "J07MA020") + { + dr["TagValue"] = Convert.ToDouble(dr["TagValue"]).ToString("0.####"); + } + else + { + dr["TagValue"] = Convert.ToDouble(dr["TagValue"]).ToString("0.##"); + } + + if (opName == "J07MA150") + { + dr["变量排序"] = 1; + dr["IsGoodBad"] = 1; + } + + + } + + + + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, err.Message); + } + } + } + /// + /// 数据表 + /// + /// + private static object GetValueByTagTypeCodeID(ConcurrentDictionary opTagList, int TagTypeCodeID) + { + try + { + return opTagList.Where(x => x.Value.TagTypeCodeID == TagTypeCodeID).ToList()[0].Value.TagValue; + + } + catch (Exception err) { return "-3"; } + } + /// + /// 根据工位名称,读取工位对应的质量数据,带合格标志 + /// + /// + /// + public static Hashtable ReadPLC_OpName_Qd(ConcurrentDictionary tagValues) + { + //lock (l) + { + + //var tagValues = DtWebApi.ReadWritePLC.ReadPLC_OpName(opName); //GetDbAndMaxLengthByOpNameByBytes(opName); + + var keyValues = tagValues.OrderBy(x => x.Key).ToDictionary(k => k.Key, v => v.Value); + + TagFormat tagFormatTemp; + int tagIndex = 1; + int isOK = 0; + + Hashtable ht = new Hashtable(); + + + foreach (KeyValuePair _cd in keyValues) + { + if (_cd.Key.ToString()[0].ToString() == "7") + { + tagFormatTemp = _cd.Value; + if (tagIndex % 3 == 1) + { + isOK = Convert.ToInt32(tagFormatTemp.TagValue); + } + else if (tagIndex % 3 == 2) + { + var TF = _cd.Value; + + QualityDataType qualityDataType; + qualityDataType = GetQualityDataType(TF); + qualityDataType.isGoodBad = isOK; + ht.Add(qualityDataType.tagID, qualityDataType); + } + else if (tagIndex % 3 == 0) + { + var TF = (TagFormat)_cd.Value; + + QualityDataType qualityDataType; + qualityDataType = GetQualityDataType(TF); + qualityDataType.isGoodBad = isOK; + ht.Add(qualityDataType.tagID, qualityDataType); + } + + tagIndex++; + } + //Console.WriteLine($"key:{kv.Key} value:{kv.Value}"); + } + return ht; + } + } + + //public static Hashtable ReadPLC_OpName_Entite(string opName) + //{ + // //lock (l) + // { + + // var tagValues = DtWebApi.ReadWritePLC.ReadPLC_OpName(opName); //GetDbAndMaxLengthByOpNameByBytes(opName); + + // var keyValues = tagValues.OrderBy(x => x.Key).ToDictionary(k => k.Key, v => v.Value); + + // TagFormat tagFormatTemp; + // int tagIndex = 1; + // int isOK = 0; + + // Hashtable ht = new Hashtable(); + + + // foreach (KeyValuePair _cd in keyValues) + // { + // if (_cd.Key.ToString()[0].ToString() == "7") + // { + // tagFormatTemp = _cd.Value; + // if (tagIndex % 3 == 1) + // { + // isOK = Convert.ToInt32(tagFormatTemp.TagValue); + // } + // else if (tagIndex % 3 == 2) + // { + // var TF = _cd.Value; + + // QualityDataType qualityDataType; + // qualityDataType = GetQualityDataType(TF); + // qualityDataType.isGoodBad = isOK; + // ht.Add(qualityDataType.tagID, qualityDataType); + // } + // else if (tagIndex % 3 == 0) + // { + // var TF = (TagFormat)_cd.Value; + + // QualityDataType qualityDataType; + // qualityDataType = GetQualityDataType(TF); + // qualityDataType.isGoodBad = isOK; + // ht.Add(qualityDataType.tagID, qualityDataType); + // } + + // tagIndex++; + // } + // //Console.WriteLine($"key:{kv.Key} value:{kv.Value}"); + // } + // return ht; + // } + //} + public static QualityDataType GetQualityDataType(TagFormat TF) + { + QualityDataType qualityDataType; + + qualityDataType = new QualityDataType(); + + qualityDataType.tagID = TF.TagID; + qualityDataType.tagTypeID = TF.TagTypeID;//变量类型 + qualityDataType.opName = TF.OpName; + int.TryParse(TF.TagQuality, out int TagQuality); + qualityDataType.tagQuality = TagQuality; + qualityDataType.tagValueType = TF.TagTypeCodeID; + int.TryParse(TF.TagOrderBy, out int TagOrderBy); + qualityDataType.tagOrderBy = TagOrderBy; + int.TryParse(TF.TagItemOrderBy, out int TagItemOrderBy); + qualityDataType.tagItemOrderBy = TagItemOrderBy; + qualityDataType.tagProperty = TF.TagProperty;//变量特点 + qualityDataType.tagValue = TF.TagValue;//变量值 + + return qualityDataType; + } + + public static bool BaseData_tagTable_QualityData_B5A_IndexInsert(string EngineID, string tagID, string EngineType, int EngineTypeID, string opName, int isGoodBad, string PartPalletCode, out int Id_tagCF) + { + string procedureName; + procedureName = "测量数据合格索引_增加"; + Id_tagCF = 0; + SqlParameter[] thisParms = new SqlParameter[8]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@EngineID", EngineID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@TagID_CF", tagID); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@EngineType", EngineType); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@EngineTypeID", EngineTypeID); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[5] = new System.Data.SqlClient.SqlParameter("@托盘编号", PartPalletCode); + thisParms[6] = new System.Data.SqlClient.SqlParameter("@合格标志", isGoodBad); + thisParms[7] = new System.Data.SqlClient.SqlParameter("@Id_tagCF", Id_tagCF); + thisParms[7].Direction = ParameterDirection.Output; + + if (DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms)) + { + Id_tagCF = Convert.ToInt32(thisParms[7].Value.ToString()); + return true; + } + return false; + } + public static bool BaseData_tagTable_QualityData_B5A_Insert(int Id_tagCF, int engineTypeID, string engineID, string opName, DataTable dt, bool IsCheck = false) + { + string procedureName; + procedureName = "测量数据合格_增加"; + SqlParameter[] thisParms = new SqlParameter[7]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@Id_tagCF", Id_tagCF); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@EngineTypeID", engineTypeID); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@EngineID", engineID); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@TagID", SqlDbType.Int, 4, "TagID"); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@TagValue", SqlDbType.NVarChar, 100, "TagValue"); + thisParms[5] = new System.Data.SqlClient.SqlParameter("@IsGoodBad", SqlDbType.Int, 4, "IsGoodBad"); + //是否保存无合格标志数据数据 + thisParms[6] = new System.Data.SqlClient.SqlParameter("@IsCheck", IsCheck); + //thisParms[6] = new System.Data.SqlClient.SqlParameter("@测量位置", SqlDbType.NVarChar, 50, "测量位置"); + //thisParms[7] = new System.Data.SqlClient.SqlParameter("@测量项目", SqlDbType.NVarChar, 50, "测量项目"); + //thisParms[8] = new System.Data.SqlClient.SqlParameter("@工位号", opName); //为了给J07MA020 保留四位精度而设置 + //thisParms[9] = new System.Data.SqlClient.SqlParameter("@理论值", SqlDbType.NVarChar, 50, "理论值"); + //thisParms[10] = new System.Data.SqlClient.SqlParameter("@上限值", SqlDbType.NVarChar, 50, "上限值"); + //thisParms[11] = new System.Data.SqlClient.SqlParameter("@下限值", SqlDbType.NVarChar, 50, "下限值"); + //thisParms[12] = new System.Data.SqlClient.SqlParameter("@测量单位", SqlDbType.NVarChar, 50, "测量单位"); + //thisParms[13] = new System.Data.SqlClient.SqlParameter("@列位置", SqlDbType.Int, 4, "列位置"); + //thisParms[14] = new System.Data.SqlClient.SqlParameter("@变量排序", SqlDbType.Int, 4, "变量排序"); + //table.Columns.Add("TagID", typeof(System.Int32)); + //table.Columns.Add("TagValue", typeof(System.String)); + //table.Columns.Add("IsGoodBad", typeof(System.Int32)); + //table.Columns.Add("测量位置", typeof(System.String)); + //table.Columns.Add("测量项目", typeof(System.String)); + //table.Columns.Add("工位号", typeof(System.String)); + //table.Columns.Add("理论值", typeof(System.String)); + //table.Columns.Add("上限值", typeof(System.String)); + //table.Columns.Add("下限值", typeof(System.String)); + //table.Columns.Add("测量单位", typeof(System.String)); + //table.Columns.Add("列位置", typeof(System.Int32)); + //table.Columns.Add("变量排序", typeof(System.Int32)); + return DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, dt); + } + + + public static int MesRead_J07MA150(string opName, string tagValue, string tagid) + { + int qualityMask = 0; + + if (tagValue == "0") + { + MIS_BASE.Write_TagTypeID(20, opName, false); + } + else + { + qualityMask = SaveQualityData_J07MA150(opName, Convert.ToInt32(tagValue), tagid); + MIS_BASE.Write_TagTypeID(20, opName, true); + } + return qualityMask; + } + /// + /// 返回合格标志, 注油工位 质量数据为字符串,读取备用点 变量类型代码 = 41 + /// + /// + /// + /// + /// + private static int SaveQualityData_J07MA150(string opName, int tagValue, string tagID) + { + int id_tagCF; + int qualityMask = 0; + int engineTypeID = 0; + string engineID = ""; + string engineType = ""; + string partPallet = ""; + string orderFormPlc = ""; + DataTable dt_WWW; + Hashtable valueList; + try + { + + //过滤出来质量数据 //获得带合格标志的质量数据 + var rtList = MIS_BASE.ReadPLC_OpName(opName); //GetDbAndMaxLengthByOpNameByBytes(opName); + var pp = JsonConvert.SerializeObject(rtList); + var tagValues = JsonConvert.DeserializeObject>(pp); + valueList = ReadPLC_OpName_Qd_J07MA150(tagValues); + //valueList = ReadPLC_OpName_Qd(tagValues); + + engineTypeID = Convert.ToInt32(GetValueByTagTypeCodeID(tagValues, Convert.ToInt32(EnumTagTypeCodeID.EngineTypeID))); + engineID = GetValueByTagTypeCodeID(tagValues, Convert.ToInt32(EnumTagTypeCodeID.EngineID)).ToString(); + engineType = GetValueByTagTypeCodeID(tagValues, Convert.ToInt32(EnumTagTypeCodeID.EngineType)).ToString(); + orderFormPlc = GetValueByTagTypeCodeID(tagValues, Convert.ToInt32(EnumTagTypeCodeID.OrderFormPLC)).ToString(); + engineID = GetValueByTagTypeCodeID(tagValues, Convert.ToInt32(EnumTagTypeCodeID.EngineID)).ToString(); + qualityMask = Convert.ToInt32(GetValueByTagTypeCodeID(tagValues, Convert.ToInt32(EnumTagTypeCodeID.QualityMask))); + + + + + + //获得带基本信息的质量数据表 + GetQualityDataTable(valueList, opName, MIS_BASE.BasicDataTagValue, + MIS_BASE.BasicDataTagValueUpDown, out dt_WWW); + + + DateTime lastupdatetime = DateTime.Now; + //保存质量数 + BaseData_tagTable_QualityData_B5A_IndexInsert(engineID, tagID, engineType, engineTypeID, opName, qualityMask, partPallet, out id_tagCF); + BaseData_tagTable_QualityData_B5A_Insert(id_tagCF, engineTypeID, engineID, opName, dt_WWW); + + // } + BaseDataSystemMES.Material_Insert(opName, 1); + + //更新订单完工数量及物料 + SendMessageFun.SendMessage("24c", "111", opName); + + //回写保存完成数据 + MIS_BASE.Write_TagTypeID(20, opName, true); + } + catch (Exception err) + { + MIS_BASE.Write_TagTypeID(20, opName, true); + ////ApplicationLog.WriteLog(err, err.Message); + } + return qualityMask; + } + public static Hashtable ReadPLC_OpName_Qd_J07MA150(ConcurrentDictionary tagValues) + { + //lock (l) + { + + //var tagValues = DtWebApi.ReadWritePLC.ReadPLC_OpName(opName); //GetDbAndMaxLengthByOpNameByBytes(opName); + + var keyValues = tagValues.OrderBy(x => x.Key).ToDictionary(k => k.Key, v => v.Value); + + TagFormat tagFormatTemp; + int tagIndex = 1; + int isOK = 1; + + Hashtable ht = new Hashtable(); + + + //var TF = _cd.Value; + ////var TF = Read_TagTypeID(39, opName, out OrderForm); + + //QualityDataType qualityDataType; + //qualityDataType = GetQualityDataType(TF); + //qualityDataType.isGoodBad = isOK; + //ht.Add(qualityDataType.tagID, qualityDataType); + + + foreach (KeyValuePair _cd in keyValues) + { + + if (_cd.Value.TagTypeCodeID.ToString() == "41") + { + tagFormatTemp = _cd.Value; + + var TF = _cd.Value; + + QualityDataType qualityDataType; + qualityDataType = GetQualityDataType(TF); + qualityDataType.isGoodBad = isOK; + qualityDataType.tagItemOrderBy = 1; + qualityDataType.tagOrderBy = 1; + ht.Add(qualityDataType.tagID, qualityDataType); + } + //Console.WriteLine($"key:{kv.Key} value:{kv.Value}"); + } + return ht; + } + } + + } +} \ No newline at end of file diff --git a/MIS_FuntionSaveData/MIS_FuntionSaveData/Funtion.WorkStart.cs b/MIS_FuntionSaveData/MIS_FuntionSaveData/Funtion.WorkStart.cs new file mode 100644 index 0000000..54f9b66 --- /dev/null +++ b/MIS_FuntionSaveData/MIS_FuntionSaveData/Funtion.WorkStart.cs @@ -0,0 +1,186 @@ +using DataLinkMesWork; +using MesServerFunctions; +using MesServerWork; +using System; +using System.Configuration; +using System.Data; +using System.Data.SqlClient; + +namespace MisDataSaveDateMesRead +{ + public partial class Funtion + { + public static string MqttTargetTopic = ConfigurationManager.AppSettings["MqttTargetTopic"]; + + private static void WorkStart(DoWhatPlc.CustomeEvetnArgs e) + { + //var ro = rv.ReturnValueToObject(); + + string opName = e.OpName.ToString(); + DateTime arrivedTime = Convert.ToDateTime(e.TimeStampBefore); + DateTime leavedTime = Convert.ToDateTime(e.TimeStamp); + int TimeDiff = e.TagKeepTime; + //int targetTime = 0; + string isPass = ""; + + int QualityMark = 0; + string tagValue = "0"; + switch (e.TagValue.ToString().ToLower()) + { + case "1": + case "true": + tagValue = "1"; + break; + default: + tagValue = "0"; + break; + } + + + + int EngineTypeID = -1;//机型代码 + int PartPalletCode = -1;//托盘编号 + string EngineType = "-1";//机型 + string EngineID = "-1";//工件编号 + //if (hashtable_EngineGetOver_EngineTypeID.Contains(opName)) + //{ + // EngineTypeID = Convert.ToInt32( hashtable_EngineGetOver_EngineTypeID[opName]); + //} + //if (hashtable_EngineGetOver_EngineType.Contains(opName)) + //{ + // EngineType = hashtable_EngineGetOver_EngineType[opName].ToString(); + //} + //if (hashtable_EngineGetOver_EngineID.Contains(opName)) + //{ + // EngineID = hashtable_EngineGetOver_EngineID[opName].ToString(); + //} + //if (hashtable_PartPalletCode.Contains(opName)) + //{ + // PartPalletCode = Convert.ToInt32(hashtable_PartPalletCode[opName]); + //} + //int EngineTypeID;//机型代码 + //int PartPallet_Code;//托盘编号 + //string EngineType;//机型 + //string EngineID;//工件编号 + string OrderForm; + MIS_BASE.GetEngineTypeFromPLC(opName, out EngineTypeID, out EngineType, out EngineID, out int PartPallet_Code, out OrderForm); + + //MIS_BASE.GetEngineTypeFromPLC(opName, out EngineTypeID, out EngineType, out EngineID, out PartPallet_Code); + + //EngineData Enginedata = (EngineData)EngineData_Hash_Read(opName); + //WorkStartInsert_AutoWorkStation(opName, EngineID, PartPalletCode, arrivedTime, leavedTime, TimeDiff, targetTime, null, isPass, 0); + + if (tagValue == "0") + { + QualityMark = Convert.ToInt32(MIS_BASE.ReadPLC(21, opName)); + + if (QualityMark == 1) + { + isPass = "1"; + } + else + { + isPass = "0"; + } + + WorkStartInsert_V2022(opName, arrivedTime, leavedTime, TimeDiff, isPass); + + MIS_BASE.Write_TagTypeID(5, opName, false);//MES传递机型 + MIS_BASE.Write_TagTypeID(66, opName, false);//允许工作 + MIS_BASE.Write_TagTypeID(51, opName, false);//合格放行 + MIS_BASE.Write_TagTypeID(8, opName, false);//不合格放行 + MIS_BASE.Write_TagTypeID(7, opName, false);//工作完成 + MIS_BASE.Write_TagTypeID(20, opName, false);//保存完成 + + } + + //通知WEB更新产量 + SendMessage.SendActuallyCount(opName, 0); + } + + //} + /// + /// 基本数据_工作日历_班次产量查询_New + /// + /// + /// 在线产量 + /// 在线节拍 + static public void OpNameCount_New(string opName, out int opNameCount, out int opNameCountTime) + { + opNameCount = 0; + opNameCountTime = 0; + string procedureName; + procedureName = "基本数据_工作日历_班次产量查询_New"; + SqlParameter[] thisParms = new SqlParameter[3]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@在线产量", 0); + thisParms[1].Direction = ParameterDirection.Output; + thisParms[2] = new System.Data.SqlClient.SqlParameter("@在线节拍", 0); + thisParms[2].Direction = ParameterDirection.Output; + if (DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms)) + { + opNameCount = Convert.ToInt32(thisParms[1].Value); + opNameCountTime = Convert.ToInt32(thisParms[2].Value); + } + } + /// + /// 测量数据发动机在线状态_增加数据_自动工位 + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + static public void WorkStartInsert_AutoWorkStation(string opName, string EngineID, int Pallet, DateTime arrivedTime, DateTime leavedTime, int TimeDiff, int Target, string lineType, string isPass, int OpNameUpDownType) + { + string procedureName; + procedureName = "测量数据发动机在线状态_增加数据_自动工位"; + SqlParameter[] thisParms = new SqlParameter[10]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@发动机号", EngineID); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@托盘编号", Pallet); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@到达时间", arrivedTime); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@离开时间", leavedTime); + thisParms[5] = new System.Data.SqlClient.SqlParameter("@在线时间", TimeDiff); + thisParms[6] = new System.Data.SqlClient.SqlParameter("@目标时间", Target); + thisParms[7] = new System.Data.SqlClient.SqlParameter("@线体类型", lineType); + thisParms[8] = new System.Data.SqlClient.SqlParameter("@是否合格", isPass); + thisParms[9] = new System.Data.SqlClient.SqlParameter("@工位上下线类型", OpNameUpDownType); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } + + static public void WorkStartInsert_V2022(string opName, DateTime arrivedTime, DateTime leavedTime, int TimeDiff, string isPass) + { + string procedureName; + procedureName = "测量数据发动机在线状态_增加数据_V2022"; + SqlParameter[] thisParms = new SqlParameter[5]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@到达时间", arrivedTime); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@离开时间", leavedTime); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@在线时间", TimeDiff); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@是否合格", isPass); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } + + static public void WorkStartInsert(string opName, DateTime arrivedTime, DateTime leavedTime, int TimeDiff, int Target, string lineType, string isPass, int OpNameUpDownType) + { + string procedureName; + procedureName = "测量数据发动机在线状态_增加数据"; + SqlParameter[] thisParms = new SqlParameter[8]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@到达时间", arrivedTime); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@离开时间", leavedTime); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@在线时间", TimeDiff); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@目标时间", Target); + thisParms[5] = new System.Data.SqlClient.SqlParameter("@线体类型", lineType); + thisParms[6] = new System.Data.SqlClient.SqlParameter("@是否合格", isPass); + thisParms[7] = new System.Data.SqlClient.SqlParameter("@工位上下线类型", OpNameUpDownType); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } + } +} diff --git a/MIS_FuntionSaveData/MIS_FuntionSaveData/MIS_Funtion.cs b/MIS_FuntionSaveData/MIS_FuntionSaveData/MIS_Funtion.cs new file mode 100644 index 0000000..41dc5eb --- /dev/null +++ b/MIS_FuntionSaveData/MIS_FuntionSaveData/MIS_Funtion.cs @@ -0,0 +1,269 @@ +using DoWhatPlc; +using MesServerWork; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using bizFacade; +using System.Data; +using MesServerFunctions; + +namespace MisDataSaveDateMesRead +{ + public partial class Funtion + { + /// + /// 发动机类型转换表 + /// SELECT ID,发动机机型代码 FROM MES_计划BOM_发动机型号代码 + /// + public static Hashtable hashtable_EngineTypeID = new Hashtable(); + /// + /// 记录工件到位的发动机机型代码 + /// + public static Hashtable hashtable_EngineGetOver_EngineTypeID = new Hashtable(); + /// + /// 记录工件到位的发动机机型 + /// + public static Hashtable hashtable_EngineGetOver_EngineType = new Hashtable(); + /// + /// 记录工件到位的发动机号 + /// + public static Hashtable hashtable_EngineGetOver_EngineID = new Hashtable(); + /// + /// 记录工件到位的订单号 + /// + public static Hashtable hashtable_EngineGetOver_OrderForm = new Hashtable(); + + public static Hashtable hashtable_EngineGetOver = new Hashtable(); + + public static Hashtable hashtable_PartPalletCode = new Hashtable(); + /// + /// 保存质量数据和过站信息 + /// + /// + public static void MIS_Funtion(object e) + { + try + { + + string recData = e.ToString(); + List dataArray = DoWhatPlc.MessageText.GetCmdStringList(recData); + + //string[] dataArray = recData.Split('|'); + //if (dataArray.Count != 4) + //return; + //消息来源 + string m_Source = dataArray[0].ToString(); + //消息类型 + string m_Command = dataArray[1].ToString(); + //工位号 + string m_OpName = dataArray[2].ToString(); + //消息参数 + string m_Value = dataArray[3].ToString(); + + DoWhatPlc.CustomeEvetnArgs msgEvent = Newtonsoft.Json.JsonConvert.DeserializeObject(m_Value); + //DoWhatPlc.ReturnValueString rv = Newtonsoft.Json.JsonConvert.DeserializeObject(m_Value); + //Console.WriteLine($"【【{rv.TagID}【【【【{ rv.TagKeepTime}"); + if (msgEvent == null) return; + int tagType; + int tagTypeCodeID; + string opName; + string tagValue; + string tagid; + //DoWhatPlc.ReturnValueString msgEvent = rv; + if (msgEvent.TagValue == null) return; + tagType = Convert.ToInt32(msgEvent.TagTypeID); + opName = msgEvent.OpName.ToString(); + tagid = msgEvent.TagID.ToString(); + tagTypeCodeID = Convert.ToInt32(msgEvent.TagTypeCodeID); + + + switch (tagType) + { + case 11: + switch (msgEvent.TagValue.ToString().ToLower()) + { + case "1": + case "true": + tagValue = "1"; + break; + default: + tagValue = "0"; + break; + } + break; + default: + tagValue = msgEvent.TagValue.ToString(); + break; + } + ///根据信号处理逻辑 + switch (tagTypeCodeID) + { + case 19: + //允许保存 + MesRead(opName, tagValue, tagid); + break; + case 14: + //心跳 + //Heartbeat(opName, tagValue); + break; + case 44://PLC传递机型过后 才允许保存过站信息,否则不允许保存 + //EngTypeGetOver(opName, tagValue); + break; + case 2://工件到位 离开信息 + + if (tagValue == "0") + { + bool S_EngineGetOver; + MIS_BASE.Read_EngineGetOver_PLC(opName, out S_EngineGetOver); + //传递机型 + //if (S_EngineGetOver) + { + //if (hashtable_EngineGetOver[opName].ToString() == "1") + { + WorkStart(msgEvent); + } + } + } + break; + case 51: + //if (hashtableOpName_IsHaveComputer[opName].ToString() == "1") + //{ + // SaveProductLeaveData(opName, 1); + //} + + break; + case 8: + //if (hashtableOpName_IsHaveComputer[opName].ToString() == "1") + //{ + // SaveProductLeaveData(opName, 2); + //} + break; + case 103: + + //Alarm_Insert(msgEvent); + + break; + } + + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, err.Message); + } + } + + + + //public static void MIS_Funtion(object e) + // { + // try + // { + + // string recData = e.ToString(); + // string[] dataArray = recData.Split('|'); + // if (dataArray.Length != 4) + // return; + // //消息来源 + // string m_Source = dataArray[0].ToString(); + // //消息类型 + // string m_Command = dataArray[1].ToString(); + // //工位号 + // string m_OpName = dataArray[2].ToString(); + // //消息参数 + // string m_Value = dataArray[3].ToString(); + + // DoWhatPlc.ReturnValueString rv = Newtonsoft.Json.JsonConvert.DeserializeObject(m_Value); + // //Console.WriteLine($"【【{rv.TagID}【【【【{ rv.TagKeepTime}"); + // if (rv == null) return; + // int tagType; + // int tagTypeCodeID; + // string opName; + // string tagValue; + // int tagid; + // DoWhatPlc.ReturnValueString msgEvent = rv; + // if (msgEvent.TagValue == null) return; + // tagType = Convert.ToInt32(msgEvent.TagTypeID); + // opName = msgEvent.OpName.ToString(); + // tagid = Convert.ToInt32(msgEvent.TagID); + // tagTypeCodeID = Convert.ToInt32(msgEvent.TagTypeCodeID); + + + // switch (tagType) + // { + // case 11: + // switch (msgEvent.TagValue.ToLower()) + // { + // case "1": + // case "true": + // tagValue = "1"; + // break; + // default: + // tagValue = "0"; + // break; + // } + // break; + // default: + // tagValue = msgEvent.TagValue.ToString(); + // break; + // } + // ///根据信号处理逻辑 + // switch (tagTypeCodeID) + // { + // case 19: + // //允许保存 + // MesRead(opName, tagValue, tagid); + // break; + // case 14: + // //心跳 + // //Heartbeat(opName, tagValue); + // break; + // case 44://PLC传递机型过后 才允许保存过站信息,否则不允许保存 + // EngTypeGetOver(opName, tagValue); + // break; + // case 2://工件到位 离开信息 + + // if (tagValue == "0") + // { + // //传递机型 + // //if (hashtable_EngineGetOver.Contains(opName)) + // { + // //if (hashtable_EngineGetOver[opName].ToString() == "1") + // { + // WorkStart(e); + // } + // } + // } + // break; + // case 51: + // //if (hashtableOpName_IsHaveComputer[opName].ToString() == "1") + // //{ + // // SaveProductLeaveData(opName, 1); + // //} + + // break; + // case 8: + // //if (hashtableOpName_IsHaveComputer[opName].ToString() == "1") + // //{ + // // SaveProductLeaveData(opName, 2); + // //} + // break; + // case 103: + + // Alarm_Insert(e); + + // break; + // } + + // } + // catch (Exception err) + // { + // ////ApplicationLog.WriteLog(err, err.Message); + // } + // } + + + } +} \ No newline at end of file diff --git a/MIS_FuntionSaveData/MIS_FuntionSaveData/Properties/AssemblyInfo.cs b/MIS_FuntionSaveData/MIS_FuntionSaveData/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..36dc948 --- /dev/null +++ b/MIS_FuntionSaveData/MIS_FuntionSaveData/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// 有关程序集的一般信息由以下 +// 控制。更改这些特性值可修改 +// 与程序集关联的信息。 +[assembly: AssemblyTitle("MIS_FuntionSaveData")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("MIS_FuntionSaveData")] +[assembly: AssemblyCopyright("Copyright © 2022")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// 将 ComVisible 设置为 false 会使此程序集中的类型 +//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型 +//请将此类型的 ComVisible 特性设置为 true。 +[assembly: ComVisible(false)] + +// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID +[assembly: Guid("55b510c1-59e9-4bfd-ae84-d76d46f6e365")] + +// 程序集的版本信息由下列四个值组成: +// +// 主版本 +// 次版本 +// 生成号 +// 修订号 +// +//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值 +//通过使用 "*",如下所示: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Mes32X32.ico b/Mes32X32.ico new file mode 100644 index 0000000..ec465b2 Binary files /dev/null and b/Mes32X32.ico differ diff --git a/MesMonitor/--PlcMonitor/PlcMonitor.sln b/MesMonitor/--PlcMonitor/PlcMonitor.sln new file mode 100644 index 0000000..68f3289 --- /dev/null +++ b/MesMonitor/--PlcMonitor/PlcMonitor.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.32929.386 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PlcMonitor", "PlcMonitor\PlcMonitor.csproj", "{67F90D19-10E5-4CFB-8667-BFF6AFDAF6C0}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {67F90D19-10E5-4CFB-8667-BFF6AFDAF6C0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {67F90D19-10E5-4CFB-8667-BFF6AFDAF6C0}.Debug|Any CPU.Build.0 = Debug|Any CPU + {67F90D19-10E5-4CFB-8667-BFF6AFDAF6C0}.Release|Any CPU.ActiveCfg = Release|Any CPU + {67F90D19-10E5-4CFB-8667-BFF6AFDAF6C0}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {F0FF1176-C12C-41BC-9ED3-6FE5BE278F63} + EndGlobalSection +EndGlobal diff --git a/MesMonitor/--PlcMonitor/PlcMonitor/App.config b/MesMonitor/--PlcMonitor/PlcMonitor/App.config new file mode 100644 index 0000000..731f6de --- /dev/null +++ b/MesMonitor/--PlcMonitor/PlcMonitor/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/MesMonitor/--PlcMonitor/PlcMonitor/Form1.Designer.cs b/MesMonitor/--PlcMonitor/PlcMonitor/Form1.Designer.cs new file mode 100644 index 0000000..b41964f --- /dev/null +++ b/MesMonitor/--PlcMonitor/PlcMonitor/Form1.Designer.cs @@ -0,0 +1,41 @@ + +namespace PlcMonitor +{ + partial class Form1 + { + /// + /// 必需的设计器变量。 + /// + 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.components = new System.ComponentModel.Container(); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(800, 450); + this.Text = "Form1"; + } + + #endregion + } +} + diff --git a/MesMonitor/--PlcMonitor/PlcMonitor/Form1.cs b/MesMonitor/--PlcMonitor/PlcMonitor/Form1.cs new file mode 100644 index 0000000..bae5c92 --- /dev/null +++ b/MesMonitor/--PlcMonitor/PlcMonitor/Form1.cs @@ -0,0 +1,20 @@ +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 PlcMonitor +{ + public partial class Form1 : Form + { + public Form1() + { + InitializeComponent(); + } + } +} diff --git a/MesMonitor/--PlcMonitor/PlcMonitor/PlcMonitor.csproj b/MesMonitor/--PlcMonitor/PlcMonitor/PlcMonitor.csproj new file mode 100644 index 0000000..f7590ed --- /dev/null +++ b/MesMonitor/--PlcMonitor/PlcMonitor/PlcMonitor.csproj @@ -0,0 +1,80 @@ + + + + + Debug + AnyCPU + {67F90D19-10E5-4CFB-8667-BFF6AFDAF6C0} + WinExe + PlcMonitor + PlcMonitor + v4.6.1 + 512 + true + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + Form + + + Form1.cs + + + + + ResXFileCodeGenerator + Resources.Designer.cs + Designer + + + True + Resources.resx + + + SettingsSingleFileGenerator + Settings.Designer.cs + + + True + Settings.settings + True + + + + + + + \ No newline at end of file diff --git a/MesMonitor/--PlcMonitor/PlcMonitor/Program.cs b/MesMonitor/--PlcMonitor/PlcMonitor/Program.cs new file mode 100644 index 0000000..498d7db --- /dev/null +++ b/MesMonitor/--PlcMonitor/PlcMonitor/Program.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace PlcMonitor +{ + static class Program + { + /// + /// 应用程序的主入口点。 + /// + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + Application.Run(new Form1()); + } + } +} diff --git a/MesMonitor/--PlcMonitor/PlcMonitor/Properties/AssemblyInfo.cs b/MesMonitor/--PlcMonitor/PlcMonitor/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..11eaed2 --- /dev/null +++ b/MesMonitor/--PlcMonitor/PlcMonitor/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// 有关程序集的一般信息由以下 +// 控制。更改这些特性值可修改 +// 与程序集关联的信息。 +[assembly: AssemblyTitle("PlcMonitor")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("PlcMonitor")] +[assembly: AssemblyCopyright("Copyright © 2022")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// 将 ComVisible 设置为 false 会使此程序集中的类型 +//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型 +//请将此类型的 ComVisible 特性设置为 true。 +[assembly: ComVisible(false)] + +// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID +[assembly: Guid("67f90d19-10e5-4cfb-8667-bff6afdaf6c0")] + +// 程序集的版本信息由下列四个值组成: +// +// 主版本 +// 次版本 +// 生成号 +// 修订号 +// +//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值 +//通过使用 "*",如下所示: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/MesMonitor/--PlcMonitor/PlcMonitor/Properties/Resources.Designer.cs b/MesMonitor/--PlcMonitor/PlcMonitor/Properties/Resources.Designer.cs new file mode 100644 index 0000000..8ffe0a3 --- /dev/null +++ b/MesMonitor/--PlcMonitor/PlcMonitor/Properties/Resources.Designer.cs @@ -0,0 +1,70 @@ +//------------------------------------------------------------------------------ +// +// 此代码由工具生成。 +// 运行时版本: 4.0.30319.42000 +// +// 对此文件的更改可能导致不正确的行为,如果 +// 重新生成代码,则所做更改将丢失。 +// +//------------------------------------------------------------------------------ + + +namespace PlcMonitor.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("PlcMonitor.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/MesMonitor/--PlcMonitor/PlcMonitor/Properties/Resources.resx b/MesMonitor/--PlcMonitor/PlcMonitor/Properties/Resources.resx new file mode 100644 index 0000000..af7dbeb --- /dev/null +++ b/MesMonitor/--PlcMonitor/PlcMonitor/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/MesMonitor/--PlcMonitor/PlcMonitor/Properties/Settings.Designer.cs b/MesMonitor/--PlcMonitor/PlcMonitor/Properties/Settings.Designer.cs new file mode 100644 index 0000000..669219e --- /dev/null +++ b/MesMonitor/--PlcMonitor/PlcMonitor/Properties/Settings.Designer.cs @@ -0,0 +1,29 @@ +//------------------------------------------------------------------------------ +// +// 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 PlcMonitor.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/MesMonitor/--PlcMonitor/PlcMonitor/Properties/Settings.settings b/MesMonitor/--PlcMonitor/PlcMonitor/Properties/Settings.settings new file mode 100644 index 0000000..3964565 --- /dev/null +++ b/MesMonitor/--PlcMonitor/PlcMonitor/Properties/Settings.settings @@ -0,0 +1,7 @@ + + + + + + + diff --git a/MesMonitor/--SignalChangeMonitor/FunctionForm_HashiTable.cs b/MesMonitor/--SignalChangeMonitor/FunctionForm_HashiTable.cs new file mode 100644 index 0000000..6e6efd4 --- /dev/null +++ b/MesMonitor/--SignalChangeMonitor/FunctionForm_HashiTable.cs @@ -0,0 +1,103 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace MisDataName +{ + class FunctionForm_HashiTable + { + public static Hashtable OpName_Hash = new Hashtable(); + public static object OpName_Hash_Read(string Key) + { + if (OpName_Hash.ContainsKey(Key)) + { + return OpName_Hash[Key]; + + } + else + { + return null; + } + + } + + public static void OpName_Hash_Write(string Key, object obj) + { + + if (OpName_Hash.ContainsKey(Key)) + { + + OpName_Hash[Key] = obj; + } + else + { + OpName_Hash.Add(Key, obj); + } + + } + + + public static Hashtable SignalName = new Hashtable(); + public static string SignalName_Hash_Read(string Key) + { + if (SignalName.ContainsKey(Key)) + { + return SignalName[Key].ToString (); + + } + else + { + return null; + } + + } + + public static void SignalName_Hash_Write(string Key, string str) + { + + if (SignalName.ContainsKey(Key)) + { + + SignalName[Key] = str; + } + else + { + SignalName.Add(Key, str); + } + + } + + + public static Hashtable SignalConfig = new Hashtable(); + public static object SignalConfig_Hash_Read(string Key) + { + if (SignalConfig.ContainsKey(Key)) + { + return SignalConfig[Key]; + + } + else + { + return null; + } + + } + + public static void SignalConfig_Write(string Key, object str) + { + + if (SignalConfig.ContainsKey(Key)) + { + + SignalConfig[Key] = str; + } + else + { + SignalConfig.Add(Key, str); + } + + } + } +} diff --git a/MesMonitor/--SignalChangeMonitor/MainSignalChangeEvent.cs b/MesMonitor/--SignalChangeMonitor/MainSignalChangeEvent.cs new file mode 100644 index 0000000..88f947d --- /dev/null +++ b/MesMonitor/--SignalChangeMonitor/MainSignalChangeEvent.cs @@ -0,0 +1,55 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SystemFramework; + +namespace MisDataName +{ + public partial class SecondForm + { + + void InitMainSignalEvent() + { + MisData.PlcChange = new PlcChangeEvent(MainSignalChange); + } + + void MainSignalChange(OpcData.CustomeEvetnArgs msgEvent) + { + try + { + int tagType; + string opName, tagValue; + + if (msgEvent.TagValue == null) return; + tagType = Convert.ToInt32(msgEvent.TagType); + opName = msgEvent.OpName.ToString(); + switch (Convert.ToInt32(msgEvent.TagValueType)) + { + case 11: + tagValue = (Convert.ToInt32(msgEvent.TagValue)).ToString(); + break; + default: + tagValue = msgEvent.TagValue.ToString(); + break; + } + + if (Convert.ToInt32(msgEvent.TagValueType)==11) + { + + WriteWorkStationSignal(opName, tagType.ToString(), Convert.ToBoolean(Convert.ToInt32(tagValue))); + } + + + } + catch (Exception err) + { + ApplicationLog.WriteLog(err, err.Message); + + } + + } + + + } +} diff --git a/MesMonitor/--SignalChangeMonitor/PlcSignalDynamicCreate.cs b/MesMonitor/--SignalChangeMonitor/PlcSignalDynamicCreate.cs new file mode 100644 index 0000000..54c7f3f --- /dev/null +++ b/MesMonitor/--SignalChangeMonitor/PlcSignalDynamicCreate.cs @@ -0,0 +1,138 @@ +using MesControl; +using System; +using System.Collections.Generic; +using System.Data; +using System.Linq; +using System.Text; +using System.Xml.Linq; +using SystemFramework; + +namespace MisDataName +{ + public delegate void ControlConnectPLC(); + public partial class SecondForm + { + ControlConnectPLC PlcConnectTimer; + + void InitFormDynamicControls() + { + try + { + // DataTable dt_OpName=(DataTable) FunctionForm_HashiTable.OpName_Hash_Read("OpNameList"); + + List signalItems = InitWorkStationSignal(); + RecordWorkStationSignal(signalItems); + + int RowsWidth = SignalPanel.Width-20; + int RowsNum = RowsWidth / 133; + int i = 0; + + foreach (var opName in MesWork.PlcLinkForm.opNameList) + { + PlcWorkStationSignal plcWorkStationSignal = new PlcWorkStationSignal(); + + plcWorkStationSignal.BackColor = System.Drawing.Color.Transparent; + plcWorkStationSignal.Location = new System.Drawing.Point(3 + ((i % RowsNum) * 133), (i / RowsNum) * ((signalItems.Count * 25) + 60)); + plcWorkStationSignal.MaximumSize = new System.Drawing.Size(0, 0); + plcWorkStationSignal.MinimumSize = new System.Drawing.Size(0, 0); + plcWorkStationSignal.Name = "plcWorkStationSignal_" + opName; + plcWorkStationSignal.Size = new System.Drawing.Size(136, 60); + plcWorkStationSignal.TabIndex = i; + plcWorkStationSignal.SignalItems = signalItems; + plcWorkStationSignal.WorkStationNameText = opName; + plcWorkStationSignal.WS_PlcLabelText = "PLC连接"; + plcWorkStationSignal.TestPLC_Interval = 10000; + + plcWorkStationSignal.TestPLC_Enable = true; + PlcConnectTimer += plcWorkStationSignal.ExternalTimerExcute; + + this.SignalPanel.Controls.Add(plcWorkStationSignal); + i++; + } + + + } + catch (Exception err) + { + ApplicationLog.WriteLog(err, err.Message); + } + + } + + public List InitWorkStationSignal() + { + try + { + List signalItems = new List(); + MesBoolSignal MBS; + signalItems.Clear(); + XDocument SystemConfig = XDocument.Load("SystemConfig.xml"); + IEnumerable plc = SystemConfig.Descendants ("PLC"); + IEnumerable plcSignal = plc.Elements(); + foreach (XElement PlcSignal in plcSignal) + { + XElement Name = PlcSignal.Element("Name"); + XElement TagType = PlcSignal.Element("TagType"); + XElement Text = PlcSignal.Element("Text"); + XElement Index = PlcSignal.Element("Index"); + XElement Enabled = PlcSignal.Element("Enabled"); + + MBS = new MesBoolSignal(); + MBS.Name = "TagType_" + TagType.Value ; + MBS.SignalText = Text.Value ; + MBS.SignalImage = MesBoolSignal.SignalImage_Enum.none; + + if (Convert.ToBoolean(Enabled.Value)) + { + signalItems.Add(MBS); + } + } + IEnumerable mes = SystemConfig.Descendants("MES"); + IEnumerable mesSignal = mes.Elements(); + foreach (XElement MesSignal in mesSignal) + { + XElement Name = MesSignal.Element("Name"); + XElement TagType = MesSignal.Element("TagType"); + XElement Text = MesSignal.Element("Text"); + XElement Index = MesSignal.Element("Index"); + XElement Enabled = MesSignal.Element("Enabled"); + + MBS = new MesBoolSignal(); + MBS.Name = "TagType_" + TagType.Value; + MBS.SignalText = Text.Value; + MBS.SignalImage = MesBoolSignal.SignalImage_Enum.none; + + if (Convert .ToBoolean ( Enabled .Value)) + { + signalItems.Add(MBS); + } + + } + + return signalItems; + } + catch (Exception err) + { + ApplicationLog.WriteLog(err, err.Message); + return null; + } + } + + + string[] SignalNames = new string[50]; + + void RecordWorkStationSignal(List items) + { + + for (int i=0;i< items.Count;i++) + { + SignalNames[i] = items[i].Name; + } + + + } + + + + } +} diff --git a/MesMonitor/--SignalChangeMonitor/SecondForm.Designer.cs b/MesMonitor/--SignalChangeMonitor/SecondForm.Designer.cs new file mode 100644 index 0000000..8ec36c1 --- /dev/null +++ b/MesMonitor/--SignalChangeMonitor/SecondForm.Designer.cs @@ -0,0 +1,91 @@ +namespace MisDataName +{ + partial class SecondForm + { + /// + /// 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.components = new System.ComponentModel.Container(); + this.SignalPanel = new System.Windows.Forms.Panel(); + this.groupBox_PlcSignal = new System.Windows.Forms.GroupBox(); + this.timer_ControlInternalChange = new System.Windows.Forms.Timer(this.components); + this.groupBox_PlcSignal.SuspendLayout(); + this.SuspendLayout(); + // + // SignalPanel + // + this.SignalPanel.AutoScroll = true; + this.SignalPanel.Location = new System.Drawing.Point(6, 20); + this.SignalPanel.Name = "SignalPanel"; + this.SignalPanel.Size = new System.Drawing.Size(706, 650); + this.SignalPanel.TabIndex = 0; + // + // groupBox_PlcSignal + // + this.groupBox_PlcSignal.Controls.Add(this.SignalPanel); + this.groupBox_PlcSignal.Location = new System.Drawing.Point(12, 12); + this.groupBox_PlcSignal.Name = "groupBox_PlcSignal"; + this.groupBox_PlcSignal.Size = new System.Drawing.Size(718, 676); + this.groupBox_PlcSignal.TabIndex = 1; + this.groupBox_PlcSignal.TabStop = false; + this.groupBox_PlcSignal.Text = "LineStatus"; + // + // timer_ControlInternalChange + // + this.timer_ControlInternalChange.Enabled = true; + this.timer_ControlInternalChange.Interval = 400; + this.timer_ControlInternalChange.Tick += new System.EventHandler(this.timer_ControlInternalChange_Tick); + // + // SecondForm + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(741, 700); + this.Controls.Add(this.groupBox_PlcSignal); + this.MaximizeBox = false; + this.MaximumSize = new System.Drawing.Size(757, 738); + this.MinimizeBox = false; + this.MinimumSize = new System.Drawing.Size(757, 738); + this.Name = "SecondForm"; + this.ShowIcon = false; + this.ShowInTaskbar = false; + this.StartPosition = System.Windows.Forms.FormStartPosition.Manual; + this.Text = "PlcSignal"; + this.TopMost = true; + this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.SecondForm_FormClosing); + this.LocationChanged += new System.EventHandler(this.SecondForm_LocationChanged); + this.groupBox_PlcSignal.ResumeLayout(false); + this.ResumeLayout(false); + + } + + #endregion + + private System.Windows.Forms.Panel SignalPanel; + private System.Windows.Forms.GroupBox groupBox_PlcSignal; + private System.Windows.Forms.Timer timer_ControlInternalChange; + } +} \ No newline at end of file diff --git a/MesMonitor/--SignalChangeMonitor/SecondForm.cs b/MesMonitor/--SignalChangeMonitor/SecondForm.cs new file mode 100644 index 0000000..8fab8a2 --- /dev/null +++ b/MesMonitor/--SignalChangeMonitor/SecondForm.cs @@ -0,0 +1,231 @@ +using MesControl; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Windows.Forms; +using SystemFramework; + +namespace MisDataName +{ + public partial class SecondForm : Form + { + + + public SecondForm(Point Position) + { + InitializeComponent(); + InitFormDynamicControls(); + InitMainSignalEvent(); + FormPositionInit(Position); + InitOtherFormAction(); + SyncForm_Init(); + + } + Form MainForm; + public SecondForm(object mainForm) + { + MainForm = (Form)mainForm; + InitializeComponent(); + InitFormDynamicControls(); + InitMainSignalEvent(); + Point Position = new Point(MainForm.Left + MainForm.Width, MainForm.Top); + + FormPositionInit(Position); + InitOtherFormAction(); + SyncForm_Init(); + + } + + void WorkStation_RefreshWorkStationStatus(string OpName, bool value) + { + try + { + PlcWorkStationSignal plcWorkStationSignal = (PlcWorkStationSignal)Controls.Find("plcWorkStationSignal_" + OpName, true)[0]; + plcWorkStationSignal.PlcConnectStatusChange(value); + } + catch (Exception err) + { + ApplicationLog.WriteLog(err, err.Message); + } + } + + + void WriteWorkStationSignal(string OpName,string SignalName,bool value) + { + try + { + if (Array.IndexOf(SignalNames, "TagType_"+SignalName)!=-1) + { + PlcWorkStationSignal plcWorkStationSignal = (PlcWorkStationSignal)Controls.Find("plcWorkStationSignal_" + OpName, true)[0]; + plcWorkStationSignal.SignalChange("TagType_"+SignalName, value); + if (SignalName=="14") + { + WorkStation_RefreshWorkStationStatus(OpName, value); + } + + } + } + catch (Exception err) + { + ApplicationLog.WriteLog(err, err.Message); + } + + } + + + private void SecondForm_FormClosing(object sender, FormClosingEventArgs e) + { + try + { + MisData.PlcChange =null; + if (MisData.SyncSecondForm != null) + { + SyncForm_Cancel(); + } + CancelOtherFormAction(); + MainForm.BeginInvoke(MainMenuRefresh, "ToolStripMenuItem_VWSStatus"); + this.Dispose(); + } + catch (Exception err) + { + ApplicationLog.WriteLog(err, err.Message); + } + } + + + void SyncForm_Init() + { + try + { + MisData.SyncSecondForm = new SyncOtherForm(FormSync); + MisData.MainFormActive = new MisDataName.SyncOtherForm(MainFormActive); + } + catch (Exception err) + { + ApplicationLog.WriteLog(err, err.Message); + } + } + + void SyncForm_Cancel() + { + MisData.SyncSecondForm = null; + MisData.MainFormActive = null; + } + + void FormPositionInit(Point Position) + { + try + { + this.Location = (Point)new Size(Position); + } + catch (Exception err) + { + ApplicationLog.WriteLog(err, err.Message); + } + + } + + void FormSync(object Position) + { + try + { + this.Location = (Point)Position; + } + catch (Exception err) + { + ApplicationLog.WriteLog(err, err.Message); + } + } + + void MainFormActive(object obj) + { + + if(Convert .ToBoolean (obj )) + { + this.TopMost = true; + this.TopMost = false; + } + + } + + void InitOtherFormAction() + { + try + { + MisData.SecondFormClose = new MainAct(this.Close); + MisData.OtherFormHide = new MainAct(HideThisForm); + MisData.OtherFormShow = new MainAct(ShowThisForm); + } + catch (Exception err) + { + ApplicationLog.WriteLog(err, err.Message); + } + } + + void CancelOtherFormAction() + { + MisData.SecondFormClose = null; + MisData.OtherFormHide = null; + MisData.OtherFormShow = null; + + } + + void ShowThisForm() + { + this.Show(); + this.WindowState = FormWindowState.Normal; + } + + void HideThisForm() + { + this.Hide(); + } + + + + private void SecondForm_LocationChanged(object sender, EventArgs e) + { + try + { + Point MainPosation=(Point)MisData.QueryMainFormPosition(null); + + if(Math.Abs ( MainPosation .X -this .Left)<25&& Math.Abs(MainPosation.Y - this.Top ) < 20) + { + if (MisData.SyncSecondForm == null) + { + SyncForm_Init(); + MainForm.Invoke(MisData.MainActived); + FormSync(MainPosation); + + } + } + else + { + if (MisData.SyncSecondForm != null) + { + SyncForm_Cancel(); + } + } + } + catch (Exception err) + { + ApplicationLog.WriteLog(err, err.Message); + } + + + } + + private void timer_ControlInternalChange_Tick(object sender, EventArgs e) + { + if(PlcConnectTimer!=null) + { + PlcConnectTimer(); + } + + } + } +} diff --git a/MesMonitor/--SignalChangeMonitor/SecondForm.resx b/MesMonitor/--SignalChangeMonitor/SecondForm.resx new file mode 100644 index 0000000..09d1f58 --- /dev/null +++ b/MesMonitor/--SignalChangeMonitor/SecondForm.resx @@ -0,0 +1,123 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + \ No newline at end of file diff --git a/MesMonitor/--SignalChangeMonitor/SecondFormDelegate.cs b/MesMonitor/--SignalChangeMonitor/SecondFormDelegate.cs new file mode 100644 index 0000000..434652c --- /dev/null +++ b/MesMonitor/--SignalChangeMonitor/SecondFormDelegate.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace MisDataName +{ + public delegate void SecondAct(string ControlName); + + public partial class SecondForm + { + public static SecondAct MainMenuRefresh; + + } +} diff --git a/MesMonitor/--SignalChangeMonitor/vssver2.scc b/MesMonitor/--SignalChangeMonitor/vssver2.scc new file mode 100644 index 0000000..a05b956 Binary files /dev/null and b/MesMonitor/--SignalChangeMonitor/vssver2.scc differ diff --git a/MesMonitor/MonitorForm/App.config b/MesMonitor/MonitorForm/App.config new file mode 100644 index 0000000..5647eb1 --- /dev/null +++ b/MesMonitor/MonitorForm/App.config @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/MesMonitor/MonitorForm/Form1.Designer.cs b/MesMonitor/MonitorForm/Form1.Designer.cs new file mode 100644 index 0000000..a594139 --- /dev/null +++ b/MesMonitor/MonitorForm/Form1.Designer.cs @@ -0,0 +1,41 @@ + +namespace MonitorFrom +{ + partial class Form1 + { + /// + /// 必需的设计器变量。 + /// + 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.components = new System.ComponentModel.Container(); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(800, 450); + this.Text = "Form1"; + } + + #endregion + } +} + diff --git a/MesMonitor/MonitorForm/Form1.cs b/MesMonitor/MonitorForm/Form1.cs new file mode 100644 index 0000000..94de9ff --- /dev/null +++ b/MesMonitor/MonitorForm/Form1.cs @@ -0,0 +1,20 @@ +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 MonitorFrom +{ + public partial class Form1 : Form + { + public Form1() + { + InitializeComponent(); + } + } +} diff --git a/MesMonitor/MonitorForm/FunctionForm_HashiTable.cs b/MesMonitor/MonitorForm/FunctionForm_HashiTable.cs new file mode 100644 index 0000000..6e6efd4 --- /dev/null +++ b/MesMonitor/MonitorForm/FunctionForm_HashiTable.cs @@ -0,0 +1,103 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace MisDataName +{ + class FunctionForm_HashiTable + { + public static Hashtable OpName_Hash = new Hashtable(); + public static object OpName_Hash_Read(string Key) + { + if (OpName_Hash.ContainsKey(Key)) + { + return OpName_Hash[Key]; + + } + else + { + return null; + } + + } + + public static void OpName_Hash_Write(string Key, object obj) + { + + if (OpName_Hash.ContainsKey(Key)) + { + + OpName_Hash[Key] = obj; + } + else + { + OpName_Hash.Add(Key, obj); + } + + } + + + public static Hashtable SignalName = new Hashtable(); + public static string SignalName_Hash_Read(string Key) + { + if (SignalName.ContainsKey(Key)) + { + return SignalName[Key].ToString (); + + } + else + { + return null; + } + + } + + public static void SignalName_Hash_Write(string Key, string str) + { + + if (SignalName.ContainsKey(Key)) + { + + SignalName[Key] = str; + } + else + { + SignalName.Add(Key, str); + } + + } + + + public static Hashtable SignalConfig = new Hashtable(); + public static object SignalConfig_Hash_Read(string Key) + { + if (SignalConfig.ContainsKey(Key)) + { + return SignalConfig[Key]; + + } + else + { + return null; + } + + } + + public static void SignalConfig_Write(string Key, object str) + { + + if (SignalConfig.ContainsKey(Key)) + { + + SignalConfig[Key] = str; + } + else + { + SignalConfig.Add(Key, str); + } + + } + } +} diff --git a/MesMonitor/MonitorForm/MainSignalChangeEvent.cs b/MesMonitor/MonitorForm/MainSignalChangeEvent.cs new file mode 100644 index 0000000..6337822 --- /dev/null +++ b/MesMonitor/MonitorForm/MainSignalChangeEvent.cs @@ -0,0 +1,126 @@ +using DoWhatPlc; +using MesControl; +using MQTTnet; +using MQTTnet.Client.Connecting; +using MQTTnet.Client.Disconnecting; +using MQTTnet.Client.Receiving; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading; +//using SystemFramework; + +namespace MisDataName +{ + public partial class SecondForm + { + public MesWorkMqtt.Mqtt2 mqtt2; + public void InitMqtt2(string url, string topic) + { + mqtt2 = new MesWorkMqtt.Mqtt2(); + mqtt2.MqttUrl = url; + mqtt2.topic = topic; + mqtt2.StartAsync(); + mqtt2.mqttClient.ConnectedHandler = new MqttClientConnectedHandlerDelegate(OnSubscriberConnected); + mqtt2.mqttClient.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(OnSubscriberDisconnected); + mqtt2.mqttClient.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(OnSubscriberMessageReceived); + + //MesServerCode哈希表创建 + //MesServerWork.MIS_BASE.InitHashtable_MesServerCode(); + + } + private void OnSubscriberConnected(MqttClientConnectedEventArgs x) + { + var rec = x.AuthenticateResult.ResultCode.ToString(); + + } + + private void OnSubscriberDisconnected(MqttClientDisconnectedEventArgs x) + { + + } + + private void OnSubscriberMessageReceived(MqttApplicationMessageReceivedEventArgs x) + { + var rec = x.ApplicationMessage.ConvertPayloadToString(); + + + //处理MES业务 + ThreadPool.QueueUserWorkItem(MainSignalChange, rec); + } + + + void WorkStation_RefreshWorkStationStatus(string OpName, bool value) + { + try + { + PlcWorkStationSignal plcWorkStationSignal = (PlcWorkStationSignal)Controls.Find("plcWorkStationSignal_" + OpName, true)[0]; + plcWorkStationSignal.PlcConnectStatusChange(value); + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, err.Message); + } + } + void InitMainSignalEvent() + { + //MisData.PlcChange = new PlcChangeEvent(MainSignalChange); + } + + void MainSignalChange(object e) + { + string recData = e.ToString(); + string[] dataArray = recData.Split('|'); + if (dataArray.Length != 4) + return; + //消息来源 + string m_Source = dataArray[0].ToString(); + //消息类型 + string m_Command = dataArray[1].ToString(); + //工位号 + string m_OpName = dataArray[2].ToString(); + //消息参数 + string m_Value = dataArray[3].ToString(); + + DoWhatPlc.ReturnValueString rv = Newtonsoft.Json.JsonConvert.DeserializeObject(m_Value); + //Console.WriteLine($"【【{rv.TagID}【【【【{ rv.TagKeepTime}"); + + int tagType; + string opName; + string tagValue; + int tagid; + DoWhatPlc.ReturnValueString msgEvent = rv; + if (msgEvent.TagValue == null) return; + tagType = Convert.ToInt32(msgEvent.TagTypeID); + opName = msgEvent.OpName.ToString(); + tagid = Convert.ToInt32(msgEvent.TagID); + int tagTypeCodeID = Convert.ToInt32(msgEvent.TagTypeCodeID); + switch (tagType) + { + case 11: + switch (msgEvent.TagValue.ToLower()) + { + case "1": + case "true": + tagValue = "1"; + break; + default: + tagValue = "0"; + break; + } + break; + default: + tagValue = msgEvent.TagValue.ToString(); + break; + } + if (tagType == 11) + { + + WriteWorkStationSignal(opName, tagTypeCodeID.ToString(), Convert.ToBoolean(Convert.ToInt32(tagValue))); + } + } + + + } +} diff --git a/MesMonitor/MonitorForm/Mes32X32.ico b/MesMonitor/MonitorForm/Mes32X32.ico new file mode 100644 index 0000000..ec465b2 Binary files /dev/null and b/MesMonitor/MonitorForm/Mes32X32.ico differ diff --git a/MesMonitor/MonitorForm/MonitorForm.csproj b/MesMonitor/MonitorForm/MonitorForm.csproj new file mode 100644 index 0000000..199e39e --- /dev/null +++ b/MesMonitor/MonitorForm/MonitorForm.csproj @@ -0,0 +1,136 @@ + + + + + Debug + AnyCPU + {488BADD9-579F-4BF3-91DC-9FA95E3181A5} + WinExe + MonitorFrom + MonitorFrom + v4.6.1 + 512 + true + true + + + AnyCPU + true + full + false + bin\MonitorForm\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + Mes32X32.ico + + + + False + ..\..\Common\dll\MQTTnet.dll + + + False + ..\..\Common\dll\MQTTnet.Extensions.ManagedClient.dll + + + + + + + + + + + + + + + + + Form + + + Form1.cs + + + + Form + + + Form + + + + + Form + + + SecondForm.cs + + + Form + + + ResXFileCodeGenerator + Resources.Designer.cs + Designer + + + True + Resources.resx + + + SecondForm.cs + + + SettingsSingleFileGenerator + Settings.Designer.cs + + + True + Settings.settings + True + + + + + + + + {1a10fdb2-1a6a-44a8-ab4d-33387563247e} + 00-0Json8.3.1 + + + {f55da1a0-a982-4479-8c47-0d9a5aaf3e18} + 00MesWorkMqtt + + + {0d1af432-439a-4920-8692-43ae139f5530} + 01_01DoWhatPlc + + + {3e6d1dd5-01c9-435f-9941-61f906ce35bb} + 02_02WebApiCallPLC + + + {fab322cc-531d-4aea-986a-b921b64d8d3f} + MesControl + + + + + + + \ No newline at end of file diff --git a/MesMonitor/MonitorForm/MonitorForm.sln b/MesMonitor/MonitorForm/MonitorForm.sln new file mode 100644 index 0000000..b7d74e9 --- /dev/null +++ b/MesMonitor/MonitorForm/MonitorForm.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.32901.82 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MonitorForm", "MonitorForm.csproj", "{488BADD9-579F-4BF3-91DC-9FA95E3181A5}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {488BADD9-579F-4BF3-91DC-9FA95E3181A5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {488BADD9-579F-4BF3-91DC-9FA95E3181A5}.Debug|Any CPU.Build.0 = Debug|Any CPU + {488BADD9-579F-4BF3-91DC-9FA95E3181A5}.Release|Any CPU.ActiveCfg = Release|Any CPU + {488BADD9-579F-4BF3-91DC-9FA95E3181A5}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {2139453F-8DE4-42E7-92A1-7A305D62E5B6} + EndGlobalSection +EndGlobal diff --git a/MesMonitor/MonitorForm/PlcSignalDynamicCreate.cs b/MesMonitor/MonitorForm/PlcSignalDynamicCreate.cs new file mode 100644 index 0000000..bbe736d --- /dev/null +++ b/MesMonitor/MonitorForm/PlcSignalDynamicCreate.cs @@ -0,0 +1,138 @@ +using MesControl; +using System; +using System.Collections.Generic; +using System.Data; +using System.Linq; +using System.Text; +using System.Xml.Linq; +//using SystemFramework; + +namespace MisDataName +{ + public delegate void ControlConnectPLC(); + public partial class SecondForm + { + ControlConnectPLC PlcConnectTimer; + + void InitFormDynamicControls() + { + try + { + // DataTable dt_OpName=(DataTable) FunctionForm_HashiTable.OpName_Hash_Read("OpNameList"); + + List signalItems = InitWorkStationSignal(); + RecordWorkStationSignal(signalItems); + + int RowsWidth = SignalPanel.Width-20; + int RowsNum = RowsWidth / 133; + int i = 0; + var opNameList = DtWebApi.OpcDemo.Get_opNameList(); + foreach (var opName in opNameList) + { + PlcWorkStationSignal plcWorkStationSignal = new PlcWorkStationSignal(); + + plcWorkStationSignal.BackColor = System.Drawing.Color.Transparent; + plcWorkStationSignal.Location = new System.Drawing.Point(3 + ((i % RowsNum) * 133), (i / RowsNum) * ((signalItems.Count * 25) + 60)); + plcWorkStationSignal.MaximumSize = new System.Drawing.Size(0, 0); + plcWorkStationSignal.MinimumSize = new System.Drawing.Size(0, 0); + plcWorkStationSignal.Name = "plcWorkStationSignal_" + opName; + plcWorkStationSignal.Size = new System.Drawing.Size(136, 60); + plcWorkStationSignal.TabIndex = i; + plcWorkStationSignal.SignalItems = signalItems; + plcWorkStationSignal.WorkStationNameText = opName; + plcWorkStationSignal.WS_PlcLabelText = "PLC连接"; + plcWorkStationSignal.TestPLC_Interval = 10000; + + plcWorkStationSignal.TestPLC_Enable = true; + PlcConnectTimer += plcWorkStationSignal.ExternalTimerExcute; + + this.SignalPanel.Controls.Add(plcWorkStationSignal); + i++; + } + + + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, err.Message); + } + + } + + public List InitWorkStationSignal() + { + try + { + List signalItems = new List(); + MesBoolSignal MBS; + signalItems.Clear(); + XDocument SystemConfig = XDocument.Load("SystemConfig.xml"); + IEnumerable plc = SystemConfig.Descendants ("PLC"); + IEnumerable plcSignal = plc.Elements(); + foreach (XElement PlcSignal in plcSignal) + { + XElement Name = PlcSignal.Element("Name"); + XElement TagType = PlcSignal.Element("TagType"); + XElement Text = PlcSignal.Element("Text"); + XElement Index = PlcSignal.Element("Index"); + XElement Enabled = PlcSignal.Element("Enabled"); + + MBS = new MesBoolSignal(); + MBS.Name = "TagType_" + TagType.Value ; + MBS.SignalText = Text.Value ; + MBS.SignalImage = MesBoolSignal.SignalImage_Enum.none; + + if (Convert.ToBoolean(Enabled.Value)) + { + signalItems.Add(MBS); + } + } + IEnumerable mes = SystemConfig.Descendants("MES"); + IEnumerable mesSignal = mes.Elements(); + foreach (XElement MesSignal in mesSignal) + { + XElement Name = MesSignal.Element("Name"); + XElement TagType = MesSignal.Element("TagType"); + XElement Text = MesSignal.Element("Text"); + XElement Index = MesSignal.Element("Index"); + XElement Enabled = MesSignal.Element("Enabled"); + + MBS = new MesBoolSignal(); + MBS.Name = "TagType_" + TagType.Value; + MBS.SignalText = Text.Value; + MBS.SignalImage = MesBoolSignal.SignalImage_Enum.none; + + if (Convert .ToBoolean ( Enabled .Value)) + { + signalItems.Add(MBS); + } + + } + + return signalItems; + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, err.Message); + return null; + } + } + + + string[] SignalNames; + + void RecordWorkStationSignal(List items) + { + SignalNames = new string[items.Count]; + for (int i=0;i< items.Count;i++) + { + SignalNames[i] = items[i].Name; + } + + + } + + + + } +} diff --git a/MesMonitor/MonitorForm/Program.cs b/MesMonitor/MonitorForm/Program.cs new file mode 100644 index 0000000..67147e1 --- /dev/null +++ b/MesMonitor/MonitorForm/Program.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace MisDataName +{ + static class Program + { + /// + /// 应用程序的主入口点。 + /// + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + Application.Run(new SecondForm()); + } + } +} diff --git a/MesMonitor/MonitorForm/Properties/AssemblyInfo.cs b/MesMonitor/MonitorForm/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..53b0405 --- /dev/null +++ b/MesMonitor/MonitorForm/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// 有关程序集的一般信息由以下 +// 控制。更改这些特性值可修改 +// 与程序集关联的信息。 +[assembly: AssemblyTitle("MonitorFrom")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("MonitorFrom")] +[assembly: AssemblyCopyright("Copyright © 2022")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// 将 ComVisible 设置为 false 会使此程序集中的类型 +//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型 +//请将此类型的 ComVisible 特性设置为 true。 +[assembly: ComVisible(false)] + +// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID +[assembly: Guid("488badd9-579f-4bf3-91dc-9fa95e3181a5")] + +// 程序集的版本信息由下列四个值组成: +// +// 主版本 +// 次版本 +// 生成号 +// 修订号 +// +//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值 +//通过使用 "*",如下所示: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/MesMonitor/MonitorForm/Properties/Resources.Designer.cs b/MesMonitor/MonitorForm/Properties/Resources.Designer.cs new file mode 100644 index 0000000..6340659 --- /dev/null +++ b/MesMonitor/MonitorForm/Properties/Resources.Designer.cs @@ -0,0 +1,70 @@ +//------------------------------------------------------------------------------ +// +// 此代码由工具生成。 +// 运行时版本: 4.0.30319.42000 +// +// 对此文件的更改可能导致不正确的行为,如果 +// 重新生成代码,则所做更改将丢失。 +// +//------------------------------------------------------------------------------ + + +namespace MonitorFrom.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("MonitorFrom.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/MesMonitor/MonitorForm/Properties/Resources.resx b/MesMonitor/MonitorForm/Properties/Resources.resx new file mode 100644 index 0000000..af7dbeb --- /dev/null +++ b/MesMonitor/MonitorForm/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/MesMonitor/MonitorForm/Properties/Settings.Designer.cs b/MesMonitor/MonitorForm/Properties/Settings.Designer.cs new file mode 100644 index 0000000..f0dceaa --- /dev/null +++ b/MesMonitor/MonitorForm/Properties/Settings.Designer.cs @@ -0,0 +1,29 @@ +//------------------------------------------------------------------------------ +// +// 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 MonitorFrom.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/MesMonitor/MonitorForm/Properties/Settings.settings b/MesMonitor/MonitorForm/Properties/Settings.settings new file mode 100644 index 0000000..3964565 --- /dev/null +++ b/MesMonitor/MonitorForm/Properties/Settings.settings @@ -0,0 +1,7 @@ + + + + + + + diff --git a/MesMonitor/MonitorForm/SecondForm.Designer.cs b/MesMonitor/MonitorForm/SecondForm.Designer.cs new file mode 100644 index 0000000..138ee52 --- /dev/null +++ b/MesMonitor/MonitorForm/SecondForm.Designer.cs @@ -0,0 +1,83 @@ +namespace MisDataName +{ + partial class SecondForm + { + /// + /// 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.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(SecondForm)); + this.groupBox_PlcSignal = new System.Windows.Forms.GroupBox(); + this.SignalPanel = new MisDataName.MyPanel(); + this.groupBox_PlcSignal.SuspendLayout(); + this.SuspendLayout(); + // + // groupBox_PlcSignal + // + this.groupBox_PlcSignal.Controls.Add(this.SignalPanel); + this.groupBox_PlcSignal.Location = new System.Drawing.Point(12, 12); + this.groupBox_PlcSignal.Name = "groupBox_PlcSignal"; + this.groupBox_PlcSignal.Size = new System.Drawing.Size(718, 676); + this.groupBox_PlcSignal.TabIndex = 1; + this.groupBox_PlcSignal.TabStop = false; + this.groupBox_PlcSignal.Text = "LineStatus"; + // + // SignalPanel + // + this.SignalPanel.AutoScroll = true; + this.SignalPanel.Location = new System.Drawing.Point(6, 20); + this.SignalPanel.Name = "SignalPanel"; + this.SignalPanel.Size = new System.Drawing.Size(706, 650); + this.SignalPanel.TabIndex = 0; + // + // SecondForm + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(741, 699); + this.Controls.Add(this.groupBox_PlcSignal); + this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); + this.MaximizeBox = false; + this.MaximumSize = new System.Drawing.Size(757, 738); + this.MinimizeBox = false; + this.MinimumSize = new System.Drawing.Size(757, 738); + this.Name = "SecondForm"; + this.ShowIcon = false; + this.ShowInTaskbar = false; + this.StartPosition = System.Windows.Forms.FormStartPosition.Manual; + this.Text = "PlcSignal 2022-10-16"; + this.TopMost = true; + this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.SecondForm_FormClosing); + this.groupBox_PlcSignal.ResumeLayout(false); + this.ResumeLayout(false); + + } + + #endregion + + private MyPanel SignalPanel; + private System.Windows.Forms.GroupBox groupBox_PlcSignal; + } +} \ No newline at end of file diff --git a/MesMonitor/MonitorForm/SecondForm.cs b/MesMonitor/MonitorForm/SecondForm.cs new file mode 100644 index 0000000..759ee94 --- /dev/null +++ b/MesMonitor/MonitorForm/SecondForm.cs @@ -0,0 +1,86 @@ +using MesControl; +using MQTTnet; +using MQTTnet.Client.Connecting; +using MQTTnet.Client.Disconnecting; +using MQTTnet.Client.Receiving; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading; +using System.Windows.Forms; +//using SystemFramework; + +namespace MisDataName +{ + public partial class SecondForm : Form + { + public SecondForm() + { + InitializeComponent(); + InitFormDynamicControls(); + InitMainSignalEvent(); + //InitOtherFormAction(); + //SyncForm_Init(); + + string url; + string topic; + url = System.Configuration.ConfigurationManager.AppSettings["MqttUrl"]; + topic = System.Configuration.ConfigurationManager.AppSettings["MqttTargetTopicPLC"]; + + InitMqtt2(url, topic); + + } + + + + + void WriteWorkStationSignal(string OpName,string SignalName,bool value) + { + try + { + if (Array.IndexOf(SignalNames, "TagType_"+SignalName)!=-1) + { + PlcWorkStationSignal plcWorkStationSignal = (PlcWorkStationSignal)Controls.Find("plcWorkStationSignal_" + OpName, true)[0]; + plcWorkStationSignal.SignalChange("TagType_"+SignalName, value); + if (SignalName=="14") + { + WorkStation_RefreshWorkStationStatus(OpName, value); + } + + } + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, err.Message); + } + + } + + + private void SecondForm_FormClosing(object sender, FormClosingEventArgs e) + { + try + { + this.Dispose(); + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, err.Message); + } + } + } + + class MyPanel : Panel + { + public MyPanel() + { + this.SetStyle(ControlStyles.UserPaint, true); + this.SetStyle(ControlStyles.AllPaintingInWmPaint, true); + this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true); + } + } +} diff --git a/MesMonitor/MonitorForm/SecondForm.resx b/MesMonitor/MonitorForm/SecondForm.resx new file mode 100644 index 0000000..900f82a --- /dev/null +++ b/MesMonitor/MonitorForm/SecondForm.resx @@ -0,0 +1,197 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + + + AAABAAEAICAAAAEAIACoEAAAFgAAACgAAAAgAAAAQAAAAAEAIAAAAAAAABAAABMLAAATCwAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMgChADIAoQIyAKEgMgChczIA + occyAKHqMgChmTIAoTwyAKEJMgChAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMgChADIAoQQyAKEvMgChdzIA + odYyAKH7MgCh/zIAof8yAKH/MgCh6jIAoacyAKFJMgChEjIAoQAyAKEAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAyAKEAMgChADIAoQoyAKE+MgChkTIA + oeoyAKH+MgCh+TIAoe0yAKH+MgCh/zIAofwyAKH3MgCh/jIAofgyAKHBMgChZDIAoR4yAKEBMgChAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAyAKEAMgChATIAoRUyAKFcMgChujIA + ofEyAKH/MgCh9DIAobcyAKFPMgChfjIAof8yAKH/MgCh5TIAoVUyAKGLMgCh4jIAofwyAKH9MgCh2TIA + oYcyAKEoMgChBTIAoQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAyAKEAMgChAjIAoSYyAKF2MgCh0DIA + ofcyAKH+MgCh8zIAof8yAKGjMgChDTIAoQAyAKFpMgCh/zIAof8yAKHhMgChHjIAoQIyAKEiMgChbjIA + ocoyAKH3MgCh/jIAoeUyAKGfMgChQTIAoQsyAKEAAAAAAAAAAAAAAAAAMgChCDIAoUEyAKGXMgCh4jIA + of4yAKH/MgChzzIAoW0yAKFoMgCh+zIAoZcyAKEAMgChADIAoWkyAKH/MgCh/zIAoeEyAKEeMgChADIA + oQAyAKEBMgChETIAoVAyAKGiMgCh8DIAof8yAKH0MgChuTIAoW0yAKEVMgChADIAoQAyAKG2MgCh7TIA + of8yAKHvMgCh7jIAofgyAKFLMgChADIAoTcyAKH1MgChlzIAoQAyAKEAMgChaTIAof8yAKH/MgCh4TIA + oR4yAKEAAAAAAAAAAAAAAAAAMgChADIAoQcyAKE4MgChijIAod8yAKH9MgCh+zIAoc4yAKFdMgChADIA + of8yAKHlMgChlDIAoToyAKGgMgCh7jIAoSwyAKEAMgChFzIAodgyAKGZMgChADIAoQAyAKFpMgCh/zIA + of8yAKHxMgChfDIAoSkyAKEBMgChAAAAAAAAAAAAAAAAADIAoQAyAKECMgChITIAoW8yAKG/MgCh/zIA + oZYyAKEAMgCh/zIAoZoyAKEBMgChADIAoZkyAKHSMgChEjIAoQAyAKEGMgChujIAoZoyAKEAMgChADIA + oWkyAKH/MgCh/zIAof0yAKH+MgCh4TIAoZIyAKFEMgChDjIAoQAyAKEAAAAAAAAAAAAAAAAAMgChADIA + oUIyAKH7MgChlzIAoQAyAKH/MgChlzIAoQAyAKEAMgChmjIAobMyAKEEMgChADIAoQAyAKGcMgChmzIA + oQAyAKEAMgChaTIAof8yAKH/MgCh4zIAoZYyAKHRMgCh+zIAofQyAKHDMgChZDIAoSIyAKEBMgChAAAA + AAAyAKEAMgChPzIAofsyAKGXMgChADIAof8yAKGXMgChADIAoQAyAKGaMgChiDIAoQAAAAAAMgChADIA + oYgyAKGaMgChADIAoQAyAKFpMgCh/zIAof8yAKHhMgChIDIAoRIyAKFeMgChqzIAoe0yAKH+MgCh3jIA + oYYyAKEqMgChADIAoQAyAKE/MgCh+zIAoZcyAKEAMgCh/zIAoZcyAKEAMgChADIAoZgyAKFtMgChAAAA + AAAyAKEAMgChXDIAoZQyAKEAMgChADIAoWkyAKH/MgCh/zIAoeEyAKEeMgChADIAoQAyAKEGMgChMDIA + oX8yAKHTMgCh+jIAoWkyAKEAMgChADIAoT8yAKH7MgChlzIAoQAyAKH/MgChlzIAoQAyAKEAMgChlTIA + oWMyAKEAAAAAADIAoQAyAKE2MgChhTIAoQAyAKEAMgChaTIAof8yAKH/MgCh4TIAoR4yAKEAAAAAAAAA + AAAyAKEAMgChATIAoRUyAKFYMgChQDIAoQAyAKEAMgChPzIAofsyAKGXMgChADIAof8yAKGXMgChADIA + oQAyAKGLMgChQTIAoQAyAKEFMgChADIAoSMyAKF4MgChADIAoQAyAKFpMgCh/zIAof8yAKHhMgChHjIA + oQAAAAAAAAAAAAAAAAAAAAAAMgChADIAoQAyAKEBMgChADIAoQAyAKE/MgCh+zIAoZcyAKEAMgCh/zIA + oZcyAKEAMgChADIAoXcyAKEkMgChBzIAoUIyAKEBMgChFjIAoWUyAKEBMgChADIAoWkyAKH/MgCh/zIA + oeEyAKEeMgChADIAoQAyAKE5MgChSTIAoQ8yAKEBMgChAAAAAAAAAAAAMgChADIAoT8yAKH7MgChlzIA + oQAyAKH/MgChlzIAoQAyAKECMgChWzIAoQ8yAKEVMgChhTIAoQoyAKEHMgChMzIAoQEyAKEAMgChaTIA + of8yAKH/MgCh4TIAoR4yAKEAMgChADIAoWkyAKH1MgChyzIAoX8yAKE4MgChBTIAoQAyAKEAMgChPzIA + ofsyAKGXMgChADIAof8yAKGXMgChADIAoQMyAKFZMgChCzIAoS4yAKHDMgChGjIAoQAAAAAAAAAAADIA + oQAyAKFpMgCh/zIAof8yAKHhMgChHjIAoQAyAKEAMgChLDIAoaEyAKHkMgCh/DIAoe8yAKGrMgChUzIA + oREyAKFBMgCh+zIAoZcyAKEAMgCh/zIAoZcyAKEAMgChBzIAoVAyAKEEMgChQTIAodoyAKEjMgChAAAA + AAAAAAAAMgChADIAoWkyAKH/MgCh/zIAoeEyAKEeMgChAAAAAAAyAKEAMgChBjIAoSAyAKFyMgChwjIA + ofMyAKH4MgCh0zIAobMyAKH9MgChljIAoQAyAKH/MgChlzIAoQAyAKEBMgChBDIAoQAyAKFKMgCh7jIA + oT0yAKEAAAAAADIAoQAyAKEAMgChbDIAof8yAKH/MgCh4TIAoR8yAKEAAAAAAAAAAAAAAAAAMgChADIA + oQEyAKELMgChRzIAoZYyAKHeMgCh/TIAof8yAKGWMgChADIAof8yAKGXMgChAAAAAAAAAAAAMgChADIA + oW0yAKH/MgChZDIAoQAyAKEEMgChHDIAoWAyAKHPMgCh/zIAof8yAKH3MgChkTIAoS8yAKELMgChADIA + oQAAAAAAAAAAAAAAAAAyAKEAMgChATIAoSAyAKF2MgCh/zIAoZYyAKEAMgCh/zIAoZcyAKEAAAAAADIA + oQAyAKEAMgChljIAof8yAKGeMgChOTIAoZEyAKHcMgCh+TIAof8yAKH/MgCh/zIAof8yAKH+MgCh6jIA + obgyAKFXMgChITIAoQEyAKEAAAAAAAAAAAAAAAAAMgChADIAoT8yAKH7MgChlzIAoQAyAKH/MgChlzIA + oQAAAAAAMgChADIAoQwyAKG9MgCh/zIAofMyAKHyMgCh/jIAof8yAKH/MgCh/zIAofoyAKH3MgCh/jIA + of8yAKH/MgCh/zIAofsyAKHbMgChmzIAoUwyAKENMgChATIAoQAyAKEAMgChPzIAofsyAKGXMgChADIA + of8yAKGXMgChATIAoRkyAKFbMgChsTIAofAyAKH/MgCh/zIAof8yAKH/MgCh/DIAoeYyAKGxMgChVTIA + oUIyAKGFMgCh1TIAofUyAKH/MgCh/zIAof8yAKH/MgCh9DIAocUyAKGDMgChMDIAoQYyAKE/MgCh+zIA + oZcyAKEAMgCh/zIAocEyAKGOMgCh2TIAofcyAKH/MgCh/zIAof8yAKH/MgCh7jIAobMyAKFwMgChJjIA + oQoyAKEAMgChADIAoQEyAKEXMgChTTIAoZsyAKHYMgCh/TIAof8yAKH/MgCh/zIAof4yAKHqMgChszIA + oZgyAKH+MgChljIAoQAyAKH/MgCh/zIAof8yAKH/MgCh/zIAof8yAKH0MgChyTIAoYEyAKE/MgChBzIA + oQAAAAAAMgChADIAoSIyAKF2MgChQjIAoRIyAKEAMgChATIAoR4yAKFjMgChrjIAoecyAKH9MgCh/zIA + of8yAKH/MgCh/zIAof8yAKGWMgChADIAof8yAKH/MgCh/zIAofkyAKHWMgChmjIAoUIyAKERMgChATIA + oQAyAKEGMgChFTIAoQMyAKEAMgChKDIAoZUyAKHHMgChxjIAoXcyAKE3MgChBzIAoQAyAKEGMgChKTIA + oXYyAKHDMgCh7jIAof4yAKH/MgCh/zIAoZYyAKEAMgChrjIAoeYyAKH+MgCh0zIAoVcyAKELMgChADIA + oQAyAKEAMgChADIAoVUyAKHAMgChkjIAoVYyAKEUMgChATIAoRYyAKFhMgChqzIAodUyAKGmMgChZTIA + oR8yAKEDMgChBDIAoS0yAKGiMgCh9DIAofUyAKHGMgChWTIAoQAyAKEGMgChKjIAoWsyAKHBMgCh3DIA + ocEyAKFwMgChJTIAoQYyAKEAMgChDDIAoTgyAKF/MgChyjIAocMyAKGUMgChMzIAoQsyAKEEMgChJjIA + oWUyAKG/MgCh0TIAoaYyAKGoMgCh1TIAodYyAKGNMgChQTIAoRAyAKEAMgChAAAAAAAyAKEAMgChADIA + oQ8yAKE8MgChkDIAoc8yAKHfMgChpDIAoVIyAKEcMgChADIAoQEyAKETMgChRzIAoZ8yAKHGMgChvzIA + oWQyAKEtMgChMzIAoY8yAKHvMgCh5zIAoa8yAKFcMgChHDIAoQMyAKEAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAADIAoQAyAKECMgChFTIAoVcyAKGaMgCh3DIAodEyAKGaMgChSDIAoQsyAKEAMgChATIA + oSUyAKGGMgCh6TIAofEyAKHhMgChtzIAoXAyAKErMgChBTIAoQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMgChADIAoQIyAKElMgChXTIAobgyAKHbMgChxTIA + oYUyAKFbMgChqzIAodEyAKHLMgChhDIAoTsyAKELMgChAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAyAKEAMgChCzIA + oTcyAKGTMgCh0zIAofAyAKG2MgChWjIAoRcyAKEBMgChAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAA/+Af//+AB//8AAD/8AAAP8AIAA8AGDABARg+AQEYD4ERGAPxMZgAcTOY + ADEzmDAxM5g8MTKIPzEgCDDxIAgwMSB4MAEgeDgBJHg+ATxAD8E8AAHxOAAAMQAAAAEAAwABABwgAQBE + BAEBwAABAEAAA+AAAA/4AAB//wAD///gD/8= + + + \ No newline at end of file diff --git a/MesMonitor/MonitorForm/SecondFormDelegate.cs b/MesMonitor/MonitorForm/SecondFormDelegate.cs new file mode 100644 index 0000000..434652c --- /dev/null +++ b/MesMonitor/MonitorForm/SecondFormDelegate.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace MisDataName +{ + public delegate void SecondAct(string ControlName); + + public partial class SecondForm + { + public static SecondAct MainMenuRefresh; + + } +} diff --git a/MesMonitor/SignalChangeMonitorControl/MesBoolSignal.Designer.cs b/MesMonitor/SignalChangeMonitorControl/MesBoolSignal.Designer.cs new file mode 100644 index 0000000..2989846 --- /dev/null +++ b/MesMonitor/SignalChangeMonitorControl/MesBoolSignal.Designer.cs @@ -0,0 +1,79 @@ +namespace MesControl +{ + partial class MesBoolSignal + { + /// + /// 必需的设计器变量。 + /// + private System.ComponentModel.IContainer components = null; + + /// + /// 清理所有正在使用的资源。 + /// + /// 如果应释放托管资源,为 true;否则为 false。 + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region 组件设计器生成的代码 + + /// + /// 设计器支持所需的方法 - 不要修改 + /// 使用代码编辑器修改此方法的内容。 + /// + private void InitializeComponent() + { + this.pictureBox_Signal = new System.Windows.Forms.PictureBox(); + this.label_SignalName = new System.Windows.Forms.Label(); + ((System.ComponentModel.ISupportInitialize)(this.pictureBox_Signal)).BeginInit(); + this.SuspendLayout(); + // + // pictureBox_Signal + // + this.pictureBox_Signal.BackgroundImage = global::MesControl.Properties.Resources.none; + this.pictureBox_Signal.Location = new System.Drawing.Point(3, 1); + this.pictureBox_Signal.Name = "pictureBox_Signal"; + this.pictureBox_Signal.Size = new System.Drawing.Size(20, 20); + this.pictureBox_Signal.TabIndex = 0; + this.pictureBox_Signal.TabStop = false; + // + // label_SignalName + // + this.label_SignalName.AutoSize = true; + this.label_SignalName.Font = new System.Drawing.Font("宋体", 12F); + this.label_SignalName.Location = new System.Drawing.Point(32, 3); + this.label_SignalName.MaximumSize = new System.Drawing.Size(72, 16); + this.label_SignalName.MinimumSize = new System.Drawing.Size(72, 16); + this.label_SignalName.Name = "label_SignalName"; + this.label_SignalName.Size = new System.Drawing.Size(72, 16); + this.label_SignalName.TabIndex = 1; + this.label_SignalName.Text = "心跳信号"; + // + // MesBoolSignal + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.BackColor = System.Drawing.Color.Transparent; + this.Controls.Add(this.label_SignalName); + this.Controls.Add(this.pictureBox_Signal); + this.MaximumSize = new System.Drawing.Size(110, 22); + this.MinimumSize = new System.Drawing.Size(110, 22); + this.Name = "MesBoolSignal"; + this.Size = new System.Drawing.Size(110, 22); + ((System.ComponentModel.ISupportInitialize)(this.pictureBox_Signal)).EndInit(); + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private System.Windows.Forms.PictureBox pictureBox_Signal; + private System.Windows.Forms.Label label_SignalName; + } +} diff --git a/MesMonitor/SignalChangeMonitorControl/MesBoolSignal.cs b/MesMonitor/SignalChangeMonitorControl/MesBoolSignal.cs new file mode 100644 index 0000000..c3e1d98 --- /dev/null +++ b/MesMonitor/SignalChangeMonitorControl/MesBoolSignal.cs @@ -0,0 +1,111 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Drawing; +using System.Data; +using System.Linq; +using System.Text; +using System.Windows.Forms; + +namespace MesControl +{ + public partial class MesBoolSignal : UserControl + { + public MesBoolSignal() + { + InitializeComponent(); + } + + /// + /// 外部调用控件触发的信号 + /// + /// + public void InputBoolSignal(bool Signal) + { + + if (Signal) + { + + pictureBox_Signal.BackgroundImage = Properties.Resources.green; + } + else + { + pictureBox_Signal.BackgroundImage = Properties.Resources.init; + } + + } + + [Browsable(true)] + [Description("控件中显示的文本内容"), Category("SignalText"), DefaultValue("")] + public string SignalText + { + get + { + return label_SignalName.Text; + } + + set + { + label_SignalName.Text = value; + } + + } + + SignalImage_Enum enum1; + + [Browsable(true)] + [Description("控件用于显示状态的图片"), Category("SignalImage"), DefaultValue("none")] + public SignalImage_Enum SignalImage + { + get + { + return enum1; + } + set + { + SetSignalImage(value); + enum1 = value; + + + + } + + + } + + + + public enum SignalImage_Enum + { + + none, init, green, yellow, red + + } + + void SetSignalImage(SignalImage_Enum Image) + { + switch (Image) + { + case SignalImage_Enum.none: + pictureBox_Signal.BackgroundImage = Properties.Resources.none; + break; + case SignalImage_Enum.init: + pictureBox_Signal.BackgroundImage = Properties.Resources.init; + break; + case SignalImage_Enum.green: + pictureBox_Signal.BackgroundImage = Properties.Resources.green; + break; + case SignalImage_Enum.yellow: + pictureBox_Signal.BackgroundImage = Properties.Resources.yellow; + break; + case SignalImage_Enum.red: + pictureBox_Signal.BackgroundImage = Properties.Resources.red; + break; + + } + + } + + + } +} diff --git a/MesMonitor/SignalChangeMonitorControl/MesBoolSignal.resx b/MesMonitor/SignalChangeMonitorControl/MesBoolSignal.resx new file mode 100644 index 0000000..1810bb4 --- /dev/null +++ b/MesMonitor/SignalChangeMonitorControl/MesBoolSignal.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 + + + True + + + True + + \ No newline at end of file diff --git a/MesMonitor/SignalChangeMonitorControl/MesControl.csproj b/MesMonitor/SignalChangeMonitorControl/MesControl.csproj new file mode 100644 index 0000000..624392c --- /dev/null +++ b/MesMonitor/SignalChangeMonitorControl/MesControl.csproj @@ -0,0 +1,139 @@ + + + + + Debug + AnyCPU + {FAB322CC-531D-4AEA-986A-B921B64D8D3F} + Library + Properties + MesControl + MesControl + v4.6.1 + 512 + + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + false + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + false + + + + + + + + + + + + + + + UserControl + + + MesBoolSignal.cs + + + UserControl + + + PlcWorkStationSignal.cs + + + UserControl + + + PlcConnect.cs + + + + True + True + Resources.resx + + + UserControl + + + + + + MesBoolSignal.cs + + + PlcWorkStationSignal.cs + + + ResXFileCodeGenerator + Designer + Resources.Designer.cs + + + PlcConnect.cs + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/MesMonitor/SignalChangeMonitorControl/MesControl.sln b/MesMonitor/SignalChangeMonitorControl/MesControl.sln new file mode 100644 index 0000000..542454f --- /dev/null +++ b/MesMonitor/SignalChangeMonitorControl/MesControl.sln @@ -0,0 +1,55 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.32901.82 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MesControl", "MesControl.csproj", "{FAB322CC-531D-4AEA-986A-B921B64D8D3F}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "00-0Json8.3.1", "..\..\Common\00-1Json8.3\Json8.3\00-0Json8.3.1.csproj", "{1A10FDB2-1A6A-44A8-AB4D-33387563247E}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "00MesWorkMqtt", "..\..\Common\00MesWorkMqtt\MesWorkMqtt\00MesWorkMqtt.csproj", "{F55DA1A0-A982-4479-8C47-0D9A5AAF3E18}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "01_01DoWhatPlc", "..\..\Common\01DoWhatPlc\01_01DoWhatPlc.csproj", "{0D1AF432-439A-4920-8692-43AE139F5530}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "02_02WebApiCallPLC", "..\..\Common\02WebApiCall\02_02WebApiCallPLC.csproj", "{3E6D1DD5-01C9-435F-9941-61F906CE35BB}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MonitorForm", "..\MonitorForm\MonitorForm.csproj", "{488BADD9-579F-4BF3-91DC-9FA95E3181A5}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {FAB322CC-531D-4AEA-986A-B921B64D8D3F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {FAB322CC-531D-4AEA-986A-B921B64D8D3F}.Debug|Any CPU.Build.0 = Debug|Any CPU + {FAB322CC-531D-4AEA-986A-B921B64D8D3F}.Release|Any CPU.ActiveCfg = Release|Any CPU + {FAB322CC-531D-4AEA-986A-B921B64D8D3F}.Release|Any CPU.Build.0 = Release|Any CPU + {1A10FDB2-1A6A-44A8-AB4D-33387563247E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {1A10FDB2-1A6A-44A8-AB4D-33387563247E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {1A10FDB2-1A6A-44A8-AB4D-33387563247E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {1A10FDB2-1A6A-44A8-AB4D-33387563247E}.Release|Any CPU.Build.0 = Release|Any CPU + {F55DA1A0-A982-4479-8C47-0D9A5AAF3E18}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F55DA1A0-A982-4479-8C47-0D9A5AAF3E18}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F55DA1A0-A982-4479-8C47-0D9A5AAF3E18}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F55DA1A0-A982-4479-8C47-0D9A5AAF3E18}.Release|Any CPU.Build.0 = Release|Any CPU + {0D1AF432-439A-4920-8692-43AE139F5530}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {0D1AF432-439A-4920-8692-43AE139F5530}.Debug|Any CPU.Build.0 = Debug|Any CPU + {0D1AF432-439A-4920-8692-43AE139F5530}.Release|Any CPU.ActiveCfg = Release|Any CPU + {0D1AF432-439A-4920-8692-43AE139F5530}.Release|Any CPU.Build.0 = Release|Any CPU + {3E6D1DD5-01C9-435F-9941-61F906CE35BB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {3E6D1DD5-01C9-435F-9941-61F906CE35BB}.Debug|Any CPU.Build.0 = Debug|Any CPU + {3E6D1DD5-01C9-435F-9941-61F906CE35BB}.Release|Any CPU.ActiveCfg = Release|Any CPU + {3E6D1DD5-01C9-435F-9941-61F906CE35BB}.Release|Any CPU.Build.0 = Release|Any CPU + {488BADD9-579F-4BF3-91DC-9FA95E3181A5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {488BADD9-579F-4BF3-91DC-9FA95E3181A5}.Debug|Any CPU.Build.0 = Debug|Any CPU + {488BADD9-579F-4BF3-91DC-9FA95E3181A5}.Release|Any CPU.ActiveCfg = Release|Any CPU + {488BADD9-579F-4BF3-91DC-9FA95E3181A5}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {6372AD35-C9E4-4A9A-A52E-4F41531AC05B} + EndGlobalSection +EndGlobal diff --git a/MesMonitor/SignalChangeMonitorControl/PlcConnect.Designer.cs b/MesMonitor/SignalChangeMonitorControl/PlcConnect.Designer.cs new file mode 100644 index 0000000..5e44fd1 --- /dev/null +++ b/MesMonitor/SignalChangeMonitorControl/PlcConnect.Designer.cs @@ -0,0 +1,81 @@ +namespace MesControl +{ + partial class PlcConnect + { + /// + /// 必需的设计器变量。 + /// + private System.ComponentModel.IContainer components = null; + + /// + /// 清理所有正在使用的资源。 + /// + /// 如果应释放托管资源,为 true;否则为 false。 + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region 组件设计器生成的代码 + + /// + /// 设计器支持所需的方法 - 不要修改 + /// 使用代码编辑器修改此方法的内容。 + /// + private void InitializeComponent() + { + this.pictureBox_OpName = new System.Windows.Forms.PictureBox(); + this.label_OpName = new System.Windows.Forms.Label(); + ((System.ComponentModel.ISupportInitialize)(this.pictureBox_OpName)).BeginInit(); + this.SuspendLayout(); + // + // pictureBox_OpName + // + this.pictureBox_OpName.BackgroundImage = global::MesControl.Properties.Resources.BreakPLC; + this.pictureBox_OpName.Location = new System.Drawing.Point(3, 1); + this.pictureBox_OpName.MaximumSize = new System.Drawing.Size(20, 20); + this.pictureBox_OpName.MinimumSize = new System.Drawing.Size(20, 20); + this.pictureBox_OpName.Name = "pictureBox_OpName"; + this.pictureBox_OpName.Size = new System.Drawing.Size(20, 20); + this.pictureBox_OpName.TabIndex = 0; + this.pictureBox_OpName.TabStop = false; + // + // label_OpName + // + this.label_OpName.AutoSize = true; + this.label_OpName.Font = new System.Drawing.Font("宋体", 12F); + this.label_OpName.Location = new System.Drawing.Point(32, 3); + this.label_OpName.MaximumSize = new System.Drawing.Size(72, 16); + this.label_OpName.MinimumSize = new System.Drawing.Size(72, 16); + this.label_OpName.Name = "label_OpName"; + this.label_OpName.Size = new System.Drawing.Size(72, 16); + this.label_OpName.TabIndex = 1; + this.label_OpName.Text = "通讯状态"; + // + // PlcConnect + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.BackColor = System.Drawing.Color.Transparent; + this.Controls.Add(this.label_OpName); + this.Controls.Add(this.pictureBox_OpName); + this.MaximumSize = new System.Drawing.Size(110, 22); + this.MinimumSize = new System.Drawing.Size(110, 22); + this.Name = "PlcConnect"; + this.Size = new System.Drawing.Size(110, 22); + ((System.ComponentModel.ISupportInitialize)(this.pictureBox_OpName)).EndInit(); + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private System.Windows.Forms.PictureBox pictureBox_OpName; + private System.Windows.Forms.Label label_OpName; + } +} diff --git a/MesMonitor/SignalChangeMonitorControl/PlcConnect.cs b/MesMonitor/SignalChangeMonitorControl/PlcConnect.cs new file mode 100644 index 0000000..6bbf2e1 --- /dev/null +++ b/MesMonitor/SignalChangeMonitorControl/PlcConnect.cs @@ -0,0 +1,221 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Drawing; +using System.Data; +using System.Linq; +using System.Text; +using System.Windows.Forms; + +namespace MesControl +{ + public delegate void PlcStatusHandle(); + public partial class PlcConnect: UserControl + { + public PlcConnect() + { + InitializeComponent(); + + } + public static PlcStatusHandle PlcBreakChange,PlcConnectChange; + + + #region 内部变量 + int externalTimerTimes =0; + + int testPlcBreakInterval=10000; + + int testPlcBreakTime=0; + + int externalTimerInterval = 200; + + bool isBreakPLC = true; + + bool plcTestEnable; + + bool plcBreakIsChanged=false; + bool plcConnectIsChanged = false; + + #endregion + #region 内部方法 + + void TimerTimeChange() + { + if (externalTimerTimes == 999) + { + externalTimerTimes = 0; + } + else + { + externalTimerTimes++; + } + + if (testPlcBreakTime > 0) + { + testPlcBreakTime--; + plcBreakIsChanged = false; + + if (PlcConnectChange!=null&&!plcConnectIsChanged) + { + PlcConnectChange(); + plcConnectIsChanged = true; + } + } + else + { + if (plcTestEnable) + { + if(PlcBreakChange != null&& !plcBreakIsChanged) + { + PlcBreakChange(); + plcBreakIsChanged = true; + } + plcConnectIsChanged = false; + } + isBreakPLC = true; + } + + } + #endregion + + #region 外部方法 + public void ExternalTimer() + { + + if (!isBreakPLC) + { + switch (externalTimerTimes % 5) + { + case 0: + pictureBox_OpName.BackgroundImage = Properties.Resources.PlcConnect0; + break; + case 1: + pictureBox_OpName.BackgroundImage = Properties.Resources.PlcConnect1; + break; + case 2: + pictureBox_OpName.BackgroundImage = Properties.Resources.PlcConnect2; + break; + case 3: + pictureBox_OpName.BackgroundImage = Properties.Resources.PlcConnect3; + break; + case 4: + pictureBox_OpName.BackgroundImage = Properties.Resources.PlcConnect4; + break; + + } + } + else + { + pictureBox_OpName.BackgroundImage = Properties.Resources.BreakPLC; + } + + + TimerTimeChange(); + } + + + + + public void ExternalPlcConnect() + { + testPlcBreakTime = (testPlcBreakInterval / externalTimerInterval) + 1; + isBreakPLC = false; + + } + + public void PlcBreak() + { + pictureBox_OpName.BackgroundImage = Properties.Resources.BreakPLC; + isBreakPLC = true; + } + + #endregion + + #region 属性 + + [Browsable(true)] + [Description("控件中显示的文本内容"), Category("外观"), DefaultValue("OP0000")] + public string LabelText + { + get + { + return label_OpName.Text; + } + + set + { + label_OpName.Text = value; + } + + } + + + [Browsable(true)] + [Description("外部定时器周期"), Category("行为"), DefaultValue("200")] + public int ExternalTimerInterval + { + get + { + return externalTimerInterval; + } + + set + { + externalTimerInterval = value; + } + + } + + [Browsable(true)] + [Description("检测PLC在线状态超时,超过此时间,PLC为离线状态"), Category("行为"), DefaultValue("200")] + public int TestPlcBreakInterval + { + get + { + return testPlcBreakInterval; + } + + set + { + testPlcBreakInterval = value; + } + + } + + [Browsable(true)] + [Description("指示PLC是否为断开状态"), Category("行为"), DefaultValue("True")] + public bool IsBreakPLC + { + get + { + return isBreakPLC; + } + + set + { + isBreakPLC = value; + } + + } + + [Browsable(true)] + [Description("是否启用检测PLC在线状态功能"), Category("行为"), DefaultValue("True")] + public bool PlcTestEnable + { + get + { + return plcTestEnable; + } + + set + { + plcTestEnable = value; + } + + } + + #endregion + + + } +} diff --git a/MesMonitor/SignalChangeMonitorControl/PlcConnect.resx b/MesMonitor/SignalChangeMonitorControl/PlcConnect.resx new file mode 100644 index 0000000..0abf881 --- /dev/null +++ b/MesMonitor/SignalChangeMonitorControl/PlcConnect.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/MesMonitor/SignalChangeMonitorControl/PlcWorkStationSignal.Designer.cs b/MesMonitor/SignalChangeMonitorControl/PlcWorkStationSignal.Designer.cs new file mode 100644 index 0000000..e4e1488 --- /dev/null +++ b/MesMonitor/SignalChangeMonitorControl/PlcWorkStationSignal.Designer.cs @@ -0,0 +1,80 @@ +namespace MesControl +{ + partial class PlcWorkStationSignal + { + /// + /// 必需的设计器变量。 + /// + private System.ComponentModel.IContainer components = null; + + /// + /// 清理所有正在使用的资源。 + /// + /// 如果应释放托管资源,为 true;否则为 false。 + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region 组件设计器生成的代码 + + /// + /// 设计器支持所需的方法 - 不要修改 + /// 使用代码编辑器修改此方法的内容。 + /// + private void InitializeComponent() + { + this.groupBox_WorkStationGrp = new System.Windows.Forms.GroupBox(); + this.plcConnect_WorkStation = new MesControl.PlcConnect(); + this.groupBox_WorkStationGrp.SuspendLayout(); + this.SuspendLayout(); + // + // groupBox_WorkStationGrp + // + this.groupBox_WorkStationGrp.BackColor = System.Drawing.Color.Transparent; + this.groupBox_WorkStationGrp.Controls.Add(this.plcConnect_WorkStation); + this.groupBox_WorkStationGrp.Location = new System.Drawing.Point(4, 4); + this.groupBox_WorkStationGrp.Name = "groupBox_WorkStationGrp"; + this.groupBox_WorkStationGrp.Size = new System.Drawing.Size(125, 50); + this.groupBox_WorkStationGrp.TabIndex = 0; + this.groupBox_WorkStationGrp.TabStop = false; + this.groupBox_WorkStationGrp.Text = "OP0000"; + // + // plcConnect_WorkStation + // + this.plcConnect_WorkStation.BackColor = System.Drawing.Color.Transparent; + this.plcConnect_WorkStation.ExternalTimerInterval = 200; + this.plcConnect_WorkStation.IsBreakPLC = false; + this.plcConnect_WorkStation.LabelText = "通讯状态"; + this.plcConnect_WorkStation.Location = new System.Drawing.Point(7, 21); + this.plcConnect_WorkStation.MaximumSize = new System.Drawing.Size(110, 22); + this.plcConnect_WorkStation.MinimumSize = new System.Drawing.Size(110, 22); + this.plcConnect_WorkStation.Name = "plcConnect_WorkStation"; + this.plcConnect_WorkStation.PlcTestEnable = false; + this.plcConnect_WorkStation.Size = new System.Drawing.Size(110, 22); + this.plcConnect_WorkStation.TabIndex = 0; + this.plcConnect_WorkStation.TestPlcBreakInterval = 0; + // + // PlcWorkStationSignal + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.BackColor = System.Drawing.Color.Transparent; + this.Controls.Add(this.groupBox_WorkStationGrp); + this.Name = "PlcWorkStationSignal"; + this.Size = new System.Drawing.Size(136, 60); + this.groupBox_WorkStationGrp.ResumeLayout(false); + this.ResumeLayout(false); + + } + + #endregion + + private System.Windows.Forms.GroupBox groupBox_WorkStationGrp; + private PlcConnect plcConnect_WorkStation; + } +} diff --git a/MesMonitor/SignalChangeMonitorControl/PlcWorkStationSignal.cs b/MesMonitor/SignalChangeMonitorControl/PlcWorkStationSignal.cs new file mode 100644 index 0000000..da90c09 --- /dev/null +++ b/MesMonitor/SignalChangeMonitorControl/PlcWorkStationSignal.cs @@ -0,0 +1,228 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Drawing; +using System.Data; +using System.Linq; +using System.Text; +using System.Windows.Forms; + +namespace MesControl +{ + public delegate void WorkStationPlcBreakChanged(); + public partial class PlcWorkStationSignal : UserControl + { + public PlcWorkStationSignal() + { + InitializeComponent(); + PlcConnect.PlcBreakChange = new PlcStatusHandle(internalPlcBreak); + PlcConnect.PlcConnectChange = new PlcStatusHandle(internalPlcConnect); + this.SetStyle(ControlStyles.UserPaint, true); + this.SetStyle(ControlStyles.AllPaintingInWmPaint, true); + this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true); + + } + + public EventHandler WorkStationPlcStatusChange; + + #region 工位信号方法与属性 + + public void InitSignalControl() + { + + + for (int i = 0; i < SignalItems.Count; i++) + { + + MesBoolSignal mesBoolSignalNew = new MesBoolSignal(); + this.groupBox_WorkStationGrp.Controls.Add(mesBoolSignalNew);//扩展GroupBox + mesBoolSignalNew.BackColor = System.Drawing.Color.Transparent; + mesBoolSignalNew.Location = new System.Drawing.Point(7, 46 + (25 * i)); + mesBoolSignalNew.Name = SignalItems[i].Name; + mesBoolSignalNew.SignalImage = MesBoolSignal.SignalImage_Enum.none; + mesBoolSignalNew.SignalText = SignalItems[i].SignalText; + mesBoolSignalNew.Size = new System.Drawing.Size(110, 22); + mesBoolSignalNew.TabIndex = i; + + } + + //groupbox大小 + groupBox_WorkStationGrp.Size = new Size(125, 50 + (SignalItems.Count * 25)); + //控件大小 + this.Size = new Size(136, 60 + (SignalItems.Count * 25)); + + } + + private List signalItems = new List(); + [Browsable(true)] + [Description("MES信号控件集合"), Category("数据")] + [TypeConverter(typeof(System.ComponentModel.CollectionConverter))] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] + public List SignalItems + { + get + { + return signalItems; + } + + set + { + signalItems = value; + InitSignalControl(); + } + } + + /// + ///更改工位各个信号状态(默认) + /// + /// + /// + public void SignalChange(string SignalName, bool Value) + { + MesBoolSignal thisControl = (MesBoolSignal)Controls.Find(SignalName, true)[0]; + if (thisControl != null) + thisControl.SignalImage = Value ? MesBoolSignal.SignalImage_Enum.green : MesBoolSignal.SignalImage_Enum.init; + + } + + #endregion + + #region PLC在线状态属性与方法 + + ///////////////////////////////////////////////方法/////////////////////////////////////////////////// + + public void PlcConnectStatusChange(bool value) + { + plcConnect_WorkStation.ExternalPlcConnect(); + + } + public void ExternalTimerExcute() + { + plcConnect_WorkStation.ExternalTimer(); + } + + public void PlcBreak() + { + plcConnect_WorkStation.PlcBreak(); + } + + void internalPlcBreak() + { + if (WorkStationPlcStatusChange != null) + { + WorkStationPlcStatusChange(groupBox_WorkStationGrp.Text+"&Breaked",null); + } + + } + + void internalPlcConnect() + { + if (WorkStationPlcStatusChange != null) + { + WorkStationPlcStatusChange(groupBox_WorkStationGrp.Text + "&Connected", null); + } + } + + + //////////////////////////////////////////////////////////////属性/////////////////////////////////////////////// + + [Browsable(true)] + [Description("检测PLC在线状态开关"), Category("行为"), DefaultValue(true)] + public bool TestPLC_Enable + { + get + { + return plcConnect_WorkStation.PlcTestEnable; + } + set + { + plcConnect_WorkStation.PlcTestEnable = value; + } + } + + [Browsable(true)] + [Description("PLC心跳超时(超过此时间认为PLC离线)"), Category("行为"), DefaultValue(10000)] + public int TestPLC_Interval + { + get + { + return plcConnect_WorkStation.TestPlcBreakInterval; + } + set + { + + plcConnect_WorkStation.TestPlcBreakInterval = value; + + } + } + + + [Browsable(true)] + [Description("外部定时器循环时间"), Category("行为"), DefaultValue(200)] + public int ExternalTimerInterval + { + get + { + return plcConnect_WorkStation.ExternalTimerInterval; + } + set + { + plcConnect_WorkStation.ExternalTimerInterval = value; + } + } + + [Browsable(true)] + [Description("PLC在线状态"), Category("行为"), DefaultValue(false)] + public bool PLC_ConnectStatus + { + get + { + return plcConnect_WorkStation.IsBreakPLC; + } + set + { + plcConnect_WorkStation.IsBreakPLC = value; + } + } + + #endregion + + #region 当前控件方法与属性 + + [Browsable(true)] + [Description("控件显示的工位号"), Category("外观"), DefaultValue("OP0000")] + public string WorkStationNameText + { + get + { + return groupBox_WorkStationGrp.Text; + } + set + { + groupBox_WorkStationGrp.Text = value; + + } + + } + + [Browsable(true)] + [Description("控件中plc通讯显示的文本内容"), Category("外观"), DefaultValue("PLC连接")] + public string WS_PlcLabelText + { + get + { + return plcConnect_WorkStation.LabelText ; + } + + set + { + plcConnect_WorkStation.LabelText = value; + } + + } + + + #endregion + + } +} diff --git a/MesMonitor/SignalChangeMonitorControl/PlcWorkStationSignal.resx b/MesMonitor/SignalChangeMonitorControl/PlcWorkStationSignal.resx new file mode 100644 index 0000000..48f62a6 --- /dev/null +++ b/MesMonitor/SignalChangeMonitorControl/PlcWorkStationSignal.resx @@ -0,0 +1,123 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + \ No newline at end of file diff --git a/MesMonitor/SignalChangeMonitorControl/Properties/AssemblyInfo.cs b/MesMonitor/SignalChangeMonitorControl/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..68d5529 --- /dev/null +++ b/MesMonitor/SignalChangeMonitorControl/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// 有关程序集的一般信息由以下 +// 控制。更改这些特性值可修改 +// 与程序集关联的信息。 +[assembly: AssemblyTitle("MesControl")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("MesControl")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +//将 ComVisible 设置为 false 将使此程序集中的类型 +//对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型, +//请将此类型的 ComVisible 特性设置为 true。 +[assembly: ComVisible(false)] + +// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID +[assembly: Guid("fab322cc-531d-4aea-986a-b921b64d8d3f")] + +// 程序集的版本信息由下列四个值组成: +// +// 主版本 +// 次版本 +// 生成号 +// 修订号 +// +//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, +// 方法是按如下所示使用“*”: : +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/MesMonitor/SignalChangeMonitorControl/Properties/Resources.Designer.cs b/MesMonitor/SignalChangeMonitorControl/Properties/Resources.Designer.cs new file mode 100644 index 0000000..543a51e --- /dev/null +++ b/MesMonitor/SignalChangeMonitorControl/Properties/Resources.Designer.cs @@ -0,0 +1,193 @@ +//------------------------------------------------------------------------------ +// +// 此代码由工具生成。 +// 运行时版本:4.0.30319.42000 +// +// 对此文件的更改可能会导致不正确的行为,并且如果 +// 重新生成代码,这些更改将会丢失。 +// +//------------------------------------------------------------------------------ + +namespace MesControl.Properties { + using System; + + + /// + /// 一个强类型的资源类,用于查找本地化的字符串等。 + /// + // 此类是由 StronglyTypedResourceBuilder + // 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。 + // 若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen + // (以 /str 作为命令选项),或重新生成 VS 项目。 + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.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 (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("MesControl.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// 重写当前线程的 CurrentUICulture 属性 + /// 重写当前线程的 CurrentUICulture 属性。 + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + + /// + /// 查找 System.Drawing.Bitmap 类型的本地化资源。 + /// + internal static System.Drawing.Bitmap BreakPLC { + get { + object obj = ResourceManager.GetObject("BreakPLC", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// 查找 System.Drawing.Bitmap 类型的本地化资源。 + /// + internal static System.Drawing.Bitmap green { + get { + object obj = ResourceManager.GetObject("green", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// 查找 System.Drawing.Bitmap 类型的本地化资源。 + /// + internal static System.Drawing.Bitmap init { + get { + object obj = ResourceManager.GetObject("init", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// 查找 System.Drawing.Bitmap 类型的本地化资源。 + /// + internal static System.Drawing.Bitmap none { + get { + object obj = ResourceManager.GetObject("none", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// 查找 System.Drawing.Bitmap 类型的本地化资源。 + /// + internal static System.Drawing.Bitmap PlcConnect0 { + get { + object obj = ResourceManager.GetObject("PlcConnect0", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// 查找 System.Drawing.Bitmap 类型的本地化资源。 + /// + internal static System.Drawing.Bitmap PlcConnect1 { + get { + object obj = ResourceManager.GetObject("PlcConnect1", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// 查找 System.Drawing.Bitmap 类型的本地化资源。 + /// + internal static System.Drawing.Bitmap PlcConnect2 { + get { + object obj = ResourceManager.GetObject("PlcConnect2", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// 查找 System.Drawing.Bitmap 类型的本地化资源。 + /// + internal static System.Drawing.Bitmap PlcConnect3 { + get { + object obj = ResourceManager.GetObject("PlcConnect3", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// 查找 System.Drawing.Bitmap 类型的本地化资源。 + /// + internal static System.Drawing.Bitmap PlcConnect4 { + get { + object obj = ResourceManager.GetObject("PlcConnect4", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// 查找 System.Drawing.Bitmap 类型的本地化资源。 + /// + internal static System.Drawing.Bitmap PlcConnectBig { + get { + object obj = ResourceManager.GetObject("PlcConnectBig", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// 查找 System.Drawing.Bitmap 类型的本地化资源。 + /// + internal static System.Drawing.Bitmap PlcConnectSmall { + get { + object obj = ResourceManager.GetObject("PlcConnectSmall", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// 查找 System.Drawing.Bitmap 类型的本地化资源。 + /// + internal static System.Drawing.Bitmap red { + get { + object obj = ResourceManager.GetObject("red", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// 查找 System.Drawing.Bitmap 类型的本地化资源。 + /// + internal static System.Drawing.Bitmap yellow { + get { + object obj = ResourceManager.GetObject("yellow", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + } +} diff --git a/MesMonitor/SignalChangeMonitorControl/Properties/Resources.resx b/MesMonitor/SignalChangeMonitorControl/Properties/Resources.resx new file mode 100644 index 0000000..e9eebfc --- /dev/null +++ b/MesMonitor/SignalChangeMonitorControl/Properties/Resources.resx @@ -0,0 +1,160 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + + ..\Resources\red.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\yellow.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\PlcConnect1.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\PlcConnect0.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\PlcConnect3.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\none.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\PlcConnectSmall.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\PlcConnect2.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\init.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\PlcConnectBig.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\BreakPLC.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\green.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + ..\Resources\PlcConnect4.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + \ No newline at end of file diff --git a/MesMonitor/SignalChangeMonitorControl/Properties/_system~.ini b/MesMonitor/SignalChangeMonitorControl/Properties/_system~.ini new file mode 100644 index 0000000..e69de29 diff --git a/MesMonitor/SignalChangeMonitorControl/Resources/BreakPLC.png b/MesMonitor/SignalChangeMonitorControl/Resources/BreakPLC.png new file mode 100644 index 0000000..4873366 Binary files /dev/null and b/MesMonitor/SignalChangeMonitorControl/Resources/BreakPLC.png differ diff --git a/MesMonitor/SignalChangeMonitorControl/Resources/PlcConnect0.png b/MesMonitor/SignalChangeMonitorControl/Resources/PlcConnect0.png new file mode 100644 index 0000000..73e71bd Binary files /dev/null and b/MesMonitor/SignalChangeMonitorControl/Resources/PlcConnect0.png differ diff --git a/MesMonitor/SignalChangeMonitorControl/Resources/PlcConnect1.png b/MesMonitor/SignalChangeMonitorControl/Resources/PlcConnect1.png new file mode 100644 index 0000000..8c0a417 Binary files /dev/null and b/MesMonitor/SignalChangeMonitorControl/Resources/PlcConnect1.png differ diff --git a/MesMonitor/SignalChangeMonitorControl/Resources/PlcConnect2.png b/MesMonitor/SignalChangeMonitorControl/Resources/PlcConnect2.png new file mode 100644 index 0000000..671a278 Binary files /dev/null and b/MesMonitor/SignalChangeMonitorControl/Resources/PlcConnect2.png differ diff --git a/MesMonitor/SignalChangeMonitorControl/Resources/PlcConnect3.png b/MesMonitor/SignalChangeMonitorControl/Resources/PlcConnect3.png new file mode 100644 index 0000000..165eaeb Binary files /dev/null and b/MesMonitor/SignalChangeMonitorControl/Resources/PlcConnect3.png differ diff --git a/MesMonitor/SignalChangeMonitorControl/Resources/PlcConnect4.png b/MesMonitor/SignalChangeMonitorControl/Resources/PlcConnect4.png new file mode 100644 index 0000000..9fc042d Binary files /dev/null and b/MesMonitor/SignalChangeMonitorControl/Resources/PlcConnect4.png differ diff --git a/MesMonitor/SignalChangeMonitorControl/Resources/PlcConnectBig.png b/MesMonitor/SignalChangeMonitorControl/Resources/PlcConnectBig.png new file mode 100644 index 0000000..f2a21c0 Binary files /dev/null and b/MesMonitor/SignalChangeMonitorControl/Resources/PlcConnectBig.png differ diff --git a/MesMonitor/SignalChangeMonitorControl/Resources/PlcConnectSmall.png b/MesMonitor/SignalChangeMonitorControl/Resources/PlcConnectSmall.png new file mode 100644 index 0000000..8f43514 Binary files /dev/null and b/MesMonitor/SignalChangeMonitorControl/Resources/PlcConnectSmall.png differ diff --git a/MesMonitor/SignalChangeMonitorControl/Resources/_system~.ini b/MesMonitor/SignalChangeMonitorControl/Resources/_system~.ini new file mode 100644 index 0000000..e69de29 diff --git a/MesMonitor/SignalChangeMonitorControl/Resources/green.png b/MesMonitor/SignalChangeMonitorControl/Resources/green.png new file mode 100644 index 0000000..c4b463e Binary files /dev/null and b/MesMonitor/SignalChangeMonitorControl/Resources/green.png differ diff --git a/MesMonitor/SignalChangeMonitorControl/Resources/init.png b/MesMonitor/SignalChangeMonitorControl/Resources/init.png new file mode 100644 index 0000000..c148366 Binary files /dev/null and b/MesMonitor/SignalChangeMonitorControl/Resources/init.png differ diff --git a/MesMonitor/SignalChangeMonitorControl/Resources/none.png b/MesMonitor/SignalChangeMonitorControl/Resources/none.png new file mode 100644 index 0000000..8ec6c8d Binary files /dev/null and b/MesMonitor/SignalChangeMonitorControl/Resources/none.png differ diff --git a/MesMonitor/SignalChangeMonitorControl/Resources/red.png b/MesMonitor/SignalChangeMonitorControl/Resources/red.png new file mode 100644 index 0000000..26a05cb Binary files /dev/null and b/MesMonitor/SignalChangeMonitorControl/Resources/red.png differ diff --git a/MesMonitor/SignalChangeMonitorControl/Resources/yellow.png b/MesMonitor/SignalChangeMonitorControl/Resources/yellow.png new file mode 100644 index 0000000..ee71881 Binary files /dev/null and b/MesMonitor/SignalChangeMonitorControl/Resources/yellow.png differ diff --git a/MesMonitor/SignalChangeMonitorControl/SignalInit.cs b/MesMonitor/SignalChangeMonitorControl/SignalInit.cs new file mode 100644 index 0000000..3b5b0a8 --- /dev/null +++ b/MesMonitor/SignalChangeMonitorControl/SignalInit.cs @@ -0,0 +1,37 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace MesControl +{ + public partial class PlcWorkStationSignal + { + void initsignal() + { + //private PlcConnect plcConnect_WorkStation; + //this.plcConnect_WorkStation = new MesControl.PlcConnect(); + //this.groupBox_WorkStationGrp.Controls.Add(this.plcConnect_WorkStation); + + //// + //// plcConnect_WorkStation + //// + //this.plcConnect_WorkStation.BackColor = System.Drawing.Color.Transparent; + //this.plcConnect_WorkStation.ExternalTimerInterval = 200; + //this.plcConnect_WorkStation.IsBreakPLC = false; + //this.plcConnect_WorkStation.LabelText = "通讯状态"; + //this.plcConnect_WorkStation.Location = new System.Drawing.Point(7, 21); + //this.plcConnect_WorkStation.MaximumSize = new System.Drawing.Size(110, 22); + //this.plcConnect_WorkStation.MinimumSize = new System.Drawing.Size(110, 22); + //this.plcConnect_WorkStation.Name = "plcConnect_WorkStation"; + //this.plcConnect_WorkStation.PlcTestEnable = false; + //this.plcConnect_WorkStation.Size = new System.Drawing.Size(110, 22); + //this.plcConnect_WorkStation.TabIndex = 0; + //this.plcConnect_WorkStation.TestPlcBreakInterval = 0; + + } + + + + } +} diff --git a/MesMonitor/SignalChangeMonitorControl/_system~.ini b/MesMonitor/SignalChangeMonitorControl/_system~.ini new file mode 100644 index 0000000..e69de29 diff --git a/MisDataFun/MesFun/App.config b/MisDataFun/MesFun/App.config new file mode 100644 index 0000000..ae1df8a --- /dev/null +++ b/MisDataFun/MesFun/App.config @@ -0,0 +1,29 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/MisDataFun/MesFun/MesFun.csproj b/MisDataFun/MesFun/MesFun.csproj new file mode 100644 index 0000000..cbdaad6 --- /dev/null +++ b/MisDataFun/MesFun/MesFun.csproj @@ -0,0 +1,99 @@ + + + + + Debug + AnyCPU + {7675A31A-4E0A-4A46-B5DC-D7B9747A8347} + WinExe + MesFun + MesFun + v4.6.1 + 512 + true + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + Form + + + MesFunction.cs + + + + + ResXFileCodeGenerator + Resources.Designer.cs + Designer + + + True + Resources.resx + + + SettingsSingleFileGenerator + Settings.Designer.cs + + + True + Settings.settings + True + + + + + + + + {f55da1a0-a982-4479-8c47-0d9a5aaf3e18} + 00MesWorkMqtt + + + {a0de975b-3afc-4f39-920e-29a874480a36} + 13.4MisDataFunDll + + + {55b510c1-59e9-4bfd-ae84-d76d46f6e365} + 13.3MIS_FuntionSaveData + + + {807fcc00-d1d5-45df-a60d-e295640eb6aa} + 13.2TagTypeCodeID + + + + \ No newline at end of file diff --git a/MisDataFun/MesFun/MesFunction.Designer.cs b/MisDataFun/MesFun/MesFunction.Designer.cs new file mode 100644 index 0000000..f12a529 --- /dev/null +++ b/MisDataFun/MesFun/MesFunction.Designer.cs @@ -0,0 +1,40 @@ +namespace MesFun +{ + partial class MesFunction + { + /// + /// 必需的设计器变量。 + /// + 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.components = new System.ComponentModel.Container(); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(800, 450); + this.Text = "Form1"; + } + + #endregion + } +} + diff --git a/MisDataFun/MesFun/MesFunction.cs b/MisDataFun/MesFun/MesFunction.cs new file mode 100644 index 0000000..44c1a4b --- /dev/null +++ b/MisDataFun/MesFun/MesFunction.cs @@ -0,0 +1,42 @@ +using MisDataSaveDate; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Configuration; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace MesFun +{ + public partial class MesFunction : Form + { + public MesFunction() + { + InitializeComponent(); + } + + + private void InitMqtt() + { + string url; + string topicMqttTargetTopicPLC; + string topicMqttTargetTopicTagTypeCodeID; + url = ConfigurationManager.AppSettings["MqttUrl"]; + //与web页面返回监控的主题一样的 + topicMqttTargetTopicPLC = ConfigurationManager.AppSettings["MqttTargetTopicPLC"]; + topicMqttTargetTopicTagTypeCodeID = ConfigurationManager.AppSettings["MqttTargetTopicTagTypeCodeID"]; + + //变量变化日志 + new InitMqtt2(url, topicMqttTargetTopicTagTypeCodeID); + MesWorkMqtt.Mqtt.StartAsync(); + //保存质量数据 + new MisDataSaveDate.Funtion().InitMqtt2(url, topicMqttTargetTopicPLC); + //处理MES业务的Function + new MisDataFunDll.MisDataFun().InitMqtt2(url, topicMqttTargetTopicPLC); + } + } +} diff --git a/MisDataFun/MesFun/Program.cs b/MisDataFun/MesFun/Program.cs new file mode 100644 index 0000000..6330aa6 --- /dev/null +++ b/MisDataFun/MesFun/Program.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace MesFun +{ + internal static class Program + { + /// + /// 应用程序的主入口点。 + /// + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + Application.Run(new MesFunction()); + } + } +} diff --git a/MisDataFun/MesFun/Properties/AssemblyInfo.cs b/MisDataFun/MesFun/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..bd25c48 --- /dev/null +++ b/MisDataFun/MesFun/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// 有关程序集的一般信息由以下 +// 控制。更改这些特性值可修改 +// 与程序集关联的信息。 +[assembly: AssemblyTitle("MesFun")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("MesFun")] +[assembly: AssemblyCopyright("Copyright © 2023")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// 将 ComVisible 设置为 false 会使此程序集中的类型 +//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型 +//请将此类型的 ComVisible 特性设置为 true。 +[assembly: ComVisible(false)] + +// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID +[assembly: Guid("7675a31a-4e0a-4a46-b5dc-d7b9747a8347")] + +// 程序集的版本信息由下列四个值组成: +// +// 主版本 +// 次版本 +// 生成号 +// 修订号 +// +//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值 +//通过使用 "*",如下所示: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/MisDataFun/MesFun/Properties/Resources.Designer.cs b/MisDataFun/MesFun/Properties/Resources.Designer.cs new file mode 100644 index 0000000..ca22eb9 --- /dev/null +++ b/MisDataFun/MesFun/Properties/Resources.Designer.cs @@ -0,0 +1,71 @@ +//------------------------------------------------------------------------------ +// +// 此代码由工具生成。 +// 运行时版本: 4.0.30319.42000 +// +// 对此文件的更改可能导致不正确的行为,如果 +// 重新生成代码,则所做更改将丢失。 +// +//------------------------------------------------------------------------------ + +namespace MesFun.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("MesFun.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/MisDataFun/MesFun/Properties/Resources.resx b/MisDataFun/MesFun/Properties/Resources.resx new file mode 100644 index 0000000..af7dbeb --- /dev/null +++ b/MisDataFun/MesFun/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/MisDataFun/MesFun/Properties/Settings.Designer.cs b/MisDataFun/MesFun/Properties/Settings.Designer.cs new file mode 100644 index 0000000..d103f39 --- /dev/null +++ b/MisDataFun/MesFun/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 MesFun.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/MisDataFun/MesFun/Properties/Settings.settings b/MisDataFun/MesFun/Properties/Settings.settings new file mode 100644 index 0000000..3964565 --- /dev/null +++ b/MisDataFun/MesFun/Properties/Settings.settings @@ -0,0 +1,7 @@ + + + + + + + diff --git a/MisDataFun/MesFunDll/MesFunDll.cs b/MisDataFun/MesFunDll/MesFunDll.cs new file mode 100644 index 0000000..44b203d --- /dev/null +++ b/MisDataFun/MesFunDll/MesFunDll.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MesFun +{ + public class Funtion + { + } +} diff --git a/MisDataFun/MesFunDll/MesFunDll.csproj b/MisDataFun/MesFunDll/MesFunDll.csproj new file mode 100644 index 0000000..d421896 --- /dev/null +++ b/MisDataFun/MesFunDll/MesFunDll.csproj @@ -0,0 +1,48 @@ + + + + + Debug + AnyCPU + {FA0F10D0-7898-49F2-BB4B-BE550F511F57} + Library + Properties + MesFunDll + MesFunDll + v4.6.1 + 512 + true + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/MisDataFun/MesFunDll/Properties/AssemblyInfo.cs b/MisDataFun/MesFunDll/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..3b80d31 --- /dev/null +++ b/MisDataFun/MesFunDll/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// 有关程序集的一般信息由以下 +// 控制。更改这些特性值可修改 +// 与程序集关联的信息。 +[assembly: AssemblyTitle("MesFunDll")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("MesFunDll")] +[assembly: AssemblyCopyright("Copyright © 2023")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// 将 ComVisible 设置为 false 会使此程序集中的类型 +//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型 +//请将此类型的 ComVisible 特性设置为 true。 +[assembly: ComVisible(false)] + +// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID +[assembly: Guid("fa0f10d0-7898-49f2-bb4b-be550f511f57")] + +// 程序集的版本信息由下列四个值组成: +// +// 主版本 +// 次版本 +// 生成号 +// 修订号 +// +//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值 +//通过使用 "*",如下所示: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/MisDataFun/MisDataFun.sln b/MisDataFun/MisDataFun.sln new file mode 100644 index 0000000..1822aae --- /dev/null +++ b/MisDataFun/MisDataFun.sln @@ -0,0 +1,244 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.4.33205.214 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MisDataFun", "MisDataFun\MisDataFun.csproj", "{DD9131C7-BF40-45B0-827A-C5E46FC8A89E}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "00-0Json8.3.1", "..\Common\00-1Json8.3\Json8.3\00-0Json8.3.1.csproj", "{1A10FDB2-1A6A-44A8-AB4D-33387563247E}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "00MesWorkMqtt", "..\Common\00MesWorkMqtt\MesWorkMqtt\00MesWorkMqtt.csproj", "{F55DA1A0-A982-4479-8C47-0D9A5AAF3E18}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "01_01DoWhatPlc", "..\Common\01DoWhatPlc\01_01DoWhatPlc.csproj", "{0D1AF432-439A-4920-8692-43AE139F5530}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "04-DataBaseAccess", "..\Common\04DataBaseAccess\DataBaseAccess\04-DataBaseAccess.csproj", "{F434E066-4C59-47C8-AA82-6F48CC84501A}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "07BusinessFacade", "..\Common\07WebBusinessFacade\BusinessFacade\07BusinessFacade.csproj", "{F0A0C525-03FD-428A-9B17-7F54AA0E4475}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "08-WebFun_base", "..\Common\08WebFun_base\WebFun_base\08-WebFun_base.csproj", "{D98BE764-ADEB-488D-9714-61E308AA8201}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "09-MesDataFunction", "..\Common\09MesDataFunction\MesDataFunction\09-MesDataFunction.csproj", "{90E76FB4-646D-45E2-95DB-0B8AB4E465D6}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "03Function", "03Function", "{4BF576F8-7AFE-41D3-A998-2AE62375DEC6}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "01Common", "01Common", "{7CAB05BF-8588-4D5C-B369-C2F773F1A16E}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "13.3MIS_FuntionSaveData", "..\MIS_FuntionSaveData\MIS_FuntionSaveData\13.3MIS_FuntionSaveData.csproj", "{55B510C1-59E9-4BFD-AE84-D76D46F6E365}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "13.4MisDataFunction", "..\MisDataFunDll\MisDataFunDll\13.4MisDataFunction.csproj", "{A0DE975B-3AFC-4F39-920E-29A874480A36}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "00-1AppConfigSetForm", "..\Common\00-2AppConfigSet\AppConfigSet\00-1AppConfigSetForm.csproj", "{5FD5DE57-CC26-4FD0-B852-5362123BC4FF}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "10MesControl", "..\Common\10SignalChangeMonitorControl\10MesControl.csproj", "{FAB322CC-531D-4AEA-986A-B921B64D8D3F}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "11MonitorForm", "..\Common\11MonitorForm\11MonitorForm.csproj", "{488BADD9-579F-4BF3-91DC-9FA95E3181A5}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "12SendMessageToWeb", "SendMessageToWebMqtt\12SendMessageToWeb.csproj", "{E4EB6420-906D-4672-947A-CA33DDCDADFC}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "00_MyLog4Net", "..\Common\MyLog4Net\00_MyLog4Net.csproj", "{1DC48C83-1842-4DE8-ACAF-26E1E7F7C58F}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "99-DataBaseAccess2", "..\Common\99DataBaseAccess2\DataBaseAccess\99-DataBaseAccess2.csproj", "{5C0C572B-F8F1-41DE-B049-4D40AE29CD21}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Function1051", "..\MisDataFunction\MesServer.Function\Function1051\Function1051.csproj", "{B5A0BAA3-C1A7-4AAB-9486-2E650ADACA7E}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Function1053", "..\MisDataFunction\MesServer.Function\Function1053\Function1053.csproj", "{CA8A12C5-7BF0-4489-93FA-180B1C492BBA}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Function1052", "..\MisDataFunction\MesServer.Function\Function1052\Function1052.csproj", "{5FEE5C91-8419-49FF-B2C2-47476F0B8C68}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "02_02WebApiCallPLC", "..\Common\02WebApiCall\02_02WebApiCallPLC.csproj", "{3E6D1DD5-01C9-435F-9941-61F906CE35BB}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Debug|x86 = Debug|x86 + Release|Any CPU = Release|Any CPU + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {DD9131C7-BF40-45B0-827A-C5E46FC8A89E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {DD9131C7-BF40-45B0-827A-C5E46FC8A89E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {DD9131C7-BF40-45B0-827A-C5E46FC8A89E}.Debug|x86.ActiveCfg = Debug|Any CPU + {DD9131C7-BF40-45B0-827A-C5E46FC8A89E}.Debug|x86.Build.0 = Debug|Any CPU + {DD9131C7-BF40-45B0-827A-C5E46FC8A89E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {DD9131C7-BF40-45B0-827A-C5E46FC8A89E}.Release|Any CPU.Build.0 = Release|Any CPU + {DD9131C7-BF40-45B0-827A-C5E46FC8A89E}.Release|x86.ActiveCfg = Release|Any CPU + {DD9131C7-BF40-45B0-827A-C5E46FC8A89E}.Release|x86.Build.0 = Release|Any CPU + {1A10FDB2-1A6A-44A8-AB4D-33387563247E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {1A10FDB2-1A6A-44A8-AB4D-33387563247E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {1A10FDB2-1A6A-44A8-AB4D-33387563247E}.Debug|x86.ActiveCfg = Debug|Any CPU + {1A10FDB2-1A6A-44A8-AB4D-33387563247E}.Debug|x86.Build.0 = Debug|Any CPU + {1A10FDB2-1A6A-44A8-AB4D-33387563247E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {1A10FDB2-1A6A-44A8-AB4D-33387563247E}.Release|Any CPU.Build.0 = Release|Any CPU + {1A10FDB2-1A6A-44A8-AB4D-33387563247E}.Release|x86.ActiveCfg = Release|Any CPU + {1A10FDB2-1A6A-44A8-AB4D-33387563247E}.Release|x86.Build.0 = Release|Any CPU + {F55DA1A0-A982-4479-8C47-0D9A5AAF3E18}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F55DA1A0-A982-4479-8C47-0D9A5AAF3E18}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F55DA1A0-A982-4479-8C47-0D9A5AAF3E18}.Debug|x86.ActiveCfg = Debug|Any CPU + {F55DA1A0-A982-4479-8C47-0D9A5AAF3E18}.Debug|x86.Build.0 = Debug|Any CPU + {F55DA1A0-A982-4479-8C47-0D9A5AAF3E18}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F55DA1A0-A982-4479-8C47-0D9A5AAF3E18}.Release|Any CPU.Build.0 = Release|Any CPU + {F55DA1A0-A982-4479-8C47-0D9A5AAF3E18}.Release|x86.ActiveCfg = Release|Any CPU + {F55DA1A0-A982-4479-8C47-0D9A5AAF3E18}.Release|x86.Build.0 = Release|Any CPU + {0D1AF432-439A-4920-8692-43AE139F5530}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {0D1AF432-439A-4920-8692-43AE139F5530}.Debug|Any CPU.Build.0 = Debug|Any CPU + {0D1AF432-439A-4920-8692-43AE139F5530}.Debug|x86.ActiveCfg = Debug|Any CPU + {0D1AF432-439A-4920-8692-43AE139F5530}.Debug|x86.Build.0 = Debug|Any CPU + {0D1AF432-439A-4920-8692-43AE139F5530}.Release|Any CPU.ActiveCfg = Release|Any CPU + {0D1AF432-439A-4920-8692-43AE139F5530}.Release|Any CPU.Build.0 = Release|Any CPU + {0D1AF432-439A-4920-8692-43AE139F5530}.Release|x86.ActiveCfg = Release|Any CPU + {0D1AF432-439A-4920-8692-43AE139F5530}.Release|x86.Build.0 = Release|Any CPU + {F434E066-4C59-47C8-AA82-6F48CC84501A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F434E066-4C59-47C8-AA82-6F48CC84501A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F434E066-4C59-47C8-AA82-6F48CC84501A}.Debug|x86.ActiveCfg = Debug|Any CPU + {F434E066-4C59-47C8-AA82-6F48CC84501A}.Debug|x86.Build.0 = Debug|Any CPU + {F434E066-4C59-47C8-AA82-6F48CC84501A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F434E066-4C59-47C8-AA82-6F48CC84501A}.Release|Any CPU.Build.0 = Release|Any CPU + {F434E066-4C59-47C8-AA82-6F48CC84501A}.Release|x86.ActiveCfg = Release|Any CPU + {F434E066-4C59-47C8-AA82-6F48CC84501A}.Release|x86.Build.0 = Release|Any CPU + {F0A0C525-03FD-428A-9B17-7F54AA0E4475}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F0A0C525-03FD-428A-9B17-7F54AA0E4475}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F0A0C525-03FD-428A-9B17-7F54AA0E4475}.Debug|x86.ActiveCfg = Debug|Any CPU + {F0A0C525-03FD-428A-9B17-7F54AA0E4475}.Debug|x86.Build.0 = Debug|Any CPU + {F0A0C525-03FD-428A-9B17-7F54AA0E4475}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F0A0C525-03FD-428A-9B17-7F54AA0E4475}.Release|Any CPU.Build.0 = Release|Any CPU + {F0A0C525-03FD-428A-9B17-7F54AA0E4475}.Release|x86.ActiveCfg = Release|Any CPU + {F0A0C525-03FD-428A-9B17-7F54AA0E4475}.Release|x86.Build.0 = Release|Any CPU + {D98BE764-ADEB-488D-9714-61E308AA8201}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {D98BE764-ADEB-488D-9714-61E308AA8201}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D98BE764-ADEB-488D-9714-61E308AA8201}.Debug|x86.ActiveCfg = Debug|Any CPU + {D98BE764-ADEB-488D-9714-61E308AA8201}.Debug|x86.Build.0 = Debug|Any CPU + {D98BE764-ADEB-488D-9714-61E308AA8201}.Release|Any CPU.ActiveCfg = Release|Any CPU + {D98BE764-ADEB-488D-9714-61E308AA8201}.Release|Any CPU.Build.0 = Release|Any CPU + {D98BE764-ADEB-488D-9714-61E308AA8201}.Release|x86.ActiveCfg = Release|Any CPU + {D98BE764-ADEB-488D-9714-61E308AA8201}.Release|x86.Build.0 = Release|Any CPU + {90E76FB4-646D-45E2-95DB-0B8AB4E465D6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {90E76FB4-646D-45E2-95DB-0B8AB4E465D6}.Debug|Any CPU.Build.0 = Debug|Any CPU + {90E76FB4-646D-45E2-95DB-0B8AB4E465D6}.Debug|x86.ActiveCfg = Debug|Any CPU + {90E76FB4-646D-45E2-95DB-0B8AB4E465D6}.Debug|x86.Build.0 = Debug|Any CPU + {90E76FB4-646D-45E2-95DB-0B8AB4E465D6}.Release|Any CPU.ActiveCfg = Release|Any CPU + {90E76FB4-646D-45E2-95DB-0B8AB4E465D6}.Release|Any CPU.Build.0 = Release|Any CPU + {90E76FB4-646D-45E2-95DB-0B8AB4E465D6}.Release|x86.ActiveCfg = Release|Any CPU + {90E76FB4-646D-45E2-95DB-0B8AB4E465D6}.Release|x86.Build.0 = Release|Any CPU + {55B510C1-59E9-4BFD-AE84-D76D46F6E365}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {55B510C1-59E9-4BFD-AE84-D76D46F6E365}.Debug|Any CPU.Build.0 = Debug|Any CPU + {55B510C1-59E9-4BFD-AE84-D76D46F6E365}.Debug|x86.ActiveCfg = Debug|Any CPU + {55B510C1-59E9-4BFD-AE84-D76D46F6E365}.Debug|x86.Build.0 = Debug|Any CPU + {55B510C1-59E9-4BFD-AE84-D76D46F6E365}.Release|Any CPU.ActiveCfg = Release|Any CPU + {55B510C1-59E9-4BFD-AE84-D76D46F6E365}.Release|Any CPU.Build.0 = Release|Any CPU + {55B510C1-59E9-4BFD-AE84-D76D46F6E365}.Release|x86.ActiveCfg = Release|Any CPU + {55B510C1-59E9-4BFD-AE84-D76D46F6E365}.Release|x86.Build.0 = Release|Any CPU + {A0DE975B-3AFC-4F39-920E-29A874480A36}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A0DE975B-3AFC-4F39-920E-29A874480A36}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A0DE975B-3AFC-4F39-920E-29A874480A36}.Debug|x86.ActiveCfg = Debug|Any CPU + {A0DE975B-3AFC-4F39-920E-29A874480A36}.Debug|x86.Build.0 = Debug|Any CPU + {A0DE975B-3AFC-4F39-920E-29A874480A36}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A0DE975B-3AFC-4F39-920E-29A874480A36}.Release|Any CPU.Build.0 = Release|Any CPU + {A0DE975B-3AFC-4F39-920E-29A874480A36}.Release|x86.ActiveCfg = Release|Any CPU + {A0DE975B-3AFC-4F39-920E-29A874480A36}.Release|x86.Build.0 = Release|Any CPU + {5FD5DE57-CC26-4FD0-B852-5362123BC4FF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {5FD5DE57-CC26-4FD0-B852-5362123BC4FF}.Debug|Any CPU.Build.0 = Debug|Any CPU + {5FD5DE57-CC26-4FD0-B852-5362123BC4FF}.Debug|x86.ActiveCfg = Debug|Any CPU + {5FD5DE57-CC26-4FD0-B852-5362123BC4FF}.Debug|x86.Build.0 = Debug|Any CPU + {5FD5DE57-CC26-4FD0-B852-5362123BC4FF}.Release|Any CPU.ActiveCfg = Release|Any CPU + {5FD5DE57-CC26-4FD0-B852-5362123BC4FF}.Release|Any CPU.Build.0 = Release|Any CPU + {5FD5DE57-CC26-4FD0-B852-5362123BC4FF}.Release|x86.ActiveCfg = Release|Any CPU + {5FD5DE57-CC26-4FD0-B852-5362123BC4FF}.Release|x86.Build.0 = Release|Any CPU + {FAB322CC-531D-4AEA-986A-B921B64D8D3F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {FAB322CC-531D-4AEA-986A-B921B64D8D3F}.Debug|Any CPU.Build.0 = Debug|Any CPU + {FAB322CC-531D-4AEA-986A-B921B64D8D3F}.Debug|x86.ActiveCfg = Debug|Any CPU + {FAB322CC-531D-4AEA-986A-B921B64D8D3F}.Debug|x86.Build.0 = Debug|Any CPU + {FAB322CC-531D-4AEA-986A-B921B64D8D3F}.Release|Any CPU.ActiveCfg = Release|Any CPU + {FAB322CC-531D-4AEA-986A-B921B64D8D3F}.Release|Any CPU.Build.0 = Release|Any CPU + {FAB322CC-531D-4AEA-986A-B921B64D8D3F}.Release|x86.ActiveCfg = Release|Any CPU + {FAB322CC-531D-4AEA-986A-B921B64D8D3F}.Release|x86.Build.0 = Release|Any CPU + {488BADD9-579F-4BF3-91DC-9FA95E3181A5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {488BADD9-579F-4BF3-91DC-9FA95E3181A5}.Debug|Any CPU.Build.0 = Debug|Any CPU + {488BADD9-579F-4BF3-91DC-9FA95E3181A5}.Debug|x86.ActiveCfg = Debug|Any CPU + {488BADD9-579F-4BF3-91DC-9FA95E3181A5}.Debug|x86.Build.0 = Debug|Any CPU + {488BADD9-579F-4BF3-91DC-9FA95E3181A5}.Release|Any CPU.ActiveCfg = Release|Any CPU + {488BADD9-579F-4BF3-91DC-9FA95E3181A5}.Release|Any CPU.Build.0 = Release|Any CPU + {488BADD9-579F-4BF3-91DC-9FA95E3181A5}.Release|x86.ActiveCfg = Release|Any CPU + {488BADD9-579F-4BF3-91DC-9FA95E3181A5}.Release|x86.Build.0 = Release|Any CPU + {E4EB6420-906D-4672-947A-CA33DDCDADFC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E4EB6420-906D-4672-947A-CA33DDCDADFC}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E4EB6420-906D-4672-947A-CA33DDCDADFC}.Debug|x86.ActiveCfg = Debug|Any CPU + {E4EB6420-906D-4672-947A-CA33DDCDADFC}.Debug|x86.Build.0 = Debug|Any CPU + {E4EB6420-906D-4672-947A-CA33DDCDADFC}.Release|Any CPU.ActiveCfg = Release|Any CPU + {E4EB6420-906D-4672-947A-CA33DDCDADFC}.Release|Any CPU.Build.0 = Release|Any CPU + {E4EB6420-906D-4672-947A-CA33DDCDADFC}.Release|x86.ActiveCfg = Release|Any CPU + {E4EB6420-906D-4672-947A-CA33DDCDADFC}.Release|x86.Build.0 = Release|Any CPU + {1DC48C83-1842-4DE8-ACAF-26E1E7F7C58F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {1DC48C83-1842-4DE8-ACAF-26E1E7F7C58F}.Debug|Any CPU.Build.0 = Debug|Any CPU + {1DC48C83-1842-4DE8-ACAF-26E1E7F7C58F}.Debug|x86.ActiveCfg = Debug|Any CPU + {1DC48C83-1842-4DE8-ACAF-26E1E7F7C58F}.Debug|x86.Build.0 = Debug|Any CPU + {1DC48C83-1842-4DE8-ACAF-26E1E7F7C58F}.Release|Any CPU.ActiveCfg = Release|Any CPU + {1DC48C83-1842-4DE8-ACAF-26E1E7F7C58F}.Release|Any CPU.Build.0 = Release|Any CPU + {1DC48C83-1842-4DE8-ACAF-26E1E7F7C58F}.Release|x86.ActiveCfg = Release|Any CPU + {1DC48C83-1842-4DE8-ACAF-26E1E7F7C58F}.Release|x86.Build.0 = Release|Any CPU + {5C0C572B-F8F1-41DE-B049-4D40AE29CD21}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {5C0C572B-F8F1-41DE-B049-4D40AE29CD21}.Debug|Any CPU.Build.0 = Debug|Any CPU + {5C0C572B-F8F1-41DE-B049-4D40AE29CD21}.Debug|x86.ActiveCfg = Debug|Any CPU + {5C0C572B-F8F1-41DE-B049-4D40AE29CD21}.Debug|x86.Build.0 = Debug|Any CPU + {5C0C572B-F8F1-41DE-B049-4D40AE29CD21}.Release|Any CPU.ActiveCfg = Release|Any CPU + {5C0C572B-F8F1-41DE-B049-4D40AE29CD21}.Release|Any CPU.Build.0 = Release|Any CPU + {5C0C572B-F8F1-41DE-B049-4D40AE29CD21}.Release|x86.ActiveCfg = Release|Any CPU + {5C0C572B-F8F1-41DE-B049-4D40AE29CD21}.Release|x86.Build.0 = Release|Any CPU + {B5A0BAA3-C1A7-4AAB-9486-2E650ADACA7E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B5A0BAA3-C1A7-4AAB-9486-2E650ADACA7E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B5A0BAA3-C1A7-4AAB-9486-2E650ADACA7E}.Debug|x86.ActiveCfg = Debug|Any CPU + {B5A0BAA3-C1A7-4AAB-9486-2E650ADACA7E}.Debug|x86.Build.0 = Debug|Any CPU + {B5A0BAA3-C1A7-4AAB-9486-2E650ADACA7E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B5A0BAA3-C1A7-4AAB-9486-2E650ADACA7E}.Release|Any CPU.Build.0 = Release|Any CPU + {B5A0BAA3-C1A7-4AAB-9486-2E650ADACA7E}.Release|x86.ActiveCfg = Release|Any CPU + {B5A0BAA3-C1A7-4AAB-9486-2E650ADACA7E}.Release|x86.Build.0 = Release|Any CPU + {CA8A12C5-7BF0-4489-93FA-180B1C492BBA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {CA8A12C5-7BF0-4489-93FA-180B1C492BBA}.Debug|Any CPU.Build.0 = Debug|Any CPU + {CA8A12C5-7BF0-4489-93FA-180B1C492BBA}.Debug|x86.ActiveCfg = Debug|Any CPU + {CA8A12C5-7BF0-4489-93FA-180B1C492BBA}.Debug|x86.Build.0 = Debug|Any CPU + {CA8A12C5-7BF0-4489-93FA-180B1C492BBA}.Release|Any CPU.ActiveCfg = Release|Any CPU + {CA8A12C5-7BF0-4489-93FA-180B1C492BBA}.Release|Any CPU.Build.0 = Release|Any CPU + {CA8A12C5-7BF0-4489-93FA-180B1C492BBA}.Release|x86.ActiveCfg = Release|Any CPU + {CA8A12C5-7BF0-4489-93FA-180B1C492BBA}.Release|x86.Build.0 = Release|Any CPU + {5FEE5C91-8419-49FF-B2C2-47476F0B8C68}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {5FEE5C91-8419-49FF-B2C2-47476F0B8C68}.Debug|Any CPU.Build.0 = Debug|Any CPU + {5FEE5C91-8419-49FF-B2C2-47476F0B8C68}.Debug|x86.ActiveCfg = Debug|Any CPU + {5FEE5C91-8419-49FF-B2C2-47476F0B8C68}.Debug|x86.Build.0 = Debug|Any CPU + {5FEE5C91-8419-49FF-B2C2-47476F0B8C68}.Release|Any CPU.ActiveCfg = Release|Any CPU + {5FEE5C91-8419-49FF-B2C2-47476F0B8C68}.Release|Any CPU.Build.0 = Release|Any CPU + {5FEE5C91-8419-49FF-B2C2-47476F0B8C68}.Release|x86.ActiveCfg = Release|Any CPU + {5FEE5C91-8419-49FF-B2C2-47476F0B8C68}.Release|x86.Build.0 = Release|Any CPU + {3E6D1DD5-01C9-435F-9941-61F906CE35BB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {3E6D1DD5-01C9-435F-9941-61F906CE35BB}.Debug|Any CPU.Build.0 = Debug|Any CPU + {3E6D1DD5-01C9-435F-9941-61F906CE35BB}.Debug|x86.ActiveCfg = Debug|Any CPU + {3E6D1DD5-01C9-435F-9941-61F906CE35BB}.Debug|x86.Build.0 = Debug|Any CPU + {3E6D1DD5-01C9-435F-9941-61F906CE35BB}.Release|Any CPU.ActiveCfg = Release|Any CPU + {3E6D1DD5-01C9-435F-9941-61F906CE35BB}.Release|Any CPU.Build.0 = Release|Any CPU + {3E6D1DD5-01C9-435F-9941-61F906CE35BB}.Release|x86.ActiveCfg = Release|Any CPU + {3E6D1DD5-01C9-435F-9941-61F906CE35BB}.Release|x86.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {1A10FDB2-1A6A-44A8-AB4D-33387563247E} = {7CAB05BF-8588-4D5C-B369-C2F773F1A16E} + {F55DA1A0-A982-4479-8C47-0D9A5AAF3E18} = {7CAB05BF-8588-4D5C-B369-C2F773F1A16E} + {0D1AF432-439A-4920-8692-43AE139F5530} = {7CAB05BF-8588-4D5C-B369-C2F773F1A16E} + {F434E066-4C59-47C8-AA82-6F48CC84501A} = {7CAB05BF-8588-4D5C-B369-C2F773F1A16E} + {F0A0C525-03FD-428A-9B17-7F54AA0E4475} = {7CAB05BF-8588-4D5C-B369-C2F773F1A16E} + {D98BE764-ADEB-488D-9714-61E308AA8201} = {7CAB05BF-8588-4D5C-B369-C2F773F1A16E} + {90E76FB4-646D-45E2-95DB-0B8AB4E465D6} = {7CAB05BF-8588-4D5C-B369-C2F773F1A16E} + {5FD5DE57-CC26-4FD0-B852-5362123BC4FF} = {7CAB05BF-8588-4D5C-B369-C2F773F1A16E} + {FAB322CC-531D-4AEA-986A-B921B64D8D3F} = {7CAB05BF-8588-4D5C-B369-C2F773F1A16E} + {488BADD9-579F-4BF3-91DC-9FA95E3181A5} = {7CAB05BF-8588-4D5C-B369-C2F773F1A16E} + {E4EB6420-906D-4672-947A-CA33DDCDADFC} = {7CAB05BF-8588-4D5C-B369-C2F773F1A16E} + {1DC48C83-1842-4DE8-ACAF-26E1E7F7C58F} = {7CAB05BF-8588-4D5C-B369-C2F773F1A16E} + {5C0C572B-F8F1-41DE-B049-4D40AE29CD21} = {7CAB05BF-8588-4D5C-B369-C2F773F1A16E} + {B5A0BAA3-C1A7-4AAB-9486-2E650ADACA7E} = {4BF576F8-7AFE-41D3-A998-2AE62375DEC6} + {CA8A12C5-7BF0-4489-93FA-180B1C492BBA} = {4BF576F8-7AFE-41D3-A998-2AE62375DEC6} + {5FEE5C91-8419-49FF-B2C2-47476F0B8C68} = {4BF576F8-7AFE-41D3-A998-2AE62375DEC6} + {3E6D1DD5-01C9-435F-9941-61F906CE35BB} = {7CAB05BF-8588-4D5C-B369-C2F773F1A16E} + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {9BB32B35-134E-4853-B853-73A014D416DF} + EndGlobalSection +EndGlobal diff --git a/MisDataFun/MisDataFun/App.config b/MisDataFun/MisDataFun/App.config new file mode 100644 index 0000000..717d6ca --- /dev/null +++ b/MisDataFun/MisDataFun/App.config @@ -0,0 +1,49 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/MisDataFun/MisDataFun/Mes32X32.ico b/MisDataFun/MisDataFun/Mes32X32.ico new file mode 100644 index 0000000..ec465b2 Binary files /dev/null and b/MisDataFun/MisDataFun/Mes32X32.ico differ diff --git a/MisDataFun/MisDataFun/MisAddition/ControlData.cs b/MisDataFun/MisDataFun/MisAddition/ControlData.cs new file mode 100644 index 0000000..8980bc8 --- /dev/null +++ b/MisDataFun/MisDataFun/MisAddition/ControlData.cs @@ -0,0 +1,38 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Windows.Forms; + +namespace MisDataName +{ + public struct ControlData + { + public ControlData(Control Ctrl, string OpName) + { + string[] Array_NameSplit; + Array_NameSplit = Ctrl.Name.Split('_'); + TagType = Convert.ToInt32(Array_NameSplit[2]); + opName = OpName; + btn = Ctrl; + + } + + public int TagType; + public string opName; + public Control btn; + + + } + public struct ControlChangeByTagType + { + public ControlChangeByTagType(int tagType, string value) + { + TagType = tagType; + Value = value; + } + + public int TagType; + public string Value; + } +} diff --git a/MisDataFun/MisDataFun/MisAddition/ForOtherForm.cs b/MisDataFun/MisDataFun/MisAddition/ForOtherForm.cs new file mode 100644 index 0000000..2766d58 --- /dev/null +++ b/MisDataFun/MisDataFun/MisAddition/ForOtherForm.cs @@ -0,0 +1,83 @@ +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading; +using System.Windows.Forms; +using SystemFramework; + +namespace MisDataName +{ + public partial class MisData + { + void OpenSecondForm_Thread() + { + try + { + ToolStripMenuItem_VWSStatus.Checked = true; + + Thread t = new Thread(new ParameterizedThreadStart(OpenSecondForm)); + t.Start(this); + SecondForm.MainMenuRefresh = new MisDataName.SecondAct(RefreshToolStripMenuItem_Checked_ByName); + } + catch (Exception err) + { + ApplicationLog.WriteLog(err, err.Message ); + } + } + + Form Sencondform; + void OpenSecondForm( object ThisForm) + { + try + { + SecondForm f1 = new SecondForm( ThisForm); + Sencondform = f1; + f1.ShowDialog(); + } + catch (Exception err) + { + ApplicationLog.WriteLog(err, err.Message ); + } + } + + void RefreshToolStripMenuItem_Checked_ByName(string ControlName) + { + try + { + ToolStripItem[] tsItems = menuStrip_Main.Items.Find(ControlName, true); + ToolStripMenuItem tsmItem = (ToolStripMenuItem)tsItems[0]; + if (PlcChange == null) + { + tsmItem.Checked = false; + } + else + { + tsmItem.Checked = true; + } + } + catch (Exception err) + { + ApplicationLog.WriteLog(err, err.Message ); + } +} + + object QueryFormPosition(object obj) + { + try + { + return new Point(this.Left + this.Width, this.Top); + } + catch (Exception err) + { + ApplicationLog.WriteLog(err, err.Message); + return null; + + } + + } + + + } +} diff --git a/MisDataFun/MisDataFun/MisAddition/ManualSimulateSignal.cs b/MisDataFun/MisDataFun/MisAddition/ManualSimulateSignal.cs new file mode 100644 index 0000000..7a161e2 --- /dev/null +++ b/MisDataFun/MisDataFun/MisAddition/ManualSimulateSignal.cs @@ -0,0 +1,515 @@ +using BasicData; + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading; +using System.Windows.Forms; +using SystemFramework; + +namespace MisDataName +{ + public partial class MisData + { + public void InitFormBtnColor() + { + try + { + if (!Cbx_StatusDisplay.Checked) return; + string OpName = WorkStationNum_Now; + foreach (Control GroupBox in this.groupBox_SignialSimulator.Controls) + { + foreach (Control Btn in GroupBox.Controls) + { + if (Btn.Name.Length < 8) continue; + if (Btn.Name.Substring(0, 8) == "Btn_PLC_" || Btn.Name.Substring(0, 8) == "Btn_MES_") + { + ControlData Ctrl1 = new ControlData(Btn, OpName); + Thread t=new Thread(new ParameterizedThreadStart(InitFormBtn_Thread)); + t.Start(Ctrl1); + } + } + } + } + catch (Exception err) + { + ApplicationLog.WriteLog(err, err.Message); + + } + + + } + + static object test; + static void InitFormBtn_Thread(Object obj) + { + try + { + ControlData Btn = (ControlData)obj; + + test = ReadPLC(Btn.TagType, Btn.opName); + + bool Result = Convert.ToBoolean(test); + if (Btn.btn.InvokeRequired) + { + Action actionDelegate = (x) => { Btn.btn.BackColor = x; }; + if (Result) + { + Btn.btn.BeginInvoke(actionDelegate, System.Drawing.Color.Green); + } + else + { + Btn.btn.BeginInvoke(actionDelegate, System.Drawing.Color.SlateGray); + } + } + else + { + if (Result) + { + Btn.btn.BackColor = System.Drawing.Color.Green; + } + else + { + Btn.btn.BackColor = System.Drawing.Color.SlateGray; + } + } + } + catch (Exception err) + { + ControlData Btn = (ControlData)obj; + ApplicationLog.WriteLog(err, err.Message+"采集数据值:"+ ";按钮名称:"+test+ Btn.btn .Name +"工位号"+ WorkStationNum_Now); + } + } + + + + + + + /// + /// 通过点击界面按钮写入Bool信号 + /// + /// + /// + private void WriteBoolSignalByFormBtn(Object Sender) + { + try + { + string BtnName = ((System.Windows.Forms.Control)Sender).Name; + string[] Array_BtnNameSplit = BtnName.Split('_'); + int tagType = Convert.ToInt32(Array_BtnNameSplit[2]); + string OpName = WorkStationNum_Now; + + QualityDataQueryStruct QualityQueryStruct = new QualityDataQueryStruct(OpName, tagType); + Thread t = new Thread(new ParameterizedThreadStart(WriteBoolSignal_Thread)); + t.Start(QualityQueryStruct); + + } + catch (Exception err) + { + ApplicationLog.WriteLog(err, err.Message); + + } + } + + void WriteBoolSignal_Thread(object obj) + { + try + { + QualityDataQueryStruct QDQ = (QualityDataQueryStruct)obj; + if (IsDemoMesServer==1) + { + string tagValueStr = ""; + Read_TagTypeID(QDQ.tagType, QDQ.OpName, out tagValueStr); + + if (tagValueStr=="1") + { + tagValueStr = "True"; + } + else if (tagValueStr == "0") + { + tagValueStr = "False"; + } + + bool ReadResult = Convert.ToBoolean(tagValueStr); + if (ReadResult) + { + Write_TagTypeID(QDQ.tagType, QDQ.OpName, false); + } + else + { + Write_TagTypeID(QDQ.tagType, QDQ.OpName, true); + } + } + else + { + bool ReadResult = Convert.ToBoolean(MesDataFunction.OpcOperation.ReadPLC(QDQ.tagType, QDQ.OpName)); + if (ReadResult) + { + MesDataFunction.OpcOperation.WritePLC(QDQ.tagType, QDQ.OpName, false); + } + else + { + MesDataFunction.OpcOperation.WritePLC(QDQ.tagType, QDQ.OpName, true); + } + } + } + catch (Exception err) + { + ApplicationLog.WriteLog(err, err.Message); + + } + + } + + + + /// + /// 写入机型 + /// + /// + private void WriteNormalDataBygroupBox_SignialSimulatorWriteBtn(object Sender) + { + try + { + string BtnName = ((System.Windows.Forms.Control)Sender).Name; + string OpName = WorkStationNum_Now; + if (BtnName == "Btn_Write_PLC") + { + foreach (Control Tbx in this.groupBox_PLC.Controls) + { + if (Tbx.Name.Length < 12) continue; + if (Tbx.Name.Substring(0, 8) != "Tbx_PLC_") continue; + + string[] TbxName_Split = Tbx.Name.Split('_'); + int TagType = Convert.ToInt32(TbxName_Split[2]); + int tagDataType = Convert.ToInt32(MesDataFunction.OpcOperation.hashtable_TagTypeDataType[TagType.ToString()]); + + string tagValue = Tbx.Text.Trim(); + short tagValue_int; + string tagValue_str; + byte tagValue_byte; + bool tagValue_bool; + + switch (tagDataType) + { + case 2: + if (!Regex.IsMatch(tagValue, @"^[-]?\d*$")) + { + MessageBox.Show("文本框\"" + Tbx.Name + "\"输入不是整数!"); + return; + } + if (tagValue == "") return; + tagValue_int = Convert.ToInt16(tagValue); + WriteAnyData_Thread(TagType, OpName, tagValue_int); + break; + case 8: + tagValue_str = tagValue.ToString(); + WriteAnyData_Thread(TagType, OpName, tagValue_str); + break; + case 17: + if (!Regex.IsMatch(tagValue, @"^[-]?\d*$")) + { + MessageBox.Show("文本框\"" + Tbx.Name + "\"输入不是整数!"); + return; + } + if (Convert.ToInt32(tagValue) > 255) + { + MessageBox.Show("文本框\"" + Tbx.Name + "\"输入数据不在范围内"); + return; + } + if (tagValue == "") return; + tagValue_byte = Convert.ToByte(tagValue); + WriteAnyData_Thread(TagType, OpName, tagValue_byte); + break; + case 11: + tagValue_bool = Convert.ToBoolean(Convert.ToInt32(tagValue)); + WriteAnyData_Thread(TagType, OpName, tagValue_bool); + break; + default: + tagValue_str = tagValue.ToString(); + WriteAnyData_Thread(TagType, OpName, tagValue_str); + break; + } + } + } + else if (BtnName == "Btn_Write_MES") + { + foreach (Control Tbx in this.groupBox_MES.Controls) + { + if (Tbx.Name.Length < 12) continue; + if (Tbx.Name.Substring(0, 8) != "Tbx_MES_") continue; + + string[] TbxName_Split = Tbx.Name.Split('_'); + int TagType = Convert.ToInt32(TbxName_Split[2]); + int tagDataType = Convert.ToInt32(MesDataFunction.OpcOperation.hashtable_TagTypeDataType[TagType.ToString()]); + + string tagValue = Tbx.Text.Trim(); + short tagValue_int; + string tagValue_str; + byte tagValue_byte; + bool tagValue_bool; + + switch (tagDataType) + { + case 2: + if (!Regex.IsMatch(tagValue, @"^[-]?\d*$")) + { + MessageBox.Show("文本框\"" + Tbx.Name + "\"输入不是整数!"); + return; + } + tagValue_int = Convert.ToInt16(tagValue); + WriteAnyData_Thread(TagType, OpName, tagValue_int); + break; + case 8: + tagValue_str = tagValue.ToString(); + WriteAnyData_Thread(TagType, OpName, tagValue_str); + break; + case 17: + if (!Regex.IsMatch(tagValue, @"^[-]?\d*$")) + { + MessageBox.Show("文本框\"" + Tbx.Name + "\"输入不是整数!"); + return; + } + if (Convert.ToInt32(tagValue) > 255) + { + MessageBox.Show("文本框\"" + Tbx.Name + "\"输入数据不在范围内"); + return; + } + tagValue_byte = Convert.ToByte(tagValue); + WriteAnyData_Thread(TagType, OpName, tagValue_byte); + break; + case 11: + tagValue_bool = Convert.ToBoolean(Convert.ToInt32(tagValue)); + WriteAnyData_Thread(TagType, OpName, tagValue_bool); + break; + default: + tagValue_str = tagValue.ToString(); + WriteAnyData_Thread(TagType, OpName, tagValue_str); + break; + } + } + } + + } + catch (Exception err) + { + ApplicationLog.WriteLog(err, err.Message); + } + } + + + void WriteAnyData_Thread(int tagType, string opName, object tagValue) + { + try + { + QualityDataQueryStruct QualityStruct = new QualityDataQueryStruct(opName, tagType, tagValue); + + Thread t = new Thread(new ParameterizedThreadStart(WriteNormalDataBygroupBox_SignialSimulatorWriteBtn_Thread)); + t.Start(QualityStruct); + } + catch (Exception err) + { + ApplicationLog.WriteLog(err, err.Message); + } + } + + void WriteNormalDataBygroupBox_SignialSimulatorWriteBtn_Thread(object obj) + { + try + { + QualityDataQueryStruct QualityStruct = (QualityDataQueryStruct)obj; + + WritePLC(QualityStruct.tagType, QualityStruct. OpName, QualityStruct.tagValue); + } + catch (Exception err) + { + ApplicationLog.WriteLog(err, err.Message); + } + } + + + + /// + /// 根据工位号查询质量数据,返回质量数据列表 + /// + /// + /// + QualityDataType[] ReadPLC_ValueListForQualityDataTypeArray(string opName) + { + try + { + int i1 = 0; + Hashtable valueList; + valueList = MisDataFunction.Function.ReadPLC_Sync_DataList_MesRead(opName); + if (valueList != null) + { + QualityDataType[] QualityValue = new QualityDataType[valueList.Count]; + foreach (DictionaryEntry de in valueList) + { + try + { + QualityValue[i1] = (QualityDataType)de.Value; + i1++; + } + catch (Exception err) + { + ApplicationLog.WriteLog(err, err.Message); + } + } + //ThisWorkStationData = QualityValue; + return QualityValue; + } + return null; + } + catch (Exception err) + { + + ApplicationLog.WriteLog(err, err.Message); + return null; + } + + + } + + + public QualityDataType[] ThisWorkStationData + { get; set; } + + object QueryThisWorkStationDataByTagTypeFromThisWorkStationDataProperty(int TagType) + { + try + { + foreach (QualityDataType Data in ThisWorkStationData) + { + if (Data.tagValueType == TagType) + { + return Data.tagValue; + + } + + } + return null; + } + catch (Exception err) + { + ApplicationLog.WriteLog(err, err.Message); + return null; + } + + } + + void RefreshBtnColor(object obj) + { + try + { + ControlChangeByTagType ControlValue = (ControlChangeByTagType)obj; + + if (!Cbx_StatusDisplay.Checked) return; + string OpName = WorkStationNum_Now; + + foreach (Control GroupBox in this.groupBox_SignialSimulator.Controls) + { + foreach (Control Btn in GroupBox.Controls) + { + if (Btn.Name.Length < 8) continue; + if (Btn.Name.Substring(0, 8) == "Btn_PLC_" || Btn.Name.Substring(0, 8) == "Btn_MES_") + { + string BtnName = Btn.Name; + string[] BtnName_SplitArray = BtnName.Split('_'); + if (Btn.InvokeRequired) + { + Action ActionDelegate = (x) => { Btn.BackColor = x; }; + if (Convert.ToInt32(BtnName_SplitArray[2]) == ControlValue.TagType) + { + if (ControlValue.Value == "1") + { + Btn.BeginInvoke(ActionDelegate, System.Drawing.Color.Green); + + } + else + { + Btn.BeginInvoke(ActionDelegate, System.Drawing.Color.LightGray); + } + } + + + } + else + { + if (Convert.ToInt32(BtnName_SplitArray[2]) == ControlValue.TagType) + { + if (ControlValue.Value == "1") + { + Btn.BackColor = System.Drawing.Color.Green; + } + else + { + + Btn.BackColor = System.Drawing.Color.LightGray; + } + } + } + } + + } + } + } + catch (Exception err) + { + ApplicationLog.WriteLog(err, err.Message); + + } + + } + void RefreshBtnColor_Thread(int TagType, string Value) + { + ControlChangeByTagType ControlValue = new ControlChangeByTagType(TagType, Value); + Thread t = new Thread(new ParameterizedThreadStart(RefreshBtnColor)); + t.Start(ControlValue); + } + + + /// + /// 按钮颜色还原 + /// + void RefreshBtnColorWriteNull() + { + try + { + string OpName = WorkStationNum_Now; + + foreach (Control GroupBox in this.groupBox_SignialSimulator.Controls) + { + foreach (Control Btn in GroupBox.Controls) + { + if (Btn.Name.Length < 8) continue; + if (Btn.Name.Substring(0, 8) == "Btn_PLC_" || Btn.Name.Substring(0, 8) == "Btn_MES_") + { + if (Btn.InvokeRequired) + { + Action ActionDelegate = (x) => { Btn.BackColor = x; }; + Btn.BeginInvoke(ActionDelegate, System.Drawing.Color.LightGray); + } + else + { + Btn.BackColor = System.Drawing.Color.LightGray; + } + + } + } + } + } + catch (Exception err) + { + ApplicationLog.WriteLog(err, err.Message); + + } + + } + + } +} diff --git a/MisDataFun/MisDataFun/MisAddition/MisAdditionInit.cs b/MisDataFun/MisDataFun/MisAddition/MisAdditionInit.cs new file mode 100644 index 0000000..ba9e047 --- /dev/null +++ b/MisDataFun/MisDataFun/MisAddition/MisAdditionInit.cs @@ -0,0 +1,89 @@ +using System; +using System.Collections.Generic; +using System.Data; +using System.Linq; +using System.Text; +using System.Threading; +using SystemFramework; + +namespace MisDataName +{ + partial class MisData + { + + void TestPlcConnectInit() + { + //try + //{ + // DataTable dt_OpName = (DataTable)FunctionForm_HashiTable.OpName_Hash_Read("OpNameList"); + // for (int i=0;i< dt_OpName.Rows .Count;i++) + // { + // TestPlcConnect NewPlcConnect = new TestPlcConnect(dt_OpName.Rows [i][0].ToString ()); + // TestPlcConnect.TestPlcTimerChangedDelegate += NewPlcConnect.ExternalTimerExcute; + // NewPlcConnect.PlcConnect += PlcStatusChanged_Connect; + // NewPlcConnect.PlcBreak += PlcStatusChanged_Break; + // TestPlcConnect.HashTable_Write(TestPlcConnect.WorkStationTestExample, dt_OpName.Rows[i][0].ToString(), NewPlcConnect); + + // } + //} + //catch (Exception err) + //{ + // ApplicationLog.WriteLog(err, err.Message); + + //} + } + + public static void PlcStatusChanged_Connect(object sender, EventArgs e) + { + try + { + //查询在线工位数量 + int i= TestPlcConnect. CalculateWorkStationCount("OnlineWorkStation"); + + if (MisData.TestPlcStatusDel!=null ) + MisData.TestPlcStatusDel(i.ToString (), e); + } + catch (Exception err) + { + ApplicationLog.WriteLog(err, err.Message); + + } + + } + + public static void PlcStatusChanged_Break(object sender, EventArgs e) + { + try + { + //查询在线工位数量 + int i = TestPlcConnect.CalculateWorkStationCount("OnlineWorkStation"); + + if (MisData.TestPlcStatusDel != null) + MisData.TestPlcStatusDel(i.ToString(), e); + } + catch (Exception err) + { + ApplicationLog.WriteLog(err, err.Message); + + } + } + + void ListBox1_Item_Init() + { + listBox1.Items.Clear(); + try + { + if (MesDataFunction.OpcOperation.hashtable_TagType == null) return; + foreach (var i in MesDataFunction.OpcOperation.hashtable_TagType) + { + listBox1.Items.Add("MES|" + i.ToString() + "|" + WorkStationNum_Now + "|1"); + } + } + catch + { + + } + + } + } +} diff --git a/MisDataFun/MisDataFun/MisAddition/QualityDataQueryStruct.cs b/MisDataFun/MisDataFun/MisAddition/QualityDataQueryStruct.cs new file mode 100644 index 0000000..d238909 --- /dev/null +++ b/MisDataFun/MisDataFun/MisAddition/QualityDataQueryStruct.cs @@ -0,0 +1,87 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Windows.Forms; + +namespace MisDataSaveDate +{ + public struct QualityDataQueryStruct + { + + public QualityDataQueryStruct(string opName, Control ctrl) + { + OpName = opName; + Ctrl = ctrl; + tagType = 0; + tagValue = ""; + tagID = ""; + tagTypeID = 0; + tempForm = null; + tagValue2 = null; + + } + + public QualityDataQueryStruct(string opName, int TagType) + { + + OpName = opName; + Ctrl = null; + tagType = TagType; + tagValue = ""; + tagID = ""; + tagTypeID = 0; + tempForm = null; + tagValue2 = null; + } + + public QualityDataQueryStruct(string opName, int TagType, Control ctrl) + { + + OpName = opName; + Ctrl = ctrl; + tagType = TagType; + tagValue = ""; + tagID = ""; + tagTypeID = 0; + tempForm = null; + tagValue2 = null; + } + public QualityDataQueryStruct(string opName, int TagType, object TagValue) + { + + OpName = opName; + Ctrl = null; + tagType = TagType; + tagValue = TagValue; + tagID = ""; + tagTypeID = 0; + tempForm = null; + tagValue2 = null; + } + public QualityDataQueryStruct(string TagID, int TagTypeID, object TagValue, object TagValue2, Form TempForm) + { + + OpName = ""; + Ctrl = null; + tagType = 0; + tagValue = TagValue; + tagID = TagID; + tagTypeID = TagTypeID; + tempForm = TempForm; + tagValue2 = TagValue2; + } + + + public string OpName; + public Control Ctrl; + public int tagType; + public object tagValue; + public object tagValue2; + public string tagID; + public int tagTypeID; + public Form tempForm; + + + } +} diff --git a/MisDataFun/MisDataFun/MisAddition/ReadThisStationProductInfo.cs b/MisDataFun/MisDataFun/MisAddition/ReadThisStationProductInfo.cs new file mode 100644 index 0000000..fc76213 --- /dev/null +++ b/MisDataFun/MisDataFun/MisAddition/ReadThisStationProductInfo.cs @@ -0,0 +1,107 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading; +using System.Windows.Forms; +using SystemFramework; + +namespace MisDataName +{ + public partial class MisData + { + + void ReadPLC_ProductInfo() + { + try + { + foreach (Control Tbx in this.groupBox_PLC.Controls) + { + + Thread t = new Thread(new ParameterizedThreadStart(ReadPLC_ProductInfo_Thread)); + t.Start(Tbx); + } + } + catch (Exception err) + { + ApplicationLog.WriteLog(err, err.Message); + + } + } + + + + void ReadPLC_ProductInfo_Thread(object obj) + { + try + { + Control Tbx = (Control)obj; + if (Tbx.Name.Length < 12) return; + if (Tbx.Name.Substring(0, 8) != "Tbx_PLC_") return; + string[] TbxName_Split = Tbx.Name.Split('_'); + int TagType = Convert.ToInt32(TbxName_Split[2]); + if (Tbx.InvokeRequired ) + { + Action actionDelegate = (x) => { Tbx.Text = x; }; + Tbx.BeginInvoke(actionDelegate, ReadPLC(TagType, WorkStationNum_Now).ToString()); + } + else + { + Tbx.Text = ReadPLC(TagType, WorkStationNum_Now).ToString(); + } + + } + catch (Exception err) + { + ApplicationLog.WriteLog(err, err.Message); + } + } + + + void ReadMES_ProductInfo() + { + try + { + foreach (Control Tbx in this.groupBox_MES.Controls) + { + Thread t = new Thread(new ParameterizedThreadStart(ReadMES_ProductInfo_Thread)); + t.Start(Tbx); + } + } + catch (Exception err) + { + ApplicationLog.WriteLog(err, err.Message); + + } + } + void ReadMES_ProductInfo_Thread(object obj) + { + try + { + Control Tbx = (Control)obj; + + if (Tbx.Name.Length < 12) return; + if (Tbx.Name.Substring(0, 8) != "Tbx_MES_") return; + + string[] TbxName_Split = Tbx.Name.Split('_'); + int TagType = Convert.ToInt32(TbxName_Split[2]); + if (Tbx .InvokeRequired ) + { + Action ActionDelegate = (x) => { Tbx.Text = x; }; + Tbx.BeginInvoke(ActionDelegate, ReadPLC(TagType, WorkStationNum_Now).ToString()); + } + else + { + Tbx.Text = ReadPLC(TagType, WorkStationNum_Now).ToString(); + } + + } + catch (Exception err) + { + ApplicationLog.WriteLog(err, err.Message); + } + } + + + } +} diff --git a/MisDataFun/MisDataFun/MisAddition/TestPlcConnect.cs b/MisDataFun/MisDataFun/MisAddition/TestPlcConnect.cs new file mode 100644 index 0000000..4882b86 --- /dev/null +++ b/MisDataFun/MisDataFun/MisAddition/TestPlcConnect.cs @@ -0,0 +1,175 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading; + +namespace MisDataName +{ + public delegate void TestPlcDelegate(); + public class TestPlcConnect + { + public static Hashtable WorkStationStatus_Hash = new Hashtable(); + public static Hashtable WorkStationTestExample = new Hashtable(); + + string WorkStationStr = ""; + + public EventHandler PlcBreak,PlcConnect; + + bool PlcStatus=false ; + + static int testTime = 10; + int TestInterval = testTime; + + string OpName; + + + public TestPlcConnect(string opName) + { + OpName = opName; + } + + public void ExternalSignalChange() + { + TestInterval = testTime; + if(!PlcStatus) + { + + WorkStationStr=ReadWorkStationStr("OnlineWorkStation"); + HashTable_Write(WorkStationStatus_Hash,"OnlineWorkStation", String_Combine(WorkStationStr, OpName)); + WorkStationStr = ReadWorkStationStr("DownlineWorkStation"); + HashTable_Write(WorkStationStatus_Hash, "DownlineWorkStation", String_Spl(WorkStationStr, OpName)); + + if (PlcConnect != null) + { + PlcConnect(OpName, null); + } + + + PlcStatus = true; + } + + + } + + public void ExternalTimerExcute() + { + if (TestInterval>0) + { + TestInterval--; + } + else + { + + if(PlcStatus) + { + + WorkStationStr = ReadWorkStationStr("DownlineWorkStation"); + HashTable_Write(WorkStationStatus_Hash, "DownlineWorkStation", String_Combine(WorkStationStr, OpName)); + WorkStationStr = ReadWorkStationStr("OnlineWorkStation"); + HashTable_Write(WorkStationStatus_Hash, "OnlineWorkStation", String_Spl(WorkStationStr, OpName)); + + if (PlcBreak != null) + { + PlcBreak(OpName, null); + } + + PlcStatus = false; + } + + + } + + } + + + public static void HashTable_Write(Hashtable hashtable, string Key,object obj) + { + if (hashtable.ContainsKey (Key)) + { + hashtable[Key] = obj; + } + else + { + hashtable.Add(Key, obj); + } + + + } + + public static object HashTable_Read(Hashtable hashtable, string Key) + { + if (hashtable.ContainsKey(Key)) + { + return hashtable[Key]; + } + else + { + return null; + } + } + + string ReadWorkStationStr(string Key) + { + if ( HashTable_Read(WorkStationStatus_Hash, Key) !=null ) + { + return HashTable_Read(WorkStationStatus_Hash, Key).ToString(); + + } + return ""; + } + + + string String_Combine(string MainStr,string AddStr) + { + return MainStr+ AddStr + "|"; + + } + string String_Spl(string MainStr, string DelStr) + { + return MainStr.Replace(DelStr + "|", ""); + } + + + + public static int CalculateWorkStationCount(string Key) + { + string wksta=""; + if(WorkStationStatus_Hash.ContainsKey (Key)) + { + wksta = WorkStationStatus_Hash[Key].ToString(); + } + string[] wksta_SplitArray = wksta.Split('|'); + + return wksta_SplitArray.Length-1; + + } + + + + + public static void HeartBeatChange(string OpName, int TagTypeID) + { + if (TagTypeID == 14) + { + Thread t = new Thread(new ParameterizedThreadStart(HeartBeatChange_Thread)); + t.Start(OpName); + } + + + } + + static void HeartBeatChange_Thread(object obj) + { + string OpName = (string)obj; + if (TestPlcConnect.HashTable_Read(TestPlcConnect.WorkStationTestExample, OpName) != null) + { + TestPlcConnect PlcConnectExample = (TestPlcConnect)TestPlcConnect.HashTable_Read(TestPlcConnect.WorkStationTestExample, OpName); + PlcConnectExample.ExternalSignalChange(); + } + + } + + } +} diff --git a/MisDataFun/MisDataFun/MisAddition/ThisStationStatusDisplay.cs b/MisDataFun/MisDataFun/MisAddition/ThisStationStatusDisplay.cs new file mode 100644 index 0000000..999a536 --- /dev/null +++ b/MisDataFun/MisDataFun/MisAddition/ThisStationStatusDisplay.cs @@ -0,0 +1,128 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Windows.Forms; + +using SystemFramework; +using System.Threading; + +namespace MisDataName +{ + public partial class MisData + { + + void initStationStatus() + { + try + { + if (!Cbx_StatusDisplay.Checked) return; + foreach (Control Tbx in this.groupBox_WorkStationStatus.Controls) + { + Thread t = new Thread(new ParameterizedThreadStart(initStationStatus_Thread)); + t.Start(Tbx); + + } + } + catch (Exception err) + { + ApplicationLog.WriteLog(err, err.Message); + + } + } + + void initStationStatus_Thread(object obj ) + { + try + { + Control Tbx = (Control)obj; + if (Tbx.Name.Length < 12) return ; + if (Tbx.Name.Substring(0, 11) == "Tbx_Status_") + { + string[] TbxNameSplitArray = Tbx.Name.Split('_'); + int Tagtype = Convert.ToInt32(TbxNameSplitArray[2]); + if (Tbx .InvokeRequired ) + { + Action ActionDelegate = (x) => { Tbx.Text = x; }; + Tbx.BeginInvoke(ActionDelegate, MesDataFunction.OpcOperation.ReadPLC(Tagtype, WorkStationNum_Now).ToString()); + } + else + { + Tbx.Text = MesDataFunction.OpcOperation.ReadPLC(Tagtype, WorkStationNum_Now).ToString(); + } + } + } + catch (Exception err) + { + ApplicationLog.WriteLog(err, err.Message); + } + } + + + void RefreshStationStatus(object obj) + { + try + { + ControlChangeByTagType ControlValue = (ControlChangeByTagType)obj; + + if (!Cbx_StatusDisplay.Checked) return; + foreach (Control Tbx in this.groupBox_WorkStationStatus.Controls) + { + if (Tbx.Name.Length < 12) continue; + if (Tbx.Name.Substring(0, 11) == "Tbx_Status_") + { + string[] TbxNameSplitArray = Tbx.Name.Split('_'); + int Tagtype = Convert.ToInt32(TbxNameSplitArray[2]); + if (ControlValue.TagType == Tagtype) + { + if (Tbx.InvokeRequired) + { + Action ActionDelegate = (x) => { Tbx.Text = x; }; + Tbx.BeginInvoke(ActionDelegate, ControlValue.Value); + } + else + { + Tbx.Text = ControlValue.Value; + } + + } + } + } + } + catch (Exception err) + { + ApplicationLog.WriteLog(err, err.Message); + + } + + } + void RefreshStationStatus_Thread(int TargetTagtype, string TbxText) + { + ControlChangeByTagType ControlValue = new MisDataName.ControlChangeByTagType(TargetTagtype, TbxText); + Thread t = new Thread(new ParameterizedThreadStart(RefreshStationStatus)); + t.Start(ControlValue); + } + + void RefreshStationStatusWriteNull() + { + try + { + foreach (Control Tbx in this.groupBox_WorkStationStatus.Controls) + { + if (Tbx.Name.Length < 12) continue; + if (Tbx.Name.Substring(0, 11) == "Tbx_Status_") + { + Tbx.Text = "未开启同步"; + } + } + } + catch (Exception err) + { + ApplicationLog.WriteLog(err, err.Message); + + } + + } + + } +} diff --git a/MisDataFun/MisDataFun/MisAddition/WriteQualityValueForm.Designer.cs b/MisDataFun/MisDataFun/MisAddition/WriteQualityValueForm.Designer.cs new file mode 100644 index 0000000..0c2fcb2 --- /dev/null +++ b/MisDataFun/MisDataFun/MisAddition/WriteQualityValueForm.Designer.cs @@ -0,0 +1,114 @@ +namespace MisDataSaveDate +{ + partial class WriteQualityValueForm + { + /// + /// 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.label_Message = new System.Windows.Forms.Label(); + this.textBox_InputValue = new System.Windows.Forms.TextBox(); + this.button_OK = new System.Windows.Forms.Button(); + this.button_Cancle = new System.Windows.Forms.Button(); + this.comboBox_InputValue = new System.Windows.Forms.ComboBox(); + this.SuspendLayout(); + // + // label_Message + // + this.label_Message.AutoSize = true; + this.label_Message.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.label_Message.Location = new System.Drawing.Point(15, 10); + this.label_Message.Name = "label_Message"; + this.label_Message.Size = new System.Drawing.Size(41, 12); + this.label_Message.TabIndex = 0; + this.label_Message.Text = "label1"; + // + // textBox_InputValue + // + this.textBox_InputValue.Location = new System.Drawing.Point(10, 50); + this.textBox_InputValue.Name = "textBox_InputValue"; + this.textBox_InputValue.Size = new System.Drawing.Size(475, 21); + this.textBox_InputValue.TabIndex = 1; + // + // button_OK + // + this.button_OK.Location = new System.Drawing.Point(268, 81); + this.button_OK.Name = "button_OK"; + this.button_OK.Size = new System.Drawing.Size(95, 25); + this.button_OK.TabIndex = 2; + this.button_OK.Text = "OK"; + this.button_OK.UseVisualStyleBackColor = true; + this.button_OK.Click += new System.EventHandler(this.button_OK_Click); + // + // button_Cancle + // + this.button_Cancle.Location = new System.Drawing.Point(369, 81); + this.button_Cancle.Name = "button_Cancle"; + this.button_Cancle.Size = new System.Drawing.Size(95, 25); + this.button_Cancle.TabIndex = 2; + this.button_Cancle.Text = "Cancel"; + this.button_Cancle.UseVisualStyleBackColor = true; + this.button_Cancle.Click += new System.EventHandler(this.button_Cancle_Click); + // + // comboBox_InputValue + // + this.comboBox_InputValue.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; + this.comboBox_InputValue.FormattingEnabled = true; + this.comboBox_InputValue.Items.AddRange(new object[] { + "false", + "true"}); + this.comboBox_InputValue.Location = new System.Drawing.Point(10, 50); + this.comboBox_InputValue.Name = "comboBox_InputValue"; + this.comboBox_InputValue.Size = new System.Drawing.Size(475, 20); + this.comboBox_InputValue.TabIndex = 3; + // + // WriteQualityValueForm + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(494, 111); + this.Controls.Add(this.comboBox_InputValue); + this.Controls.Add(this.button_Cancle); + this.Controls.Add(this.button_OK); + this.Controls.Add(this.textBox_InputValue); + this.Controls.Add(this.label_Message); + this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow; + this.Name = "WriteQualityValueForm"; + this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; + this.Text = "Write value"; + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private System.Windows.Forms.Label label_Message; + private System.Windows.Forms.TextBox textBox_InputValue; + private System.Windows.Forms.Button button_OK; + private System.Windows.Forms.Button button_Cancle; + private System.Windows.Forms.ComboBox comboBox_InputValue; + } +} \ No newline at end of file diff --git a/MisDataFun/MisDataFun/MisAddition/WriteQualityValueForm.cs b/MisDataFun/MisDataFun/MisAddition/WriteQualityValueForm.cs new file mode 100644 index 0000000..d710f8a --- /dev/null +++ b/MisDataFun/MisDataFun/MisAddition/WriteQualityValueForm.cs @@ -0,0 +1,275 @@ +using System; +using System.Windows.Forms; +using BasicData; +using System.Text.RegularExpressions; +using SystemFramework; +using System.Threading; +using MesDataFunction; + +namespace MisDataSaveDate +{ + public partial class WriteQualityValueForm : Form + { + QualityDataType SelectListData; + Form MainForm; + public WriteQualityValueForm(QualityDataType SelectData,Form Mainform) + { + try + { + InitializeComponent(); + SelectListData = new QualityDataType(); + SelectListData = SelectData; + SetForm(SelectData.tagTypeID, SelectData.tagValue); + MainForm = Mainform; + + + } + catch (Exception err) + { + ApplicationLog.WriteLog(err, err.Message); + } + } + + private void button_OK_Click(object sender, EventArgs e) + { + try + { + if (!TagTypeID_Confirm(SelectListData.tagTypeID)) return; + + this.Hide () ; + + QualityDataQueryStruct QualityStruct = new QualityDataQueryStruct(SelectListData.tagID , SelectListData.tagTypeID , comboBox_InputValue.SelectedIndex.ToString(), textBox_InputValue.Text,this); + Thread t = new Thread(new ParameterizedThreadStart(WriteQualityDataByTagID_Thread)); + t.Start(QualityStruct); + + if (QualityStruct.tagTypeID == 11) + { + MyLog4Net.MyLogHelper.Error($"手动修改值【{SelectListData.opName}】{SelectListData.tagID}:", QualityStruct.tagValue.ToString()); + } + else + { + MyLog4Net.MyLogHelper.Error($"手动修改值【{SelectListData.opName}】{SelectListData.tagID}:", QualityStruct.tagValue2.ToString()); + } + + } + catch (Exception err) + { + ApplicationLog.WriteLog(err, err.Message); + + } + } + + + void WriteQualityDataByTagID_Thread(object obj) + { + try + { + QualityDataQueryStruct QualityStruct = (QualityDataQueryStruct)obj; + Form ThisForm = (Form)QualityStruct.tempForm; + + + if (QualityStruct.tagTypeID == 11) + { + MesWorkPlc.WritePLC(QualityStruct.tagID, QualityStruct.tagValue.ToString()); + } + else + { + MesWorkPlc.WritePLC(SelectListData.tagID, QualityStruct.tagValue2.ToString()); + } + MainForm.BeginInvoke (MisDataFun.MainFormRefresh, null, null); + Action ActionDelete = () => { this.Close();this.Dispose(); }; + if(this.InvokeRequired ) + { + ThisForm.BeginInvoke(ActionDelete); + } + else + { + ActionDelete(); + } + + + } + catch (Exception err) + { + ApplicationLog.WriteLog(err, err.Message); + + } + + } + + + + + private void button_Cancle_Click(object sender, EventArgs e) + { + this.Close(); + this.Dispose(); + } + + + + void SetForm( int TagTypeID,object TagValue) + { + try + { + switch (TagTypeID) + { + case 11://BOOL + comboBox_InputValue.Enabled = true; + comboBox_InputValue.Visible = true; + textBox_InputValue.Enabled = false; + textBox_InputValue.Visible = false; + label_Message.Text = "Data type: Boolean"; + if (Convert.ToBoolean(TagValue)) + { + comboBox_InputValue.SelectedIndex = 1; + } + else + { + comboBox_InputValue.SelectedIndex = 0; + } + + break; + + case 2://INT. + label_Message.Text = "Data type: Int16 Range from -32768 to 32767"; + comboBox_InputValue.Enabled = false; + comboBox_InputValue.Visible = false; + textBox_InputValue.Enabled = true; + textBox_InputValue.Visible = true; + textBox_InputValue.Text = TagValue.ToString(); + + break; + case 17://BYTE + label_Message.Text = "Data type: Byte Range from 0 to 255"; + comboBox_InputValue.Enabled = false; + comboBox_InputValue.Visible = false; + textBox_InputValue.Enabled = true; + textBox_InputValue.Visible = true; + textBox_InputValue.Text = TagValue.ToString(); + + break; + case 8://STRING + label_Message.Text = "Data type: String"; + comboBox_InputValue.Enabled = false; + comboBox_InputValue.Visible = false; + textBox_InputValue.Enabled = true; + textBox_InputValue.Visible = true; + textBox_InputValue.Text = TagValue.ToString(); + + break; + case 18://Word + label_Message.Text = "Data type: UInt16 Range from 0 to 65535"; + comboBox_InputValue.Enabled = false; + comboBox_InputValue.Visible = false; + textBox_InputValue.Enabled = true; + textBox_InputValue.Visible = true; + textBox_InputValue.Text = TagValue.ToString(); + + break; + case 4://real + label_Message.Text = "Data type: Single Range from -3.402823E+38 to 3.402823E+38"; + comboBox_InputValue.Enabled = false; + comboBox_InputValue.Visible = false; + textBox_InputValue.Enabled = true; + textBox_InputValue.Visible = true; + textBox_InputValue.Text = TagValue.ToString(); + + break; + default://Unknow + label_Message.Text = "Data type: Unknow"; + comboBox_InputValue.Enabled = false; + comboBox_InputValue.Visible = false; + textBox_InputValue.Enabled = true; + textBox_InputValue.Visible = true; + textBox_InputValue.Text = TagValue.ToString(); + + break; + + } + } + catch (Exception err) + { + ApplicationLog.WriteLog(err, err.Message); + + } + + + } + + bool TagTypeID_Confirm( int TagTypeID) + { + try + { + switch (TagTypeID) + { + + + case 2://INT + //TextBox存在非数字字符 报错 + if (!Regex.IsMatch(textBox_InputValue.Text, @"^[-]?\d*$")) + { + MessageBox.Show("输入不是整数!"); + return false; + } + if (textBox_InputValue.Text.Length > 9) + { + MessageBox.Show("输入数据不在范围内"); + return false; + } + break; + case 17://BYTE + //TextBox存在非数字字符 报错 + if (!Regex.IsMatch(textBox_InputValue.Text, @"^[-]?\d*$")) + { + MessageBox.Show("输入不是整数!"); + return false; + } + if (Convert.ToInt32(textBox_InputValue.Text.Trim()) > 255) + { + MessageBox.Show("输入数据不在范围内"); + return false; + } + break; + case 8://STRING + + break; + case 18://Word + //TextBox存在非数字字符 报错 + if (!Regex.IsMatch(textBox_InputValue.Text, @"^[-]?\d*$")) + { + MessageBox.Show("输入不是整数!"); + return false; + } + if (textBox_InputValue.Text.Trim().Length > 4) + { + MessageBox.Show("输入数据不在范围内"); + return false; + } + break; + case 4://real + //TextBox存在非数字字符 报错 + //TextBox存在非数字字符 报错 + if (!Regex.IsMatch(textBox_InputValue.Text, @"^-?\d+\.?\d*$")) + { + MessageBox.Show("输入不是实数!"); + return false; + } + + break; + default: + break; + + } + + return true; + } + catch (Exception err) + { + ApplicationLog.WriteLog(err, err.Message); + return true; + } + } + + } +} diff --git a/MisDataFun/MisDataFun/MisAddition/WriteQualityValueForm.resx b/MisDataFun/MisDataFun/MisAddition/WriteQualityValueForm.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/MisDataFun/MisDataFun/MisAddition/WriteQualityValueForm.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/MisDataFun/MisDataFun/MisDataFun.Designer.cs b/MisDataFun/MisDataFun/MisDataFun.Designer.cs new file mode 100644 index 0000000..c31d88e --- /dev/null +++ b/MisDataFun/MisDataFun/MisDataFun.Designer.cs @@ -0,0 +1,1215 @@ + +namespace MisDataSaveDate +{ + partial class MisDataFun + { + /// + /// 必需的设计器变量。 + /// + 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.components = new System.ComponentModel.Container(); + System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MisDataFun)); + this.menuStrip1 = new System.Windows.Forms.MenuStrip(); + this.ToolStripMenuItem_PlcDebug = new System.Windows.Forms.ToolStripMenuItem(); + this.修改配置文件ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.帮助ToolStripMenuItem = 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.groupBox5 = new System.Windows.Forms.GroupBox(); + this.textBox_WEB_TO_MES = new System.Windows.Forms.TextBox(); + this.groupBox1 = new System.Windows.Forms.GroupBox(); + this.textBox_PLC_TO_MES = new System.Windows.Forms.TextBox(); + this.groupBox3 = new System.Windows.Forms.GroupBox(); + this.textBox_MES_TO_WEB = new System.Windows.Forms.TextBox(); + this.panel1 = new System.Windows.Forms.Panel(); + this.tableLayoutPanel3 = new System.Windows.Forms.TableLayoutPanel(); + this.checkBox_PLC_TO_MES = new System.Windows.Forms.CheckBox(); + this.button_PLC_TO_MES_Clear = new System.Windows.Forms.Button(); + this.button_PLC_TO_MES_Big = new System.Windows.Forms.Button(); + this.button_PLC_TO_MES_Small = new System.Windows.Forms.Button(); + this.panel3 = new System.Windows.Forms.Panel(); + this.tableLayoutPanel2 = new System.Windows.Forms.TableLayoutPanel(); + this.dataGridView_CheckOpName = new System.Windows.Forms.DataGridView(); + this.选择 = new System.Windows.Forms.DataGridViewCheckBoxColumn(); + this.工位号 = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.checkBox__MES_TO_WEB = new System.Windows.Forms.CheckBox(); + this.button_MES_TO_WEB_Clear = new System.Windows.Forms.Button(); + this.button_MES_TO_WEB_Small = new System.Windows.Forms.Button(); + this.button_MES_TO_WEB_Big = new System.Windows.Forms.Button(); + this.panel4 = new System.Windows.Forms.Panel(); + this.tableLayoutPanel4 = new System.Windows.Forms.TableLayoutPanel(); + this.button_WEB_TO_MES_Big = new System.Windows.Forms.Button(); + this.button_WEB_TO_MES_Small = new System.Windows.Forms.Button(); + this.checkBox_WEB_TO_MES = new System.Windows.Forms.CheckBox(); + this.button_WEB_TO_MES_Clear = new System.Windows.Forms.Button(); + this.panel5 = new System.Windows.Forms.Panel(); + this.comboBox1 = new System.Windows.Forms.ComboBox(); + this.textBox_MqttText = new System.Windows.Forms.TextBox(); + this.panel2 = new System.Windows.Forms.Panel(); + this.tableLayoutPanel5 = new System.Windows.Forms.TableLayoutPanel(); + this.panel6 = new System.Windows.Forms.Panel(); + this.button_SaveData = new System.Windows.Forms.Button(); + this.label1 = new System.Windows.Forms.Label(); + this.label3 = new System.Windows.Forms.Label(); + this.comboBox_OpNameList = new System.Windows.Forms.ComboBox(); + this.label2 = new System.Windows.Forms.Label(); + this.button_ToWEB = new System.Windows.Forms.Button(); + this.button_WebToMES = new System.Windows.Forms.Button(); + this.tabControl1 = new System.Windows.Forms.TabControl(); + this.tabPage6 = new System.Windows.Forms.TabPage(); + this.tabPage1 = new System.Windows.Forms.TabPage(); + this.tabPage2 = new System.Windows.Forms.TabPage(); + this.tabPage3 = new System.Windows.Forms.TabPage(); + this.tabPage4 = new System.Windows.Forms.TabPage(); + this.tabPage5 = new System.Windows.Forms.TabPage(); + this.btn_MqttStatus = new System.Windows.Forms.Button(); + this.panel7 = new System.Windows.Forms.Panel(); + this.button3 = new System.Windows.Forms.Button(); + this.button1 = new System.Windows.Forms.Button(); + this.button2 = new System.Windows.Forms.Button(); + this.cb_QdData = new System.Windows.Forms.CheckBox(); + this.cb_MonitorData = new System.Windows.Forms.CheckBox(); + this.listView_ShowQualityData = new System.Windows.Forms.ListView(); + this.columnHeader1 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); + this.columnHeader2 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); + this.columnHeader3 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); + this.columnHeader4 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); + this.columnHeader5 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); + this.label5 = new System.Windows.Forms.Label(); + this.comboBox_OpName = new System.Windows.Forms.ComboBox(); + this.button_ReadData = new System.Windows.Forms.Button(); + this.label4 = new System.Windows.Forms.Label(); + this.richTextBox1_mqtt = new System.Windows.Forms.RichTextBox(); + this.timer_Status = new System.Windows.Forms.Timer(this.components); + this.statusStrip1 = new System.Windows.Forms.StatusStrip(); + this.toolStripStatusLabel_RunningStatu = new System.Windows.Forms.ToolStripStatusLabel(); + this.toolStripStatusLabel_RunningStatus = new System.Windows.Forms.ToolStripStatusLabel(); + this.toolStripStatusLabel2 = new System.Windows.Forms.ToolStripStatusLabel(); + this.toolStripStatusLabel_StartTime = new System.Windows.Forms.ToolStripStatusLabel(); + this.toolStripStatusLabel3 = new System.Windows.Forms.ToolStripStatusLabel(); + this.toolStripStatusLabel_RunTime = new System.Windows.Forms.ToolStripStatusLabel(); + this.toolStripStatusLabel1 = new System.Windows.Forms.ToolStripStatusLabel(); + this.toolStripStatusLabel_WorkStationNum = new System.Windows.Forms.ToolStripStatusLabel(); + this.toolStripStatusLabel6 = new System.Windows.Forms.ToolStripStatusLabel(); + this.toolStripStatusLabel_OnlineNum = new System.Windows.Forms.ToolStripStatusLabel(); + this.toolStripStatusLabel8 = new System.Windows.Forms.ToolStripStatusLabel(); + this.toolStripStatusLabel_DownLine = new System.Windows.Forms.ToolStripStatusLabel(); + this.toolStripStatusLabel4 = new System.Windows.Forms.ToolStripStatusLabel(); + this.toolStripStatusLabel_Version = new System.Windows.Forms.ToolStripStatusLabel(); + this.timer_TestPLC = new System.Windows.Forms.Timer(this.components); + this.menuStrip1.SuspendLayout(); + this.tableLayoutPanel1.SuspendLayout(); + this.groupBox5.SuspendLayout(); + this.groupBox1.SuspendLayout(); + this.groupBox3.SuspendLayout(); + this.panel1.SuspendLayout(); + this.tableLayoutPanel3.SuspendLayout(); + this.panel3.SuspendLayout(); + this.tableLayoutPanel2.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView_CheckOpName)).BeginInit(); + this.panel4.SuspendLayout(); + this.tableLayoutPanel4.SuspendLayout(); + this.panel5.SuspendLayout(); + this.panel2.SuspendLayout(); + this.tableLayoutPanel5.SuspendLayout(); + this.panel6.SuspendLayout(); + this.tabControl1.SuspendLayout(); + this.panel7.SuspendLayout(); + this.statusStrip1.SuspendLayout(); + this.SuspendLayout(); + // + // menuStrip1 + // + this.menuStrip1.GripMargin = new System.Windows.Forms.Padding(2, 2, 0, 2); + this.menuStrip1.ImageScalingSize = new System.Drawing.Size(24, 24); + this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { + this.ToolStripMenuItem_PlcDebug, + 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(6, 3, 0, 3); + this.menuStrip1.Size = new System.Drawing.Size(1497, 34); + this.menuStrip1.TabIndex = 2; + this.menuStrip1.Text = "menuStrip1"; + // + // ToolStripMenuItem_PlcDebug + // + this.ToolStripMenuItem_PlcDebug.Name = "ToolStripMenuItem_PlcDebug"; + this.ToolStripMenuItem_PlcDebug.Size = new System.Drawing.Size(130, 28); + this.ToolStripMenuItem_PlcDebug.Text = "PLC信号调试"; + this.ToolStripMenuItem_PlcDebug.Click += new System.EventHandler(this.ToolStripMenuItem_PlcDebug_Click); + // + // 修改配置文件ToolStripMenuItem + // + this.修改配置文件ToolStripMenuItem.Name = "修改配置文件ToolStripMenuItem"; + this.修改配置文件ToolStripMenuItem.Size = new System.Drawing.Size(134, 28); + this.修改配置文件ToolStripMenuItem.Text = "修改配置文件"; + this.修改配置文件ToolStripMenuItem.Click += new System.EventHandler(this.修改配置文件ToolStripMenuItem_Click); + // + // 帮助ToolStripMenuItem + // + this.帮助ToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { + this.版本信息ToolStripMenuItem, + this.关于迈思ToolStripMenuItem}); + this.帮助ToolStripMenuItem.Name = "帮助ToolStripMenuItem"; + this.帮助ToolStripMenuItem.Size = new System.Drawing.Size(62, 28); + this.帮助ToolStripMenuItem.Text = "帮助"; + // + // 版本信息ToolStripMenuItem + // + this.版本信息ToolStripMenuItem.Name = "版本信息ToolStripMenuItem"; + this.版本信息ToolStripMenuItem.Size = new System.Drawing.Size(182, 34); + this.版本信息ToolStripMenuItem.Text = "版本信息"; + this.版本信息ToolStripMenuItem.Click += new System.EventHandler(this.版本信息ToolStripMenuItem_Click); + // + // 关于迈思ToolStripMenuItem + // + this.关于迈思ToolStripMenuItem.Name = "关于迈思ToolStripMenuItem"; + this.关于迈思ToolStripMenuItem.Size = new System.Drawing.Size(182, 34); + this.关于迈思ToolStripMenuItem.Text = "关于迈思"; + this.关于迈思ToolStripMenuItem.Click += new System.EventHandler(this.关于迈思ToolStripMenuItem_Click); + // + // tableLayoutPanel1 + // + this.tableLayoutPanel1.ColumnCount = 2; + this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); + this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 300F)); + this.tableLayoutPanel1.Controls.Add(this.groupBox5, 0, 2); + this.tableLayoutPanel1.Controls.Add(this.groupBox1, 0, 0); + this.tableLayoutPanel1.Controls.Add(this.groupBox3, 0, 1); + this.tableLayoutPanel1.Controls.Add(this.panel1, 1, 0); + this.tableLayoutPanel1.Controls.Add(this.panel3, 1, 1); + this.tableLayoutPanel1.Controls.Add(this.panel4, 1, 2); + this.tableLayoutPanel1.Controls.Add(this.panel5, 1, 3); + this.tableLayoutPanel1.Controls.Add(this.panel2, 0, 3); + this.tableLayoutPanel1.Location = new System.Drawing.Point(501, 478); + this.tableLayoutPanel1.Name = "tableLayoutPanel1"; + this.tableLayoutPanel1.RowCount = 4; + this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 20F)); + this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 30F)); + this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 20F)); + this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 30F)); + this.tableLayoutPanel1.Size = new System.Drawing.Size(885, 512); + this.tableLayoutPanel1.TabIndex = 3; + // + // groupBox5 + // + this.groupBox5.Controls.Add(this.textBox_WEB_TO_MES); + this.groupBox5.Dock = System.Windows.Forms.DockStyle.Fill; + this.groupBox5.Location = new System.Drawing.Point(3, 258); + this.groupBox5.Name = "groupBox5"; + this.groupBox5.Size = new System.Drawing.Size(579, 96); + this.groupBox5.TabIndex = 4; + this.groupBox5.TabStop = false; + this.groupBox5.Text = "页面发送到MES系统信息"; + // + // textBox_WEB_TO_MES + // + this.textBox_WEB_TO_MES.Dock = System.Windows.Forms.DockStyle.Fill; + this.textBox_WEB_TO_MES.Location = new System.Drawing.Point(3, 24); + this.textBox_WEB_TO_MES.Multiline = true; + this.textBox_WEB_TO_MES.Name = "textBox_WEB_TO_MES"; + this.textBox_WEB_TO_MES.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; + this.textBox_WEB_TO_MES.Size = new System.Drawing.Size(573, 69); + this.textBox_WEB_TO_MES.TabIndex = 1; + // + // groupBox1 + // + this.groupBox1.Controls.Add(this.textBox_PLC_TO_MES); + this.groupBox1.Location = new System.Drawing.Point(3, 3); + this.groupBox1.Name = "groupBox1"; + this.groupBox1.Size = new System.Drawing.Size(579, 96); + this.groupBox1.TabIndex = 0; + this.groupBox1.TabStop = false; + this.groupBox1.Text = "设备PLC信号"; + // + // textBox_PLC_TO_MES + // + this.textBox_PLC_TO_MES.Dock = System.Windows.Forms.DockStyle.Fill; + this.textBox_PLC_TO_MES.Location = new System.Drawing.Point(3, 24); + this.textBox_PLC_TO_MES.Multiline = true; + this.textBox_PLC_TO_MES.Name = "textBox_PLC_TO_MES"; + this.textBox_PLC_TO_MES.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; + this.textBox_PLC_TO_MES.Size = new System.Drawing.Size(573, 69); + this.textBox_PLC_TO_MES.TabIndex = 0; + // + // groupBox3 + // + this.groupBox3.Controls.Add(this.textBox_MES_TO_WEB); + this.groupBox3.Dock = System.Windows.Forms.DockStyle.Fill; + this.groupBox3.Location = new System.Drawing.Point(3, 105); + this.groupBox3.Name = "groupBox3"; + this.groupBox3.Size = new System.Drawing.Size(579, 147); + this.groupBox3.TabIndex = 2; + this.groupBox3.TabStop = false; + this.groupBox3.Text = "MES系统发送到页面信息"; + // + // textBox_MES_TO_WEB + // + this.textBox_MES_TO_WEB.Dock = System.Windows.Forms.DockStyle.Fill; + this.textBox_MES_TO_WEB.Location = new System.Drawing.Point(3, 24); + this.textBox_MES_TO_WEB.Multiline = true; + this.textBox_MES_TO_WEB.Name = "textBox_MES_TO_WEB"; + this.textBox_MES_TO_WEB.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; + this.textBox_MES_TO_WEB.Size = new System.Drawing.Size(573, 120); + this.textBox_MES_TO_WEB.TabIndex = 1; + // + // panel1 + // + this.panel1.Controls.Add(this.tableLayoutPanel3); + this.panel1.Dock = System.Windows.Forms.DockStyle.Fill; + this.panel1.Location = new System.Drawing.Point(588, 3); + this.panel1.Name = "panel1"; + this.panel1.Size = new System.Drawing.Size(294, 96); + this.panel1.TabIndex = 10; + // + // tableLayoutPanel3 + // + this.tableLayoutPanel3.ColumnCount = 4; + this.tableLayoutPanel3.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 30F)); + this.tableLayoutPanel3.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 20F)); + this.tableLayoutPanel3.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 20F)); + this.tableLayoutPanel3.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 30F)); + this.tableLayoutPanel3.Controls.Add(this.checkBox_PLC_TO_MES, 0, 0); + this.tableLayoutPanel3.Controls.Add(this.button_PLC_TO_MES_Clear, 3, 0); + this.tableLayoutPanel3.Controls.Add(this.button_PLC_TO_MES_Big, 2, 0); + this.tableLayoutPanel3.Controls.Add(this.button_PLC_TO_MES_Small, 1, 0); + this.tableLayoutPanel3.Dock = System.Windows.Forms.DockStyle.Fill; + this.tableLayoutPanel3.Location = new System.Drawing.Point(0, 0); + this.tableLayoutPanel3.Name = "tableLayoutPanel3"; + this.tableLayoutPanel3.RowCount = 2; + this.tableLayoutPanel3.RowStyles.Add(new System.Windows.Forms.RowStyle()); + this.tableLayoutPanel3.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F)); + this.tableLayoutPanel3.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 21F)); + this.tableLayoutPanel3.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 21F)); + this.tableLayoutPanel3.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 21F)); + this.tableLayoutPanel3.Size = new System.Drawing.Size(294, 96); + this.tableLayoutPanel3.TabIndex = 3; + // + // checkBox_PLC_TO_MES + // + this.checkBox_PLC_TO_MES.AutoSize = true; + this.checkBox_PLC_TO_MES.Dock = System.Windows.Forms.DockStyle.Fill; + this.checkBox_PLC_TO_MES.Location = new System.Drawing.Point(3, 3); + this.checkBox_PLC_TO_MES.Name = "checkBox_PLC_TO_MES"; + this.checkBox_PLC_TO_MES.Size = new System.Drawing.Size(82, 33); + this.checkBox_PLC_TO_MES.TabIndex = 0; + this.checkBox_PLC_TO_MES.Text = "监控"; + this.checkBox_PLC_TO_MES.UseVisualStyleBackColor = true; + // + // button_PLC_TO_MES_Clear + // + this.button_PLC_TO_MES_Clear.Dock = System.Windows.Forms.DockStyle.Fill; + this.button_PLC_TO_MES_Clear.Location = new System.Drawing.Point(207, 3); + this.button_PLC_TO_MES_Clear.Name = "button_PLC_TO_MES_Clear"; + this.button_PLC_TO_MES_Clear.Size = new System.Drawing.Size(84, 33); + this.button_PLC_TO_MES_Clear.TabIndex = 1; + this.button_PLC_TO_MES_Clear.Text = "清空"; + this.button_PLC_TO_MES_Clear.UseVisualStyleBackColor = true; + // + // button_PLC_TO_MES_Big + // + this.button_PLC_TO_MES_Big.Location = new System.Drawing.Point(149, 3); + this.button_PLC_TO_MES_Big.Name = "button_PLC_TO_MES_Big"; + this.button_PLC_TO_MES_Big.Size = new System.Drawing.Size(51, 30); + this.button_PLC_TO_MES_Big.TabIndex = 2; + this.button_PLC_TO_MES_Big.Text = "+"; + this.button_PLC_TO_MES_Big.UseVisualStyleBackColor = true; + // + // button_PLC_TO_MES_Small + // + this.button_PLC_TO_MES_Small.Location = new System.Drawing.Point(91, 3); + this.button_PLC_TO_MES_Small.Name = "button_PLC_TO_MES_Small"; + this.button_PLC_TO_MES_Small.Size = new System.Drawing.Size(51, 30); + this.button_PLC_TO_MES_Small.TabIndex = 2; + this.button_PLC_TO_MES_Small.Text = "-"; + this.button_PLC_TO_MES_Small.UseVisualStyleBackColor = true; + // + // panel3 + // + this.panel3.Controls.Add(this.tableLayoutPanel2); + this.panel3.Dock = System.Windows.Forms.DockStyle.Fill; + this.panel3.Location = new System.Drawing.Point(588, 105); + this.panel3.Name = "panel3"; + this.panel3.Size = new System.Drawing.Size(294, 147); + this.panel3.TabIndex = 12; + // + // tableLayoutPanel2 + // + this.tableLayoutPanel2.ColumnCount = 4; + this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 30F)); + 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, 30F)); + this.tableLayoutPanel2.Controls.Add(this.dataGridView_CheckOpName, 0, 1); + this.tableLayoutPanel2.Controls.Add(this.checkBox__MES_TO_WEB, 0, 0); + this.tableLayoutPanel2.Controls.Add(this.button_MES_TO_WEB_Clear, 3, 0); + this.tableLayoutPanel2.Controls.Add(this.button_MES_TO_WEB_Small, 1, 0); + this.tableLayoutPanel2.Controls.Add(this.button_MES_TO_WEB_Big, 2, 0); + this.tableLayoutPanel2.Dock = System.Windows.Forms.DockStyle.Fill; + this.tableLayoutPanel2.Location = new System.Drawing.Point(0, 0); + this.tableLayoutPanel2.Name = "tableLayoutPanel2"; + this.tableLayoutPanel2.RowCount = 2; + this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle()); + this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F)); + this.tableLayoutPanel2.Size = new System.Drawing.Size(294, 147); + this.tableLayoutPanel2.TabIndex = 1; + // + // dataGridView_CheckOpName + // + this.dataGridView_CheckOpName.AllowUserToAddRows = false; + this.dataGridView_CheckOpName.AllowUserToDeleteRows = false; + this.dataGridView_CheckOpName.AllowUserToResizeColumns = false; + this.dataGridView_CheckOpName.AllowUserToResizeRows = false; + this.dataGridView_CheckOpName.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; + this.dataGridView_CheckOpName.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { + this.选择, + this.工位号}); + this.tableLayoutPanel2.SetColumnSpan(this.dataGridView_CheckOpName, 4); + this.dataGridView_CheckOpName.Dock = System.Windows.Forms.DockStyle.Fill; + this.dataGridView_CheckOpName.Location = new System.Drawing.Point(3, 42); + this.dataGridView_CheckOpName.MultiSelect = false; + this.dataGridView_CheckOpName.Name = "dataGridView_CheckOpName"; + this.dataGridView_CheckOpName.RowHeadersVisible = false; + this.dataGridView_CheckOpName.RowHeadersWidth = 62; + this.dataGridView_CheckOpName.RowTemplate.Height = 30; + this.dataGridView_CheckOpName.Size = new System.Drawing.Size(288, 102); + this.dataGridView_CheckOpName.TabIndex = 3; + // + // 选择 + // + this.选择.DataPropertyName = "选择"; + this.选择.HeaderText = "选择"; + this.选择.MinimumWidth = 8; + this.选择.Name = "选择"; + this.选择.Width = 60; + // + // 工位号 + // + this.工位号.DataPropertyName = "工位号"; + this.工位号.HeaderText = "工位号"; + this.工位号.MinimumWidth = 8; + this.工位号.Name = "工位号"; + this.工位号.Resizable = System.Windows.Forms.DataGridViewTriState.True; + this.工位号.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable; + this.工位号.Width = 218; + // + // checkBox__MES_TO_WEB + // + this.checkBox__MES_TO_WEB.AutoSize = true; + this.checkBox__MES_TO_WEB.Dock = System.Windows.Forms.DockStyle.Fill; + this.checkBox__MES_TO_WEB.Location = new System.Drawing.Point(3, 3); + this.checkBox__MES_TO_WEB.Name = "checkBox__MES_TO_WEB"; + this.checkBox__MES_TO_WEB.Size = new System.Drawing.Size(82, 33); + this.checkBox__MES_TO_WEB.TabIndex = 0; + this.checkBox__MES_TO_WEB.Text = "监控"; + this.checkBox__MES_TO_WEB.UseVisualStyleBackColor = true; + // + // button_MES_TO_WEB_Clear + // + this.button_MES_TO_WEB_Clear.Dock = System.Windows.Forms.DockStyle.Fill; + this.button_MES_TO_WEB_Clear.Location = new System.Drawing.Point(207, 3); + this.button_MES_TO_WEB_Clear.Name = "button_MES_TO_WEB_Clear"; + this.button_MES_TO_WEB_Clear.Size = new System.Drawing.Size(84, 33); + this.button_MES_TO_WEB_Clear.TabIndex = 2; + this.button_MES_TO_WEB_Clear.Text = "清空"; + this.button_MES_TO_WEB_Clear.UseVisualStyleBackColor = true; + // + // button_MES_TO_WEB_Small + // + this.button_MES_TO_WEB_Small.Location = new System.Drawing.Point(91, 3); + this.button_MES_TO_WEB_Small.Name = "button_MES_TO_WEB_Small"; + this.button_MES_TO_WEB_Small.Size = new System.Drawing.Size(51, 30); + this.button_MES_TO_WEB_Small.TabIndex = 4; + this.button_MES_TO_WEB_Small.Text = "-"; + this.button_MES_TO_WEB_Small.UseVisualStyleBackColor = true; + // + // button_MES_TO_WEB_Big + // + this.button_MES_TO_WEB_Big.Location = new System.Drawing.Point(149, 3); + this.button_MES_TO_WEB_Big.Name = "button_MES_TO_WEB_Big"; + this.button_MES_TO_WEB_Big.Size = new System.Drawing.Size(51, 30); + this.button_MES_TO_WEB_Big.TabIndex = 4; + this.button_MES_TO_WEB_Big.Text = "+"; + this.button_MES_TO_WEB_Big.UseVisualStyleBackColor = true; + // + // panel4 + // + this.panel4.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; + this.panel4.Controls.Add(this.tableLayoutPanel4); + this.panel4.Dock = System.Windows.Forms.DockStyle.Fill; + this.panel4.Location = new System.Drawing.Point(588, 258); + this.panel4.Name = "panel4"; + this.panel4.Size = new System.Drawing.Size(294, 96); + this.panel4.TabIndex = 13; + // + // tableLayoutPanel4 + // + this.tableLayoutPanel4.ColumnCount = 4; + this.tableLayoutPanel4.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 30F)); + this.tableLayoutPanel4.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 20F)); + this.tableLayoutPanel4.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 20F)); + this.tableLayoutPanel4.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 30F)); + this.tableLayoutPanel4.Controls.Add(this.button_WEB_TO_MES_Big, 2, 0); + this.tableLayoutPanel4.Controls.Add(this.button_WEB_TO_MES_Small, 1, 0); + this.tableLayoutPanel4.Controls.Add(this.checkBox_WEB_TO_MES, 0, 0); + this.tableLayoutPanel4.Controls.Add(this.button_WEB_TO_MES_Clear, 3, 0); + this.tableLayoutPanel4.Dock = System.Windows.Forms.DockStyle.Fill; + this.tableLayoutPanel4.Location = new System.Drawing.Point(0, 0); + this.tableLayoutPanel4.Name = "tableLayoutPanel4"; + this.tableLayoutPanel4.RowCount = 2; + this.tableLayoutPanel4.RowStyles.Add(new System.Windows.Forms.RowStyle()); + this.tableLayoutPanel4.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F)); + this.tableLayoutPanel4.Size = new System.Drawing.Size(292, 94); + this.tableLayoutPanel4.TabIndex = 0; + // + // button_WEB_TO_MES_Big + // + this.button_WEB_TO_MES_Big.Location = new System.Drawing.Point(148, 3); + this.button_WEB_TO_MES_Big.Name = "button_WEB_TO_MES_Big"; + this.button_WEB_TO_MES_Big.Size = new System.Drawing.Size(51, 30); + this.button_WEB_TO_MES_Big.TabIndex = 6; + this.button_WEB_TO_MES_Big.Text = "+"; + this.button_WEB_TO_MES_Big.UseVisualStyleBackColor = true; + // + // button_WEB_TO_MES_Small + // + this.button_WEB_TO_MES_Small.Location = new System.Drawing.Point(90, 3); + this.button_WEB_TO_MES_Small.Name = "button_WEB_TO_MES_Small"; + this.button_WEB_TO_MES_Small.Size = new System.Drawing.Size(51, 30); + this.button_WEB_TO_MES_Small.TabIndex = 5; + this.button_WEB_TO_MES_Small.Text = "-"; + this.button_WEB_TO_MES_Small.UseVisualStyleBackColor = true; + // + // checkBox_WEB_TO_MES + // + this.checkBox_WEB_TO_MES.AutoSize = true; + this.checkBox_WEB_TO_MES.Dock = System.Windows.Forms.DockStyle.Fill; + this.checkBox_WEB_TO_MES.Location = new System.Drawing.Point(3, 3); + this.checkBox_WEB_TO_MES.Name = "checkBox_WEB_TO_MES"; + this.checkBox_WEB_TO_MES.Size = new System.Drawing.Size(81, 33); + this.checkBox_WEB_TO_MES.TabIndex = 0; + this.checkBox_WEB_TO_MES.Text = "监控"; + this.checkBox_WEB_TO_MES.UseVisualStyleBackColor = true; + // + // button_WEB_TO_MES_Clear + // + this.button_WEB_TO_MES_Clear.Dock = System.Windows.Forms.DockStyle.Fill; + this.button_WEB_TO_MES_Clear.Location = new System.Drawing.Point(206, 3); + this.button_WEB_TO_MES_Clear.Name = "button_WEB_TO_MES_Clear"; + this.button_WEB_TO_MES_Clear.Size = new System.Drawing.Size(83, 33); + this.button_WEB_TO_MES_Clear.TabIndex = 1; + this.button_WEB_TO_MES_Clear.Text = "清空"; + this.button_WEB_TO_MES_Clear.UseVisualStyleBackColor = true; + // + // panel5 + // + this.panel5.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; + this.panel5.Controls.Add(this.comboBox1); + this.panel5.Controls.Add(this.textBox_MqttText); + this.panel5.Dock = System.Windows.Forms.DockStyle.Fill; + this.panel5.Location = new System.Drawing.Point(589, 360); + this.panel5.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); + this.panel5.Name = "panel5"; + this.panel5.Size = new System.Drawing.Size(292, 149); + this.panel5.TabIndex = 14; + // + // comboBox1 + // + this.comboBox1.FormattingEnabled = true; + this.comboBox1.Location = new System.Drawing.Point(4, 9); + this.comboBox1.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); + this.comboBox1.Name = "comboBox1"; + this.comboBox1.Size = new System.Drawing.Size(280, 26); + this.comboBox1.TabIndex = 4; + // + // textBox_MqttText + // + this.textBox_MqttText.Location = new System.Drawing.Point(4, 48); + this.textBox_MqttText.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); + this.textBox_MqttText.Multiline = true; + this.textBox_MqttText.Name = "textBox_MqttText"; + this.textBox_MqttText.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; + this.textBox_MqttText.Size = new System.Drawing.Size(277, 139); + this.textBox_MqttText.TabIndex = 15; + // + // panel2 + // + this.panel2.Controls.Add(this.tableLayoutPanel5); + this.panel2.Dock = System.Windows.Forms.DockStyle.Fill; + this.panel2.Location = new System.Drawing.Point(4, 360); + this.panel2.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); + this.panel2.Name = "panel2"; + this.panel2.Size = new System.Drawing.Size(577, 149); + this.panel2.TabIndex = 15; + // + // tableLayoutPanel5 + // + this.tableLayoutPanel5.ColumnCount = 2; + this.tableLayoutPanel5.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); + this.tableLayoutPanel5.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 300F)); + this.tableLayoutPanel5.Controls.Add(this.panel6, 1, 0); + this.tableLayoutPanel5.Controls.Add(this.tabControl1, 0, 0); + this.tableLayoutPanel5.Dock = System.Windows.Forms.DockStyle.Fill; + this.tableLayoutPanel5.Location = new System.Drawing.Point(0, 0); + this.tableLayoutPanel5.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); + this.tableLayoutPanel5.Name = "tableLayoutPanel5"; + this.tableLayoutPanel5.RowCount = 1; + this.tableLayoutPanel5.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F)); + this.tableLayoutPanel5.Size = new System.Drawing.Size(577, 149); + this.tableLayoutPanel5.TabIndex = 0; + // + // panel6 + // + this.panel6.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; + this.panel6.Controls.Add(this.button_SaveData); + this.panel6.Controls.Add(this.label1); + this.panel6.Controls.Add(this.label3); + this.panel6.Controls.Add(this.comboBox_OpNameList); + this.panel6.Controls.Add(this.label2); + this.panel6.Controls.Add(this.button_ToWEB); + this.panel6.Controls.Add(this.button_WebToMES); + this.panel6.Dock = System.Windows.Forms.DockStyle.Fill; + this.panel6.Location = new System.Drawing.Point(281, 3); + this.panel6.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); + this.panel6.Name = "panel6"; + this.panel6.Size = new System.Drawing.Size(292, 143); + this.panel6.TabIndex = 0; + // + // button_SaveData + // + this.button_SaveData.Location = new System.Drawing.Point(20, 142); + this.button_SaveData.Name = "button_SaveData"; + this.button_SaveData.Size = new System.Drawing.Size(84, 27); + this.button_SaveData.TabIndex = 4; + this.button_SaveData.Text = "保存质量数据"; + this.button_SaveData.UseVisualStyleBackColor = true; + // + // label1 + // + this.label1.AutoSize = true; + this.label1.Location = new System.Drawing.Point(6, 9); + this.label1.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); + this.label1.Name = "label1"; + this.label1.Size = new System.Drawing.Size(62, 18); + this.label1.TabIndex = 2; + this.label1.Text = "工位号"; + // + // label3 + // + this.label3.AutoSize = true; + this.label3.Location = new System.Drawing.Point(94, 93); + this.label3.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); + this.label3.Name = "label3"; + this.label3.Size = new System.Drawing.Size(188, 18); + this.label3.TabIndex = 3; + this.label3.Text = "WEB|CMD|OpName|Walue"; + // + // comboBox_OpNameList + // + this.comboBox_OpNameList.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; + this.comboBox_OpNameList.FormattingEnabled = true; + this.comboBox_OpNameList.Location = new System.Drawing.Point(76, 3); + this.comboBox_OpNameList.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); + this.comboBox_OpNameList.Name = "comboBox_OpNameList"; + this.comboBox_OpNameList.Size = new System.Drawing.Size(208, 26); + this.comboBox_OpNameList.TabIndex = 1; + // + // label2 + // + this.label2.AutoSize = true; + this.label2.Location = new System.Drawing.Point(94, 51); + this.label2.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); + this.label2.Name = "label2"; + this.label2.Size = new System.Drawing.Size(188, 18); + this.label2.TabIndex = 3; + this.label2.Text = "MES|CMD|OpName|Walue"; + // + // button_ToWEB + // + this.button_ToWEB.Location = new System.Drawing.Point(8, 45); + this.button_ToWEB.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); + this.button_ToWEB.Name = "button_ToWEB"; + this.button_ToWEB.Size = new System.Drawing.Size(78, 33); + this.button_ToWEB.TabIndex = 0; + this.button_ToWEB.Text = "到页面"; + this.button_ToWEB.UseVisualStyleBackColor = true; + // + // button_WebToMES + // + this.button_WebToMES.Location = new System.Drawing.Point(9, 87); + this.button_WebToMES.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); + this.button_WebToMES.Name = "button_WebToMES"; + this.button_WebToMES.Size = new System.Drawing.Size(76, 33); + this.button_WebToMES.TabIndex = 0; + this.button_WebToMES.Text = "到业务"; + this.button_WebToMES.UseVisualStyleBackColor = true; + // + // tabControl1 + // + this.tabControl1.Controls.Add(this.tabPage6); + this.tabControl1.Controls.Add(this.tabPage1); + this.tabControl1.Controls.Add(this.tabPage2); + this.tabControl1.Controls.Add(this.tabPage3); + this.tabControl1.Controls.Add(this.tabPage4); + this.tabControl1.Controls.Add(this.tabPage5); + this.tabControl1.Dock = System.Windows.Forms.DockStyle.Fill; + this.tabControl1.Location = new System.Drawing.Point(4, 3); + this.tabControl1.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); + this.tabControl1.Name = "tabControl1"; + this.tabControl1.SelectedIndex = 0; + this.tabControl1.Size = new System.Drawing.Size(269, 143); + this.tabControl1.TabIndex = 1; + // + // tabPage6 + // + this.tabPage6.Location = new System.Drawing.Point(4, 28); + this.tabPage6.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); + this.tabPage6.Name = "tabPage6"; + this.tabPage6.Size = new System.Drawing.Size(261, 111); + this.tabPage6.TabIndex = 5; + this.tabPage6.Text = "订单信息"; + this.tabPage6.UseVisualStyleBackColor = true; + // + // tabPage1 + // + this.tabPage1.Location = new System.Drawing.Point(4, 28); + this.tabPage1.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); + this.tabPage1.Name = "tabPage1"; + this.tabPage1.Padding = new System.Windows.Forms.Padding(4, 3, 4, 3); + this.tabPage1.Size = new System.Drawing.Size(259, 110); + this.tabPage1.TabIndex = 0; + this.tabPage1.Text = "产品信息"; + this.tabPage1.UseVisualStyleBackColor = true; + // + // tabPage2 + // + this.tabPage2.Location = new System.Drawing.Point(4, 28); + this.tabPage2.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); + this.tabPage2.Name = "tabPage2"; + this.tabPage2.Padding = new System.Windows.Forms.Padding(4, 3, 4, 3); + this.tabPage2.Size = new System.Drawing.Size(259, 110); + this.tabPage2.TabIndex = 1; + this.tabPage2.Text = "工步信息"; + this.tabPage2.UseVisualStyleBackColor = true; + // + // tabPage3 + // + this.tabPage3.Location = new System.Drawing.Point(4, 28); + this.tabPage3.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); + this.tabPage3.Name = "tabPage3"; + this.tabPage3.Size = new System.Drawing.Size(259, 110); + this.tabPage3.TabIndex = 2; + this.tabPage3.Text = "物料信息"; + this.tabPage3.UseVisualStyleBackColor = true; + // + // tabPage4 + // + this.tabPage4.Location = new System.Drawing.Point(4, 28); + this.tabPage4.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); + this.tabPage4.Name = "tabPage4"; + this.tabPage4.Size = new System.Drawing.Size(259, 110); + this.tabPage4.TabIndex = 3; + this.tabPage4.Text = "操作图片"; + this.tabPage4.UseVisualStyleBackColor = true; + // + // tabPage5 + // + this.tabPage5.Location = new System.Drawing.Point(4, 28); + this.tabPage5.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); + this.tabPage5.Name = "tabPage5"; + this.tabPage5.Size = new System.Drawing.Size(259, 110); + this.tabPage5.TabIndex = 4; + this.tabPage5.Text = "PLC信号"; + this.tabPage5.UseVisualStyleBackColor = true; + // + // btn_MqttStatus + // + this.btn_MqttStatus.Location = new System.Drawing.Point(1210, 10); + this.btn_MqttStatus.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); + this.btn_MqttStatus.Name = "btn_MqttStatus"; + this.btn_MqttStatus.Size = new System.Drawing.Size(242, 58); + this.btn_MqttStatus.TabIndex = 4; + this.btn_MqttStatus.Text = "MQTT服务状态"; + this.btn_MqttStatus.UseVisualStyleBackColor = true; + // + // panel7 + // + this.panel7.Controls.Add(this.button3); + this.panel7.Controls.Add(this.button1); + this.panel7.Controls.Add(this.button2); + this.panel7.Controls.Add(this.cb_QdData); + this.panel7.Controls.Add(this.cb_MonitorData); + this.panel7.Controls.Add(this.btn_MqttStatus); + this.panel7.Controls.Add(this.listView_ShowQualityData); + this.panel7.Controls.Add(this.label5); + this.panel7.Controls.Add(this.comboBox_OpName); + this.panel7.Controls.Add(this.button_ReadData); + this.panel7.Controls.Add(this.label4); + this.panel7.Controls.Add(this.richTextBox1_mqtt); + this.panel7.Location = new System.Drawing.Point(14, 38); + this.panel7.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); + this.panel7.Name = "panel7"; + this.panel7.Size = new System.Drawing.Size(1466, 974); + this.panel7.TabIndex = 5; + // + // button3 + // + this.button3.Location = new System.Drawing.Point(585, 10); + this.button3.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); + this.button3.Name = "button3"; + this.button3.Size = new System.Drawing.Size(112, 34); + this.button3.TabIndex = 1478; + this.button3.Text = "button1"; + this.button3.UseVisualStyleBackColor = true; + this.button3.Click += new System.EventHandler(this.button3_Click); + // + // button1 + // + this.button1.Location = new System.Drawing.Point(464, 10); + this.button1.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); + this.button1.Name = "button1"; + this.button1.Size = new System.Drawing.Size(112, 34); + this.button1.TabIndex = 1478; + this.button1.Text = "button1"; + this.button1.UseVisualStyleBackColor = true; + this.button1.Click += new System.EventHandler(this.button1_Click); + // + // button2 + // + this.button2.Location = new System.Drawing.Point(966, 10); + this.button2.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); + this.button2.Name = "button2"; + this.button2.Size = new System.Drawing.Size(237, 54); + this.button2.TabIndex = 1477; + this.button2.Text = "初始化报警"; + this.button2.UseVisualStyleBackColor = true; + this.button2.Click += new System.EventHandler(this.button2_Click); + // + // cb_QdData + // + this.cb_QdData.AutoSize = true; + this.cb_QdData.Location = new System.Drawing.Point(16, 40); + this.cb_QdData.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); + this.cb_QdData.Name = "cb_QdData"; + this.cb_QdData.Size = new System.Drawing.Size(106, 22); + this.cb_QdData.TabIndex = 1475; + this.cb_QdData.Text = "质量数据"; + this.cb_QdData.UseVisualStyleBackColor = true; + // + // cb_MonitorData + // + this.cb_MonitorData.AutoSize = true; + this.cb_MonitorData.Location = new System.Drawing.Point(16, 10); + this.cb_MonitorData.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); + this.cb_MonitorData.Name = "cb_MonitorData"; + this.cb_MonitorData.Size = new System.Drawing.Size(106, 22); + this.cb_MonitorData.TabIndex = 1476; + this.cb_MonitorData.Text = "监控数据"; + this.cb_MonitorData.UseVisualStyleBackColor = true; + // + // listView_ShowQualityData + // + this.listView_ShowQualityData.AllowColumnReorder = true; + this.listView_ShowQualityData.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { + this.columnHeader1, + this.columnHeader2, + this.columnHeader3, + this.columnHeader4, + this.columnHeader5}); + this.listView_ShowQualityData.FullRowSelect = true; + this.listView_ShowQualityData.GridLines = true; + this.listView_ShowQualityData.HideSelection = false; + this.listView_ShowQualityData.Location = new System.Drawing.Point(16, 70); + this.listView_ShowQualityData.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2); + this.listView_ShowQualityData.Name = "listView_ShowQualityData"; + this.listView_ShowQualityData.ShowItemToolTips = true; + this.listView_ShowQualityData.Size = new System.Drawing.Size(736, 900); + this.listView_ShowQualityData.TabIndex = 1473; + this.listView_ShowQualityData.UseCompatibleStateImageBehavior = false; + this.listView_ShowQualityData.View = System.Windows.Forms.View.Details; + this.listView_ShowQualityData.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(this.listView_ShowQualityData_MouseDoubleClick); + // + // columnHeader1 + // + this.columnHeader1.Text = "TagID"; + this.columnHeader1.Width = 70; + // + // columnHeader2 + // + this.columnHeader2.Text = "测量项目"; + this.columnHeader2.Width = 130; + // + // columnHeader3 + // + this.columnHeader3.Text = "值"; + this.columnHeader3.Width = 100; + // + // columnHeader4 + // + this.columnHeader4.Text = "工位号"; + this.columnHeader4.Width = 70; + // + // columnHeader5 + // + this.columnHeader5.Text = "地址"; + this.columnHeader5.Width = 100; + // + // label5 + // + this.label5.AutoSize = true; + this.label5.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.label5.Location = new System.Drawing.Point(136, 10); + this.label5.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); + this.label5.Name = "label5"; + this.label5.Size = new System.Drawing.Size(98, 18); + this.label5.TabIndex = 1471; + this.label5.Text = "工位编号:"; + // + // comboBox_OpName + // + this.comboBox_OpName.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; + this.comboBox_OpName.Font = new System.Drawing.Font("宋体", 12F); + this.comboBox_OpName.FormattingEnabled = true; + this.comboBox_OpName.Location = new System.Drawing.Point(140, 32); + this.comboBox_OpName.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); + this.comboBox_OpName.Name = "comboBox_OpName"; + this.comboBox_OpName.Size = new System.Drawing.Size(132, 32); + this.comboBox_OpName.TabIndex = 1472; + this.comboBox_OpName.SelectedIndexChanged += new System.EventHandler(this.comboBox_OpName_SelectedIndexChanged); + // + // button_ReadData + // + this.button_ReadData.Location = new System.Drawing.Point(280, 28); + this.button_ReadData.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); + this.button_ReadData.Name = "button_ReadData"; + this.button_ReadData.Size = new System.Drawing.Size(93, 39); + this.button_ReadData.TabIndex = 1474; + this.button_ReadData.Text = "读取数据"; + this.button_ReadData.UseVisualStyleBackColor = true; + this.button_ReadData.Click += new System.EventHandler(this.button_ReadData_Click); + // + // label4 + // + this.label4.AutoSize = true; + this.label4.Location = new System.Drawing.Point(770, 46); + this.label4.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); + this.label4.Name = "label4"; + this.label4.Size = new System.Drawing.Size(44, 18); + this.label4.TabIndex = 1; + this.label4.Text = "日志"; + // + // richTextBox1_mqtt + // + this.richTextBox1_mqtt.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; + this.richTextBox1_mqtt.Location = new System.Drawing.Point(765, 70); + this.richTextBox1_mqtt.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); + this.richTextBox1_mqtt.Name = "richTextBox1_mqtt"; + this.richTextBox1_mqtt.ReadOnly = true; + this.richTextBox1_mqtt.Size = new System.Drawing.Size(686, 900); + this.richTextBox1_mqtt.TabIndex = 0; + this.richTextBox1_mqtt.Text = ""; + // + // timer_Status + // + this.timer_Status.Enabled = true; + this.timer_Status.Tick += new System.EventHandler(this.timer_Status_Tick); + // + // statusStrip1 + // + this.statusStrip1.ImageScalingSize = new System.Drawing.Size(20, 20); + this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { + this.toolStripStatusLabel_RunningStatu, + this.toolStripStatusLabel_RunningStatus, + this.toolStripStatusLabel2, + this.toolStripStatusLabel_StartTime, + this.toolStripStatusLabel3, + this.toolStripStatusLabel_RunTime, + this.toolStripStatusLabel1, + this.toolStripStatusLabel_WorkStationNum, + this.toolStripStatusLabel6, + this.toolStripStatusLabel_OnlineNum, + this.toolStripStatusLabel8, + this.toolStripStatusLabel_DownLine, + this.toolStripStatusLabel4, + this.toolStripStatusLabel_Version}); + this.statusStrip1.Location = new System.Drawing.Point(0, 1019); + this.statusStrip1.Name = "statusStrip1"; + this.statusStrip1.Padding = new System.Windows.Forms.Padding(2, 0, 21, 0); + this.statusStrip1.Size = new System.Drawing.Size(1497, 35); + this.statusStrip1.TabIndex = 1479; + this.statusStrip1.Text = "statusStrip1"; + // + // toolStripStatusLabel_RunningStatu + // + this.toolStripStatusLabel_RunningStatu.Name = "toolStripStatusLabel_RunningStatu"; + this.toolStripStatusLabel_RunningStatu.Size = new System.Drawing.Size(100, 28); + this.toolStripStatusLabel_RunningStatu.Text = "运行状态:"; + // + // toolStripStatusLabel_RunningStatus + // + this.toolStripStatusLabel_RunningStatus.ActiveLinkColor = System.Drawing.Color.Red; + this.toolStripStatusLabel_RunningStatus.AutoSize = false; + this.toolStripStatusLabel_RunningStatus.BackColor = System.Drawing.Color.Yellow; + this.toolStripStatusLabel_RunningStatus.Name = "toolStripStatusLabel_RunningStatus"; + this.toolStripStatusLabel_RunningStatus.Size = new System.Drawing.Size(62, 28); + this.toolStripStatusLabel_RunningStatus.Text = "变量模拟"; + // + // toolStripStatusLabel2 + // + this.toolStripStatusLabel2.BorderSides = System.Windows.Forms.ToolStripStatusLabelBorderSides.Left; + this.toolStripStatusLabel2.Name = "toolStripStatusLabel2"; + this.toolStripStatusLabel2.Size = new System.Drawing.Size(104, 28); + this.toolStripStatusLabel2.Text = "启动时间:"; + // + // toolStripStatusLabel_StartTime + // + this.toolStripStatusLabel_StartTime.AutoSize = false; + this.toolStripStatusLabel_StartTime.BorderSides = System.Windows.Forms.ToolStripStatusLabelBorderSides.Right; + this.toolStripStatusLabel_StartTime.Name = "toolStripStatusLabel_StartTime"; + this.toolStripStatusLabel_StartTime.Size = new System.Drawing.Size(130, 28); + this.toolStripStatusLabel_StartTime.Text = "2018/08/08 08:08:08"; + // + // toolStripStatusLabel3 + // + this.toolStripStatusLabel3.Name = "toolStripStatusLabel3"; + this.toolStripStatusLabel3.Size = new System.Drawing.Size(100, 28); + this.toolStripStatusLabel3.Text = "运行时长:"; + // + // toolStripStatusLabel_RunTime + // + this.toolStripStatusLabel_RunTime.AutoSize = false; + this.toolStripStatusLabel_RunTime.BorderSides = System.Windows.Forms.ToolStripStatusLabelBorderSides.Right; + this.toolStripStatusLabel_RunTime.Name = "toolStripStatusLabel_RunTime"; + this.toolStripStatusLabel_RunTime.Size = new System.Drawing.Size(145, 28); + this.toolStripStatusLabel_RunTime.Text = "0天0小时0分0秒"; + // + // toolStripStatusLabel1 + // + this.toolStripStatusLabel1.Name = "toolStripStatusLabel1"; + this.toolStripStatusLabel1.Size = new System.Drawing.Size(100, 28); + this.toolStripStatusLabel1.Text = "工位数量:"; + // + // toolStripStatusLabel_WorkStationNum + // + this.toolStripStatusLabel_WorkStationNum.AutoSize = false; + this.toolStripStatusLabel_WorkStationNum.BorderSides = System.Windows.Forms.ToolStripStatusLabelBorderSides.Right; + this.toolStripStatusLabel_WorkStationNum.Name = "toolStripStatusLabel_WorkStationNum"; + this.toolStripStatusLabel_WorkStationNum.Size = new System.Drawing.Size(35, 28); + this.toolStripStatusLabel_WorkStationNum.Text = "100"; + // + // toolStripStatusLabel6 + // + this.toolStripStatusLabel6.Name = "toolStripStatusLabel6"; + this.toolStripStatusLabel6.Size = new System.Drawing.Size(100, 28); + this.toolStripStatusLabel6.Text = "在线数量:"; + // + // toolStripStatusLabel_OnlineNum + // + this.toolStripStatusLabel_OnlineNum.AutoSize = false; + this.toolStripStatusLabel_OnlineNum.BorderSides = System.Windows.Forms.ToolStripStatusLabelBorderSides.Right; + this.toolStripStatusLabel_OnlineNum.Name = "toolStripStatusLabel_OnlineNum"; + this.toolStripStatusLabel_OnlineNum.Size = new System.Drawing.Size(35, 28); + this.toolStripStatusLabel_OnlineNum.Text = "0"; + // + // toolStripStatusLabel8 + // + this.toolStripStatusLabel8.Name = "toolStripStatusLabel8"; + this.toolStripStatusLabel8.Size = new System.Drawing.Size(100, 28); + this.toolStripStatusLabel8.Text = "离线数量:"; + // + // toolStripStatusLabel_DownLine + // + this.toolStripStatusLabel_DownLine.AutoSize = false; + this.toolStripStatusLabel_DownLine.BorderSides = System.Windows.Forms.ToolStripStatusLabelBorderSides.Right; + this.toolStripStatusLabel_DownLine.Name = "toolStripStatusLabel_DownLine"; + this.toolStripStatusLabel_DownLine.Size = new System.Drawing.Size(35, 28); + this.toolStripStatusLabel_DownLine.Text = "0"; + // + // toolStripStatusLabel4 + // + this.toolStripStatusLabel4.Name = "toolStripStatusLabel4"; + this.toolStripStatusLabel4.Size = new System.Drawing.Size(64, 28); + this.toolStripStatusLabel4.Text = "版本:"; + // + // toolStripStatusLabel_Version + // + this.toolStripStatusLabel_Version.Name = "toolStripStatusLabel_Version"; + this.toolStripStatusLabel_Version.Size = new System.Drawing.Size(62, 28); + this.toolStripStatusLabel_Version.Text = "8.6.12"; + // + // timer_TestPLC + // + this.timer_TestPLC.Interval = 1000; + this.timer_TestPLC.Tick += new System.EventHandler(this.timer_TestPLC_Tick); + // + // MisDataFun + // + this.AutoScaleDimensions = new System.Drawing.SizeF(9F, 18F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(1497, 1054); + this.Controls.Add(this.statusStrip1); + this.Controls.Add(this.panel7); + this.Controls.Add(this.tableLayoutPanel1); + this.Controls.Add(this.menuStrip1); + this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); + this.MainMenuStrip = this.menuStrip1; + this.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); + this.MaximumSize = new System.Drawing.Size(2863, 1577); + this.MinimumSize = new System.Drawing.Size(1464, 1030); + this.Name = "MisDataFun"; + this.Text = "MesServer Function V2024-01-17"; + this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.MisDataFun_FormClosing); + this.Load += new System.EventHandler(this.SaveData_Load); + this.menuStrip1.ResumeLayout(false); + this.menuStrip1.PerformLayout(); + this.tableLayoutPanel1.ResumeLayout(false); + this.groupBox5.ResumeLayout(false); + this.groupBox5.PerformLayout(); + this.groupBox1.ResumeLayout(false); + this.groupBox1.PerformLayout(); + this.groupBox3.ResumeLayout(false); + this.groupBox3.PerformLayout(); + this.panel1.ResumeLayout(false); + this.tableLayoutPanel3.ResumeLayout(false); + this.tableLayoutPanel3.PerformLayout(); + this.panel3.ResumeLayout(false); + this.tableLayoutPanel2.ResumeLayout(false); + this.tableLayoutPanel2.PerformLayout(); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView_CheckOpName)).EndInit(); + this.panel4.ResumeLayout(false); + this.tableLayoutPanel4.ResumeLayout(false); + this.tableLayoutPanel4.PerformLayout(); + this.panel5.ResumeLayout(false); + this.panel5.PerformLayout(); + this.panel2.ResumeLayout(false); + this.tableLayoutPanel5.ResumeLayout(false); + this.panel6.ResumeLayout(false); + this.panel6.PerformLayout(); + this.tabControl1.ResumeLayout(false); + this.panel7.ResumeLayout(false); + this.panel7.PerformLayout(); + this.statusStrip1.ResumeLayout(false); + this.statusStrip1.PerformLayout(); + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + private System.Windows.Forms.MenuStrip menuStrip1; + private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; + private System.Windows.Forms.GroupBox groupBox1; + private System.Windows.Forms.TextBox textBox_PLC_TO_MES; + private System.Windows.Forms.Button button_WEB_TO_MES_Clear; + private System.Windows.Forms.CheckBox checkBox_WEB_TO_MES; + private System.Windows.Forms.GroupBox groupBox3; + private System.Windows.Forms.TextBox textBox_MES_TO_WEB; + private System.Windows.Forms.GroupBox groupBox5; + private System.Windows.Forms.TextBox textBox_WEB_TO_MES; + private System.Windows.Forms.Panel panel1; + private System.Windows.Forms.TableLayoutPanel tableLayoutPanel3; + private System.Windows.Forms.CheckBox checkBox_PLC_TO_MES; + private System.Windows.Forms.Button button_PLC_TO_MES_Clear; + private System.Windows.Forms.Button button_PLC_TO_MES_Big; + private System.Windows.Forms.Button button_PLC_TO_MES_Small; + private System.Windows.Forms.Panel panel3; + private System.Windows.Forms.TableLayoutPanel tableLayoutPanel2; + private System.Windows.Forms.DataGridView dataGridView_CheckOpName; + private System.Windows.Forms.DataGridViewCheckBoxColumn 选择; + private System.Windows.Forms.DataGridViewTextBoxColumn 工位号; + private System.Windows.Forms.CheckBox checkBox__MES_TO_WEB; + private System.Windows.Forms.Button button_MES_TO_WEB_Clear; + private System.Windows.Forms.Button button_MES_TO_WEB_Small; + private System.Windows.Forms.Button button_MES_TO_WEB_Big; + private System.Windows.Forms.Panel panel4; + private System.Windows.Forms.TableLayoutPanel tableLayoutPanel4; + private System.Windows.Forms.Button button_WEB_TO_MES_Big; + private System.Windows.Forms.Button button_WEB_TO_MES_Small; + private System.Windows.Forms.Panel panel5; + private System.Windows.Forms.Button button_WebToMES; + private System.Windows.Forms.Button button_ToWEB; + private System.Windows.Forms.TextBox textBox_MqttText; + private System.Windows.Forms.Label label1; + private System.Windows.Forms.ComboBox comboBox_OpNameList; + private System.Windows.Forms.Label label2; + private System.Windows.Forms.Label label3; + private System.Windows.Forms.ToolStripMenuItem ToolStripMenuItem_PlcDebug; + private System.Windows.Forms.ComboBox comboBox1; + private System.Windows.Forms.Panel panel2; + private System.Windows.Forms.TableLayoutPanel tableLayoutPanel5; + private System.Windows.Forms.Panel panel6; + private System.Windows.Forms.TabControl tabControl1; + private System.Windows.Forms.TabPage tabPage1; + private System.Windows.Forms.TabPage tabPage2; + private System.Windows.Forms.TabPage tabPage3; + private System.Windows.Forms.TabPage tabPage4; + private System.Windows.Forms.TabPage tabPage5; + private System.Windows.Forms.TabPage tabPage6; + private System.Windows.Forms.Button button_SaveData; + private System.Windows.Forms.Button btn_MqttStatus; + private System.Windows.Forms.Panel panel7; + private System.Windows.Forms.RichTextBox richTextBox1_mqtt; + private System.Windows.Forms.Label label4; + private System.Windows.Forms.Timer timer_Status; + private System.Windows.Forms.ListView listView_ShowQualityData; + private System.Windows.Forms.ColumnHeader columnHeader1; + private System.Windows.Forms.ColumnHeader columnHeader2; + private System.Windows.Forms.ColumnHeader columnHeader3; + private System.Windows.Forms.ColumnHeader columnHeader4; + private System.Windows.Forms.ColumnHeader columnHeader5; + private System.Windows.Forms.Label label5; + private System.Windows.Forms.ComboBox comboBox_OpName; + private System.Windows.Forms.Button button_ReadData; + private System.Windows.Forms.CheckBox cb_QdData; + private System.Windows.Forms.CheckBox cb_MonitorData; + private System.Windows.Forms.StatusStrip statusStrip1; + private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel_RunningStatu; + private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel_RunningStatus; + private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel2; + private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel_StartTime; + private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel3; + private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel_RunTime; + private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel1; + private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel_WorkStationNum; + private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel6; + private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel_OnlineNum; + private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel8; + private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel_DownLine; + private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel4; + private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel_Version; + private System.Windows.Forms.ToolStripMenuItem 修改配置文件ToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem 帮助ToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem 版本信息ToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem 关于迈思ToolStripMenuItem; + private System.Windows.Forms.Timer timer_TestPLC; + private System.Windows.Forms.Button button2; + private System.Windows.Forms.Button button1; + private System.Windows.Forms.Button button3; + } +} + diff --git a/MisDataFun/MisDataFun/MisDataFun.cs b/MisDataFun/MisDataFun/MisDataFun.cs new file mode 100644 index 0000000..37af2ce --- /dev/null +++ b/MisDataFun/MisDataFun/MisDataFun.cs @@ -0,0 +1,1060 @@ +using bizFacade; +using DataLinkMesWork; +using DataLinkMesWork2; +//using DataMirrorToolsPage; +using MesDataFunction; +using MesServerFunctions; +using MesServerWork; +using MesWork; +using MesWork.PLC; +using MesWorkMqtt; +using MisDataFun; +using MQTTnet; +using MQTTnet.Client.Connecting; +using MQTTnet.Client.Disconnecting; +using MQTTnet.Client.Receiving; +using MQTTnet.Extensions.ManagedClient; +using MQTTnet.Protocol; +using NPOI.SS.UserModel; +using NPOI.XWPF.UserModel; +using OpcData; +using System; +using System.Collections; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.ComponentModel; +using System.Configuration; +using System.Data; +using System.Data.SqlClient; +using System.Diagnostics; +using System.Drawing; +using System.Linq; +using System.Runtime.Remoting.Metadata.W3cXsd2001; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using System.Windows.Forms; +using SystemFramework; +using static NPOI.HSSF.Util.HSSFColor; +using static System.Net.Mime.MediaTypeNames; + +namespace MisDataSaveDate +{ + /// + /// + /// + /// + /// + public delegate void RefreshForm(object obj1, EventArgs obj2); + public partial class MisDataFun: Form + { + static Hashtable hashtableTopicList = new Hashtable(); + static bool OnLineMqtt = false; + private WebApi.InitServer initServer = null; + /// + /// + /// + public static int IsWriteMonitorLog = Convert.ToInt32(ConfigurationManager.AppSettings["IsWriteMonitorLog"]); + /// + /// + /// + public static int IsDemoMesServer = Convert.ToInt32(ConfigurationManager.AppSettings["IsDemoMesServer"]); + public static string IsRecordTagStatus = ConfigurationManager.AppSettings["IsRecordTagStatus"]; + static bool loadFinish = false; + /// + /// 允许使用附加功能的变量,只有在系统开始加载Tag时,才允许读取PLC数据 + /// + public static bool AllowLoad; + /// + /// + /// + List opNameList; + /// + /// + /// + DateTime StartTime; + /// + /// + /// + /// + /// + public delegate void RefreshForm(object obj1, EventArgs obj2); + /// + /// + /// + public static RefreshForm MainFormRefresh, TestPlcStatusDel; + public BasicData.QualityDataType[] ThisWorkStationData { get; set; } + + public MisDataFun() + { + InitializeComponent(); + Never_Know.Hello_You_All_Never_Know = Hello_You_All_Never_Know; + MisData01(); + Init_dataGridView_CheckOpName(); + MIS_BASE.InitHashtable_MesServerCode(); + InitMesSerVerCode(); + // 从配置读取 端口 + initServer = new WebApi.InitServer(Convert.ToInt32(ConfigurationManager.AppSettings["ApiPort"])); + ApplicationConfig.ConnectionString_MES = ConfigurationManager.AppSettings["ConnectionString_MES"]; + + // 查所有点位 挨个去查数值 查看是否有数值 = -1 or -2 + //var sql = + // $" SELECT" + + // $" *" + + // $" FROM [MES_基本变量_原始数据]" + + // $" WHERE 工位号 = 'OP070' and 是否启用 = 1"; + //DataAccess2.ExecuteDataTable(sql, out DataTable dt); + //if (dt.Rows.Count > 0) + //{ + // for (int i = 0; i < dt.Rows.Count; i++) + // { + // DataRow row = dt.Rows[i]; + // int code = Convert.ToInt32(row["变量类型代码"]); + // string OpName = row["工位号"].ToString(); + // if (code== 105 || code == 103) continue; + // var data = MIS_BASE.ReadPLC(code, OpName); + // } + //} + //return; + + // 自监控心跳 + InitAllOpHeartBeat(); + } + + private void InitAllOpHeartBeat() + { + + DataTable dt; + DataTable dt1; + try + { + dt1 = BaseDataSystemMES.GetCheckOpName(); + + new Thread(new ThreadStart(delegate () { + while (true) + { + for (int i = 0; i < dt1.Rows.Count; i++) + { + string PLC_HeartBeat; + string OpName = dt1.Rows[i]["工位号"].ToString(); + MIS_BASE.Read_TagTypeID(14, OpName, out PLC_HeartBeat); + MIS_BASE.WritePLC(15, OpName, PLC_HeartBeat); + } + Thread.Sleep(3000); + } + })) + { IsBackground = true }.Start(); + + } + catch (Exception ex) + { + } + } + + public static DataTable GetCheckOpName() + { + DataTable dt = new DataTable(); + string produceName = "MES_计划BOM_工位与名称_查询"; + SqlParameter[] thisParms = null; + + + DataAccess2.ExecuteStoredProcedure(produceName, ref thisParms, out dt); + + return dt; + } + + public void MisData01() + { + DataTable dt_Signal; + DataTable dt_Device; + DataTable dt_TagTypeDataType; + dt_Signal = bizFacade.BaseDataSystemMES.dt_Signal(); + dt_Device = bizFacade.BaseDataSystemMES.dt_Device(); + dt_TagTypeDataType = bizFacade.BaseDataSystemMES.dt_TagTypeDataType(); + var mp = new MesWorkPlc(); + + StartTime = Convert.ToDateTime(toolStripStatusLabel_StartTime.Text = DateTime.Now.ToString()); + Runtime_Thread(); + + if (mp.LoadOPCData(dt_Signal, dt_Device, IsDemoMesServer, IsWriteMonitorLog, true)) + { + MesDataFunction.LoadTagTypeCodeID.Load(dt_TagTypeDataType); + + //查询出“全部原始基本数据列表” + var drs = MesWork.PlcLinkForm.dt_BasicData.Select($"是否启用 = 1 and 变量类型代码=101 or 变量类型代码 = 102 or 变量类型代码 = 105 and 监控属性代码 = '{DataLinkMesWork.ApplicationConfig.MES_Code.ToString()}'"); + if (drs.Length > 1) + { + MIS_BASE.BasicDataTagValue = MesWork.PlcLinkForm.dt_BasicData.Select($"是否启用 = 1 and 变量类型代码=101 or 变量类型代码 = 102 or 变量类型代码 = 105 and 监控属性代码 = '{DataLinkMesWork.ApplicationConfig.MES_Code.ToString()}'").CopyToDataTable(); + if (MIS_BASE.BasicDataTagValue.Columns.Contains("上限值")) + { + MIS_BASE.BasicDataTagValue.Columns["上限值"].ColumnName = "值上限"; + } + if (MIS_BASE.BasicDataTagValue.Columns.Contains("下限值")) + { + MIS_BASE.BasicDataTagValue.Columns["下限值"].ColumnName = "值下限"; + } + } + + // BasicDataTagValue = MesWork.PlcLinkForm.dt_BasicData.Select($"是否启用 = 1 and 监控属性代码 = '{DataLinkMesWork.ApplicationConfig.MES_Code.ToString()}'").CopyToDataTable(); + //查询出“MES_基本数据_测量范围” + MesServerWork.MIS_BASE.BasicDataTagValueUpDown = MesWork.PlcLinkForm.dt_BasicData; + if (MesServerWork.MIS_BASE.BasicDataTagValueUpDown.Columns.Contains("上限值")) + { + MesServerWork.MIS_BASE.BasicDataTagValueUpDown.Columns["上限值"].ColumnName = "值上限"; + } + if (MesServerWork.MIS_BASE.BasicDataTagValueUpDown.Columns.Contains("下限值")) + { + MesServerWork.MIS_BASE.BasicDataTagValueUpDown.Columns["下限值"].ColumnName = "值下限"; + } + // 模拟时,写入质量数据 + InitBasicDataTagValue(); + // 变量代码与其他字段的对应关系 + MesServerWork.MIS_BASE.InitHashtableTagID(); + InitcomboBox_OpName(); + + loadFinish = true; + AllowLoad = true; + MainFormRefresh = new RefreshForm(button_ReadData_Click); + WorkStationNum_Now = comboBox_OpName.SelectedValue.ToString(); + TestPlcStatusDel = new RefreshForm(RefreshPlcConnectStatus); + if (IsDemoMesServer == 1) + { + toolStripStatusLabel_RunningStatus.Text = "变量模拟"; + toolStripStatusLabel_RunningStatus.BackColor = System.Drawing.Color.Yellow; + } + else + { + toolStripStatusLabel_RunningStatus.Text = "PLC"; + toolStripStatusLabel_RunningStatus.BackColor = System.Drawing.Color.Green; + } + MesWorkPlc.D_OPCTagData_TagDataOnChangeMIS-= OPCTagData_TagDataOnChange; + MesWorkPlc.D_OPCTagData_TagDataOnChangeMIS+= OPCTagData_TagDataOnChange; + + } + + + } + + /// + /// 获得Function调用信息 + /// + private void InitMesSerVerCode() + { + MisDataFunDll.MisDataFun.GetMesServerCodeAndMesDll(out MisDataFunDll.MisDataFun.hashtable_MesServerCode, out MisDataFunDll.MisDataFun.hashtable_MesDll); + MisDataFunDll.MisDataFun.GetBaseData_tagTable_TagName(out MisDataFunDll.MisDataFun.hashtable_TagName, out MisDataFunDll.MisDataFun.hashtable_TagTypeTagName); + + FuntionMesRead.GetAlarmInit(); + + } + + public void SaveData_Load(object sender, EventArgs e) + { + MyLog4Net.MyLogHelper.LogCommit += MyLogHelper_LogCommit; + MqttLink(); + Thread.Sleep(200); + var deviceState = MesWorkPlc.StartServer(); //开启监控服务 + timer_TestPLC.Enabled = true; + } + /// + /// 模拟时,写入质量数据 + /// + private void InitBasicDataTagValue() + { + if (IsDemoMesServer != 1) return; + string tagID; + double tagValue; + //写工位总合格标志 变量类型代码=21 + for (int i = 0; i < MesWork.PlcLinkForm.dt_BasicData.Rows.Count; i++) + { + if (MesWork.PlcLinkForm.dt_BasicData.Rows[i]["变量类型代码"].ToString() == "21") + { + tagID = MesWork.PlcLinkForm.dt_BasicData.Rows[i]["TagID"].ToString(); + MesServerWork.MIS_BASE.WritePLC(tagID, 1); + } + + } + if (MesServerWork.MIS_BASE.BasicDataTagValue != null) + { + for (int i = 0; i < MesServerWork.MIS_BASE.BasicDataTagValue.Rows.Count; i++) + { + + try + { + switch (Convert.ToInt32(MesServerWork.MIS_BASE.BasicDataTagValue.Rows[i]["变量特点"])) + { + + case 7: + tagID = MesServerWork.MIS_BASE.BasicDataTagValue.Rows[i]["TagID"].ToString(); + MesServerWork.MIS_BASE.WritePLC(tagID, 1); + break; + case 6: + tagID = MesServerWork.MIS_BASE.BasicDataTagValue.Rows[i]["TagID"].ToString(); + tagValue = Convert.ToDouble(MesServerWork.MIS_BASE.BasicDataTagValue.Rows[i]["列位置"]) * 100 + + Convert.ToDouble(MesServerWork.MIS_BASE.BasicDataTagValue.Rows[i]["变量排序"]) / 100; + MesServerWork.MIS_BASE.WritePLC(tagID, tagValue); + break; + } + } + catch { } + + } + } + + } + + /// + /// 初始化comboBox_OpName(工位号) + /// + private void InitcomboBox_OpName() + { + //全部工位号 + comboBox_OpName.DataSource = opNameList = MesWork.PlcLinkForm.opNameList; + toolStripStatusLabel_WorkStationNum.Text = MesWork.PlcLinkForm.opNameList.Count.ToString(); + toolStripStatusLabel_DownLine.Text = toolStripStatusLabel_WorkStationNum.Text; + } + private void Init_dataGridView_CheckOpName() + { + DataTable dt; + DataTable dt1; + try + { + //dt = BaseDataSystemMES.GetCheckOpName_BQ(); + //dataGridView_CheckOpName.DataSource = dt; + + dt1 = BaseDataSystemMES.GetCheckOpName(); + comboBox_OpNameList.DataSource = dt1; + comboBox_OpNameList.ValueMember = "工位号"; + comboBox_OpNameList.DisplayMember = "工位号"; + } + catch (Exception ex) { } + + } + + + #region mqtt相关 + private void MqttLink() + { + List TopicFilterList = new List(); + string url; + //string topicMqttTargetTopicPLC; + //string topicMqttTargetTopicTagTypeCodeID; + string TopicList; + string[] TopicListFunItems; + string[] TopicListItems; + url = ConfigurationManager.AppSettings["MqttUrl"]; + TopicList = ConfigurationManager.AppSettings["TopicList"]; + TopicListItems = TopicList.Split('|'); + for (int i = 0; i < TopicListItems.Length; i++) + { + TopicListFunItems = TopicListItems[i].Split(','); + hashtableTopicList.Add(TopicListFunItems[0], TopicListFunItems[1]); + } + + MesWorkMqtt.Mqtt.StartAsync(); + + foreach (var topic in TopicListItems) + { + TopicListFunItems = topic.Split(','); + + MesWorkMqtt.Mqtt.mqttClient.SubscribeAsync(new MqttTopicFilter { Topic = TopicListFunItems[0] }); + } + MesWorkMqtt.Mqtt.mqttClient.ConnectedHandler = new MqttClientConnectedHandlerDelegate(OnSubscriberConnected); + MesWorkMqtt.Mqtt.mqttClient.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(OnSubscriberDisconnected); + MesWorkMqtt.Mqtt.mqttClient.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(OnSubscriberMessageReceived); + + } + private string Hello_You_All_Never_Know(string[] args) + { + return Guid.NewGuid().ToString(); + //return string.Empty; + } + /// + /// + /// + /// + private void OnSubscriberConnected(MqttClientConnectedEventArgs x) + { + MyLog4Net.MyLogHelper.Info("Mqtt:", "Mqtt连接成功!"); + OnLineMqtt = true; + // var rec = x.AuthenticateResult.ResultCode.ToString(); + // label_State.Text = rec; + } + /// + /// + /// + /// + private void OnSubscriberDisconnected(MqttClientDisconnectedEventArgs x) + { + //var rec = x.AuthenticateResult.ResultCode.ToString(); + try + { + MyLog4Net.MyLogHelper.Error("Mqtt:", "Mqtt断开连接!Reason:" + x.Reason); + OnLineMqtt = false; + } + catch (Exception err) + { + + } + //label_State.Text = rec; + } + /// + /// + /// + /// + public void OnSubscriberMessageReceived(MqttApplicationMessageReceivedEventArgs x) + { + //var rec = x.ApplicationMessage.ConvertPayloadToString(); + // txt_Rec.Text = txt_Rec.Text + rec + System.Environment.NewLine; + ThreadPool.QueueUserWorkItem(MIS_Funtion_WEB, x); + } + #endregion + + /// + /// mqtt 接收web和barcode数据 + /// + /// + public void MIS_Funtion_WEB(object e) + { + try + { + MqttApplicationMessageReceivedEventArgs x = (MqttApplicationMessageReceivedEventArgs)e; + var rec = x.ApplicationMessage.ConvertPayloadToString(); + MisDataFunDll.MisDataFun.TransferInfToMES(rec); + } + catch (Exception ex) + { + //MIS_Funtion(topicFunItem, "Exception:" + ex.Message); + } + + } + /// + /// 接收内部PLC数据变化 + /// + /// + public void MIS_Funtion_PLC(object e) + { + var rec = e.ToString(); + try + { + MisDataFunDll.MisDataFun.TransferInfToMES(rec); + } + catch (Exception ex) + { + //MIS_Funtion(topicFunItem, "Exception:" + ex.Message); + } + } + + + static public void TagTypeCodeID_Insert(string opName, string TagTypeCodeID, string TagID, string TagValue, DateTime arrivedTime, DateTime leavedTime, int TimeDiff) + { + string procedureName; + procedureName = "测量数据设备状态日志_增加数据"; + SqlParameter[] thisParms = new SqlParameter[7]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@信号类型代码", TagTypeCodeID); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@TagID", TagID); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@TagValue", TagValue); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@到达时间", arrivedTime); + thisParms[5] = new System.Data.SqlClient.SqlParameter("@离开时间", leavedTime); + thisParms[6] = new System.Data.SqlClient.SqlParameter("@在线时间", TimeDiff); + DataAccess2.ExecuteStoredProcedure(procedureName, ref thisParms); + } + + private void MisDataFun_FormClosing(object sender, FormClosingEventArgs e) + { + if (MessageBox.Show("您确认要退出MES程序吗?该操作会停止MES进行数据处理!", "", MessageBoxButtons.OKCancel) == DialogResult.OK) + { + // 关闭Web API服务器 + if (initServer != null) + { + initServer.Close(); + } + Process.GetCurrentProcess().Kill(); + } + else + { + e.Cancel = true; + } + } + + private void timer_Status_Tick(object sender, EventArgs e) + { + timer_Status.Enabled = false; + btn_MqttStatus.BackColor = OnLineMqtt ? Color.Green : Color.Red; + + timer_Status.Enabled = true; + } + private void MyLogHelper_LogCommit(object sender, MyLog4Net.MyLogEventArgs e) + { + var module = e.Module; + var message = e.Message; + + var log = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff") + " " + module + " " + message + "\r\n"; + if (this.InvokeRequired) + { + this.Invoke(new Action(() => + { + this.richTextBox1_mqtt.AppendText(log); + this.richTextBox1_mqtt.Focus(); + })); + } + else + { + this.richTextBox1_mqtt.AppendText(log); + this.richTextBox1_mqtt.Focus(); + } + + } + + + + + public void OPCTagData_TagDataOnChange(OpcData.CustomeEvetnArgs e) + { + + // 处理MIS业务 保存数据 + // ThreadPool.QueueUserWorkItem(Function.MIS_Funtion, e); + // 处理MES业务 Function + ThreadPool.QueueUserWorkItem(TagData_MisData_TagDataOnChangeCustomeEvetnArgs, e); + //ThreadPool.QueueUserWorkItem(TagData_MisData_TagDataOnChange, e); + // 设备状态日志 + ThreadPool.QueueUserWorkItem(TagTypeCodeID_TagDataOnChange, e); + //发送通讯服务器 MES web界面显示用 加工位号 + ThreadPool.QueueUserWorkItem(TransferInfToWebServer, e); + //改变控件状态 + //showMessagePLCInvoke(e); + //更新状态窗口控件状态 + //ExcutePlcChange(e); + } + /// + /// 发送信号变化到function + /// + /// + private void TagData_MisData_TagDataOnChangeCustomeEvetnArgs(object msgEvent) + { + + try + { + OpcData.CustomeEvetnArgs e = (OpcData.CustomeEvetnArgs)msgEvent; + string OpName = e.OpName.ToString();//工位号 + string MesCode = e.TagType.ToString();//变量类型代码 + object tagValue = e.TagValue;//变量(0或者1) + string TagTypeCodeID = e.TagTypeCodeID.ToString();//变量类型代码 + string TagID = e.TagID.ToString(); + string cmd = ""; + cmd = MIS_BASE.hashtable_TagTypeTagName[MesCode]; + string mesServerdllName; + + mesServerdllName = GetMesServeDllByOpName(OpName); + string fun = "fun_" + cmd; + int mesServerCode; + mesServerCode = GetMesServerCodeByOpName(OpName); + string rvMsg = Newtonsoft.Json.JsonConvert.SerializeObject(e); + + string msg; + if (cmd == null) + { + cmd = MesCode; + msg = $"PLC|{cmd}|{OpName}|{rvMsg}"; + } + else + { + msg = $"PLC|{cmd}|{OpName}|{rvMsg}"; + } + try + { + if (TagTypeCodeID == "14") + { + MesServerWork.MIS_BASE.WritePLC(15, OpName, tagValue); + return; + } + if (TagTypeCodeID == "103") + { + FuntionMesRead.Send_AlarmMsg(TagID, tagValue.ToString()); + } + } + catch (Exception err) + { + return; + } + MIS_Funtion_PLC(msg); + // asyncSendMessagePLC(mesServerdllName, msg, OpName); + } + catch (Exception err) + { + ApplicationLog.WriteLog(err, "TagData_Lable_TagDataOnChange"); + } + } + + /// + /// 根据工位号获取MesServerCode + /// + /// + /// + private static int GetMesServerCodeByOpName(string OpName) + { + try + { + if (MesServerWork.MIS_BASE.hashtable_MesServerCode.ContainsKey(OpName)) + { + return Convert.ToInt32(MesServerWork.MIS_BASE.hashtable_MesServerCode[OpName]); + } + return 0; + } + catch + { + return 0; + } + } + /// + /// 根据工位号获取MesServerDll + /// + /// + /// + private static string GetMesServeDllByOpName(string OpName) + { + try + { + if (MesServerWork.MIS_BASE.hashtable_MesDll.ContainsKey(OpName)) + { + return MesServerWork.MIS_BASE.hashtable_MesDll[OpName].ToString(); + } + return ""; + } + catch (Exception err) + { + ApplicationLog.WriteLog(err, "GetMesServeDllByOpName"); + return ""; + } + } + /// + /// 数据库记录信号变化 + /// + /// + private void TagTypeCodeID_TagDataOnChange(object msgEvent) + { + if (IsRecordTagStatus != "1") return; + + try + { + CustomeEvetnArgs e = (CustomeEvetnArgs)msgEvent; + + string tagValue; + if (e.TagValue == null) return; + + switch (e.TagValue.ToString().ToLower()) + { + case "1": + case "true": + tagValue = "1"; + break; + default: + tagValue = "0"; + break; + } + + string TagTypeCodeID; + string opName; + string TagID; + string TagValue; + DateTime arrivedTime; + DateTime leavedTime; + int TimeDiff; + opName = e.OpName.ToString(); + TagValue = tagValue; + TagTypeCodeID = e.TagTypeCodeID.ToString(); + TagID = e.TagID.ToString(); + leavedTime = Convert.ToDateTime(e.TimeStamp); + arrivedTime = Convert.ToDateTime(e.TimeStampBefore); + TimeDiff = Convert.ToInt32(e.TagKeepTime); + + if (TagTypeCodeID != "14" && TagTypeCodeID != "15") + { + TagTypeCodeID_Insert(opName, TagTypeCodeID, TagID, TagValue, arrivedTime, leavedTime, TimeDiff); + } + } + catch (Exception err) + { + ApplicationLog.WriteLog(err, "TagTypeCodeID_TagDataOnChange"); + } + + } + /// + /// 向MES通讯服务器发送消息 + /// + /// + private void TransferInfToWebServer(object msg1) + { + int tagType; + string opName; + OpcData.CustomeEvetnArgs msgEvent = (OpcData.CustomeEvetnArgs)msg1; + //e值不能为空 + if (msgEvent.TagValue == null) return; + tagType = Convert.ToInt32(msgEvent.TagType); + opName = msgEvent.OpName.ToString(); + + if (!MesServerWork.MIS_BASE.m_WorkStart_OpName.ContainsKey(opName)) return; //当前系统是否存在该工位 + + string cmd; + string tagValue; + string msgSvr; + try + { + switch (Convert.ToInt32(msgEvent.TagValueType)) + { + case 11: + tagValue = (Convert.ToInt32(msgEvent.TagValue)).ToString(); + break; + default: + tagValue = msgEvent.TagValue.ToString(); + break; + } + cmd = MIS_BASE.hashtable_TagTypeTagName[tagType.ToString()]; + if (Convert.ToInt32(MIS_BASE.hashtable_WebTagTypeChange[cmd]) == 0 && MIS_BASE.hashtable_WebTagTypeChange[cmd] != null) return; + + if (cmd != "" && cmd != null) + { + msgSvr = "MES|" + cmd + "|" + opName + "|" + tagValue; + } + else + { + return; + } + //MES web界面显示用 + MesServerWork.MIS_BASE.asyncSendMessageQos0(msgSvr); + } + catch (Exception err) + { + ApplicationLog.WriteLog(err, "TransferInfToWebServer"); + } + } + MesWork.OpcForm opcForm = null; + + public static string WorkStationNum_Now; + static bool ReadQualityRunning = false; + static Thread ReadQuality_t = null; + private void button_ReadData_Click(object sender, EventArgs e) + { + if (loadFinish) + { + ReadQualityData(WorkStationNum_Now); + } + } + private void ReadQualityData(string opName) + { + try + { + if (ReadQualityRunning) return; + ReadQualityRunning = true; + QualityDataQueryStruct QltyQueryStr = new QualityDataQueryStruct(opName, listView_ShowQualityData); + //ReadQualityData_Thread(QltyQueryStr); + ReadQuality_t = new Thread(new ParameterizedThreadStart(ReadQualityData_Thread)); + ReadQuality_t.Start(QltyQueryStr); + + + + //if (ReadQualityRunning) return; + //ReadQualityRunning = true; + //QualityDataQueryStruct QltyQueryStr = new QualityDataQueryStruct(opName, listView_ShowQualityData); + + //ReadQuality_t = new Thread(new ParameterizedThreadStart(ReadQualityData_Thread)); + //ReadQuality_t.Start(QltyQueryStr); + + } + catch (Exception err) + { + ApplicationLog.WriteLog(err, err.Message); + + } + } + void ReadQualityData_Thread(object obj) + { + + int fTime = 0; + try + { + + QualityDataQueryStruct QualityStruct = (QualityDataQueryStruct)obj; + + ListView listViewTemp = (ListView)QualityStruct.Ctrl; + ListViewItem listViewItem = null; + string[] listViewItemString = new string[5]; + if (listViewTemp.InvokeRequired) + { + Action ActionDelegate = () => { listViewTemp.Items.Clear(); }; + listViewTemp.Invoke(ActionDelegate); + } + else + { + listViewTemp.Items.Clear(); + } + //System.Collections.Concurrent.ConcurrentDictionary cd = null; + IEnumerable cd = null; + //IEnumerable items; + string opName = QualityStruct.OpName; + var opTagList = GetDbAndMaxLengthByOpNameByBytes(opName); + //TagID 排序 + //var cd_OpName = opTagList.OrderBy(x => x.Key).ToDictionary(k => k.Key, v => v.Value); + //全部数据 + var cd_OpName = from r in opTagList + orderby r.Key + select r; + + //质量数据 + var query_Qd = from r in opTagList + + where ((OpcBasic.TagFormat)r.Value).TagTypeCodeID == 105 + + orderby r.Key + + select r; + //监控变量 + var query_Monitor = from r in opTagList + + where ((OpcBasic.TagFormat)r.Value).TagTypeCodeID != 105 + + orderby r.Key + + select r; + + if (cb_MonitorData.Checked) + { + cd = query_Monitor; + //cd = MesWork.PlcLinkForm.ReadPLC_GroupMonitor(QualityStruct.OpName); + } + if (cb_QdData.Checked) + { + cd = query_Qd; + //cd = MesWork.PlcLinkForm.ReadPLC_GroupData_Qd(QualityStruct.OpName); + } + if (cb_MonitorData.Checked == false & cb_QdData.Checked == false) + { + cd = cd_OpName; + + //cd = MesWork.PlcLinkForm.ReadPLC_GroupData(QualityStruct.OpName); + } + if (cb_MonitorData.Checked == true & cb_QdData.Checked == true) + { + cd = cd_OpName; + //cd = MesWork.PlcLinkForm.ReadPLC_GroupData(QualityStruct.OpName); + } + + //排序 + var result2 = cd;// from pair in cd orderby pair.Key select pair; + ThisWorkStationData = new BasicData.QualityDataType[1000]; + + foreach (KeyValuePair _cd in result2) + { + var tagID = _cd.Key; + var TF = (OpcBasic.TagFormat)_cd.Value; + + listViewItemString[0] = TF.TagID; + listViewItemString[1] = TF.ItemName; + listViewItemString[2] = TF.TagValue.ToString(); + listViewItemString[3] = TF.OpName; + listViewItemString[4] = "(" + TF.TagType + ")" + TF.TagDbAndStartAdrWrite.ToString(); + + listViewItem = new ListViewItem(listViewItemString); + if (TF.IsMonitor == 1) + { + listViewItem.BackColor = Color.LimeGreen; + } + if (listViewTemp.InvokeRequired) + { + Action ActionDelegate = (x) => { listViewTemp.Items.Add(x); }; + listViewTemp.BeginInvoke(ActionDelegate, listViewItem); + } + else + { + listViewTemp.Items.Add(listViewItem); + } + ThisWorkStationData[fTime].opName = TF.OpName; + ThisWorkStationData[fTime].tagID = TF.TagID; + ThisWorkStationData[fTime].tagTypeID = TF.TagTypeID; + ThisWorkStationData[fTime].tagValue = TF.TagValue; + fTime++; + } + + ReadQualityRunning = false; + } + catch (Exception err) + { + ReadQualityRunning = false; + ApplicationLog.WriteLog(err, err.Message); + + } + } + private ConcurrentDictionary GetDbAndMaxLengthByOpNameByBytes(string opName) + { + string tagStartAdr = ""; + ushort tagAdrListMaxLength = 0; + PlcLinkForm.GetDbAndMaxLengthByOpName(opName, out tagStartAdr, out tagAdrListMaxLength); + var tagAdrListTagFormat = PlcLinkForm.ReadQualityDataList(opName, tagStartAdr, tagAdrListMaxLength); + return tagAdrListTagFormat; + } + + private void comboBox_OpName_SelectedIndexChanged(object sender, EventArgs e) + { + //此处需要异步查询当前工位在线状态 + try + { + if (AllowLoad) + { + WorkStationNum_Now = comboBox_OpName.SelectedValue.ToString(); + } + + } + catch (Exception err) + { + ApplicationLog.WriteLog(err, err.Message); + } + } + + private void listView_ShowQualityData_MouseDoubleClick(object sender, MouseEventArgs e) + { + try + { + BasicData.QualityDataType SelectData = new BasicData.QualityDataType(); + ListView.SelectedIndexCollection index = new ListView.SelectedIndexCollection(listView_ShowQualityData); + SelectData = ThisWorkStationData[index[0]]; + WriteQualityValueForm WriteForm = new WriteQualityValueForm(SelectData, this); + WriteForm.ShowDialog(); + } + catch (Exception err) + { + ApplicationLog.WriteLog(err, err.Message); + + } + } + + private void ToolStripMenuItem_PlcDebug_Click(object sender, EventArgs e) + { + if (opcForm != null) + { + opcForm.Close(); + opcForm.Dispose(); + opcForm = null; + } + + opcForm = new MesWork.OpcForm(IsDemoMesServer); + opcForm.Show(); + } + + private void 修改配置文件ToolStripMenuItem_Click(object sender, EventArgs e) + { + new AppConfigSetting.AppConfigSetForm().ShowDialog(); + } + /// + /// 关于迈思按钮 + /// + /// + /// + private void 关于迈思ToolStripMenuItem_Click(object sender, EventArgs e) + { + System.Diagnostics.Process.Start("http://www.meswork.com"); + } + /// + /// 版本信息按钮 + /// + /// + /// + private void 版本信息ToolStripMenuItem_Click(object sender, EventArgs e) + { + VersionsInformation VersionForm = new VersionsInformation(); + VersionForm.ShowDialog(); + } + private void timer_TestPLC_Tick(object sender, EventArgs e) + { + try + { + if (!AllowLoad) return; + timer_TestPLC.Enabled = false; + Runtime_Thread(); + + timer_TestPLC.Enabled = true; + + //SystemFramework.SystemClock.SystemClockTimerTick(); + } + catch (Exception err) + { + ApplicationLog.WriteLog(err, err.Message); + } + } + void RefreshPlcConnectStatus(object sender, EventArgs e) + { + try + { + toolStripStatusLabel_OnlineNum.Text = sender.ToString(); + toolStripStatusLabel_DownLine.Text = (Convert.ToInt32(toolStripStatusLabel_WorkStationNum.Text) - Convert.ToInt32(sender.ToString())).ToString(); + + } + catch (Exception err) + { + ApplicationLog.WriteLog(err, err.Message); + + } + + } + + private void button2_Click(object sender, EventArgs e) + { + FuntionMesRead.GetAlarmInit(); + MyLog4Net.MyLogHelper.Info($"报警更新:", "报警信息更新完成!"); + } + + private void CheckA10ReadOverStart_Click(object sender, EventArgs e) + { + if(CheckA10ReadIverStart()) + { + MIS_BASE.WritePLC(20, "OPA10", false); + MIS_BASE.WritePLC(7, "OPA10", false); + MyLog4Net.MyLogHelper.Info($"A10异常状态恢复:", "A10异常状态恢复完成!"); + } + else + { + MyLog4Net.MyLogHelper.Info($"A10异常状态恢复:", "A10异常状态获取错误!"); + } + } + + private bool CheckA10ReadIverStart() + { + // 再去查一下A10 的上线工位状态 20 保存完成 7 工作完成 19 质量数据可以读 + string checkOpName = "OPA10"; + bool isError = false; + MIS_BASE.Read_TagTypeID(20, checkOpName, out string mesReadOver); + MIS_BASE.Read_TagTypeID(7, checkOpName, out string mesWorkOver); + MIS_BASE.Read_TagTypeID(19, checkOpName, out string plcIsRead); + + if (plcIsRead == "0") + { + isError = (mesReadOver == "1" || mesWorkOver == "1"); + } + return isError; + } + + private void button1_Click(object sender, EventArgs e) + { + MIS_BASE.Write_EngineTypeGetOver_MES(comboBox_OpName.SelectedValue.ToString(), true); + } + + private void button3_Click(object sender, EventArgs e) + { + MIS_BASE.Write_EngineTypeGetOver_MES(comboBox_OpName.SelectedValue.ToString(), false); + } + + /// + /// 界面上的开启时间 + /// + void Runtime_Thread() + { + DateTime Now = DateTime.Now; + TimeSpan x = Now.Subtract(StartTime); + toolStripStatusLabel_RunTime.Text = x.Days.ToString() + "天" + x.Hours.ToString("00") + "小时" + x.Minutes.ToString("00") + "分" + x.Seconds.ToString("00") + "秒"; + //Thread t = new Thread(new ParameterizedThreadStart (Runtime)); + //t.Start(toolStripStatusLabel_RunTime); + } + + } + + +} diff --git a/MisDataFun/MisDataFun/MisDataFun.csproj b/MisDataFun/MisDataFun/MisDataFun.csproj new file mode 100644 index 0000000..e761536 --- /dev/null +++ b/MisDataFun/MisDataFun/MisDataFun.csproj @@ -0,0 +1,307 @@ + + + + + Debug + AnyCPU + {DD9131C7-BF40-45B0-827A-C5E46FC8A89E} + WinExe + MisDataFun + MisDataFun + v4.8 + 512 + true + true + + + + AnyCPU + true + full + false + bin\MisDataFun\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + Mes32X32.ico + + + app.manifest + + + + + Form + + + WriteQualityValueForm.cs + + + Form + + + MisDataFun.cs + + + Form + + + OrderForm.cs + + + + + + + + WriteQualityValueForm.cs + + + MisDataFun.cs + + + OrderForm.cs + + + ResXFileCodeGenerator + Resources.Designer.cs + Designer + + + True + Resources.resx + True + + + + + + SettingsSingleFileGenerator + Settings.Designer.cs + + + True + Settings.settings + True + + + + + + + + ..\..\dll_common\BasicData.dll + + + ..\..\dll_common\BouncyCastle.Crypto.dll + + + False + ..\..\dll_common\ConLink.dll + + + ..\..\dll_common\DataLinkMesWork.dll + + + False + ..\..\dll_common\ICSharpCode.SharpZipLib.dll + + + False + ..\..\dll_common\MesControl.dll + + + ..\..\dll_common\MesWork.DeviceDriver.dll + + + ..\..\dll_common\MesWork.PLC.dll + + + ..\..\dll_common\Monitor.MesWork.dll + + + False + ..\..\dll_fun\MQTTnet.dll + + + False + ..\..\dll_fun\MQTTnet.Extensions.ManagedClient.dll + + + ..\..\dll_common\Newtonsoft.Json.dll + + + False + ..\..\dll_common\NPOI.dll + + + False + ..\..\dll_common\NPOI.OOXML.dll + + + False + ..\..\dll_common\NPOI.OpenXml4Net.dll + + + False + ..\..\dll_common\NPOI.OpenXmlFormats.dll + + + ..\..\dll_common\Opc.Ua.Client.dll + + + ..\..\dll_common\Opc.Ua.Configuration.dll + + + ..\..\dll_common\Opc.Ua.Core.dll + + + ..\..\dll_common\OpcUaHelper.dll + + + + + + + + + + ..\packages\System.IO.4.3.0\lib\net462\System.IO.dll + True + True + + + ..\packages\System.Net.Http.4.3.4\lib\net46\System.Net.Http.dll + True + True + + + ..\packages\Microsoft.AspNet.WebApi.Client.5.2.9\lib\net45\System.Net.Http.Formatting.dll + + + ..\packages\Microsoft.AspNet.WebApi.Core.5.2.9\lib\net45\System.Web.Http.dll + + + ..\packages\Microsoft.AspNet.WebApi.SelfHost.5.2.9\lib\net45\System.Web.Http.SelfHost.dll + + + False + ..\..\dll_fun\System.Net.Security.dll + + + False + ..\..\dll_fun\System.Net.WebSockets.dll + + + False + ..\..\dll_fun\System.Net.WebSockets.Client.dll + + + ..\packages\System.Runtime.4.3.0\lib\net462\System.Runtime.dll + True + True + + + ..\packages\System.Security.Cryptography.Algorithms.4.3.0\lib\net463\System.Security.Cryptography.Algorithms.dll + True + True + + + ..\packages\System.Security.Cryptography.Encoding.4.3.0\lib\net46\System.Security.Cryptography.Encoding.dll + True + True + + + ..\packages\System.Security.Cryptography.Primitives.4.3.0\lib\net46\System.Security.Cryptography.Primitives.dll + True + True + + + ..\packages\System.Security.Cryptography.X509Certificates.4.3.0\lib\net461\System.Security.Cryptography.X509Certificates.dll + True + True + + + + + + + {5fd5de57-cc26-4fd0-b852-5362123bc4ff} + 00-1AppConfigSetForm + + + {f55da1a0-a982-4479-8c47-0d9a5aaf3e18} + 00MesWorkMqtt + + + {0d1af432-439a-4920-8692-43ae139f5530} + 01_01DoWhatPlc + + + {3e6d1dd5-01c9-435f-9941-61f906ce35bb} + 02_02WebApiCallPLC + + + {f0a0c525-03fd-428a-9b17-7f54aa0e4475} + 07BusinessFacade + + + {d98be764-adeb-488d-9714-61e308aa8201} + 08-WebFun_base + + + {90e76fb4-646d-45e2-95db-0b8ab4e465d6} + 09-MesDataFunction + + + {5c0c572b-f8f1-41de-b049-4d40ae29cd21} + 99-DataBaseAccess2 + + + {1dc48c83-1842-4de8-acaf-26e1e7f7c58f} + 00_MyLog4Net + + + {b5a0baa3-c1a7-4aab-9486-2e650adaca7e} + Function1051 + + + {5fee5c91-8419-49ff-b2c2-47476f0b8c68} + Function1052 + + + {ca8a12c5-7bf0-4489-93fa-180b1c492bba} + Function1053 + + + {a0de975b-3afc-4f39-920e-29a874480a36} + 13.4MisDataFunction + + + {55b510c1-59e9-4bfd-ae84-d76d46f6e365} + 13.3MIS_FuntionSaveData + + + {E4EB6420-906D-4672-947A-CA33DDCDADFC} + 12SendMessageToWeb + + + + + + + + + + \ No newline at end of file diff --git a/MisDataFun/MisDataFun/MisDataFun.resx b/MisDataFun/MisDataFun/MisDataFun.resx new file mode 100644 index 0000000..f3afd96 --- /dev/null +++ b/MisDataFun/MisDataFun/MisDataFun.resx @@ -0,0 +1,218 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 138, 17 + + + True + + + True + + + 258, 17 + + + 430, 17 + + + 598, 17 + + + 25 + + + + + AAABAAEAICAAAAEAIACoEAAAFgAAACgAAAAgAAAAQAAAAAEAIAAAAAAAABAAABMLAAATCwAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMgChADIAoQIyAKEgMgChczIA + occyAKHqMgChmTIAoTwyAKEJMgChAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMgChADIAoQQyAKEvMgChdzIA + odYyAKH7MgCh/zIAof8yAKH/MgCh6jIAoacyAKFJMgChEjIAoQAyAKEAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAyAKEAMgChADIAoQoyAKE+MgChkTIA + oeoyAKH+MgCh+TIAoe0yAKH+MgCh/zIAofwyAKH3MgCh/jIAofgyAKHBMgChZDIAoR4yAKEBMgChAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAyAKEAMgChATIAoRUyAKFcMgChujIA + ofEyAKH/MgCh9DIAobcyAKFPMgChfjIAof8yAKH/MgCh5TIAoVUyAKGLMgCh4jIAofwyAKH9MgCh2TIA + oYcyAKEoMgChBTIAoQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAyAKEAMgChAjIAoSYyAKF2MgCh0DIA + ofcyAKH+MgCh8zIAof8yAKGjMgChDTIAoQAyAKFpMgCh/zIAof8yAKHhMgChHjIAoQIyAKEiMgChbjIA + ocoyAKH3MgCh/jIAoeUyAKGfMgChQTIAoQsyAKEAAAAAAAAAAAAAAAAAMgChCDIAoUEyAKGXMgCh4jIA + of4yAKH/MgChzzIAoW0yAKFoMgCh+zIAoZcyAKEAMgChADIAoWkyAKH/MgCh/zIAoeEyAKEeMgChADIA + oQAyAKEBMgChETIAoVAyAKGiMgCh8DIAof8yAKH0MgChuTIAoW0yAKEVMgChADIAoQAyAKG2MgCh7TIA + of8yAKHvMgCh7jIAofgyAKFLMgChADIAoTcyAKH1MgChlzIAoQAyAKEAMgChaTIAof8yAKH/MgCh4TIA + oR4yAKEAAAAAAAAAAAAAAAAAMgChADIAoQcyAKE4MgChijIAod8yAKH9MgCh+zIAoc4yAKFdMgChADIA + of8yAKHlMgChlDIAoToyAKGgMgCh7jIAoSwyAKEAMgChFzIAodgyAKGZMgChADIAoQAyAKFpMgCh/zIA + of8yAKHxMgChfDIAoSkyAKEBMgChAAAAAAAAAAAAAAAAADIAoQAyAKECMgChITIAoW8yAKG/MgCh/zIA + oZYyAKEAMgCh/zIAoZoyAKEBMgChADIAoZkyAKHSMgChEjIAoQAyAKEGMgChujIAoZoyAKEAMgChADIA + oWkyAKH/MgCh/zIAof0yAKH+MgCh4TIAoZIyAKFEMgChDjIAoQAyAKEAAAAAAAAAAAAAAAAAMgChADIA + oUIyAKH7MgChlzIAoQAyAKH/MgChlzIAoQAyAKEAMgChmjIAobMyAKEEMgChADIAoQAyAKGcMgChmzIA + oQAyAKEAMgChaTIAof8yAKH/MgCh4zIAoZYyAKHRMgCh+zIAofQyAKHDMgChZDIAoSIyAKEBMgChAAAA + AAAyAKEAMgChPzIAofsyAKGXMgChADIAof8yAKGXMgChADIAoQAyAKGaMgChiDIAoQAAAAAAMgChADIA + oYgyAKGaMgChADIAoQAyAKFpMgCh/zIAof8yAKHhMgChIDIAoRIyAKFeMgChqzIAoe0yAKH+MgCh3jIA + oYYyAKEqMgChADIAoQAyAKE/MgCh+zIAoZcyAKEAMgCh/zIAoZcyAKEAMgChADIAoZgyAKFtMgChAAAA + AAAyAKEAMgChXDIAoZQyAKEAMgChADIAoWkyAKH/MgCh/zIAoeEyAKEeMgChADIAoQAyAKEGMgChMDIA + oX8yAKHTMgCh+jIAoWkyAKEAMgChADIAoT8yAKH7MgChlzIAoQAyAKH/MgChlzIAoQAyAKEAMgChlTIA + oWMyAKEAAAAAADIAoQAyAKE2MgChhTIAoQAyAKEAMgChaTIAof8yAKH/MgCh4TIAoR4yAKEAAAAAAAAA + AAAyAKEAMgChATIAoRUyAKFYMgChQDIAoQAyAKEAMgChPzIAofsyAKGXMgChADIAof8yAKGXMgChADIA + oQAyAKGLMgChQTIAoQAyAKEFMgChADIAoSMyAKF4MgChADIAoQAyAKFpMgCh/zIAof8yAKHhMgChHjIA + oQAAAAAAAAAAAAAAAAAAAAAAMgChADIAoQAyAKEBMgChADIAoQAyAKE/MgCh+zIAoZcyAKEAMgCh/zIA + oZcyAKEAMgChADIAoXcyAKEkMgChBzIAoUIyAKEBMgChFjIAoWUyAKEBMgChADIAoWkyAKH/MgCh/zIA + oeEyAKEeMgChADIAoQAyAKE5MgChSTIAoQ8yAKEBMgChAAAAAAAAAAAAMgChADIAoT8yAKH7MgChlzIA + oQAyAKH/MgChlzIAoQAyAKECMgChWzIAoQ8yAKEVMgChhTIAoQoyAKEHMgChMzIAoQEyAKEAMgChaTIA + of8yAKH/MgCh4TIAoR4yAKEAMgChADIAoWkyAKH1MgChyzIAoX8yAKE4MgChBTIAoQAyAKEAMgChPzIA + ofsyAKGXMgChADIAof8yAKGXMgChADIAoQMyAKFZMgChCzIAoS4yAKHDMgChGjIAoQAAAAAAAAAAADIA + oQAyAKFpMgCh/zIAof8yAKHhMgChHjIAoQAyAKEAMgChLDIAoaEyAKHkMgCh/DIAoe8yAKGrMgChUzIA + oREyAKFBMgCh+zIAoZcyAKEAMgCh/zIAoZcyAKEAMgChBzIAoVAyAKEEMgChQTIAodoyAKEjMgChAAAA + AAAAAAAAMgChADIAoWkyAKH/MgCh/zIAoeEyAKEeMgChAAAAAAAyAKEAMgChBjIAoSAyAKFyMgChwjIA + ofMyAKH4MgCh0zIAobMyAKH9MgChljIAoQAyAKH/MgChlzIAoQAyAKEBMgChBDIAoQAyAKFKMgCh7jIA + oT0yAKEAAAAAADIAoQAyAKEAMgChbDIAof8yAKH/MgCh4TIAoR8yAKEAAAAAAAAAAAAAAAAAMgChADIA + oQEyAKELMgChRzIAoZYyAKHeMgCh/TIAof8yAKGWMgChADIAof8yAKGXMgChAAAAAAAAAAAAMgChADIA + oW0yAKH/MgChZDIAoQAyAKEEMgChHDIAoWAyAKHPMgCh/zIAof8yAKH3MgChkTIAoS8yAKELMgChADIA + oQAAAAAAAAAAAAAAAAAyAKEAMgChATIAoSAyAKF2MgCh/zIAoZYyAKEAMgCh/zIAoZcyAKEAAAAAADIA + oQAyAKEAMgChljIAof8yAKGeMgChOTIAoZEyAKHcMgCh+TIAof8yAKH/MgCh/zIAof8yAKH+MgCh6jIA + obgyAKFXMgChITIAoQEyAKEAAAAAAAAAAAAAAAAAMgChADIAoT8yAKH7MgChlzIAoQAyAKH/MgChlzIA + oQAAAAAAMgChADIAoQwyAKG9MgCh/zIAofMyAKHyMgCh/jIAof8yAKH/MgCh/zIAofoyAKH3MgCh/jIA + of8yAKH/MgCh/zIAofsyAKHbMgChmzIAoUwyAKENMgChATIAoQAyAKEAMgChPzIAofsyAKGXMgChADIA + of8yAKGXMgChATIAoRkyAKFbMgChsTIAofAyAKH/MgCh/zIAof8yAKH/MgCh/DIAoeYyAKGxMgChVTIA + oUIyAKGFMgCh1TIAofUyAKH/MgCh/zIAof8yAKH/MgCh9DIAocUyAKGDMgChMDIAoQYyAKE/MgCh+zIA + oZcyAKEAMgCh/zIAocEyAKGOMgCh2TIAofcyAKH/MgCh/zIAof8yAKH/MgCh7jIAobMyAKFwMgChJjIA + oQoyAKEAMgChADIAoQEyAKEXMgChTTIAoZsyAKHYMgCh/TIAof8yAKH/MgCh/zIAof4yAKHqMgChszIA + oZgyAKH+MgChljIAoQAyAKH/MgCh/zIAof8yAKH/MgCh/zIAof8yAKH0MgChyTIAoYEyAKE/MgChBzIA + oQAAAAAAMgChADIAoSIyAKF2MgChQjIAoRIyAKEAMgChATIAoR4yAKFjMgChrjIAoecyAKH9MgCh/zIA + of8yAKH/MgCh/zIAof8yAKGWMgChADIAof8yAKH/MgCh/zIAofkyAKHWMgChmjIAoUIyAKERMgChATIA + oQAyAKEGMgChFTIAoQMyAKEAMgChKDIAoZUyAKHHMgChxjIAoXcyAKE3MgChBzIAoQAyAKEGMgChKTIA + oXYyAKHDMgCh7jIAof4yAKH/MgCh/zIAoZYyAKEAMgChrjIAoeYyAKH+MgCh0zIAoVcyAKELMgChADIA + oQAyAKEAMgChADIAoVUyAKHAMgChkjIAoVYyAKEUMgChATIAoRYyAKFhMgChqzIAodUyAKGmMgChZTIA + oR8yAKEDMgChBDIAoS0yAKGiMgCh9DIAofUyAKHGMgChWTIAoQAyAKEGMgChKjIAoWsyAKHBMgCh3DIA + ocEyAKFwMgChJTIAoQYyAKEAMgChDDIAoTgyAKF/MgChyjIAocMyAKGUMgChMzIAoQsyAKEEMgChJjIA + oWUyAKG/MgCh0TIAoaYyAKGoMgCh1TIAodYyAKGNMgChQTIAoRAyAKEAMgChAAAAAAAyAKEAMgChADIA + oQ8yAKE8MgChkDIAoc8yAKHfMgChpDIAoVIyAKEcMgChADIAoQEyAKETMgChRzIAoZ8yAKHGMgChvzIA + oWQyAKEtMgChMzIAoY8yAKHvMgCh5zIAoa8yAKFcMgChHDIAoQMyAKEAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAADIAoQAyAKECMgChFTIAoVcyAKGaMgCh3DIAodEyAKGaMgChSDIAoQsyAKEAMgChATIA + oSUyAKGGMgCh6TIAofEyAKHhMgChtzIAoXAyAKErMgChBTIAoQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMgChADIAoQIyAKElMgChXTIAobgyAKHbMgChxTIA + oYUyAKFbMgChqzIAodEyAKHLMgChhDIAoTsyAKELMgChAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAyAKEAMgChCzIA + oTcyAKGTMgCh0zIAofAyAKG2MgChWjIAoRcyAKEBMgChAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAA/+Af//+AB//8AAD/8AAAP8AIAA8AGDABARg+AQEYD4ERGAPxMZgAcTOY + ADEzmDAxM5g8MTKIPzEgCDDxIAgwMSB4MAEgeDgBJHg+ATxAD8E8AAHxOAAAMQAAAAEAAwABABwgAQBE + BAEBwAABAEAAA+AAAA/4AAB//wAD///gD/8= + + + \ No newline at end of file diff --git a/MisDataFun/MisDataFun/OrderForm.Designer.cs b/MisDataFun/MisDataFun/OrderForm.Designer.cs new file mode 100644 index 0000000..13b429f --- /dev/null +++ b/MisDataFun/MisDataFun/OrderForm.Designer.cs @@ -0,0 +1,417 @@ +namespace MisDataFun +{ + partial class OrderForm + { + /// + /// 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.dataGridView_Order = new System.Windows.Forms.DataGridView(); + this.ID = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.订单号 = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.序号 = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.订单类型 = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.生产日期 = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.班次 = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.零件号 = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.数量 = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.上线数量 = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.下线数量 = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.订单状态 = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.备注 = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.dataGridView_OrderOpNameToMobyList = new System.Windows.Forms.DataGridView(); + this.comboBox_OpName = new System.Windows.Forms.ComboBox(); + this.label1 = new System.Windows.Forms.Label(); + this.button_LoadToOpName = new System.Windows.Forms.Button(); + this.ID1 = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.工位号1 = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.订单号1 = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.序号1 = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.订单类型1 = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.生产日期1 = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.订单班次1 = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.零件号1 = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.数量1 = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.上线数量1 = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.备注1 = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.操作时间1 = new System.Windows.Forms.DataGridViewTextBoxColumn(); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView_Order)).BeginInit(); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView_OrderOpNameToMobyList)).BeginInit(); + this.SuspendLayout(); + // + // dataGridView_Order + // + this.dataGridView_Order.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; + this.dataGridView_Order.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { + this.ID, + this.订单号, + this.序号, + this.订单类型, + this.生产日期, + this.班次, + this.零件号, + this.数量, + this.上线数量, + this.下线数量, + this.订单状态, + this.备注}); + this.dataGridView_Order.Location = new System.Drawing.Point(18, 102); + this.dataGridView_Order.Margin = new System.Windows.Forms.Padding(4); + this.dataGridView_Order.MultiSelect = false; + this.dataGridView_Order.Name = "dataGridView_Order"; + this.dataGridView_Order.ReadOnly = true; + this.dataGridView_Order.RowHeadersWidth = 62; + this.dataGridView_Order.RowTemplate.Height = 23; + this.dataGridView_Order.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect; + this.dataGridView_Order.Size = new System.Drawing.Size(1731, 258); + this.dataGridView_Order.TabIndex = 0; + // + // ID + // + this.ID.DataPropertyName = "ID"; + this.ID.HeaderText = "ID"; + this.ID.MinimumWidth = 8; + this.ID.Name = "ID"; + this.ID.ReadOnly = true; + this.ID.Width = 70; + // + // 订单号 + // + this.订单号.DataPropertyName = "订单号"; + this.订单号.HeaderText = "订单号"; + this.订单号.MinimumWidth = 8; + this.订单号.Name = "订单号"; + this.订单号.ReadOnly = true; + this.订单号.Width = 150; + // + // 序号 + // + this.序号.DataPropertyName = "序号"; + this.序号.HeaderText = "序号"; + this.序号.MinimumWidth = 8; + this.序号.Name = "序号"; + this.序号.ReadOnly = true; + this.序号.Width = 70; + // + // 订单类型 + // + this.订单类型.DataPropertyName = "订单类型"; + this.订单类型.HeaderText = "订单类型"; + this.订单类型.MinimumWidth = 8; + this.订单类型.Name = "订单类型"; + this.订单类型.ReadOnly = true; + this.订单类型.Width = 150; + // + // 生产日期 + // + this.生产日期.DataPropertyName = "生产日期"; + this.生产日期.HeaderText = "生产日期"; + this.生产日期.MinimumWidth = 8; + this.生产日期.Name = "生产日期"; + this.生产日期.ReadOnly = true; + this.生产日期.Width = 150; + // + // 班次 + // + this.班次.DataPropertyName = "班次"; + this.班次.HeaderText = "班次"; + this.班次.MinimumWidth = 8; + this.班次.Name = "班次"; + this.班次.ReadOnly = true; + this.班次.Width = 70; + // + // 零件号 + // + this.零件号.DataPropertyName = "零件号"; + this.零件号.HeaderText = "零件号"; + this.零件号.MinimumWidth = 8; + this.零件号.Name = "零件号"; + this.零件号.ReadOnly = true; + this.零件号.Width = 150; + // + // 数量 + // + this.数量.DataPropertyName = "数量"; + this.数量.HeaderText = "数量"; + this.数量.MinimumWidth = 8; + this.数量.Name = "数量"; + this.数量.ReadOnly = true; + this.数量.Width = 70; + // + // 上线数量 + // + this.上线数量.DataPropertyName = "上线数量"; + this.上线数量.HeaderText = "上线数量"; + this.上线数量.MinimumWidth = 8; + this.上线数量.Name = "上线数量"; + this.上线数量.ReadOnly = true; + this.上线数量.Width = 150; + // + // 下线数量 + // + this.下线数量.DataPropertyName = "下线数量"; + this.下线数量.HeaderText = "下线数量"; + this.下线数量.MinimumWidth = 8; + this.下线数量.Name = "下线数量"; + this.下线数量.ReadOnly = true; + this.下线数量.Width = 150; + // + // 订单状态 + // + this.订单状态.DataPropertyName = "订单状态"; + this.订单状态.HeaderText = "订单状态"; + this.订单状态.MinimumWidth = 8; + this.订单状态.Name = "订单状态"; + this.订单状态.ReadOnly = true; + this.订单状态.Width = 150; + // + // 备注 + // + this.备注.DataPropertyName = "备注"; + this.备注.HeaderText = "备注"; + this.备注.MinimumWidth = 8; + this.备注.Name = "备注"; + this.备注.ReadOnly = true; + this.备注.Width = 150; + // + // dataGridView_OrderOpNameToMobyList + // + this.dataGridView_OrderOpNameToMobyList.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; + this.dataGridView_OrderOpNameToMobyList.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { + this.ID1, + this.工位号1, + this.订单号1, + this.序号1, + this.订单类型1, + this.生产日期1, + this.订单班次1, + this.零件号1, + this.数量1, + this.上线数量1, + this.备注1, + this.操作时间1}); + this.dataGridView_OrderOpNameToMobyList.Location = new System.Drawing.Point(18, 394); + this.dataGridView_OrderOpNameToMobyList.Margin = new System.Windows.Forms.Padding(4); + this.dataGridView_OrderOpNameToMobyList.MultiSelect = false; + this.dataGridView_OrderOpNameToMobyList.Name = "dataGridView_OrderOpNameToMobyList"; + this.dataGridView_OrderOpNameToMobyList.ReadOnly = true; + this.dataGridView_OrderOpNameToMobyList.RowHeadersWidth = 62; + this.dataGridView_OrderOpNameToMobyList.RowTemplate.Height = 23; + this.dataGridView_OrderOpNameToMobyList.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect; + this.dataGridView_OrderOpNameToMobyList.Size = new System.Drawing.Size(1731, 342); + this.dataGridView_OrderOpNameToMobyList.TabIndex = 0; + // + // comboBox_OpName + // + this.comboBox_OpName.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; + this.comboBox_OpName.FormattingEnabled = true; + this.comboBox_OpName.Location = new System.Drawing.Point(166, 46); + this.comboBox_OpName.Margin = new System.Windows.Forms.Padding(4); + this.comboBox_OpName.Name = "comboBox_OpName"; + this.comboBox_OpName.Size = new System.Drawing.Size(260, 26); + this.comboBox_OpName.TabIndex = 1; + // + // label1 + // + this.label1.AutoSize = true; + this.label1.Location = new System.Drawing.Point(18, 51); + this.label1.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); + this.label1.Name = "label1"; + this.label1.Size = new System.Drawing.Size(98, 18); + this.label1.TabIndex = 2; + this.label1.Text = "上线工位号"; + // + // button_LoadToOpName + // + this.button_LoadToOpName.Location = new System.Drawing.Point(534, 42); + this.button_LoadToOpName.Margin = new System.Windows.Forms.Padding(4); + this.button_LoadToOpName.Name = "button_LoadToOpName"; + this.button_LoadToOpName.Size = new System.Drawing.Size(244, 34); + this.button_LoadToOpName.TabIndex = 3; + this.button_LoadToOpName.Text = "订单下达到上线工位"; + this.button_LoadToOpName.UseVisualStyleBackColor = true; + this.button_LoadToOpName.Click += new System.EventHandler(this.button_LoadToOpName_Click); + // + // ID1 + // + this.ID1.DataPropertyName = "ID"; + this.ID1.HeaderText = "ID"; + this.ID1.MinimumWidth = 8; + this.ID1.Name = "ID1"; + this.ID1.ReadOnly = true; + this.ID1.Width = 150; + // + // 工位号1 + // + this.工位号1.DataPropertyName = "工位号"; + this.工位号1.HeaderText = "工位号"; + this.工位号1.MinimumWidth = 8; + this.工位号1.Name = "工位号1"; + this.工位号1.ReadOnly = true; + this.工位号1.Width = 150; + // + // 订单号1 + // + this.订单号1.DataPropertyName = "订单号"; + this.订单号1.HeaderText = "订单号"; + this.订单号1.MinimumWidth = 8; + this.订单号1.Name = "订单号1"; + this.订单号1.ReadOnly = true; + this.订单号1.Width = 150; + // + // 序号1 + // + this.序号1.DataPropertyName = "序号"; + this.序号1.HeaderText = "序号"; + this.序号1.MinimumWidth = 8; + this.序号1.Name = "序号1"; + this.序号1.ReadOnly = true; + this.序号1.Width = 150; + // + // 订单类型1 + // + this.订单类型1.DataPropertyName = "订单类型"; + this.订单类型1.HeaderText = "订单类型"; + this.订单类型1.MinimumWidth = 8; + this.订单类型1.Name = "订单类型1"; + this.订单类型1.ReadOnly = true; + this.订单类型1.Width = 150; + // + // 生产日期1 + // + this.生产日期1.DataPropertyName = "生产日期"; + this.生产日期1.HeaderText = "生产日期"; + this.生产日期1.MinimumWidth = 8; + this.生产日期1.Name = "生产日期1"; + this.生产日期1.ReadOnly = true; + this.生产日期1.Width = 150; + // + // 订单班次1 + // + this.订单班次1.DataPropertyName = "订单班次"; + this.订单班次1.HeaderText = "订单班次"; + this.订单班次1.MinimumWidth = 8; + this.订单班次1.Name = "订单班次1"; + this.订单班次1.ReadOnly = true; + this.订单班次1.Width = 150; + // + // 零件号1 + // + this.零件号1.DataPropertyName = "零件号"; + this.零件号1.HeaderText = "零件号"; + this.零件号1.MinimumWidth = 8; + this.零件号1.Name = "零件号1"; + this.零件号1.ReadOnly = true; + this.零件号1.Width = 150; + // + // 数量1 + // + this.数量1.DataPropertyName = "数量"; + this.数量1.HeaderText = "数量"; + this.数量1.MinimumWidth = 8; + this.数量1.Name = "数量1"; + this.数量1.ReadOnly = true; + this.数量1.Width = 150; + // + // 上线数量1 + // + this.上线数量1.DataPropertyName = "上线数量"; + this.上线数量1.HeaderText = "上线数量"; + this.上线数量1.MinimumWidth = 8; + this.上线数量1.Name = "上线数量1"; + this.上线数量1.ReadOnly = true; + this.上线数量1.Width = 150; + // + // 备注1 + // + this.备注1.DataPropertyName = "备注"; + this.备注1.HeaderText = "备注"; + this.备注1.MinimumWidth = 8; + this.备注1.Name = "备注1"; + this.备注1.ReadOnly = true; + this.备注1.Width = 150; + // + // 操作时间1 + // + this.操作时间1.DataPropertyName = "操作时间"; + this.操作时间1.HeaderText = "操作时间"; + this.操作时间1.MinimumWidth = 8; + this.操作时间1.Name = "操作时间1"; + this.操作时间1.ReadOnly = true; + this.操作时间1.Width = 150; + // + // OrderForm + // + this.AutoScaleDimensions = new System.Drawing.SizeF(9F, 18F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(1767, 754); + this.Controls.Add(this.button_LoadToOpName); + this.Controls.Add(this.label1); + this.Controls.Add(this.comboBox_OpName); + this.Controls.Add(this.dataGridView_OrderOpNameToMobyList); + this.Controls.Add(this.dataGridView_Order); + this.Margin = new System.Windows.Forms.Padding(4); + this.Name = "OrderForm"; + this.Text = "OrderForm"; + ((System.ComponentModel.ISupportInitialize)(this.dataGridView_Order)).EndInit(); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView_OrderOpNameToMobyList)).EndInit(); + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private System.Windows.Forms.DataGridView dataGridView_Order; + private System.Windows.Forms.ComboBox comboBox_OpName; + private System.Windows.Forms.Label label1; + private System.Windows.Forms.Button button_LoadToOpName; + private System.Windows.Forms.DataGridViewTextBoxColumn ID; + private System.Windows.Forms.DataGridViewTextBoxColumn 订单号; + private System.Windows.Forms.DataGridViewTextBoxColumn 序号; + private System.Windows.Forms.DataGridViewTextBoxColumn 订单类型; + private System.Windows.Forms.DataGridViewTextBoxColumn 生产日期; + private System.Windows.Forms.DataGridViewTextBoxColumn 班次; + private System.Windows.Forms.DataGridViewTextBoxColumn 零件号; + private System.Windows.Forms.DataGridViewTextBoxColumn 数量; + private System.Windows.Forms.DataGridViewTextBoxColumn 上线数量; + private System.Windows.Forms.DataGridViewTextBoxColumn 下线数量; + private System.Windows.Forms.DataGridViewTextBoxColumn 订单状态; + private System.Windows.Forms.DataGridViewTextBoxColumn 备注; + private System.Windows.Forms.DataGridView dataGridView_OrderOpNameToMobyList; + private System.Windows.Forms.DataGridViewTextBoxColumn ID1; + private System.Windows.Forms.DataGridViewTextBoxColumn 工位号1; + private System.Windows.Forms.DataGridViewTextBoxColumn 订单号1; + private System.Windows.Forms.DataGridViewTextBoxColumn 序号1; + private System.Windows.Forms.DataGridViewTextBoxColumn 订单类型1; + private System.Windows.Forms.DataGridViewTextBoxColumn 生产日期1; + private System.Windows.Forms.DataGridViewTextBoxColumn 订单班次1; + private System.Windows.Forms.DataGridViewTextBoxColumn 零件号1; + private System.Windows.Forms.DataGridViewTextBoxColumn 数量1; + private System.Windows.Forms.DataGridViewTextBoxColumn 上线数量1; + private System.Windows.Forms.DataGridViewTextBoxColumn 备注1; + private System.Windows.Forms.DataGridViewTextBoxColumn 操作时间1; + } +} \ No newline at end of file diff --git a/MisDataFun/MisDataFun/OrderForm.cs b/MisDataFun/MisDataFun/OrderForm.cs new file mode 100644 index 0000000..4124873 --- /dev/null +++ b/MisDataFun/MisDataFun/OrderForm.cs @@ -0,0 +1,73 @@ +using bizFacade; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Runtime.Remoting.Metadata.W3cXsd2001; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace MisDataFun +{ + public partial class OrderForm : Form + { + public OrderForm() + { + InitializeComponent(); + InitiOrder(); + InitOrderOpName(); + InitOredrToOpNameList(); + } + + private void InitiOrder() + { + DataTable dt; + dt = BaseDataSystemMES.GetOrder_BQ(); + dataGridView_Order.DataSource = dt; + if(dt.Rows.Count>0) + { + dataGridView_Order.Rows[0].Selected = true; + } + + } + + private void InitOrderOpName() + { + DataTable dt; + dt = BaseDataSystemMES.GetOrderOpName_BQ(); + comboBox_OpName.DataSource = dt; + comboBox_OpName.DisplayMember = "工位号"; + if(comboBox_OpName.Items.Count > 0 ) + { + comboBox_OpName.SelectedIndex= 0; + } + } + /// + /// 下达订单到线首工位 + /// + /// + /// + private void button_LoadToOpName_Click(object sender, EventArgs e) + { + string orderForm; + string opName; + orderForm = dataGridView_Order.SelectedRows[0].Cells["订单号"].Value.ToString(); + opName = comboBox_OpName.Text; + + BaseDataSystemMES.DownOrderToOpName(orderForm, opName); + InitOredrToOpNameList(); + } + /// + /// 各个工位订单列表 + /// + private void InitOredrToOpNameList() + { + DataTable dt; + dt = BaseDataSystemMES.DownOrderToOpNameMobyList(""); + dataGridView_OrderOpNameToMobyList.DataSource= dt; + } + } +} diff --git a/MisDataFun/MisDataFun/OrderForm.resx b/MisDataFun/MisDataFun/OrderForm.resx new file mode 100644 index 0000000..0a93b2a --- /dev/null +++ b/MisDataFun/MisDataFun/OrderForm.resx @@ -0,0 +1,228 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + True + + + True + + + True + + + True + + + True + + + True + + + True + + + True + + + True + + + True + + + True + + + True + + + True + + + True + + + True + + + True + + + True + + + True + + + True + + + True + + + True + + + True + + + True + + + True + + + True + + + True + + + True + + + True + + \ No newline at end of file diff --git a/MisDataFun/MisDataFun/Program.cs b/MisDataFun/MisDataFun/Program.cs new file mode 100644 index 0000000..e988b34 --- /dev/null +++ b/MisDataFun/MisDataFun/Program.cs @@ -0,0 +1,28 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace MisDataSaveDate +{ + static class Program + { + /// + /// 应用程序的主入口点。 + /// + [STAThread] + static void Main() + { + new System.Threading.Mutex(true, "PassStationSY-2", out bool bCanRun); + if (!bCanRun) + { + MessageBox.Show("PassStation 程序 已经在运行!不可重复启动!"); + return; + } + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + Application.Run(new MisDataFun()); + } + } +} diff --git a/MisDataFun/MisDataFun/Properties/AssemblyInfo.cs b/MisDataFun/MisDataFun/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..08faa00 --- /dev/null +++ b/MisDataFun/MisDataFun/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// 有关程序集的一般信息由以下 +// 控制。更改这些特性值可修改 +// 与程序集关联的信息。 +[assembly: AssemblyTitle("MisDataSaveDate")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("MisDataSaveDate")] +[assembly: AssemblyCopyright("Copyright © 2022")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// 将 ComVisible 设置为 false 会使此程序集中的类型 +//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型 +//请将此类型的 ComVisible 特性设置为 true。 +[assembly: ComVisible(false)] + +// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID +[assembly: Guid("9aede061-8490-436a-b38b-9495dc908f19")] + +// 程序集的版本信息由下列四个值组成: +// +// 主版本 +// 次版本 +// 生成号 +// 修订号 +// +//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值 +//通过使用 "*",如下所示: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/MisDataFun/MisDataFun/Properties/Resources.Designer.cs b/MisDataFun/MisDataFun/Properties/Resources.Designer.cs new file mode 100644 index 0000000..0caf2db --- /dev/null +++ b/MisDataFun/MisDataFun/Properties/Resources.Designer.cs @@ -0,0 +1,63 @@ +//------------------------------------------------------------------------------ +// +// 此代码由工具生成。 +// 运行时版本:4.0.30319.42000 +// +// 对此文件的更改可能会导致不正确的行为,并且如果 +// 重新生成代码,这些更改将会丢失。 +// +//------------------------------------------------------------------------------ + +namespace MisDataFun.Properties { + using System; + + + /// + /// 一个强类型的资源类,用于查找本地化的字符串等。 + /// + // 此类是由 StronglyTypedResourceBuilder + // 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。 + // 若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen + // (以 /str 作为命令选项),或重新生成 VS 项目。 + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.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 (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("MisDataFun.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/MisDataFun/MisDataFun/Properties/Resources.resx b/MisDataFun/MisDataFun/Properties/Resources.resx new file mode 100644 index 0000000..af7dbeb --- /dev/null +++ b/MisDataFun/MisDataFun/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/MisDataFun/MisDataFun/Properties/Settings.Designer.cs b/MisDataFun/MisDataFun/Properties/Settings.Designer.cs new file mode 100644 index 0000000..b5ad184 --- /dev/null +++ b/MisDataFun/MisDataFun/Properties/Settings.Designer.cs @@ -0,0 +1,26 @@ +//------------------------------------------------------------------------------ +// +// 此代码由工具生成。 +// 运行时版本:4.0.30319.42000 +// +// 对此文件的更改可能会导致不正确的行为,并且如果 +// 重新生成代码,这些更改将会丢失。 +// +//------------------------------------------------------------------------------ + +namespace MisDataFun.Properties { + + + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "17.0.3.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/MisDataFun/MisDataFun/Properties/Settings.settings b/MisDataFun/MisDataFun/Properties/Settings.settings new file mode 100644 index 0000000..3964565 --- /dev/null +++ b/MisDataFun/MisDataFun/Properties/Settings.settings @@ -0,0 +1,7 @@ + + + + + + + diff --git a/MisDataFun/MisDataFun/WebApi/IOrderController.cs b/MisDataFun/MisDataFun/WebApi/IOrderController.cs new file mode 100644 index 0000000..370ca99 --- /dev/null +++ b/MisDataFun/MisDataFun/WebApi/IOrderController.cs @@ -0,0 +1,43 @@ +using System.Net.Http; +using System.Text; +using System.Web.Http; +using Newtonsoft.Json.Linq; +using System.Threading.Tasks; + +/////http://127.0.0.1:9981/api/IOrder/InsertOrder + +/// +/// +/// +namespace WebApi +{ + /// + /// + /// + [RoutePrefix("api/imes")] + public class imesController : ApiController + { + readonly string headUrl = "api/imes/"; + + [HttpPost] + public async Task AGVRequestEnterH1([FromBody] JObject jobj) + { + if (jobj == null) jobj = new JObject(); + var result = await ServerController.AGV_To_MES_AgvPass(headUrl + "AGVRequestEnterH1", jobj.ToString(),"H1"); + return new HttpResponseMessage + { + Content = new StringContent(result, Encoding.GetEncoding("UTF-8"), "application/json") + }; + } + [HttpPost] + public async Task AGVRequestEnterH2([FromBody] JObject jobj) + { + if (jobj == null) jobj = new JObject(); + var result = await ServerController.AGV_To_MES_AgvPass(headUrl + "AGVRequestEnterH2", jobj.ToString(), "H2"); + return new HttpResponseMessage + { + Content = new StringContent(result, Encoding.GetEncoding("UTF-8"), "application/json") + }; + } + } +} diff --git a/MisDataFun/MisDataFun/WebApi/InitServer.cs b/MisDataFun/MisDataFun/WebApi/InitServer.cs new file mode 100644 index 0000000..0fe88a8 --- /dev/null +++ b/MisDataFun/MisDataFun/WebApi/InitServer.cs @@ -0,0 +1,142 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Net; +using System.Net.Http; +using System.Net.Http.Formatting; +using System.Net.Http.Headers; +using System.Text; +using System.Web.Http; +// CORS功能已移除 +using System.Web.Http.SelfHost; + +namespace WebApi +{ + /// + /// + /// + public class InitServer + { + /// + /// + /// + HttpSelfHostConfiguration config = null; + /// + /// + /// + HttpSelfHostServer server = null; + /// + /// + /// + /// + public InitServer(int port) + { + config = new HttpSelfHostConfiguration($"http://0.0.0.0:{port}"); + + // CORS功能已移除,简化配置 + + config.MapHttpAttributeRoutes(); + + //config.Routes.MapHttpRoute( + // name: "DefaultApi", + // routeTemplate: "api/{controller}/{id}", + // defaults: new { id = RouteParameter.Optional } + //); + + // 自定义路由匹配到action + config.Routes.MapHttpRoute( + name: "API Default", + routeTemplate: "api/{controller}/{action}/{id}", + defaults: new { id = System.Web.Http.RouteParameter.Optional } + ); + server = new HttpSelfHostServer(config); + + server.OpenAsync().Wait(); + + } + + public void Close() + { + server.CloseAsync(); + } + /// + /// + /// + public class JsonContentNegotiator : IContentNegotiator + { + /// + /// + /// + private readonly JsonMediaTypeFormatter _jsonFormatter; + /// + /// + /// + /// + public JsonContentNegotiator(JsonMediaTypeFormatter formatter) + { + _jsonFormatter = formatter; + } + /// + /// + /// X + /// + /// + /// + /// + public ContentNegotiationResult Negotiate(Type type, HttpRequestMessage request, IEnumerable formatters) + { + var result = new ContentNegotiationResult(_jsonFormatter, new MediaTypeHeaderValue("application/json")); + return result; + } + + public static string Postring1(string url, string token, Dictionary dic) + { + string results = ""; + //url = "http://172.16.22.15:8000/" + url; + + HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); + req.Method = "POST"; + req.ContentType = "application/x-www-form-urlencoded"; + req.Headers.Add("Authorization", "Bearer " + token); + + StringBuilder builder = new StringBuilder(); + int i = 0; + foreach (var item in dic) + { + if (i > 0) + builder.Append("&"); + builder.AppendFormat("{0}={1}", item.Key, item.Value); + i++; + } + byte[] data = Encoding.UTF8.GetBytes(builder.ToString()); + req.ContentLength = data.Length; + try + { + using (Stream reqStream = req.GetRequestStream()) + { + reqStream.Write(data, 0, data.Length); + reqStream.Close(); + } + HttpWebResponse resp = (HttpWebResponse)req.GetResponse(); + Stream stream = resp.GetResponseStream(); + //获取响应内容 + using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) + { + results = reader.ReadToEnd(); + } + return results; + } + catch (Exception e) + { + Console.WriteLine(e.Message); + return e.Message; + throw; + } + + } + + + + } + } +} diff --git a/MisDataFun/MisDataFun/WebApi/ServerController.cs b/MisDataFun/MisDataFun/WebApi/ServerController.cs new file mode 100644 index 0000000..f5724bc --- /dev/null +++ b/MisDataFun/MisDataFun/WebApi/ServerController.cs @@ -0,0 +1,109 @@ +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using WebApi.Models; +using WebApi.Helpers; +using System.Reflection; +using System.Net.Http; +using System.Threading.Tasks; +using MesServerWork; + + +namespace WebApi +{ + public class ServerController + { + /// + /// AGV到位,离开 + /// + /// + /// + /// + public static async Task AGV_To_MES_AgvPass(string url, string json,string position) + { + var result = new msgResHeader(); + result.code = "500"; + result.message = ""; + string opName = "OPA10"; + + string errorMessage = ""; + int AID = -1; + try + { + // 显示一下接口日志 + LogHelper.ShowMsg("Receive【" + url + "】" + json); + AID = LogHelper.SaveWebApiReqLogo(url, json); + + // 解析订单内容,存储数据库,根据实际业务来写 + AGV_To_MES_AgvPass_Req personnelBaseData = JsonConvert.DeserializeObject(json); + + // 验证必填字段 + if (!ValidationHelper.ValidateRequired(personnelBaseData, out errorMessage)) + { + LogHelper.ShowMsg($"****************{errorMessage}"); + result.message = errorMessage; + return JsonConvert.SerializeObject(result); + } + // 判断是进入还是离开 + if(personnelBaseData.agvStatus == "enter") + { + bool isIn = false; + bool isReturn = false; + + // 根据位置号判断点位 + switch (position) + { + case "H1": + MIS_BASE.WritePLC(200, opName, true); // 写入请求进入 + isIn = Convert.ToBoolean(MIS_BASE.ReadPLC(208, opName).ToString() == "1"); // 读取允许进入 + break; + case "H2": + MIS_BASE.WritePLC(203, opName, true); // 写入请求进入 + isIn = Convert.ToBoolean(MIS_BASE.ReadPLC(213, opName).ToString() == "1"); // 读取允许进入 + break; + default: + LogHelper.ShowMsg($"****************未识别的station{position}"); + result.message = $"未识别的Station{position}"; + return JsonConvert.SerializeObject(result); + } + // 判断是否允许进入 返回200 否则 返回 500不允许 + if (isIn) + { + result.code = "200"; + LogHelper.ShowMsg($"AGV状态更新: 工位={position}, 状态=允许进入"); + } + } + if (personnelBaseData.agvStatus == "leave") + { + // 根据位置号判断点位 + switch (position) + { + case "H1": + MIS_BASE.WritePLC(201, opName, true); // 写入AGV已离开 + break; + case "H2": + MIS_BASE.WritePLC(204, opName, true); // 写入AGV已离开 + break; + default: + LogHelper.ShowMsg($"****************未识别的station{position}"); + result.message = $"未识别的Station{position}"; + return JsonConvert.SerializeObject(result); + } + // 判断是否允许进入 返回200 否则 返回 500不允许 + result.code = "200"; + LogHelper.ShowMsg($"AGV状态更新: 工位={position}, 状态=已离开"); + } + + LogHelper.SaveWebApiResLogo(AID, JsonConvert.SerializeObject(result)); + } + catch (Exception err) + { + result.code = "500"; + result.message = err.Message; + Console.WriteLine($"错误: {MethodBase.GetCurrentMethod().Name} - {err.Message}"); + } + + return JsonConvert.SerializeObject(result); + } + } +} diff --git a/MisDataFun/MisDataFun/app.manifest b/MisDataFun/MisDataFun/app.manifest new file mode 100644 index 0000000..ffface3 --- /dev/null +++ b/MisDataFun/MisDataFun/app.manifest @@ -0,0 +1,79 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/MisDataFun/MisDataFun/jsconfig1.json b/MisDataFun/MisDataFun/jsconfig1.json new file mode 100644 index 0000000..afb797c --- /dev/null +++ b/MisDataFun/MisDataFun/jsconfig1.json @@ -0,0 +1,10 @@ +{ + "exclude": [ + "**/bin", + "**/bower_components", + "**/jspm_packages", + "**/node_modules", + "**/obj", + "**/platforms" + ] +} \ No newline at end of file diff --git a/MisDataFun/MisDataFun/packages.config b/MisDataFun/MisDataFun/packages.config new file mode 100644 index 0000000..90c6ec6 --- /dev/null +++ b/MisDataFun/MisDataFun/packages.config @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/MisDataFun/SendMessageToWebMqtt/12SendMessageToWeb.csproj b/MisDataFun/SendMessageToWebMqtt/12SendMessageToWeb.csproj new file mode 100644 index 0000000..baec4e8 --- /dev/null +++ b/MisDataFun/SendMessageToWebMqtt/12SendMessageToWeb.csproj @@ -0,0 +1,70 @@ + + + + + Debug + AnyCPU + {E4EB6420-906D-4672-947A-CA33DDCDADFC} + Library + Properties + SendMessageToWebMqtt + SendMessageToWebMqtt + v4.8 + 512 + true + + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + + {f55da1a0-a982-4479-8c47-0d9a5aaf3e18} + 00MesWorkMqtt + + + {f434e066-4c59-47c8-aa82-6f48cc84501a} + 04-DataBaseAccess + + + {f0a0c525-03fd-428a-9b17-7f54aa0e4475} + 07BusinessFacade + + + {90E76FB4-646D-45E2-95DB-0B8AB4E465D6} + 09-MesDataFunction + + + + \ No newline at end of file diff --git a/MisDataFun/SendMessageToWebMqtt/InitHashtable_MesServerCode.cs b/MisDataFun/SendMessageToWebMqtt/InitHashtable_MesServerCode.cs new file mode 100644 index 0000000..e2b6a68 --- /dev/null +++ b/MisDataFun/SendMessageToWebMqtt/InitHashtable_MesServerCode.cs @@ -0,0 +1,52 @@ +using DataLinkMesWork; +using System; +using System.Collections.Generic; +using System.Data; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + + +namespace MesServerFunctions +{ + + /// + /// 命令 + ///显示托盘信息√ case "ShowMoby": + ///显示操作指南√ case "ProcessList": + ///显示物料√ case "MaterialList": + ///显示操作图片√ case "PicShow": + ///显示拧紧位置√ case "ShaftPosition": + ///实时显示质量数据√ case "ShowTimelyQuality": + ///手动拧紧实时显示质量数据√case "ShowTimelyQuality_Tight": + ///√ case "OrderFormList": + ///弹窗消息√ case "Notice": + ///LED消息提醒√ case "ScrollNotice": + ///物料检测初始化√ case "MaterialCheckPosition": + ///返修质量数据显示√ case "RepairQuality" + /// + /// + public class MesServerCode + { + + /// + /// MES_基本变量_DB数据结构_获得激发变量 + /// + /// + public static DataTable BaseData_tagTable_All() + { + int MES_Code = 1; + DataTable dt = null; + string sql; + sql = "SELECT TagID,0 as TagValue,TagName,工位号,数据来源,TagTypeID,TagLong,列位置,测量位置,变量类型代码,测量项目,TagAdr,TagAdrDemo,变量特点,变量排序 FROM [MES_基本变量_原始数据] " + + " where ((变量类型代码 >= 19 and 变量类型代码 <= 27) or (变量类型代码 = 101) or (变量类型代码 = 102) or (变量类型代码 = 105) or (变量类型代码 = 1000) or (变量类型代码 = 1001) or (变量类型代码 = 1002) or (变量类型代码 = 1003) or (变量类型代码 = 1004)) and (是否启用 = 1) " + + " and (监控属性代码 = '" + MES_Code.ToString() + "')" + + " ORDER BY TagID "; + DataAccess.ExecuteDataTable(sql, out dt); + return dt; + } + + + } +} + diff --git a/MisDataFun/SendMessageToWebMqtt/Properties/AssemblyInfo.cs b/MisDataFun/SendMessageToWebMqtt/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..cc7132f --- /dev/null +++ b/MisDataFun/SendMessageToWebMqtt/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// 有关程序集的一般信息由以下 +// 控制。更改这些特性值可修改 +// 与程序集关联的信息。 +[assembly: AssemblyTitle("SendMessageToWebMqtt")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("SendMessageToWebMqtt")] +[assembly: AssemblyCopyright("Copyright © 2023")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// 将 ComVisible 设置为 false 会使此程序集中的类型 +//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型 +//请将此类型的 ComVisible 特性设置为 true。 +[assembly: ComVisible(false)] + +// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID +[assembly: Guid("e4eb6420-906d-4672-947a-ca33ddcdadfc")] + +// 程序集的版本信息由下列四个值组成: +// +// 主版本 +// 次版本 +// 生成号 +// 修订号 +// +//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值 +//通过使用 "*",如下所示: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/MisDataFun/SendMessageToWebMqtt/SendMessage.cs b/MisDataFun/SendMessageToWebMqtt/SendMessage.cs new file mode 100644 index 0000000..77fb232 --- /dev/null +++ b/MisDataFun/SendMessageToWebMqtt/SendMessage.cs @@ -0,0 +1,736 @@ +using bizFacade; +using MesServerWork; +using MesWorkMqtt; +using System; +using System.Collections.Generic; +using System.Configuration; +using System.Data; +using System.Linq; +using System.Net.Sockets; +using System.Text; +using System.Threading.Tasks; + +namespace MesServerFunctions +{ + + /// + /// 命令 + ///显示托盘信息√ case "ShowMoby": + ///显示操作指南√ case "ProcessList": + ///显示物料√ case "MaterialList": + ///显示操作图片√ case "PicShow": + ///显示拧紧位置√ case "ShaftPosition": + ///实时显示质量数据√ case "ShowTimelyQuality": + ///手动拧紧实时显示质量数据√case "ShowTimelyQuality_Tight": + ///√ case "OrderFormList": + ///弹窗消息√ case "Notice": + ///LED消息提醒√ case "ScrollNotice": + ///物料检测初始化√ case "MaterialCheckPosition": + ///返修质量数据显示√ case "RepairQuality" + /// + /// + public class SendMessage + { + /// + /// MES/InstantMessaging/BQ + /// + public static string MqttTargetTopic = ConfigurationManager.AppSettings["MqttTargetTopic"]; + /// + /// WEB/InstantMessaging/BQ/MisServer + /// + public static string MqttTargetTopicWEB = ConfigurationManager.AppSettings["MqttTargetTopicWEB"]; + /// + /// BAR/InstantMessaging/BQ + /// + public static string MqttTargetTopicBAR = ConfigurationManager.AppSettings["MqttTargetTopicBAR"]; + + public static void SendMessageBARToMES(string opName, string msgText) + { + var topic = $"{MqttTargetTopicBAR}"; + + if (msgText.Length > 0) + { + Task.Run(() => Mqtt.Publish(topic, msgText)); + } + SendMessageMESToWEB(opName, msgText); + } + public static void SendMessageMESToWEB(string opName, string msgText) + { + var topic = $"{MqttTargetTopic}/{opName}"; + + if (msgText.Length > 0) + { + Task.Run(() => Mqtt.Publish(topic, msgText)); + } + } + public static void SendMessageWEBToMES(string msgText) + { + var topic = $"{MqttTargetTopicWEB}"; + + if (msgText.Length > 0) + { + Task.Run(() => Mqtt.Publish(topic, msgText)); + } + } + /// + /// 5 显示订单、机型信息 上线工位 + /// + /// + public static void ShowMoby_FirstOpName(string opName) + { + var topic = $"{MqttTargetTopic}/{opName}"; + var responseStr = ShowMoby_String_FirstOpName(opName); + string cmd = "ShowMoby"; + if (responseStr.Length > 0) + { + Task.Run(() => Mqtt.Publish(topic, $"MES|{cmd}_Resources|{opName}|{responseStr}")); + } + } + /// + /// 5 显示订单、机型信息 非上线工位 + /// + /// + public static void ShowMoby(string opName, int type = 1) + { + var topic = $"{MqttTargetTopic}/{opName}"; + var responseStr = ShowMoby_String(opName, type); + string cmd = "ShowMoby"; + if (responseStr.Length > 0) + { + Task.Run(() => Mqtt.Publish(topic, $"MES|{cmd}_Resources|{opName}|{responseStr}")); + } + } + public static void MaterialList_Dif(string opName, string msgText) + { + var topic = $"{MqttTargetTopic}/{opName}"; + string cmd = "MaterialList_Dif"; + if (msgText.Length > 0) + { + Task.Run(() => Mqtt.Publish(topic, $"MES|{cmd}_Resources|{opName}|{msgText}")); + } + } + public static void AsyncSendMessage_Notice(string opname, string notice) + { + //通知Web界面 + BaseDataSystemMES.Web_Notice_Insert(opname, notice); + Notice(opname); + } + public static void Notice(string opName) + { + var topic = $"{MqttTargetTopic}/{opName}"; + var responseStr = Notice_String(opName); + string cmd = "Notice"; + if (responseStr.Length > 0) + { + Task.Run(() => Mqtt.Publish(topic, $"MES|{cmd}_Resources|{opName}|{responseStr}")); + } + } + /// + /// 1(直接在界面通过选择机型确认工序内容) + /// + /// + public static void ProcessList(string opName) + { + var topic = $"{MqttTargetTopic}/{opName}"; + var responseStr = ProcessList_String(opName); + string cmd = "ProcessList"; + if (responseStr.Length > 0) + { + Task.Run(() => Mqtt.Publish(topic, $"MES|{cmd}_Resources|{opName}|{responseStr}")); + } + } + public static void ProcessList_FirstOpName(string opName) + { + var topic = $"{MqttTargetTopic}/{opName}"; + var responseStr = ProcessList_String_FirstOpName(opName); + string cmd = "ProcessList"; + if (responseStr.Length > 0) + { + Task.Run(() => Mqtt.Publish(topic, $"MES|{cmd}_Resources|{opName}|{responseStr}")); + } + } + /// + /// 2显示物料 + /// + /// + public static void MaterialList(string opName) + { + var topic = $"{MqttTargetTopic}/{opName}"; + var responseStr = MaterialList_String(opName); + string cmd = "MaterialList"; + if (responseStr.Length > 0) + { + Task.Run(() => Mqtt.Publish(topic, $"MES|{cmd}_Resources|{opName}|{responseStr}")); + } + + } + public static void MaterialList_FirstOpName(string opName) + { + var topic = $"{MqttTargetTopic}/{opName}"; + var responseStr = MaterialList_String_FirstOpName(opName); + string cmd = "MaterialList"; + if (responseStr.Length > 0) + { + Task.Run(() => Mqtt.Publish(topic, $"MES|{cmd}_Resources|{opName}|{responseStr}")); + } + + } + /// + /// 3显示操作指导图片 + /// + /// + public static void PicShow(string opName) + { + var topic = $"{MqttTargetTopic}/{opName}"; + var responseStr = PicShow_String(opName); + string cmd = "PicShow"; + if (responseStr.Length > 0) + { + Task.Run(() => Mqtt.Publish(topic, $"MES|{cmd}_Resources|{opName}|{responseStr}")); + } + } + public static void PicShow_FirstOpName(string opName) + { + var topic = $"{MqttTargetTopic}/{opName}"; + var responseStr = PicShow_String_FirstOpName(opName); + string cmd = "PicShow"; + if (responseStr.Length > 0) + { + Task.Run(() => Mqtt.Publish(topic, $"MES|{cmd}_Resources|{opName}|{responseStr}")); + } + } + + /// + /// 4订单完工模块刷新完成数量 + /// + /// + public static void OrderFormList(string opName) + { + var topic = $"{MqttTargetTopic}/{opName}"; + var responseStr = OrderFormList_String(); + string cmd = "OrderFormList"; + if (responseStr.Length > 0) + { + Task.Run(() => Mqtt.Publish(topic, $"MES|{cmd}_Resources|{opName}|{responseStr}")); + } + } + + //实时显示质量数据√ + public static void ShowTimelyQuality(string opName) + { + + } + + public static void SendActuallyCount(string OpName, int tagValue) + { + //当工件离开时,更新在线产量、在线节拍 + //if (tagValue == 0) + { + try + { + int opNameCount = 0;//在线产量 + int opNameCountTime = 0;//在线节拍 + + BaseDataSystemMES.OpNameCount_BQ(OpName, out opNameCount, out opNameCountTime); //基本数据_工作日历_班次产量查询_New + + SendInfomation("ActuallyCount", opNameCount.ToString() + "&" + opNameCountTime.ToString(), OpName); + + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function01:SendActuallyCount"); + } + } + } + + public static void SendInfomation(string Command, string Value, string OpName) + { + + string SendMessage = "MES|" + Command + "|" + OpName + "|" + Value; + AsyncSendMessage(SendMessage); + } + + public static void AsyncSendMessage(string Message) + { + //lock (locker) + { + //"MES|MachinePlan|OpName|Value + var array = Message.Split('|'); + var cmd = array[1]; + var opName = array[2]; + var topic = $"{MqttTargetTopic}/{opName}"; + Task.Run(() => Mqtt.Publish(topic, Message)); + + } + + + } + private static string ProcessList_String(string OpName) + { + string jsonStr_Process = ""; + try + { + string orderNum = ""; + int EngineTypeID = 0; + string EngineType = ""; + string EngineID = ""; + string PartPallet_Code = ""; + int IsrepairBarcode = 0; + string repairBarcode = ""; + string EngineTypeString = ""; + DataTable dt_Proccess; + + MES1.Moby_Select(OpName, out orderNum, out EngineTypeID, out EngineType, out EngineID, out PartPallet_Code, out IsrepairBarcode, out repairBarcode, out EngineTypeString); + + MES.Process_Select(OpName, EngineTypeID, EngineType, out dt_Proccess); + if (dt_Proccess != null) + { + if (dt_Proccess.Rows.Count > 0) + { + jsonStr_Process = JsonHelper.CreateJsonParameters(dt_Proccess); + } + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "MesWebFun_baseFun:ProcessList"); + } + return jsonStr_Process; + } + private static string ProcessList_String_FirstOpName(string OpName) + { + string jsonStr_Process = ""; + try + { + string orderNum = ""; + int EngineTypeID = 0; + string EngineType = ""; + string EngineID = ""; + string PartPallet_Code = ""; + int IsrepairBarcode = 0; + string repairBarcode = ""; + string EngineTypeString = ""; + DataTable dt_Proccess; + + MES1.Moby_Select_FirstOpName(OpName, out orderNum, out EngineTypeID, out EngineType, out EngineID, out PartPallet_Code, out IsrepairBarcode, out repairBarcode, out EngineTypeString); + + MES.Process_Select(OpName, EngineTypeID, EngineType, out dt_Proccess); + if (dt_Proccess != null) + { + if (dt_Proccess.Rows.Count > 0) + { + jsonStr_Process = JsonHelper.CreateJsonParameters(dt_Proccess); + } + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "MesWebFun_baseFun:ProcessList"); + } + return jsonStr_Process; + } + // + private static string PicShow_String(string OpName) + { + string data = ""; + try + { + string orderNum = ""; + int EngineTypeID = 0; + string EngineType = ""; + string EngineID = ""; + string PartPallet_Code = ""; + int IsrepairBarcode = 0; + string repairBarcode = ""; + string EngineTypeString = ""; + byte[] imgBytesIn; + MES1.Moby_Select(OpName, out orderNum, out EngineTypeID, out EngineType, out EngineID, out PartPallet_Code, out IsrepairBarcode, out repairBarcode, out EngineTypeString); + BaseDataSystemMES.GetImageFile(OpName, EngineTypeID.ToString(), out imgBytesIn); + if (imgBytesIn == null) + { + return data; + } + data = Convert.ToBase64String(imgBytesIn); + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "MesWebFun_baseFun:PictureShow"); + } + return data; + } + + private static string PicShow_String_FirstOpName(string OpName) + { + string data = ""; + try + { + string orderNum = ""; + int EngineTypeID = 0; + string EngineType = ""; + string EngineID = ""; + string PartPallet_Code = ""; + int IsrepairBarcode = 0; + string repairBarcode = ""; + string EngineTypeString = ""; + byte[] imgBytesIn; + MES1.Moby_Select_FirstOpName(OpName, out orderNum, out EngineTypeID, out EngineType, out EngineID, out PartPallet_Code, out IsrepairBarcode, out repairBarcode, out EngineTypeString); + BaseDataSystemMES.GetImageFile(OpName, EngineTypeID.ToString(), out imgBytesIn); + if (imgBytesIn == null) + { + return data; + } + data = Convert.ToBase64String(imgBytesIn); + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "MesWebFun_baseFun:PictureShow"); + } + return data; + } + /// + /// 上线工位 + /// + /// + /// + private static string ShowMoby_String(string OpName, int type = 1) + { + string data = ""; + try + { + string orderNum = ""; + int EngineTypeID = 0; + string EngineType = ""; + string EngineID = ""; + string PartPallet_Code = ""; + int IsrepairBarcode = 0; + string repairBarcode = ""; + string EngineTypeString = ""; + //线首工位用 + MES1.Moby_Select(OpName, out orderNum, out EngineTypeID, out EngineType, out EngineID, out PartPallet_Code, out IsrepairBarcode, out repairBarcode, out EngineTypeString, type); + data = orderNum + "&" + EngineTypeID + "&" + EngineType + "&" + EngineID + "&" + PartPallet_Code + "&" + IsrepairBarcode + "&" + repairBarcode + "&" + EngineTypeString; + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "MesWebFun_baseFun:MobySelect"); + } + return data; + }//Moby_Select_FirstOpName + private static string ShowMoby_String_FirstOpName(string OpName) + { + string data = ""; + try + { + string orderNum = ""; + int EngineTypeID = 0; + string EngineType = ""; + string EngineID = ""; + string PartPallet_Code = ""; + int IsrepairBarcode = 0; + string repairBarcode = ""; + string EngineTypeString = ""; // BQ + //线首工位用 + MES1.Moby_Select_FirstOpName(OpName, out orderNum, out EngineTypeID, out EngineType, out EngineID, out PartPallet_Code, out IsrepairBarcode, out repairBarcode, out EngineTypeString); + data = orderNum + "&" + EngineTypeID + "&" + EngineType + "&" + EngineID + "&" + PartPallet_Code + "&" + IsrepairBarcode + "&" + repairBarcode + "&" + EngineTypeString; + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "MesWebFun_baseFun:MobySelect"); + } + return data; + } + /// + /// 非上线工位 + /// + /// + /// + //private static string ShowMoby_String(string OpName) + //{ + // string data = ""; + // try + // { + // string orderNum = ""; + // int EngineTypeID = 0; + // string EngineType = ""; + // string EngineID = ""; + // string PartPallet_Code = ""; + // int IsrepairBarcode = 0; + // string repairBarcode = ""; + // MES1.Moby_Select(OpName, out orderNum, out EngineTypeID, out EngineType, out EngineID, out PartPallet_Code, out IsrepairBarcode, out repairBarcode); + // data = orderNum + "&" + EngineTypeID + "&" + EngineType + "&" + EngineID + "&" + PartPallet_Code + "&" + IsrepairBarcode + "&" + repairBarcode; + // } + // catch (Exception err) + // { + // ////ApplicationLog.WriteLog(err, "MesWebFun_baseFun:MobySelect"); + // } + // return data; + //} + private static string MaterialList_String(string OpName) + { + string jsonStr_Materail = ""; + try + { + string orderNum = ""; + int EngineTypeID = 0; + string EngineType = ""; + string EngineID = ""; + string PartPallet_Code = ""; + int IsrepairBarcode = 0; + string repairBarcode = ""; + string EngineTypeString = ""; + + MES1.Moby_Select(OpName, out orderNum, out EngineTypeID, out EngineType, out EngineID, out PartPallet_Code, out IsrepairBarcode, out repairBarcode, out EngineTypeString); + DataTable dt_Material; + + MES.PartMaterialVerify_Select(OpName, EngineTypeID, EngineType, out dt_Material); + if (dt_Material != null) + { + if (dt_Material.Rows.Count > 0) + { + jsonStr_Materail = JsonHelper.CreateJsonParameters(dt_Material); + } + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "MesWebFun_baseFun:MaterialList"); + } + return jsonStr_Materail; + } + private static string MaterialList_String_FirstOpName(string OpName) + { + string jsonStr_Materail = ""; + try + { + string orderNum = ""; + int EngineTypeID = 0; + string EngineType = ""; + string EngineID = ""; + string PartPallet_Code = ""; + int IsrepairBarcode = 0; + string repairBarcode = ""; + string EngineTypeString = ""; + + MES1.Moby_Select_FirstOpName(OpName, out orderNum, out EngineTypeID, out EngineType, out EngineID, out PartPallet_Code, out IsrepairBarcode, out repairBarcode, out EngineTypeString); + DataTable dt_Material; + + MES.PartMaterialVerify_Select(OpName, EngineTypeID, EngineType, out dt_Material); + if (dt_Material != null) + { + if (dt_Material.Rows.Count > 0) + { + jsonStr_Materail = JsonHelper.CreateJsonParameters(dt_Material); + } + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "MesWebFun_baseFun:MaterialList"); + } + return jsonStr_Materail; + } + + private static string ShowTimelyQuality_String(string OpName) + { + string text = ""; + try + { + string orderNum = ""; + int EngineTypeID = 0; + string EngineType = ""; + string EngineID = ""; + string PartPallet_Code = ""; + int IsrepairBarcode = 0; + string repairBarcode = ""; + string EngineTypeString = ""; + DataTable dt; + + MES1.Moby_Select(OpName, out orderNum, out EngineTypeID, out EngineType, out EngineID, out PartPallet_Code, out IsrepairBarcode, out repairBarcode, out EngineTypeString); + MES.QualitySelect(OpName, EngineID, out dt); + if (dt != null) + { + if (dt.Rows.Count > 0) + { + text = JsonHelper.CreateJsonParameters(dt); + } + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "MesWebFun_baseFun:Quality_Select"); + } + return text; + } + private static string ShowTimelyQuality_String_FirstOpName(string OpName) + { + string text = ""; + try + { + string orderNum = ""; + int EngineTypeID = 0; + string EngineType = ""; + string EngineID = ""; + string PartPallet_Code = ""; + int IsrepairBarcode = 0; + string repairBarcode = ""; + string EngineTypeString = ""; + DataTable dt; + MES1.Moby_Select_FirstOpName(OpName, out orderNum, out EngineTypeID, out EngineType, out EngineID, out PartPallet_Code, out IsrepairBarcode, out repairBarcode, out EngineTypeString); + MES.QualitySelect(OpName, EngineID, out dt); + if (dt != null) + { + if (dt.Rows.Count > 0) + { + text = JsonHelper.CreateJsonParameters(dt); + } + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "MesWebFun_baseFun:Quality_Select"); + } + return text; + } + + private static string OrderFormList_String() + { + string enginetypelist = ""; + try + { + System.Data.DataTable dt = null; + ShaftPosition.EngineType_Select(out dt); + if (dt != null) + { + if (dt.Rows.Count > 0) + { + enginetypelist = JsonHelper.DataTableToJson(dt); + } + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "MesWebFun_baseFun:Orderenginetypeselect"); + } + return enginetypelist; + } + + /// + /// 消息提醒 + /// + /// + private static string Notice_String(string opname) + { + string text = ""; + try + { + System.Data.DataTable dt = null; + MES.ShowWindowNotice(opname, out dt); + if (dt != null) + { + if (dt.Rows.Count > 0) + { + text = JsonHelper.DataTableToJson(dt); + } + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "MesWebFun_baseFun:ShowWindowNotice"); + } + return text; + } + + /// + /// 批量发送WEB消息(Value为BOOL值) + /// + /// 消息编号组合 + /// 消息值组合 + /// 工位号 + static public void Sendmessage(string MessageNumm, string Value, string OpName) + { + for (int i = 0; i < MessageNumm.Length; i++) + { + Sendmessage(MessageNumm[i], Value[i].ToString(), OpName); + + } + } + + /// + /// 选择发送给WEB的消息 + /// + /// 消息类型 + /// 消息工位 + static void Sendmessage(char Num, string Value, string OpName) + { + string SendMessage; + switch (Num) + { + case '1': + //1(直接在界面通过选择机型确认工序内容) + SendMessage = "MES|ProcessList|" + OpName + "|" + Value; + AsyncSendMessage(SendMessage); + break; + + case '2': + //2显示物料 + SendMessage = "MES|MaterialList|" + OpName + "|" + Value; + AsyncSendMessage(SendMessage); + break; + + case '3': + + //3显示操作指导图片 + SendMessage = "MES|PicShow|" + OpName + "|" + Value; + AsyncSendMessage(SendMessage); + break; + case '4': + //3显示操作指导图片 + SendMessage = "MES|OrderFormList|" + OpName + "|" + Value; + AsyncSendMessage(SendMessage); + break; + + case '5': + SendMessage = "MES|ShowMoby|" + OpName + "|" + Value; + AsyncSendMessage(SendMessage); + break; + case '6': + SendMessage = "MES|MaterialCheckPosition|" + OpName + "|" + Value; + AsyncSendMessage(SendMessage); + break; + case '7': + SendMessage = "MES|WorkStart|" + OpName + "|" + Value; + AsyncSendMessage(SendMessage); + break; + case '8': + SendMessage = "MES|OrderFormList|" + OpName + "|" + Value; + AsyncSendMessage(SendMessage); + break; + case '9': + SendMessage = "MES|ConfirmOkGo|" + OpName + "|" + Value; + AsyncSendMessage(SendMessage); + break; + case 'a': + SendMessage = "MES|FixAllow|" + OpName + "|" + Value; + AsyncSendMessage(SendMessage); + break; + case 'b': + SendMessage = "MES|ShaftPosition|" + OpName + "|" + Value; + AsyncSendMessage(SendMessage); + break; + case 'c': + SendMessage = "MES|ShowQuality|" + OpName + "|" + Value; + AsyncSendMessage(SendMessage); + break; + } + } + ///// + ///// 发送信息到MES通讯服务器或者其他的 + ///// + ///// + //static private void AsyncSendMessage1(string Message) + //{ + // MIS_BASE.asyncSendMessage(Message); + //} + + + } +} \ No newline at end of file diff --git a/MisDataFun/SendMessageToWebMqtt/SendMessageFun.cs b/MisDataFun/SendMessageToWebMqtt/SendMessageFun.cs new file mode 100644 index 0000000..e9aae41 --- /dev/null +++ b/MisDataFun/SendMessageToWebMqtt/SendMessageFun.cs @@ -0,0 +1,231 @@ +using bizFacade; +using MesServerWork; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MesServerFunctions +{ + /// + /// 命令 + ///显示托盘信息√ case "ShowMoby": + ///显示操作指南√ case "ProcessList": + ///显示物料√ case "MaterialList": + ///显示操作图片√ case "PicShow": + ///显示拧紧位置√ case "ShaftPosition": + ///实时显示质量数据√ case "ShowTimelyQuality": + ///手动拧紧实时显示质量数据√case "ShowTimelyQuality_Tight": + ///√ case "OrderFormList": + ///弹窗消息√ case "Notice": + ///LED消息提醒√ case "ScrollNotice": + ///物料检测初始化√ case "MaterialCheckPosition": + ///返修质量数据显示√ case "RepairQuality" + /// + /// + public class SendMessageFun + { + /// + /// 批量发送WEB消息(Value为BOOL值) + /// 1:显示工序内容 + /// 2:显示物料 + /// 3:显示操作指导图片 + /// 5:显示机型、工件流水号、订单信息 + /// c:显示质量数据 + /// + /// 消息编号组合 + /// 消息值组合 + /// 工位号 + static public void SendMessage(string MessageNumm, string Value, string OpName) + { + for (int i = 0; i < MessageNumm.Length; i++) + { + SendMessage(MessageNumm[i], Value[i].ToString(), OpName); + + } + } + /// + /// 向WEB发送信息(value为字符串) + /// + /// 消息种类 + /// 消息内容 + /// 工位号 + static public void SendInfomation(string Command, string Value, string OpName) + { + + string SendMessage = "MES|" + Command + "|" + OpName + "|" + Value; + AsyncSendMessage(SendMessage); + } + + static public void AsyncSendMessage_Notice(string opname, string notice) + { + //通知Web界面 + BaseDataSystemMES.Web_Notice_Insert(opname, notice); + string SendMessage = "MES|Notice|" + opname + "|" + "1"; + MIS_BASE.asyncSendMessage(SendMessage); + } + /// + /// 选择发送给WEB的消息 + /// 1:显示工序内容 + /// 2:显示物料 + /// 3:显示操作指导图片 + /// 5:显示机型、工件流水号、订单信息 + /// c:显示质量数据 + /// + /// 消息类型 + /// 消息工位 + static void SendMessage(char Num, string Value, string OpName) + { + string SendMessage; + switch (Num) + { + case '1': + //1(直接在界面通过选择机型确认工序内容) + SendMessage = "MES|ProcessList|" + OpName + "|" + Value; + AsyncSendMessage(SendMessage); + break; + + case '2': + //2显示物料 + SendMessage = "MES|MaterialList|" + OpName + "|" + Value; + AsyncSendMessage(SendMessage); + break; + + case '3': + + //3显示操作指导图片 + SendMessage = "MES|PicShow|" + OpName + "|" + Value; + AsyncSendMessage(SendMessage); + break; + case '4': + //3显示操作指导图片 + SendMessage = "MES|OrderFormList|" + OpName + "|" + Value; + AsyncSendMessage(SendMessage); + break; + + case '5': + SendMessage = "MES|ShowMoby|" + OpName + "|" + Value; + AsyncSendMessage(SendMessage); + break; + case '6': + SendMessage = "MES|MaterialCheckPosition|" + OpName + "|" + Value; + AsyncSendMessage(SendMessage); + break; + case '7': + SendMessage = "MES|WorkStart|" + OpName + "|" + Value; + AsyncSendMessage(SendMessage); + break; + case '8': + SendMessage = "MES|OrderFormList|" + OpName + "|" + Value; + AsyncSendMessage(SendMessage); + break; + case '9': + SendMessage = "MES|ConfirmOkGo|" + OpName + "|" + Value; + AsyncSendMessage(SendMessage); + break; + case 'a': + SendMessage = "MES|FixAllow|" + OpName + "|" + Value; + AsyncSendMessage(SendMessage); + break; + case 'b': + SendMessage = "MES|ShaftPosition|" + OpName + "|" + Value; + AsyncSendMessage(SendMessage); + break; + case 'c': + //SendMessage = "MES|ShowQuality|" + OpName + "|" + Value; + SendMessage = "MES|ShowTimelyQuality|" + OpName + "|" + Value; + AsyncSendMessage(SendMessage); + break; + } + } + + /// + /// 向WEB发送信息(value为字符串) + /// + /// 消息种类 + /// 消息内容 + /// 工位号 + //void SendInfomation(string Command, string Value, string OpName) + //{ + + // string SendMessage = "MES|" + Command + "|" + OpName + "|" + Value; + // AsyncSendMessage(SendMessage); + //} + + + /// + /// 发送在线产量、在线节拍 + /// + /// + /// + private void SendActuallyCount(string OpName, int tagValue) + { + //当工件离开时,更新在线产量、在线节拍 + if (tagValue == 0) + { + try + { + int opNameCount = 0;//在线产量 + int opNameCountTime = 0;//在线节拍 + + BaseDataSystemMES.OpNameCount_New(OpName, out opNameCount, out opNameCountTime); //基本数据_工作日历_班次产量查询_New + + SendInfomation("ActuallyCount", opNameCount.ToString() + "&" + opNameCountTime.ToString(), OpName); + + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function01:SendActuallyCount"); + } + } + } + + /// + /// 发送信息到MES通讯服务器或者其他的 + /// + /// + static public void AsyncSendMessage(string Message) + { + MIS_BASE.asyncSendMessage(Message); + } + + ///// + ///// 发送提示消息 + ///// + ///// + //static public void AsyncSendMessage_Notice(string opname, string notice) + //{ + // //通知Web界面 + // BaseDataSystemMES.Web_Notice_Insert(opname, notice); + // string SendMessage = "MES|Notice|" + opname + "|" + "1"; + // MIS_BASE.asyncSendMessage(SendMessage); + //} + + /// + /// 发送信息到打印机 + /// + /// + private void asyncSendMessageToMark(string Message) + { + string messageSend = (string)Message; + //UDPClientSend.Send_ALL(ApplicationConfig.MES_MarkPortNum, messageSend); + } + + /// + /// 发送信息到LED + /// + /// + private void asyncSendMessageLED(string OpName) + { + + //发送到大屏幕显示 41104 + string strMessage = "MIS|" + OpName + "|" + "0" + "|" + "1"; + //UDPClientSend.Send_ALL(ApplicationConfig.Port_ShowLED_ProductCount, strMessage); + + } + + + } +} + diff --git a/MisDataFun/WebSubmit/13.1WebSubmit.csproj b/MisDataFun/WebSubmit/13.1WebSubmit.csproj new file mode 100644 index 0000000..4babaa3 --- /dev/null +++ b/MisDataFun/WebSubmit/13.1WebSubmit.csproj @@ -0,0 +1,102 @@ + + + + + Debug + AnyCPU + {624F0E91-00F5-4ED9-8537-8F9EAAEF2F1F} + Library + Properties + WebSubmit + WebSubmit + v4.6.1 + 512 + true + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + {1a10fdb2-1a6a-44a8-ab4d-33387563247e} + 00-0Json8.3.1 + + + {5fd5de57-cc26-4fd0-b852-5362123bc4ff} + 00-1AppConfigSetForm + + + {f55da1a0-a982-4479-8c47-0d9a5aaf3e18} + 00MesWorkMqtt + + + {0d1af432-439a-4920-8692-43ae139f5530} + 01_01DoWhatPlc + + + {3e6d1dd5-01c9-435f-9941-61f906ce35bb} + 02_02WebApiCallPLC + + + {f434e066-4c59-47c8-aa82-6f48cc84501a} + 04-DataBaseAccess + + + {f0a0c525-03fd-428a-9b17-7f54aa0e4475} + 07BusinessFacade + + + {d98be764-adeb-488d-9714-61e308aa8201} + 08-WebFun_base + + + {90e76fb4-646d-45e2-95db-0b8ab4e465d6} + 09-MesDataFunction + + + {e4eb6420-906d-4672-947a-ca33ddcdadfc} + 12SendMessageToWeb + + + + \ No newline at end of file diff --git a/MisDataFun/WebSubmit/Db.cs b/MisDataFun/WebSubmit/Db.cs new file mode 100644 index 0000000..91cc34b --- /dev/null +++ b/MisDataFun/WebSubmit/Db.cs @@ -0,0 +1,74 @@ +using System; +using System.Collections.Generic; +using System.Data.SqlClient; +using System.Data; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using DataLinkMesWork; + +namespace MesServerFunctions +{ + public class Db + { + /// + /// 北汽福田变速器序列号总线上线_获得机型信息 + /// + /// + /// + /// + /// + /// 0 不重号;1 重号;2:失败 + /// + public static bool GetEngineType(string partSn, out int EngineTypeID, out string EngineType, out string EngineID,out int IsRepeatedNumber) + { + DataTable dt = new DataTable(); + EngineTypeID = 0; + EngineType = ""; + EngineID = ""; + IsRepeatedNumber = 2; + string produceName = "北汽福田变速器序列号总线上线_获得机型信息"; + SqlParameter[] thisParms = new SqlParameter[1]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@变速器序列号", partSn); + + thisParms[2].Direction = ParameterDirection.Output; + if (DataAccess.ExecuteStoredProcedure(produceName, ref thisParms,out dt)) + { + if(dt.Rows.Count > 0) + { + IsRepeatedNumber = Convert.ToInt32( dt.Rows[0]["IsRepeatedNumber"]); + EngineTypeID = Convert.ToInt32(dt.Rows[0]["EngineTypeID"]); + EngineType = dt.Rows[0]["EngineType"].ToString(); + EngineID = dt.Rows[0]["EngineID"].ToString(); + return true; + } + } + return false; + } + /// + /// 北汽福田变速器序列号总线上线_增加 + /// + /// + /// + /// + /// + /// + public static bool UpLoadOpNameInsert(string partSn, int EngineTypeID, string EngineType, string OpName) + { + + string produceName = "北汽福田变速器序列号总线上线_增加"; + SqlParameter[] thisParms = new SqlParameter[1]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@变速器序列号", partSn); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@基本型号代码", EngineTypeID); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@基本型号", EngineType); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@工位号", OpName); + return DataAccess.ExecuteStoredProcedure(produceName, ref thisParms); + } + + // ALTER PROCEDURE[dbo].[北汽福田变速器序列号总线上线_增加] + // @变速器序列号 nvarchar(50)='1333 050 062 0001*146012023*12345678',--'1333 050 062 0001' + //@基本型号代码 int=1, + //@基本型号 nvarchar(50)='1333 050 062 0001', + //@工位号 nvarchar(50) = 'J05PA010' + } +} diff --git a/MisDataFun/WebSubmit/MesServerFunction/Fun_WebSubmit.cs b/MisDataFun/WebSubmit/MesServerFunction/Fun_WebSubmit.cs new file mode 100644 index 0000000..5d3139e --- /dev/null +++ b/MisDataFun/WebSubmit/MesServerFunction/Fun_WebSubmit.cs @@ -0,0 +1,100 @@ + +using System.Threading; + +namespace MesServerFunctions +{ + public partial class Functions_BASE_WebSubmit + { + + //1.工件到位后,PLC给MES传递机型(DBX0.4)(44), + //2.MES判断是否扫描完成 + //3.若扫描完成,则MES给出合格放行(DBX2.5)(51) + /// + /// 扫描条码 + /// + /// + /// + public static void fun_Barcode(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(Barcode, e); + } + + + /// + /// 传递机型 + /// + /// + /// + public static void fun_EngineTypeGetOverPLC(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(EngineTypeGetOver_PLC, e); + } + + /// + /// 合格放行 + /// + /// + /// + public void fun_ConfirmOkGo(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(ConfirmOkGo, e); + } + + /// + /// 不合格放行 + /// + /// + /// + public void fun_FalseGo(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(FalseGO, e); + } + + + /// + /// 保存完成 20 + /// + /// + /// + public void fun_MesReadOver(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(MesReadOver, e); + } + + /// + /// 保存完成 19 + /// + /// + /// + public void fun_MesRead(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(MesRead, e); + } + + /// + /// 工件到位离开(清空所有的MES信号) + /// + /// + /// + public void fun_WorkStart(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(WorkStart, e); + } + + /// + /// 处理WEB页面发送过来的请求(m_Command + "|" + m_Value;) + /// + /// + /// + public void fun_WebSubmit(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(WebSubmit, e); + } + + public int fun_SubLineLoadPartCountMatch() + { + return SubLineLoadPartCountMatch; + } + + } +} diff --git a/MisDataFun/WebSubmit/MesServerFunction/vssver2.scc b/MisDataFun/WebSubmit/MesServerFunction/vssver2.scc new file mode 100644 index 0000000..775bb6c Binary files /dev/null and b/MisDataFun/WebSubmit/MesServerFunction/vssver2.scc differ diff --git a/MisDataFun/WebSubmit/Methods/EngineGetOverBaseWork.cs b/MisDataFun/WebSubmit/Methods/EngineGetOverBaseWork.cs new file mode 100644 index 0000000..bb3faed --- /dev/null +++ b/MisDataFun/WebSubmit/Methods/EngineGetOverBaseWork.cs @@ -0,0 +1,286 @@ +using System; +using System.Data; +using bizFacade; +using MesServerWork; +//using SystemFramework; + + +namespace MesServerFunctions +{ + partial class Functions_BASE_WebSubmit + { + /// + /// 分线上总线的数量 + /// + public static int SubLineLoadPartCount = 2; + /// + /// 分线上总线已经匹配的数量 + /// + public static int SubLineLoadPartCountMatch = 0; + /// + /// 正常逻辑工作 + /// + /// + /// + /// + /// + /// + private static void EngineTypeGetOver_PLC_Work(string OpName, int EngineTypeID, string EngineType, string EngineID, int PartPallet_Code,string OrderForm) + { + int IsAllowWork; + int MES_QualityMask = 1; + int repairPart;//读取返修标志 + int IsrepairBarcode = 0;//拆解返修标志 + + //string OrderForm = "";//订单号 + string repairBarcode = "";//拆解返修条码 + + DataTable dt;//读取订单信息 + + MIS_BASE.Read_OnlineRepair(OpName, out repairPart); + BaseDataSystemMES.GetEngineID_Select(OpName, EngineID, out dt); + + if (dt != null && dt.Rows.Count > 0) + { + //OrderForm = Convert.ToString(dt.Rows[0]["订单号"]); + IsrepairBarcode = Convert.ToInt32(dt.Rows[0]["拆解标志"]); + repairBarcode = Convert.ToString(dt.Rows[0]["拆解返修条码"]); + } + //记录MOBY信息(只限总装工位) + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, OrderForm,EngineTypeID, EngineType, EngineID, PartPallet_Code, repairPart, IsrepairBarcode, repairBarcode); + SaveMobyMessage(OpName, EngineTypeID, EngineType, EngineID, OrderForm); + BaseDataSystemMES.MaterialPush_EngineIDStatus_Insert(OpName); + BaseDataSystemMES.MesServer_Process_EngineTypeOver(OpName); + Sendmessage("5123", "1111", OpName); + + MIS_BASE.Read_PalletInfo(OpName, out MES_QualityMask); + SendInfomation("QualityMask", Convert.ToString(MES_QualityMask), OpName); + if (MES_QualityMask != 1) + { + //工作完成 + MIS_BASE.Write_MaterialVerifyOver(OpName, true); + SendInfomation("NgGO", "1", OpName);//显示不合格标志 + return; + } + + BaseDataSystemMES.MesServer_Judge_IsCanWork(OpName, out IsAllowWork); + if (IsAllowWork == 1) + { + Match(OpName, EngineID, EngineTypeID, EngineType, PartPallet_Code);//匹配 + } + } + + + /// + /// 保存MOBY信息 + /// + /// + /// + /// + /// + private static void SaveMobyMessage(string OpName, int engineTypeID, string engineType, string engineID, string orderForm) + { + + if (MIS_BASE.hashtable_EngineGetOver_EngineTypeID == null) + { + MIS_BASE.InitHashtable_MesServerCode(); + } + if (MIS_BASE.hashtable_EngineGetOver_EngineTypeID.ContainsKey(OpName)) + { + MIS_BASE.hashtable_EngineGetOver_EngineTypeID[OpName] = engineTypeID; + } + if (MIS_BASE.hashtable_EngineGetOver_EngineType.ContainsKey(OpName)) + { + MIS_BASE.hashtable_EngineGetOver_EngineType[OpName] = engineType; + } + if (MIS_BASE.hashtable_EngineGetOver_EngineID.ContainsKey(OpName)) + { + MIS_BASE.hashtable_EngineGetOver_EngineID[OpName] = engineID; + } + if (MIS_BASE.hashtable_EngineGetOver_OrderForm.ContainsKey(OpName)) + { + MIS_BASE.hashtable_EngineGetOver_OrderForm[OpName] = orderForm; + } + } + + /// + /// 返修件需要工作 + /// + /// 工位号 + private static void IsNeedRepaire_OK(string OpName) + { + + int isRepair; + int engineTypeID; + + string engineType = ""; + string engineID = ""; + string palletCode = ""; + string orderForm = ""; + string repairCode = ""; + //从监控系统中查询出本工位信息 + BaseDataSystemMES.OpName_MIS_Moby_Select(OpName, + out orderForm, out engineTypeID, out engineType, + out engineID, out palletCode, out isRepair, out repairCode); + + EngineTypeGetOver_PLC_Work(OpName, engineTypeID, engineType, engineID, Convert.ToInt32(palletCode),orderForm); + } + /// + /// 正常匹配分线和总线 + /// + /// + /// 总线工件号 + /// 总线工件机型代码 + /// 总线工件机型 + private static void Match(string opName, string engineID, int engineTypeID, string engineType, int PartPallet_Code) + { + try + { + bool m_EngineGetOver_PLC_SubLine; + int engineTypeID_SubLine; + int partPallet_Code_SubLine; + int PalletInfo = 1;//总线托盘状态 + + string opName_SubLine = "";//分线工件信息 + string engineID_SubLine; + string engineType_SubLine; + string AlarmStr; + if (MIS_BASE.hashtable_OpNameRepair == null) + { + MIS_BASE.InitHashtable_MesServerCode(); + } + //第一步:获取分线中间交互工位号 + if (MIS_BASE.hashtable_OpNameRepair.ContainsKey(opName)) + { + opName_SubLine = MIS_BASE.hashtable_OpNameRepair[opName].ToString(); + } + if (opName_SubLine == "") + { + return; + } + + //第二步:获取分线传递机型信号 + MIS_BASE.Read_EngineGetOver_PLC(opName_SubLine, out m_EngineGetOver_PLC_SubLine); + if (!m_EngineGetOver_PLC_SubLine) return;//必须工件同时到位才能进行匹配 + + //第三步:判断合格标志 + MIS_BASE.Read_PalletInfo(opName_SubLine, out PalletInfo); + if (PalletInfo == 2) return; //若不合格则返回不进行匹配 + string OrderForm; + //第四步:获取分线的信息,匹配验证 + MIS_BASE.GetEngineTypeFromPLC(opName_SubLine, out engineTypeID_SubLine, out engineType_SubLine, out engineID_SubLine, out partPallet_Code_SubLine,out OrderForm); + //判断分线数据是否合格 + //if (!BaseDataSystemMES.QulityDataVerify(opName, engineID_SubLine, out AlarmStr) && !BaseDataSystemMES.QualityVerifyStatus_Hash_Read(opName)) + //{ + // SendInfomation("LineoutAlert", AlarmStr, opName); + // return; + //} + + if (engineTypeID_SubLine == engineTypeID) + { + BaseDataSystemMES.SubLineLoadPartCountMatch_Select(opName, out SubLineLoadPartCountMatch); + SubLineLoadPartCountMatch = SubLineLoadPartCountMatch + 1; + BaseDataSystemMES.SubLineLoadPartCountMatch_Update(opName, SubLineLoadPartCountMatch); + + + BaseDataSystemMES.MailLineAndSubLineData_Insert(engineID, engineTypeID, engineType, engineID_SubLine);//分线上总线数据转移 + MIS_BASE.Write_Match(opName, true);//匹配结果 + MIS_BASE.Write_MatchingCompleted(opName, true);//匹配完成 + if(SubLineLoadPartCountMatch== SubLineLoadPartCount) + { + MIS_BASE.Write_FixAllow(opName, true); + SubLineLoadPartCountMatch = 0; + BaseDataSystemMES.SubLineLoadPartCountMatch_Update(opName, SubLineLoadPartCountMatch); + + } + + SendInfomation("MatchSuccess", "1", opName); + sendmessage(opName, 1, "Match");//匹配结果 + } + else + { + MIS_BASE.Write_Match(opName, false);//匹配结果 + MIS_BASE.Write_MatchingCompleted(opName, true);//匹配完成//68:1、取消返修;2、匹配成功 自己监控发送 MES|MatchingCompleted + + //发送匹配完成和匹配结果信息 + AsyncSendMessage_Notice(opName,"匹配失败,工件型号不匹配!"); + SendInfomation("MatchSuccess", "0", opName); + sendmessage(opName, 0, "Match");//匹配结果 + } + + } + catch (Exception err) + { + ////ApplicationLog.WriteLog("Match:" + err.ToString()); + + } + } + + + + /// + /// 强制匹配分线和总线 + /// + /// + private static void ForceMatch(string opName) + { + try + { + bool m_EngineGetOver_PLC_SubLine; + bool m_EngineGetOver_PLC; + + int engineTypeID_SubLine; + int engineTypeID; + int partPallet_Code_SubLine; + int partPallet_Code; + + string opName_SubLine = "";//分线工件信息 + string engineID_SubLine; + string engineType_SubLine; + string engineID; + string engineType; + if (MIS_BASE.hashtable_OpNameRepair == null) + { + MIS_BASE.InitHashtable_MesServerCode(); + } + //获取分线中间交互工位号 + if (MIS_BASE.hashtable_OpNameRepair.ContainsKey(opName)) + { + opName_SubLine = MIS_BASE.hashtable_OpNameRepair[opName].ToString(); + } + if (opName_SubLine == "") + { + return; + } + + MIS_BASE.Read_EngineGetOver_PLC(opName_SubLine, out m_EngineGetOver_PLC_SubLine);//1:读取分线工件到位的传递机型信号。 + + if (!m_EngineGetOver_PLC_SubLine) return;//必须工件同时到位才能进行匹配 + + MIS_BASE.Read_EngineGetOver_PLC(opName, out m_EngineGetOver_PLC);//2:读取总线工件到位的传递机型信号。 + + if (!m_EngineGetOver_PLC) return;//必须工件同时到位才能进行匹配 + string OrderForm; + MIS_BASE.GetEngineTypeFromPLC(opName_SubLine, out engineTypeID_SubLine, out engineType_SubLine, out engineID_SubLine, out partPallet_Code_SubLine,out OrderForm);//获取分线的信息 + MIS_BASE.GetEngineTypeFromPLC(opName, out engineTypeID, out engineType, out engineID, out partPallet_Code, out OrderForm); + + BaseDataSystemMES.MailLineAndSubLineData_Insert(engineID, engineTypeID, engineType, engineID_SubLine);//分线上总线数据转移 + + MIS_BASE.Write_Match(opName, true);//匹配结果 + MIS_BASE.Write_MatchingCompleted(opName, true);//匹配完成 + + SendInfomation("MatchSuccess", "1", opName);//界面显示匹配成功 + + MIS_BASE.Write_FixAllow(opName, true);//允许PLC工作 + + //发送匹配完成和匹配结果信息 + sendmessage(opName, 1, "MatchingComplete");//匹配完成 + sendmessage(opName, 1, "Match");//匹配结果 + } + catch + { + + } + } + } +} diff --git a/MisDataFun/WebSubmit/Methods/SubmitToMisweb.cs b/MisDataFun/WebSubmit/Methods/SubmitToMisweb.cs new file mode 100644 index 0000000..65cb804 --- /dev/null +++ b/MisDataFun/WebSubmit/Methods/SubmitToMisweb.cs @@ -0,0 +1,145 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using bizFacade; +//using SystemFramework; + +namespace MesServerFunctions +{ + + /// + /// 此类用于向WEB发送各种类型消息 + /// + partial class Functions_BASE_WebSubmit + { + + + /// + /// 批量发送WEB消息(Value为BOOL值) + /// + /// 消息编号组合 + /// 消息值组合 + /// 工位号 + static void Sendmessage(string MessageNumm,string Value, string OpName) + { + for (int i=0;i + /// 选择发送给WEB的消息 + /// + /// 消息类型 + /// 消息工位 + static void Sendmessage(char Num,string Value, string OpName) + { + string SendMessage; + switch (Num) + { + case '1': + //1(直接在界面通过选择机型确认工序内容) + SendMessage = "MES|ProcessList|" + OpName + "|" + Value; + AsyncSendMessage(SendMessage); + break; + + case '2': + //2显示物料 + SendMessage = "MES|MaterialList|" + OpName + "|" + Value; + AsyncSendMessage(SendMessage); + break; + + case '3': + + //3显示操作指导图片 + SendMessage = "MES|PicShow|" + OpName + "|" + Value; + AsyncSendMessage(SendMessage); + break; + case '4': + //3显示操作指导图片 + SendMessage = "MES|OrderFormList|" + OpName + "|" + Value; + AsyncSendMessage(SendMessage); + break; + + case '5': + SendMessage = "MES|ShowMoby|" + OpName + "|" + Value; + AsyncSendMessage(SendMessage); + break; + case '6': + SendMessage = "MES|MaterialCheckPosition|" + OpName + "|" +Value; + AsyncSendMessage(SendMessage); + break; + case '7': + SendMessage = "MES|WorkStart|" + OpName + "|" + Value; + AsyncSendMessage(SendMessage); + break; + case '8': + SendMessage = "MES|OrderFormList|" + OpName + "|" + Value; + AsyncSendMessage(SendMessage); + break; + case '9': + SendMessage = "MES|ConfirmOkGo|" + OpName + "|" + Value; + AsyncSendMessage(SendMessage); + break; + case 'a': + SendMessage = "MES|FixAllow|" + OpName + "|" + Value; + AsyncSendMessage(SendMessage); + break; + case 'b': + SendMessage = "MES|ShaftPosition|" + OpName + "|" + Value; + AsyncSendMessage(SendMessage); + break; + case 'c': + SendMessage = "MES|ShowQuality|" + OpName + "|" + Value; + AsyncSendMessage(SendMessage); + break; + } + } + + /// + /// 向WEB发送信息(value为字符串) + /// + /// 消息种类 + /// 消息内容 + /// 工位号 + static void SendInfomation(string Command, string Value, string OpName) + { + + string SendMessage = "MES|" + Command + "|" + OpName + "|" + Value; + AsyncSendMessage(SendMessage); + } + + + /// + /// 发送在线产量、在线节拍 + /// + /// + /// + private void SendActuallyCount(string OpName, int tagValue) + { + //当工件离开时,更新在线产量、在线节拍 + if (tagValue == 0) + { + try + { + int opNameCount = 0;//在线产量 + int opNameCountTime = 0;//在线节拍 + + BaseDataSystemMES.OpNameCount_New(OpName, out opNameCount, out opNameCountTime); //基本数据_工作日历_班次产量查询_New + + SendInfomation("ActuallyCount", opNameCount.ToString() + "&" + opNameCountTime.ToString(), OpName); + + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function01:SendActuallyCount"); + } + } + } + + + } +} diff --git a/MisDataFun/WebSubmit/Methods/UDP.Send.cs b/MisDataFun/WebSubmit/Methods/UDP.Send.cs new file mode 100644 index 0000000..9b13498 --- /dev/null +++ b/MisDataFun/WebSubmit/Methods/UDP.Send.cs @@ -0,0 +1,62 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using MesServerWork; +//using BasicData; +using System.Collections; +using bizFacade; +//using SystemFramework; +using System.Data; +using System.Threading; + +namespace MesServerFunctions +{ + partial class Functions_BASE_WebSubmit + { + /// + /// 发送信息到MES通讯服务器或者其他的 + /// + /// + private static void AsyncSendMessage(string Message) + { + MIS_BASE.asyncSendMessage(Message); + } + + /// + /// 发送提示消息 + /// + /// + private static void AsyncSendMessage_Notice(string opname, string notice) + { + //通知Web界面 + BaseDataSystemMES.Web_Notice_Insert(opname, notice); + string SendMessage = "MES|Notice|" + opname + "|" + "1"; + MIS_BASE.asyncSendMessage(SendMessage); + } + + /// + /// 发送信息到打印机 + /// + /// + private void asyncSendMessageToMark(string Message) + { + string messageSend = (string)Message; + //UDPClientSend.Send_ALL(ApplicationConfig.MES_MarkPortNum, messageSend); + } + + /// + /// 发送信息到LED + /// + /// + private void asyncSendMessageLED(string OpName) + { + + //发送到大屏幕显示 41104 + string strMessage = "MIS|" + OpName + "|" + "0" + "|" + "1"; + //UDPClientSend.Send_ALL(ApplicationConfig.Port_ShowLED_ProductCount, strMessage); + + } + + } +} diff --git a/MisDataFun/WebSubmit/Methods/vssver2.scc b/MisDataFun/WebSubmit/Methods/vssver2.scc new file mode 100644 index 0000000..7b1a830 Binary files /dev/null and b/MisDataFun/WebSubmit/Methods/vssver2.scc differ diff --git a/MisDataFun/WebSubmit/OpcServer/Barcode.cs b/MisDataFun/WebSubmit/OpcServer/Barcode.cs new file mode 100644 index 0000000..ae7da43 --- /dev/null +++ b/MisDataFun/WebSubmit/OpcServer/Barcode.cs @@ -0,0 +1,86 @@ +using System; +using bizFacade; + +//using SystemFramework; +using MesServerWork; + +namespace MesServerFunctions +{ + partial class Functions_BASE_WebSubmit + { + ///第一步,判断条码类型,根据条码类型,执行对应的存储过程 + ///第二步,条码类型(将扫描的条码保存到对应的表中) + ///第三步,扫描完成之后给出允许工作信号 + /// 处理页面扫描条码 + /// + /// + /// + public static void Barcode(object e) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + string barcode = Convert.ToString(msgEvent.TagValue); + + int EngineTypeID;//机型代码 + string EngineType;//机型 + string EngineID;//工件编号 + + int IsRepeatedNumber = 2; + //1:获得申请上线信息后,扫描条码才处理业务 + bool ispartload; + MIS_BASE.Read_PartLoad(OpName, out ispartload); + if(!ispartload) + { + AsyncSendMessage_Notice(OpName, "设备请发出申请上线信号(DBX500.3=1)"); + return; + } + //2: 判断是否重号, 从数据库获得机型、机型代码等信息 + string partSn = barcode; + Db.GetEngineType( partSn, out EngineTypeID, out EngineType, out EngineID, out IsRepeatedNumber); + //IsRepeatedNumber 0 不重号;1 重号;2:失败 + + switch (IsRepeatedNumber) + { + case 0: + + ////将产品信息写入PLC + MIS_BASE.Write_EngineTypeID_MES(OpName, EngineTypeID); + MIS_BASE.Write_EngineType_MES(OpName, EngineType); + MIS_BASE.Write_EngineID_MES(OpName, EngineID); + + // 工位号],[订单号],[产品型号代码],[变速器序列号],[发动机型号],[机型基本代码],[变速器总成号] ,[托盘号] + // [产品型号代码_MES],[变速器序列号_MES],[发动机型号_MES] + // [机床上电],[循环开始],[机床故障],[上料无件],[下料堵塞],[工件到位] + // [传递机型],[申请上件],[允许保存],[保存完成],[合格标志],[前序合格] + // [工号],[班次],[是否返修件],[合格放行],[不合格放行],[扫描条码] + + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, "产品型号代码_MES", EngineTypeID.ToString()); + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, "发动机型号_MES", EngineType); + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, "变速器序列号_MES", EngineID); + + + + MIS_BASE.Write_EngineTypeGetOver_MES(OpName, true); + + //等待PLC将数据写入RFID;写入PLC的DB块,通知MES验证RFID机型数据是否正确传递 + + break; + case 1: + AsyncSendMessage_Notice(OpName, "变速器序列号 重号,请确认!"); + break; + case 2: + AsyncSendMessage_Notice(OpName, "变速器序列号获取机型代码失败 ,请确认!"); + break; + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function08:Barcode"); + } + } + + + } +} diff --git a/MisDataFun/WebSubmit/OpcServer/ConfirmOkGo.cs b/MisDataFun/WebSubmit/OpcServer/ConfirmOkGo.cs new file mode 100644 index 0000000..ee5bccf --- /dev/null +++ b/MisDataFun/WebSubmit/OpcServer/ConfirmOkGo.cs @@ -0,0 +1,35 @@ +using System; +//using SystemFramework; +using MesServerWork; + +namespace MesServerFunctions +{ + partial class Functions_BASE_WebSubmit + { + /// + /// 合格放行 + /// + /// + /// + private void ConfirmOkGo(object e) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + + if (tagValue == 1) + { + MIS_BASE.Write_MaterialVerifyOver(OpName, true);//工作完成 + SendInfomation("OrderFormList","1", OpName); + + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function08:ConfirmOkGo"); + } + } + } +} diff --git a/MisDataFun/WebSubmit/OpcServer/EngineGetOver.cs b/MisDataFun/WebSubmit/OpcServer/EngineGetOver.cs new file mode 100644 index 0000000..f572117 --- /dev/null +++ b/MisDataFun/WebSubmit/OpcServer/EngineGetOver.cs @@ -0,0 +1,87 @@ +using System; +using bizFacade; +using MesServerWork; +//using SystemFramework; + +namespace MesServerFunctions +{ + partial class Functions_BASE_WebSubmit + { + + /// + /// PLC传递机型处理 + /// + /// + /// + private static void EngineTypeGetOver_PLC(object e) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + //判断PLC机型与MES机型是否一致 + if (tagValue == 1) + { + bool MesRead = false; + + int EngineTypeID;//机型代码 + int PartPallet_Code;//托盘编号 + + string EngineType;//机型 + string EngineID;//工件编号 + + int EngineTypeID_MES;//机型代码 + string EngineType_MES;//机型 + string EngineID_MES;//工件编号 + + MIS_BASE.Read_QualityData_Read_CF(OpName, out MesRead); + + //第一步,判断允许保存和保存完成信号是否全部被清空,若未清空,则通知复位MES&PLC + if (MesRead) + { + //未能清空信号,请求复位 + SendInfomation("AskReset", "1", OpName); + return; + } + string OrderForm; + MIS_BASE.GetEngineTypeFromPLC(OpName, out EngineTypeID, out EngineType, out EngineID, out PartPallet_Code,out OrderForm); + MIS_BASE.GetEngineTypeFromPLC_MES(OpName, out EngineTypeID_MES, out EngineType_MES, out EngineID_MES); + + // 工位号],[订单号],[产品型号代码],[变速器序列号],[发动机型号],[机型基本代码],[变速器总成号] ,[托盘号] + // [产品型号代码_MES],[变速器序列号_MES],[发动机型号_MES] + // [机床上电],[循环开始],[机床故障],[上料无件],[下料堵塞],[工件到位] + // [传递机型],[申请上件],[允许保存],[保存完成],[合格标志],[前序合格] + // [工号],[班次],[是否返修件],[合格放行],[不合格放行],[扫描条码] + + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.EngineTypeID, EngineTypeID.ToString()); + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.EngineType, EngineType); + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.EngineID, EngineID); + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.PartPallet_Code, PartPallet_Code.ToString()); + + //显示当前订单信息 + SendMessage.ShowMoby(OpName); + + if (EngineTypeID_MES == EngineTypeID & EngineID_MES == EngineID & EngineType_MES== EngineType) + { + MIS_BASE.Write_FixAllow(OpName, true); + + //显示 显示绿脸 + + return; + } + else + { + SendMessage.AsyncSendMessage_Notice(OpName, "码块RFID机型与MES机型不匹配!"); + } + + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function08:EngineTypeGetOver_PLC"); + } + } + + } +} diff --git a/MisDataFun/WebSubmit/OpcServer/FalseGO.cs b/MisDataFun/WebSubmit/OpcServer/FalseGO.cs new file mode 100644 index 0000000..b533190 --- /dev/null +++ b/MisDataFun/WebSubmit/OpcServer/FalseGO.cs @@ -0,0 +1,37 @@ +using System; +using MesServerWork; +//using SystemFramework; + + +namespace MesServerFunctions +{ + partial class Functions_BASE_WebSubmit + { + + /// + /// 返修放行 + /// + /// + /// + private void FalseGO(object e) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + + if (tagValue == 1) + { + MIS_BASE.Write_MaterialVerifyOver(OpName, true);//工作完成 + SendInfomation("OrderFormList", "1", OpName); + + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function08:FalseGO"); + } + } + } +} diff --git a/MisDataFun/WebSubmit/OpcServer/MesRead.cs b/MisDataFun/WebSubmit/OpcServer/MesRead.cs new file mode 100644 index 0000000..09f6741 --- /dev/null +++ b/MisDataFun/WebSubmit/OpcServer/MesRead.cs @@ -0,0 +1,49 @@ +using System; +using bizFacade; +//using SystemFramework; +using MesServerWork; + +namespace MesServerFunctions +{ + partial class Functions_BASE_WebSubmit + { + /// + /// 保存完成(针对半自动和手动压装工位) + /// + /// + /// + private void MesRead(object e) + { + try + { + int EngineTypeID; + string EngineType; + string EngineID; + int PartPallet_Code; + string OrderForm; + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + + if (tagValue == 1) + { + MIS_BASE.GetEngineTypeFromPLC(OpName, out EngineTypeID, out EngineType, out EngineID, out PartPallet_Code, out OrderForm); + //保存数据到线首表 + if (Db.UpLoadOpNameInsert(EngineID, EngineTypeID, EngineType, OpName)) + { + MIS_BASE.Write_MesReadOver(OpName, true); + SendMessage.SendActuallyCount(OpName, tagValue);//统计在线产量,在线节拍 + } + else + { + SendMessage.AsyncSendMessage_Notice(OpName, "保存上线数据失败!"); + } + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function08:MesReadOver"); + } + } + } +} diff --git a/MisDataFun/WebSubmit/OpcServer/MesReadOver.cs b/MisDataFun/WebSubmit/OpcServer/MesReadOver.cs new file mode 100644 index 0000000..11128f3 --- /dev/null +++ b/MisDataFun/WebSubmit/OpcServer/MesReadOver.cs @@ -0,0 +1,37 @@ +using System; +using bizFacade; +//using SystemFramework; +using MesServerWork; + +namespace MesServerFunctions +{ + partial class Functions_BASE_WebSubmit + { + /// + /// 保存完成(针对半自动和手动压装工位) + /// + /// + /// + private void MesReadOver(object e) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + + if (tagValue == 1) + { + + BaseDataSystemMES.Material_Insert(OpName, tagValue); + + MIS_BASE.Write_ConfirmOkGo(OpName, true); + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function08:MesReadOver"); + } + } + } +} diff --git a/MisDataFun/WebSubmit/OpcServer/WebSubmit.cs b/MisDataFun/WebSubmit/OpcServer/WebSubmit.cs new file mode 100644 index 0000000..f85423a --- /dev/null +++ b/MisDataFun/WebSubmit/OpcServer/WebSubmit.cs @@ -0,0 +1,309 @@ +using System; +using MesServerWork; +using bizFacade; +//using SystemFramework; + + +namespace MesServerFunctions +{ + partial class Functions_BASE_WebSubmit + { + /// + /// 处理WEB页面发送过来的请求(m_Command + "|" + m_Value;) + /// + /// + /// + public static void WebSubmit(object e) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + string Content = Convert.ToString(msgEvent.TagValue); + + string opName_SubLine = ""; + string engineID = "";//工件信息 + string[] dataArray = Content.Split('|'); + + if (dataArray.Length != 2) + return; + + + string m_Command = dataArray[0].ToString();//消息类型 + string m_Value = dataArray[1].ToString();//消息参数 + string[] m_Value_array = m_Value.Split('&');//消息参数数量 + int m_Value_length = m_Value_array.Length; //消息参数长度 + + if (MIS_BASE.hashtable_EngineGetOver_EngineTypeID == null) + { + MIS_BASE.InitHashtable_MesServerCode(); + } + if (MIS_BASE.hashtable_EngineGetOver_EngineID.ContainsKey(OpName)) + { + engineID = MIS_BASE.hashtable_EngineGetOver_EngineID[OpName].ToString(); + } + if (MIS_BASE.hashtable_OpNameRepair == null) + { + MIS_BASE.InitHashtable_MesServerCode(); + } + + + //获取分线中间交互工位号 + if (MIS_BASE.hashtable_OpNameRepair.ContainsKey(OpName)) + { + opName_SubLine = MIS_BASE.hashtable_OpNameRepair[OpName].ToString(); + } + //if (opName_SubLine == "") + //{ + // return; + //} + + DoWhatPlc.CustomeEvetnArgs _e = new DoWhatPlc.CustomeEvetnArgs(); + _e.OpName = OpName; + _e.TagValue = m_Value; + + //根据请求的命令处理逻辑 + switch (m_Command) + { + case "Barcode": + if (m_Value_length > 1) return; + fun_Barcode(_e); + break; + case "ConfirmOkGo"://合格放行 + //修改托盘状态 + + BaseDataSystemMES.BaseData_tagTable_Engine_IsNG_Delete(OpName, engineID); + MIS_BASE.Write_ConfirmOkGo(OpName, true); + MIS_BASE.Write_FalseGO(OpName, false); + break; + case "FalseGO"://返修放行 + //修改托盘状态 + BaseDataSystemMES.BaseData_tagTable_Engine_IsNG_Delete(OpName, engineID); + MIS_BASE.Write_FalseGO(OpName, true); + MIS_BASE.Write_ConfirmOkGo(OpName, false); + break; + case "NgGO"://不合格放行 + //修改托盘状态 + //保存不合格信息(必须保存不合格放行信息,由于B5A的Moby没有不合格标志位) + BaseDataSystemMES.BaseData_tagTable_Engine_IsNG_Insert(OpName, engineID, "", ""); + MIS_BASE.Write_FalseGO(OpName, true); + MIS_BASE.Write_ConfirmOkGo(OpName, false); + break; + case "OnLineState"://在线0、离线1、屏蔽2 + try + { + if (m_Value_length > 1) return; + int a = Convert.ToInt32(m_Value); + if (a <= 2) + { + BaseDataSystemMES.IsOnLine_Update(OpName, m_Value.ToString()); + MIS_BASE.Write_OnLineState(OpName, Convert.ToInt32(m_Value)); + } + } + catch + { + + } + break; + case "Reset"://复位,将MES所有的信息都复位了 + SetMoby(OpName);//将MES所有信号清空 + + break; + case "FixAllow"://重新拧紧 + break; + case "IsAutoGetEngineID"://自动手动申请编号(线首) + if (m_Value_length > 1) return; + MIS_BASE.Write_IsAutoGetEngineID(OpName, Convert.ToInt32(m_Value)); + break; + case "PartPalletGoOver"://空托盘放行 + MIS_BASE.Write_RepairUpline_MES(opName_SubLine, true); + //MIS_BASE.Write_PalletInfo(opName_SubLine, 4); + //MIS_BASE.Write_UpdatePalletOK(opName_SubLine, true); + MIS_BASE.Write_MaterialVerifyOver(opName_SubLine, true); + break; + case "SetMoby"://清空托盘(线首) + SetMoby(OpName);//将MES所有信号清空 + break; + case "RepairUplineMES"://返修上线 + MIS_BASE.Write_RepairUpline_MES(OpName, true); + break; + case "CancelRepair"://将返修件置为正常件 + + break; + case "PartPalletCode"://申请写入托盘号 + //MIS_BASE.Write_PartPalletCode_PLC(OpName, 1); + break; + case "WritePartPalletCode"://写入托盘号 + if (m_Value_length > 1) return; + MIS_BASE.Write_PalletCode(OpName, Convert.ToInt32(m_Value)); + break; + case "Normal"://启用正常拧紧工位 + MIS_BASE.Write_Normal(OpName, 1); + MIS_BASE.Write_UnNormal(OpName, 0); + break; + case "UnNormal"://启用备用拧紧工位 + MIS_BASE.Write_Normal(OpName, 0); + MIS_BASE.Write_UnNormal(OpName, 1); + break; + case "ResetDevice"://复位设备 + MIS_BASE.Write_ResetDevice(OpName, true); + System.Threading.Thread.Sleep(1000); + MIS_BASE.Write_ResetDevice(OpName, false); + break; + case "IsNeedRepaire"://返修上线(返修上线点) + if (Convert.ToInt32(m_Value) == 1) + { + //修改托盘状态 + MIS_BASE.Write_PalletInfo(OpName, 3); + //通知修改成功 + MIS_BASE.Write_UpdatePalletOK(OpName, true); + IsNeedRepaire_OK(OpName); + } + else if (Convert.ToInt32(m_Value) == 0) + { + //直接给出工作完成 + MIS_BASE.Write_MaterialVerifyOver(OpName, true); + } + break; + //强制匹配 + case "ForceMatch": + if (Convert.ToInt32(m_Value) == 1) + { + ForceMatch(OpName); + } + break; + case "PalletGO": + + if (Convert.ToInt32(m_Value) == 1) + { + //直接给出工作完成 + MIS_BASE.Write_MaterialVerifyOver(opName_SubLine, true); + } + break; + case "ContinueMatch": + BaseDataSystemMES.QualityVerifyStatus_Hash_Write(OpName, true); + fun_EngineTypeGetOverPLC(_e); + break; + //初始化网页信号 + case "IniSingalToWeb": + InitializeSingalToWeb(OpName); + break; + default: break; + } + } + catch(Exception err) + { + ////ApplicationLog.WriteLog(err, "Function08:WebSubmit"); + } + } + + private static void SetMoby(string OpName) + { + try + { + //清空Moby时,需要将MES信号清空 + MIS_BASE.Write_ClearMesMoby(OpName); + + BaseDataSystemMES.MesServer_Process_EngineTypeOver(OpName); + + Sendmessage("5123", "1111", OpName); + + MIS_BASE.Write_ResetDevice(OpName, true); + System.Threading.Thread.Sleep(1000); + MIS_BASE.Write_ResetDevice(OpName, false); + } + catch + { + + } + } + + + /// + /// 网页重现登录,恢复关闭前的页面状态 + /// + /// 工位号 + private static void InitializeSingalToWeb(string Opname) + { + bool S_WorkStart;//工件到位 DBX0.1 + bool S_EngineGetOver;//传递机型 DBX0.4 + bool S_FixAllow;//允许工作 DBX3.1 + bool S_MaterialVerifyOver;//工作完成 DBX2.3 + + int IsCompleted = 0; + int S_Match = 0; + int PalletInfo_SubLine = 0;//显示分线托盘状态 + + MIS_BASE.Read_WorkStart(Opname, out S_WorkStart); + if (S_WorkStart == true) + { + SendInfomation("WorkStart", Convert.ToString(Convert.ToInt32(S_WorkStart)), Opname); + sendmessage(Opname, Convert.ToInt32(S_WorkStart), "WorkStart_Subline"); + } + + sendmessage(Opname, Convert.ToInt32(S_WorkStart), "EngineTypeGetOverMES_Subline"); + + MIS_BASE.Read_EngineGetOver_PLC(Opname, out S_EngineGetOver); + if (S_EngineGetOver == true) + { + SendInfomation("EngineTypeGetOverPLC", Convert.ToString(Convert.ToInt32(S_EngineGetOver)), Opname); + sendmessage(Opname, Convert.ToInt32(S_EngineGetOver), "EngineTypeGetOverMES_Subline"); + } + + MIS_BASE.Read_FixAllow(Opname, out S_FixAllow); + + if (S_FixAllow == true) + { + SendInfomation("FixAllow", Convert.ToString(Convert.ToInt32(S_FixAllow)), Opname); + } + + MIS_BASE.Read_MaterialVerifyOver(Opname, out S_MaterialVerifyOver); + + if (S_MaterialVerifyOver == true) + { + SendInfomation("MaterialVerifyOver", Convert.ToString(Convert.ToInt32(S_MaterialVerifyOver)), Opname); + } + + MIS_BASE.Read_MatchingCompleted(Opname, out IsCompleted); //DBX1.3 是否匹配 + MIS_BASE.Read_Match(Opname, out S_Match); //DBX1.4 匹配结果 + + if (IsCompleted == 1 && S_Match == 1)//发送匹配完成和匹配结果信息 + { + SendInfomation("MatchingCompleted", "1", Opname); + SendInfomation("Match", "1", Opname); + SendInfomation("MatchSuccess", "1", Opname);//界面显示匹配成功 + } + else if (IsCompleted == 1 && S_Match == 0) + { + SendInfomation("MatchSuccess", "0", Opname);//界面显示匹配失败 + } + + if (MIS_BASE.hashtable_OpNameRepair == null) + { + MIS_BASE.InitHashtable_MesServerCode(); + } + string Opname_SubLine = ""; + if (MIS_BASE.hashtable_OpNameRepair.ContainsKey(Opname)) + { + Opname_SubLine = MIS_BASE.hashtable_OpNameRepair[Opname].ToString(); + } + if (Opname_SubLine == "") + { + return; + } + + MIS_BASE.Read_PalletInfo(Opname, out PalletInfo_SubLine); + sendmessage(Opname, PalletInfo_SubLine, "SubQualityMask"); + SendInfomation("ShowMobySubLine", Opname_SubLine, Opname);//显示分线机型及流水号 + } + + //分线发送工件到位信号函数 + private static void sendmessage(string OpName, int tagValue, string Command) + { + string SendMessage; + SendMessage = "MES|" + Command + "|" + OpName + "|" + tagValue; + AsyncSendMessage(SendMessage); + + } + } +} diff --git a/MisDataFun/WebSubmit/OpcServer/WorkStart.cs b/MisDataFun/WebSubmit/OpcServer/WorkStart.cs new file mode 100644 index 0000000..5ca7e09 --- /dev/null +++ b/MisDataFun/WebSubmit/OpcServer/WorkStart.cs @@ -0,0 +1,59 @@ +using System; +using bizFacade; +using MesServerWork; +//using SystemFramework; + + +namespace MesServerFunctions +{ + partial class Functions_BASE_WebSubmit + { + /// + /// 工件到位与离开时,清空MES自身信号 + /// + /// + /// + private void WorkStart(object e) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + + //线首显示订单信息 + + if (tagValue == 1) + { + //清空MOBY的产品流水号 + + // 北汽福田工位状态监控MOBY_增加 + // 工位号],[订单号],[产品型号代码],[变速器序列号],[发动机型号],[机型基本代码],[变速器总成号] ,[托盘号] + // [产品型号代码_MES],[变速器序列号_MES],[发动机型号_MES] + // [机床上电],[循环开始],[机床故障],[上料无件],[下料堵塞],[工件到位] + // [传递机型],[申请上件],[允许保存],[保存完成],[合格标志],[前序合格] + // [工号],[班次],[是否返修件],[合格放行],[不合格放行],[扫描条码] + //[到达时间],[离开时间],[持续时间] + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.WorkStartIn, DateTime.Now.ToString()); + + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.EngineID, tagValue.ToString()); + + //5 显示订单、机型信息 + SendMessage.ShowMoby(OpName); + //3显示操作指导图片 + SendMessage.PicShow(OpName); + //1(直接在界面通过选择机型确认工序内容) + SendMessage.ProcessList(OpName); + } + else if (tagValue == 0) + { + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.WorkStartOut, DateTime.Now.ToString()); + } + } + catch(Exception err) + { + ////ApplicationLog.WriteLog(err, "Function08:WorkStart"); + } + } + } +} diff --git a/MisDataFun/WebSubmit/OpcServer/vssver2.scc b/MisDataFun/WebSubmit/OpcServer/vssver2.scc new file mode 100644 index 0000000..e8dac03 Binary files /dev/null and b/MisDataFun/WebSubmit/OpcServer/vssver2.scc differ diff --git a/MisDataFun/WebSubmit/Properties/AssemblyInfo.cs b/MisDataFun/WebSubmit/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..3e92884 --- /dev/null +++ b/MisDataFun/WebSubmit/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// 有关程序集的一般信息由以下 +// 控制。更改这些特性值可修改 +// 与程序集关联的信息。 +[assembly: AssemblyTitle("WebSubmit")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("WebSubmit")] +[assembly: AssemblyCopyright("Copyright © 2023")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// 将 ComVisible 设置为 false 会使此程序集中的类型 +//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型 +//请将此类型的 ComVisible 特性设置为 true。 +[assembly: ComVisible(false)] + +// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID +[assembly: Guid("624f0e91-00f5-4ed9-8537-8f9eaaef2f1f")] + +// 程序集的版本信息由下列四个值组成: +// +// 主版本 +// 次版本 +// 生成号 +// 修订号 +// +//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值 +//通过使用 "*",如下所示: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/MisDataFunDll/MisDataFunDll.sln b/MisDataFunDll/MisDataFunDll.sln new file mode 100644 index 0000000..c9ca7fb --- /dev/null +++ b/MisDataFunDll/MisDataFunDll.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.32901.82 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MisDataFunDll", "MisDataFunDll\MisDataFunDll.csproj", "{A0DE975B-3AFC-4F39-920E-29A874480A36}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {A0DE975B-3AFC-4F39-920E-29A874480A36}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A0DE975B-3AFC-4F39-920E-29A874480A36}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A0DE975B-3AFC-4F39-920E-29A874480A36}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A0DE975B-3AFC-4F39-920E-29A874480A36}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {7A06AC19-C5B2-4DD8-821B-5996EC8AF877} + EndGlobalSection +EndGlobal diff --git a/MisDataFunDll/MisDataFunDll/13.4MisDataFunction.csproj b/MisDataFunDll/MisDataFunDll/13.4MisDataFunction.csproj new file mode 100644 index 0000000..14bc7f5 --- /dev/null +++ b/MisDataFunDll/MisDataFunDll/13.4MisDataFunction.csproj @@ -0,0 +1,90 @@ + + + + + Debug + AnyCPU + {A0DE975B-3AFC-4F39-920E-29A874480A36} + Library + Properties + MisDataFunDll + MisDataFunDll + v4.8 + 512 + true + + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + ..\..\Common\dll\MQTTnet.dll + + + ..\..\Common\dll\MQTTnet.Extensions.ManagedClient.dll + + + ..\..\dll_common\Newtonsoft.Json.dll + + + + + + + + + + + + + + + + + + + {f55da1a0-a982-4479-8c47-0d9a5aaf3e18} + 00MesWorkMqtt + + + {0d1af432-439a-4920-8692-43ae139f5530} + 01_01DoWhatPlc + + + {f434e066-4c59-47c8-aa82-6f48cc84501a} + 04-DataBaseAccess + + + {f0a0c525-03fd-428a-9b17-7f54aa0e4475} + 07BusinessFacade + + + {d98be764-adeb-488d-9714-61e308aa8201} + 08-WebFun_base + + + {90e76fb4-646d-45e2-95db-0b8ab4e465d6} + 09-MesDataFunction + + + {55b510c1-59e9-4bfd-ae84-d76d46f6e365} + 13.3MIS_FuntionSaveData + + + + \ No newline at end of file diff --git a/MisDataFunDll/MisDataFunDll/MisDataFun.MES.New.cs b/MisDataFunDll/MisDataFunDll/MisDataFun.MES.New.cs new file mode 100644 index 0000000..d84be8a --- /dev/null +++ b/MisDataFunDll/MisDataFunDll/MisDataFun.MES.New.cs @@ -0,0 +1,161 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + + +namespace MisDataFunDll +{ + public partial class MisDataFun + { + /// + /// 保存质量数据和过站信息 + /// 处理function + /// + /// + public static void TransferInfToMES_WebSubmit(object text) + { + + try + { + string recData = text.ToString(); + List dataArray = DoWhatPlc.MessageText.GetCmdStringList(recData); + + //string[] dataArray = recData.Split('|'); + if (dataArray.Count != 4) + return; + //消息来源 + string m_Source = dataArray[0].ToString(); + //消息类型 Barcode + string m_Command = dataArray[1].ToString(); + //工位号 + string m_OpName = dataArray[2].ToString(); + //消息参数 + string m_Value = dataArray[3].ToString(); + + //if (!m_WorkStart_OpName.ContainsKey(m_OpName)) return; //当前系统是否存在该工位 + + switch (m_Source) + { + case "BarCode": + //处理条码逻辑 + if (m_Command == "Bar") + { + MesServerFunction(recData); + } + break; + case "WEB": + if (m_Command == "Barcode") + { + MesServerFunction(recData); + + } + else + { + string Content = m_Command + "|" + m_Value; + MesServerFunction(recData); + + } + break; + } + + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "TransferInf"); + } + + } + + public static void TransferInfToMES(object text) + { + + + + try + { + + string recData = text.ToString(); + List dataArray = DoWhatPlc.MessageText.GetCmdStringList(recData); + //string[] dataArray = recData.Split('|'); + //if (dataArray.Count != 4) + //return; + //消息来源 + string m_Source = dataArray[0].ToString(); + //消息类型 Barcode + string m_Command = dataArray[1].ToString(); + //工位号 + string m_OpName = dataArray[2].ToString(); + //消息参数 + string m_Value = dataArray[3].ToString(); + + + string mesServerdllName; + //获得工位对应的 dll + if (!GetMesServerDllNameByOpName(out mesServerdllName, m_OpName)) return; + if (mesServerdllName == null) return; + if (mesServerdllName.Length < 1) return; + + string ResultOK = ""; + object[] Paramsters = new object[1]; + Paramsters[0] = text; + + System.Reflection.Assembly assembly = null; + + bool IsOK = Hashtable_assembly.ContainsKey(mesServerdllName); + if (IsOK) + { + assembly = (System.Reflection.Assembly)Hashtable_assembly[mesServerdllName]; + } + else + { + assembly = System.Reflection.Assembly.Load(mesServerdllName); + if (assembly == null) + { + return; + } + Hashtable_assembly.Add(mesServerdllName, assembly); + } + ResultOK = Reflection.ReflectionMethod(assembly, "MesServerFunctions", "FunctionMES", "FunWork", Paramsters); + + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "TransferInf"); + } + + } + /// + /// 获得工位对应的 dll + /// + /// + /// + /// + private static bool GetMesServerDllNameByOpName(out string mesServerdllName, string opName) + { + try + { + //HashtableList hsList = DtWebApi.OpcDemo.GetHashtableList(); + //if(opName == "J07ET055") + //{ + // mesServerdllName = "Function1061"; + //} + //else + //{ + mesServerdllName = hashtable_MesDll[opName].ToString(); + //} + return true; + } + catch + { + mesServerdllName = ""; + return false; + } + } + + + + } +} + diff --git a/MisDataFunDll/MisDataFunDll/MisDataFun.MES.cs b/MisDataFunDll/MisDataFunDll/MisDataFun.MES.cs new file mode 100644 index 0000000..d8c2c45 --- /dev/null +++ b/MisDataFunDll/MisDataFunDll/MisDataFun.MES.cs @@ -0,0 +1,458 @@ +using DataLinkMesWork; +using DoWhatPlc; +using MesServerWork; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Data; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MisDataFunDll +{ + public partial class MisDataFun + { + static object locker = new object(); + /// + ///引用程序集Hashtable + /// + public static Hashtable Hashtable_assembly = new Hashtable(); + public static Hashtable hashtable_MesServerCode = new Hashtable(); + public static Hashtable hashtable_MesDll = new Hashtable(); + public static Hashtable hashtable_TagTypeTagName = new Hashtable(); + public static Hashtable hashtable_TagName = new Hashtable(); + + + ///// + ///// 保存质量数据和过站信息 + ///// 处理function + ///// + ///// + //public static void TransferInfToMES_Bak(object text) + //{ + + + + // try + // { + // //try + // //{ + // // //保存质量数据和过站信息 + // // MisDataSaveDateMesRead.Funtion.MIS_Funtion(text); + // //} + // //catch + // //{ + + // //} + // string recData = text.ToString(); + // List dataArray = DoWhatPlc.MessageText.GetCmdStringList(recData); + // //string[] dataArray = recData.Split('|'); + // //if (dataArray.Count != 4) + // //return; + // //消息来源 + // string m_Source = dataArray[0].ToString(); + // //消息类型 Barcode + // string m_Command = dataArray[1].ToString(); + // //工位号 + // string m_OpName = dataArray[2].ToString(); + // //消息参数 + // string m_Value = dataArray[3].ToString(); + + // //if (!m_WorkStart_OpName.ContainsKey(m_OpName)) return; //当前系统是否存在该工位 + + // switch (m_Source) + // { + // case "BarCode": + // //处理条码逻辑 + // if (m_Command == "Bar") + // { + // MesServerFunction(m_OpName, m_Value, "fun_Barcode"); + // } + // break; + // //case "WEB": + // // if (m_Command == "Barcode") + // // { + // // MesServerFunction(m_OpName, m_Value, "fun_Barcode"); + + // // } + // // else + // // { + // // string Content = m_Command + "|" + m_Value; + // // MesServerFunction(m_OpName, Content, "fun_WebSubmit"); + + // // } + // // break; + // case "PLC": + + // MesServerFunction(m_Value); + // break; + // } + + // } + // catch (Exception err) + // { + // ////ApplicationLog.WriteLog(err, "TransferInf"); + // } + + //} + + /// + /// 保存质量数据和过站信息 + /// 处理function + /// + /// + //public static void TransferInfToMES_WebSubmit(object text) + //{ + + + + // try + // { + // string recData = text.ToString(); + // List dataArray = DoWhatPlc.MessageText.GetCmdStringList(recData); + + // //string[] dataArray = recData.Split('|'); + // if (dataArray.Count != 4) + // return; + // //消息来源 + // string m_Source = dataArray[0].ToString(); + // //消息类型 Barcode + // string m_Command = dataArray[1].ToString(); + // //工位号 + // string m_OpName = dataArray[2].ToString(); + // //消息参数 + // string m_Value = dataArray[3].ToString(); + + // //if (!m_WorkStart_OpName.ContainsKey(m_OpName)) return; //当前系统是否存在该工位 + + // switch (m_Source) + // { + // //case "BarCode": + // // //处理条码逻辑 + // // if (m_Command == "Bar") + // // { + // // MesServerFunction(m_OpName, m_Value, "fun_Barcode"); + // // } + // // break; + // case "WEB": + // if (m_Command == "Barcode") + // { + // MesServerFunction(m_OpName, m_Value, "fun_Barcode"); + + // } + // else + // { + // string Content = m_Command + "|" + m_Value; + // MesServerFunction(m_OpName, Content, "fun_WebSubmit"); + + // } + // break; + // } + + // } + // catch (Exception err) + // { + // ////ApplicationLog.WriteLog(err, "TransferInf"); + // } + + //} + + + ///// + ///// MesServerFunction + ///// + ///// + ///// + ///// + //private static void MesServerFunction(string OpName, object tagValue, string fun) + //{ + // try + // { + + // CustomeEvetnArgs e = new CustomeEvetnArgs(); + + // string ResultOK = ""; + // string mesServerCode; + // //mesServerCode = GetMesServerCodeByOpName(OpName); + // string mesServerdllName; + // //mesServerdllName = GetMesServeDllByOpName(OpName); + // // TagType + // if (!GetMesServerCodeByOpName(out mesServerdllName, out mesServerCode, OpName)) return; + // if (mesServerdllName == null) return; + // if (mesServerdllName.Length < 1) return; + // e.OpName = OpName; + // e.TagValue = tagValue; + // switch (fun) + // { + // case "fun_Barcode": + // e.TagTypeCodeID = "Barcode"; + // break; + // case "fun_WebSubmit": + // e.TagTypeCodeID = "WebSubmit"; + // break; + // } + + + // object[] Paramsters = new object[1]; + // Paramsters[0] = e; + + // System.Reflection.Assembly assembly; + + // //自动工位不调用function + // //if (mesServerCode == "00") + // //{ + // // return; + // //} + // bool IsOK = false; + + // { + // IsOK = Hashtable_assembly.ContainsKey(mesServerdllName); + // } + // if (IsOK) + // { + // assembly = (System.Reflection.Assembly)Hashtable_assembly[mesServerdllName]; + // } + // else + // { + // assembly = System.Reflection.Assembly.Load(mesServerdllName); + // if (assembly == null) + // { + // return; + // } + // Hashtable_assembly.Add(mesServerdllName, assembly); + // } + // if(mesServerCode =="00") + // { + // fun = "FunWork"; + // ResultOK = Reflection.ReflectionMethod(assembly, "MesServerFunctions", " FunctionMES", "FunWork", Paramsters); + + // } + // else + // { + // ResultOK = Reflection.ReflectionMethod(assembly, "MesServerFunctions", "Functions_BASE_" + mesServerCode, fun, Paramsters); + + // } + // if (ResultOK != "ok") + // { + // // ApplicationLog.WriteLog("ReflectionMethod is Error:" + OpName + fun + ResultOK); + // } + // } + // catch (Exception err) + // { + // //ApplicationLog.WriteLog(err, "MesServerFunction"); + // } + //} + //static bool GetMesServerCodeByOpName(out string mesServerdllName, out string mesServerCode,string opName) + //{ + // try + // { + // //HashtableList hsList = DtWebApi.OpcDemo.GetHashtableList(); + + // mesServerCode = Convert.ToInt32(hashtable_MesServerCode[opName]).ToString("00"); + // mesServerdllName = hashtable_MesDll[opName].ToString(); + // return true; + + // } + // catch + // { + // mesServerdllName = null; + // mesServerCode = null; + // opName = null; + // return false; + // } + //} + private static bool GetMesServerCodeByOpName(out string mesServerdllName, out string mesServerCode, out string fun, string opName, string tagType = "1") + { + try + { + //HashtableList hsList = DtWebApi.OpcDemo.GetHashtableList(); + try + { + mesServerCode = Convert.ToInt32(hashtable_MesServerCode[opName]).ToString("00"); + + } + catch + { + mesServerCode = "00"; + } + mesServerdllName = hashtable_MesDll[opName].ToString(); + fun = "fun_" + hashtable_TagTypeTagName[tagType].ToString(); + return true; + + } + catch + { + mesServerdllName = null; + mesServerCode = null; + fun = null; + opName = null; + return false; + } + } + /// + /// + /// + /// 变量名称对应的变量类型代码 + /// 变量类型代码对应的变量名称 + public static void GetBaseData_tagTable_TagName(out Hashtable hashtable_TagName, out Hashtable hashtable_TagTypeTagName) + { + hashtable_TagName = new Hashtable(); + hashtable_TagTypeTagName = new Hashtable(); + + string tagName; + string tagTypeCode; + DataTable dt;//GetMesServerCodeFromMIS + dt = BaseData_tagTable_TagName(); + if (dt != null) + { + for (int i = 0; i < dt.Rows.Count; i++) + { + tagName = dt.Rows[i]["TagName"].ToString(); + tagTypeCode = dt.Rows[i]["变量类型代码"].ToString(); + if (!hashtable_TagName.Contains(tagName)) + { + hashtable_TagName.Add(tagName, tagTypeCode); + } + if (!hashtable_TagTypeTagName.Contains(tagTypeCode)) + { + hashtable_TagTypeTagName.Add(tagTypeCode, tagName); + } + } + } + } + public static DataTable BaseData_tagTable_TagName() + { + DataTable dt = null; + string sql; + sql = "SELECT distinct[TagName],[变量类型代码] FROM[MES_基本变量_原始数据] "; + DataAccess.ExecuteDataTable(sql, out dt); + return dt; + } + public static void GetMesServerCodeAndMesDll(out Hashtable hashtable_MesServerCode, out Hashtable hashtable_MesDll) + { + hashtable_MesServerCode = new Hashtable(); + hashtable_MesDll = new Hashtable(); + + string OpName; + string MesServerCode; + string MesDll; + DataTable dt;//GetMesServerCodeFromMIS + dt = GetMesServerCodeFromMIS(); + if (dt != null) + { + for (int i = 0; i < dt.Rows.Count; i++) + { + OpName = dt.Rows[i]["工位号"].ToString(); + MesServerCode = dt.Rows[i]["MesServerCode"].ToString(); + MesDll = dt.Rows[i]["MesDll"].ToString(); + if (!hashtable_MesDll.Contains(OpName)) + { + hashtable_MesDll.Add(OpName, MesDll); + } + if (!hashtable_MesServerCode.Contains(OpName)) + { + hashtable_MesServerCode.Add(OpName, MesServerCode); + } + } + } + } + public static DataTable GetMesServerCodeFromMIS() + { + DataTable dt; + string sql; + sql = "exec MES_计划BOM_工位与名称_查询应用程序"; + DataAccess.ExecuteDataTable(sql, out dt); + return dt; + } + // + + /// + /// MesServerFunction + /// + /// + /// + /// + private static void MesServerFunction(string msgValue) + { + try + { + bool IsOK = false; + //lock (locker) + { + DoWhatPlc.CustomeEvetnArgs e = Newtonsoft.Json.JsonConvert.DeserializeObject(msgValue); + string tagValue; + string mesServerCode; + string mesServerdllName; + string fun; + if (!GetMesServerCodeByOpName(out mesServerdllName, out mesServerCode, out fun, e.OpName.ToString(), e.TagTypeCodeID.ToString())) return; + if (mesServerdllName == null) return; + if (mesServerdllName.Length < 1) return; + //if (!GetMesServerCodeByOpName(out mesServerdllName, out mesServerCode, out fun, e.OpName.ToString(), e.TagType.ToString())) return; + switch (e.TagValue.ToString().ToLower()) + { + case "false": + tagValue = "0"; + break; + case "true": + tagValue = "1"; + break; + default: + tagValue = e.TagValue.ToString(); + break; + } + + string ResultOK = ""; + object[] Paramsters = new object[1]; + Paramsters[0] = e; + + System.Reflection.Assembly assembly = null; + + //自动工位不调用function + //if (mesServerCode == "00") + //{ + // return; + //} + + IsOK = Hashtable_assembly.ContainsKey(mesServerdllName); + if (IsOK) + { + assembly = (System.Reflection.Assembly)Hashtable_assembly[mesServerdllName]; + } + else + { + assembly = System.Reflection.Assembly.Load(mesServerdllName); + if (assembly == null) + { + return; + } + Hashtable_assembly.Add(mesServerdllName, assembly); + } + if (mesServerCode == "00") + { + fun = "FunWork"; + ResultOK = Reflection.ReflectionMethod(assembly, "MesServerFunctions", "FunctionMES", fun, Paramsters); + + } + else + { + ResultOK = Reflection.ReflectionMethod(assembly, "MesServerFunctions", "Functions_BASE_" + mesServerCode, fun, Paramsters); + + } + if (ResultOK != "ok") + { + // //ApplicationLog.WriteLog("ReflectionMethod is Error:" + OpName + fun + ResultOK); + } + } + + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "MesServerFunction"); + } + } + + + + } +} \ No newline at end of file diff --git a/MisDataFunDll/MisDataFunDll/MisDataFun.MIS_Funtion.cs b/MisDataFunDll/MisDataFunDll/MisDataFun.MIS_Funtion.cs new file mode 100644 index 0000000..c82de60 --- /dev/null +++ b/MisDataFunDll/MisDataFunDll/MisDataFun.MIS_Funtion.cs @@ -0,0 +1,301 @@ +using DoWhatPlc; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MisDataFunDll +{ + public partial class MisDataFun + { + //public void MIS_Funtion(object e) + //{ + // try + // { + // string recData = e.ToString(); + // string[] dataArray = recData.Split('|'); + // if (dataArray.Length != 4) + // return; + // //消息来源 + // string m_Source = dataArray[0].ToString(); + // //消息类型 + // string m_Command = dataArray[1].ToString(); + // //工位号 + // string m_OpName = dataArray[2].ToString(); + // //消息参数 + // string m_Value = dataArray[3].ToString(); + + // DoWhatPlc.ReturnValueString rv = Newtonsoft.Json.JsonConvert.DeserializeObject(m_Value); + + + // int tagType; + // string opName; + // string tagValue; + // int tagid; + // DoWhatPlc.ReturnValueString msgEvent = rv; + // if (msgEvent.TagValue == null) return; + // tagType = Convert.ToInt32(msgEvent.TagTypeID); + // opName = msgEvent.OpName.ToString(); + // tagid = Convert.ToInt32(msgEvent.TagID); + // switch (Convert.ToInt32(msgEvent.TagTypeCodeID)) + // { + // case 11: + // switch (msgEvent.TagValue.ToLower()) + // { + // case "1": + // case "true": + // tagValue = "1"; + // break; + // default: + // tagValue = "0"; + // break; + // } + // break; + // default: + // tagValue = msgEvent.TagValue.ToString(); + // break; + // } + // ///根据信号处理逻辑 + // switch (tagType) + // { + // case 19: + // //允许保存 + // //MesRead(opName, tagValue, tagid); + // break; + // case 14: + // //心跳 + // //Heartbeat(opName, tagValue); + // break; + // case 44://PLC传递机型过后 才允许保存过站信息,否则不允许保存 + // //if (tagValue == "1") + // //{ + // // IsEngTypeGetOver_Write(opName, true); + + // // EngineData Enginedata = new EngineData(MesDataFunction.OpcOperation.ReadPLC(10, opName).ToString(), Convert.ToInt32(MesDataFunction.OpcOperation.ReadPLC(80, opName))); + // // //保存产品编号、托盘号 保存过站信息用 + // // EngineData_Hash_Write(opName, Enginedata); + // //} + // break; + // case 2://工件到位 + // //WorkStart(opName, tagValue); + // break; + // case 51: + // //if (hashtableOpName_IsHaveComputer[opName].ToString() == "1") + // //{ + // // SaveProductLeaveData(opName, 1); + // //} + + // break; + // case 8: + // //if (hashtableOpName_IsHaveComputer[opName].ToString() == "1") + // //{ + // // SaveProductLeaveData(opName, 2); + // //} + // break; + // } + + // } + // catch (Exception err) + // { + // ////ApplicationLog.WriteLog(err, err.Message); + // } + //} + + + ///// + ///// 获取质量数据Hashtable + ///// + ///// + ///// + //static public Hashtable ReadPLC_Sync_DataList_MesRead(string opName) + //{ + // return (Hashtable)MesDataFunction.OpcOperation.ReadPLC_Sync_DataList_MesRead(opName); + //} + + /// + /// 允许保存(针对半自动和手动压装工位) + /// + /// + /// + //private void MesRead(string opName, string tagValue, int tagid) + //{ + // if (tagValue == "0") + // { + // MIS_BASE.Write_TagTypeID(20, opName, false); + // } + // else + // { + // SaveQualityData(opName, Convert.ToInt32(tagValue), tagid); + // } + //} + + //private void SaveQualityData(string opName, int tagValue, int tagID) + //{ + // try + // { + // int id_tagCF; + // int qualityMask = 0; + // int engineTypeID = 0; + // string engineID = ""; + // string engineType = ""; + // string engineTraceCode = ""; + // string engineCap = ""; + // string partPallet = ""; + // DataTable dt_WWW; + // dt_WWW = BaseDataSystemMES.BuildDataTables_WWW(); + // Hashtable valueList; + // Hashtable hashtable_EngineTypeID; + // Hashtable hashtable_tagTable_OpName_SaveData; + // DataTable BasicDataTagValue; + // DataTable BasicDataTagValueUpDown; + // ReadPLC_Sync_DataList_MesRead(opName, out valueList ,out BasicDataTagValue,out BasicDataTagValueUpDown,out hashtable_EngineTypeID,out hashtable_tagTable_OpName_SaveData); + // valueList = GetQualityData_GoodBad_Values(valueList); + // int mes_MustTest = 0; + // int onLineState = 0; + // int partMoveDirection = 0; + // int pressIsOK = 0; + // int pressIsNoOK = 0; + // BaseDataSystemMES.GetQualityDataTable_B5A(valueList, opName, BasicDataTagValue, + // BasicDataTagValueUpDown, + // out dt_WWW,//数据列表 + // out qualityMask,//工位合格标志 + // out engineTypeID,//发动机类型代码 + // out engineID,//发动机编号 + // out engineType, //发动机型号 + // out partPallet,//托盘编号 + // out engineTraceCode, //发动机条码 + // out engineCap,//缸盖号, + // hashtable_EngineTypeID,//发动机类型转换表 + // out mes_MustTest, out onLineState, out partMoveDirection, out pressIsOK, out pressIsNoOK); + + // // 1:通过监控系统保存采集的质量数据;0:不通过监控系统保存采集的质量数据 + // if (Convert.ToInt32(hashtable_tagTable_OpName_SaveData[opName]) != 0) + // { + // DateTime lastupdatetime = DateTime.Now; + + // BaseDataSystemMES.BaseData_tagTable_QualityData_B5A_IndexInsert(engineID, tagID, engineType, engineTypeID, opName, qualityMask, partPallet, out id_tagCF); + // BaseDataSystemMES.BaseData_tagTable_QualityData_B5A_Insert(id_tagCF, engineTypeID, engineID, opName, dt_WWW); + + // } + // MIS_BASE.Write_TagTypeID(20, opName, true); + + // } + // catch (Exception err) + // { + // MIS_BASE.Write_TagTypeID(20, opName, true); + // ////ApplicationLog.WriteLog(err, err.Message); + // } + + //} + + /// + /// 确定合格标志 + /// + /// + /// + //public Hashtable GetQualityData_GoodBad_Values(Hashtable valuList) + //{ + // try + // { + // Hashtable valuList_Temp; + // valuList_Temp = (Hashtable)valuList.Clone(); + // int[] value_GoodBad_New = new int[128]; + // int tagID; + // QualityDataType value; + // //1:获得合格标志 + // foreach (DictionaryEntry de in valuList) //ht为一个Hashtable实例 + // { + // tagID = Convert.ToInt32(de.Key); + // value = (QualityDataType)de.Value; + + // //拧紧数据合格标志 + // if (value.tagProperty == 1) + // { + // if (value.tagTypeID == 8203) + // { + // value_GoodBad_New = (int[])value.tagValue; + // break; + // } + // else + // { + // value_GoodBad_New[value.tagOrderBy - 1] = Convert.ToInt32(value.tagValue); + // } + // } + // //拧紧数据合格标志 + // if (value.tagProperty == 8) + // { + // if (value.tagTypeID == 8203) + // { + // value_GoodBad_New = (int[])value.tagValue; + // break; + // } + // else + // { + // value_GoodBad_New[value.tagOrderBy - 1] = Convert.ToInt32(value.tagValue); + // } + // } + // //压装数据合格标志 + // if (value.tagProperty == 7) + // { + // value_GoodBad_New[value.tagOrderBy - 1] = Convert.ToInt32(value.tagValue); + // } + // } + // //将合格标志赋予每个变量 + // foreach (DictionaryEntry de in valuList) //ht为一个Hashtable实例 + // { + // tagID = Convert.ToInt32(de.Key); + // value = (QualityDataType)de.Value; + // //201706061720新加 + // if (value.tagTypeID == 11) + // { + // if (value.tagValue.ToString() == "False") + // { + // value.tagValue = "0"; + // } + // else + // { + // value.tagValue = "1"; + // } + // valuList_Temp[tagID] = value; + // //value.tagValue = Convert.ToInt32(value.tagValue); + // } + + + // //测量变量 + // if (value.tagProperty == 2 || value.tagProperty == 6) + // { + // try + // { + // if (value_GoodBad_New != null) + // { + // value.isGoodBad = Convert.ToInt32(value_GoodBad_New[value.tagOrderBy - 1]); + // valuList_Temp[tagID] = value; + // } + // else + // { + // value.isGoodBad = 0; + // valuList_Temp[tagID] = value; + // } + // } + // catch (Exception err) + // { + // ////ApplicationLog.WriteLog(err, err.Message); + + // } + // } + + + + // } + // return valuList_Temp; + // } + // catch//转换出了故障时 + // { + // return valuList; + // } + //} + + } +} diff --git a/MisDataFunDll/MisDataFunDll/Properties/AssemblyInfo.cs b/MisDataFunDll/MisDataFunDll/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..b954eea --- /dev/null +++ b/MisDataFunDll/MisDataFunDll/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// 有关程序集的一般信息由以下 +// 控制。更改这些特性值可修改 +// 与程序集关联的信息。 +[assembly: AssemblyTitle("MisDataFunDll")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("MisDataFunDll")] +[assembly: AssemblyCopyright("Copyright © 2022")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// 将 ComVisible 设置为 false 会使此程序集中的类型 +//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型 +//请将此类型的 ComVisible 特性设置为 true。 +[assembly: ComVisible(false)] + +// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID +[assembly: Guid("a0de975b-3afc-4f39-920e-29a874480a36")] + +// 程序集的版本信息由下列四个值组成: +// +// 主版本 +// 次版本 +// 生成号 +// 修订号 +// +//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值 +//通过使用 "*",如下所示: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/MisDataFunDll/MisDataFunDll/Reflection.cs b/MisDataFunDll/MisDataFunDll/Reflection.cs new file mode 100644 index 0000000..d7bd835 --- /dev/null +++ b/MisDataFunDll/MisDataFunDll/Reflection.cs @@ -0,0 +1,94 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Reflection; +using System.Web; +using System.ComponentModel; + +namespace MisDataFunDll +{ + /// + /// + /// + public class Reflection + { + /// + /// 通过反射调用动态连接库方法 + /// + /// 程序集(DLL) + /// 命名空间名称,如果无命名空间写“” + /// 类名 + /// 方法名 + /// 函数参数数组 + static public string ReflectionMethod(Assembly assembly, string Namespace, string Classname, string Method, object[] Paramsters) + { + try + { + + Type t; + //类 + if (Namespace == "") + { + t = assembly.GetType(Classname); + } + else + { + t = assembly.GetType(Namespace + "." + Classname); + } + if (t == null) + { + return "类不存在"; + } + ////方法 + MethodInfo mi = t.GetMethod(Method); //获取方法 + if (mi == null) + { + return "方法不存在"; + } + ParameterInfo[] paramsInfo = mi.GetParameters(); + for (int i = 0; i < paramsInfo.Length; i++) + { + Type tType = paramsInfo[i].ParameterType; + //改变参数类型 + Paramsters[i]= SD_ChanageType(Paramsters[i],tType); + } + /// 建一个实例化的类 + object instanceObject = Activator.CreateInstance(t); + mi.Invoke(instanceObject, Paramsters); + return "ok"; + } + catch(Exception err) + { + return err.ToString(); + + } + + } + /// + /// + /// + /// + /// + /// + public static object SD_ChanageType(object value, Type convertsionType) + { + //判断convertsionType类型是否为泛型,因为nullable是泛型类, + if (convertsionType.IsGenericType && + //判断convertsionType是否为nullable泛型类 + convertsionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) + { + if (value == null || value.ToString().Length == 0) + { + return null; + } + + //如果convertsionType为nullable类,声明一个NullableConverter类,该类提供从Nullable类到基础基元类型的转换 + NullableConverter nullableConverter = new NullableConverter(convertsionType); + //将convertsionType转换为nullable对的基础基元类型 + convertsionType = nullableConverter.UnderlyingType; + } + return Convert.ChangeType(value, convertsionType); + } + } +} \ No newline at end of file diff --git a/MisDataFunction/MesServer.Function/Function1051/DataAccess/DataAccess.cs b/MisDataFunction/MesServer.Function/Function1051/DataAccess/DataAccess.cs new file mode 100644 index 0000000..a7f91fa --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1051/DataAccess/DataAccess.cs @@ -0,0 +1,16 @@ + + +namespace MesServerFunctions +{ + partial class FunctionMES + { + //针对“MIS.BizFacade.Dll”中没有的存储过程,在此类中新建 + //新建原则:所有的函数用private,只允许在内部使用 + //针对单个工艺特殊,需要新建存储过程,但是存储过程不能被加入到“MIS.BizFacade.Dll”中 + + private void aa() + { + + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1051/DataAccess/vssver2.scc b/MisDataFunction/MesServer.Function/Function1051/DataAccess/vssver2.scc new file mode 100644 index 0000000..1083b3a Binary files /dev/null and b/MisDataFunction/MesServer.Function/Function1051/DataAccess/vssver2.scc differ diff --git a/MisDataFunction/MesServer.Function/Function1051/Db.cs b/MisDataFunction/MesServer.Function/Function1051/Db.cs new file mode 100644 index 0000000..5578002 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1051/Db.cs @@ -0,0 +1,110 @@ +using System; +using System.Collections.Generic; +using System.Data.SqlClient; +using System.Data; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using DataLinkMesWork; + +namespace MesServerFunctions +{ + public class Db + { + public static bool GetEngineType_Order(string opName, string Program_No, out int EngineTypeID, out string EngineType, out string EngineID, out string OrderForm, out int isCheckOk, out int planCount, out int haveUplaodCount, out int remainingQuantity) + { + DataTable dt = new DataTable(); + isCheckOk = 2; + EngineTypeID = 0; + EngineType = ""; + EngineID = ""; + OrderForm = ""; + planCount = 0; + haveUplaodCount = 0; + remainingQuantity = 0; + string produceName = "合力_生产上线_判断机型订单是否匹配"; + SqlParameter[] thisParms = new SqlParameter[1]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + //thisParms[1] = new System.Data.SqlClient.SqlParameter("@PLC_机型代码", Program_No); + if (DataAccess.ExecuteStoredProcedure(produceName, ref thisParms, out dt)) + { + if (dt.Rows.Count > 0 && dt.Rows[0]["是否匹配"].ToString() == "1") + { + EngineTypeID = Convert.ToInt32(dt.Rows[0]["机型代码"]); + EngineType = dt.Rows[0]["机型"].ToString(); + EngineID = dt.Rows[0]["变速箱总成号"].ToString(); + OrderForm = dt.Rows[0]["订单号"].ToString(); + isCheckOk = Convert.ToInt32(dt.Rows[0]["是否匹配"]); + planCount = Convert.ToInt32(dt.Rows[0]["计划上料数量"]); + haveUplaodCount = Convert.ToInt32(dt.Rows[0]["已上料数量"]); + remainingQuantity = Convert.ToInt32(dt.Rows[0]["待上料数量"]); + return true; + } + } + return false; + } + + /// + /// 北汽福田变速器序列号总线上线_获得机型信息 + /// + /// + /// + /// + /// + /// 0 不重号;1 重号;2:失败 + /// + public static bool GetEngineTypeUpload(string partSn, out int EngineTypeID, out string EngineType, out string EngineID,out int IsRepeatedNumber) + { + DataTable dt = new DataTable(); + EngineTypeID = 0; + EngineType = ""; + EngineID = ""; + IsRepeatedNumber = 2; + string produceName = "北汽福田变速器序列号总线上线_获得机型信息"; + SqlParameter[] thisParms = new SqlParameter[1]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@变速器序列号", partSn); + + thisParms[2].Direction = ParameterDirection.Output; + if (DataAccess.ExecuteStoredProcedure(produceName, ref thisParms,out dt)) + { + if(dt.Rows.Count > 0) + { + IsRepeatedNumber = Convert.ToInt32( dt.Rows[0]["IsRepeatedNumber"]); + EngineTypeID = Convert.ToInt32(dt.Rows[0]["EngineTypeID"]); + EngineType = dt.Rows[0]["EngineType"].ToString(); + EngineID = partSn; + return true; + } + } + return false; + } + /// + /// 北汽福田变速器序列号总线上线_增加 + /// + /// + /// + /// + /// + /// + public static bool UpLoadOpNameInsert(string partSn, int EngineTypeID, string EngineType, string OpName) + { + + string produceName = "北汽福田变速器序列号总线上线_增加"; + SqlParameter[] thisParms = new SqlParameter[4]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@变速器序列号", partSn); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@基本型号代码", EngineTypeID); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@基本型号", EngineType); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@工位号", OpName); + return DataAccess.ExecuteStoredProcedure(produceName, ref thisParms); + } + public static bool UpLoadOpNameInsert_Lungu(string partSn, string OpName) + { + string produceName = "北汽福田工位_轮毂上线_记录数据"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@总成号", partSn); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@工位号", OpName); + return DataAccess.ExecuteStoredProcedure(produceName, ref thisParms); + } + + } +} diff --git a/MisDataFunction/MesServer.Function/Function1051/Function08.csproj.vspscc b/MisDataFunction/MesServer.Function/Function1051/Function08.csproj.vspscc new file mode 100644 index 0000000..82c6db2 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1051/Function08.csproj.vspscc @@ -0,0 +1,10 @@ +"" +{ +"FILE_VERSION" = "9237" +"ENLISTMENT_CHOICE" = "NEVER" +"PROJECT_FILE_RELATIVE_PATH" = "relative:MesServer.Function\\Function08" +"NUMBER_OF_EXCLUDED_FILES" = "0" +"ORIGINAL_PROJECT_FILE_PATH" = "" +"NUMBER_OF_NESTED_PROJECTS" = "0" +"SOURCE_CONTROL_SETTINGS_PROVIDER" = "PROVIDER" +} diff --git a/MisDataFunction/MesServer.Function/Function1051/Function1051.csproj b/MisDataFunction/MesServer.Function/Function1051/Function1051.csproj new file mode 100644 index 0000000..6710cce --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1051/Function1051.csproj @@ -0,0 +1,170 @@ + + + + Debug + AnyCPU + 8.0.30703 + 2.0 + {B5A0BAA3-C1A7-4AAB-9486-2E650ADACA7E} + Library + Properties + Function1051 + Function1051 + v4.8 + 512 + + + + + + + + + + + + + + true + full + false + ..\..\..\dll_fun\ + DEBUG;TRACE + prompt + 4 + AnyCPU + false + false + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + false + + + + ..\..\..\Common\dll\MQTTnet.dll + + + ..\..\..\Common\dll\MQTTnet.Extensions.ManagedClient.dll + + + False + ..\..\..\Common\dll\Newtonsoft.Json.dll + + + + + + ..\..\DLL\System.Net.Http.dll + + + ..\..\packages\System.Net.Security.4.3.2\lib\net46\System.Net.Security.dll + + + ..\..\packages\System.Net.WebSockets.4.3.0\lib\net46\System.Net.WebSockets.dll + + + ..\..\packages\System.Net.WebSockets.Client.4.3.2\lib\net46\System.Net.WebSockets.Client.dll + + + ..\..\packages\System.Security.Cryptography.Algorithms.4.3.0\lib\net461\System.Security.Cryptography.Algorithms.dll + + + ..\..\packages\System.Security.Cryptography.Encoding.4.3.0\lib\net46\System.Security.Cryptography.Encoding.dll + + + ..\..\packages\System.Security.Cryptography.Primitives.4.3.0\lib\net46\System.Security.Cryptography.Primitives.dll + + + ..\..\packages\System.Security.Cryptography.X509Certificates.4.3.0\lib\net461\System.Security.Cryptography.X509Certificates.dll + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + {f55da1a0-a982-4479-8c47-0d9a5aaf3e18} + 00MesWorkMqtt + + + {0d1af432-439a-4920-8692-43ae139f5530} + 01_01DoWhatPlc + + + {f434e066-4c59-47c8-aa82-6f48cc84501a} + 04-DataBaseAccess + + + {f0a0c525-03fd-428a-9b17-7f54aa0e4475} + 07BusinessFacade + + + {d98be764-adeb-488d-9714-61e308aa8201} + 08-WebFun_base + + + {90e76fb4-646d-45e2-95db-0b8ab4e465d6} + 09-MesDataFunction + + + {e4eb6420-906d-4672-947a-ca33ddcdadfc} + 12SendMessageToWeb + + + {55b510c1-59e9-4bfd-ae84-d76d46f6e365} + 02-13.3MIS_FuntionSaveData + + + {1dc48c83-1842-4de8-acaf-26e1e7f7c58f} + 00_MyLog4Net + + + + + + + 这台计算机上缺少此项目引用的 NuGet 程序包。使用“NuGet 程序包还原”可下载这些程序包。有关更多信息,请参见 http://go.microsoft.com/fwlink/?LinkID=322105。缺少的文件是 {0}。 + + + + + \ No newline at end of file diff --git a/MisDataFunction/MesServer.Function/Function1051/MesServerFunction/Function1051.cs b/MisDataFunction/MesServer.Function/Function1051/MesServerFunction/Function1051.cs new file mode 100644 index 0000000..a5b0779 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1051/MesServerFunction/Function1051.cs @@ -0,0 +1,294 @@ + +using MesServerWork; +using MisDataSaveDate; +using System; +using System.Collections.Generic; +using System.IO.Ports; +using System.Threading; + +namespace MesServerFunctions +{ + public partial class FunctionMES + { + object lockFunWork; + //public void FunWork(DoWhatPlc.CustomeEvetnArgs e) + public void FunWork(string recData) + { + + + lockFunWork = new object(); + lock (lockFunWork) + { + List dataArray = DoWhatPlc.MessageText.GetCmdStringList(recData); + //string[] dataArray = recData.Split('|'); + //if (dataArray.Count != 4) + //return; + //消息来源 + string m_Source = dataArray[0].ToString(); + //消息类型 Barcode + string m_Command = dataArray[1].ToString(); + //工位号 + string m_OpName = dataArray[2].ToString(); + //消息参数 + string m_Value = dataArray[3].ToString(); + + DoWhatPlc.CustomeEvetnArgs e = new DoWhatPlc.CustomeEvetnArgs();// = Newtonsoft.Json.JsonConvert.DeserializeObject(m_Value); + string tagValue; + switch (m_Source) + { + case "BarCode": + e.OpName = m_OpName; + e.TagValue = m_Value; + fun_Barcode(e); + + break; + case "WEB": + e.OpName = m_OpName; + e.TagValue = m_Command + "|" + m_Value; + fun_WebSubmit(e); + break; + case "PLC": + e = Newtonsoft.Json.JsonConvert.DeserializeObject(m_Value); + string TagID = e.TagID.ToString(); + switch (e.TagValue.ToString().ToLower()) + { + case "false": + tagValue = "0"; + break; + case "true": + tagValue = "1"; + break; + default: + tagValue = e.TagValue.ToString(); + break; + } + e.TagValue = tagValue; + switch (e.TagTypeCodeID.ToString()) + { + //PLC 工件到位 + case "2": + fun_WorkStart(e); + break; + //PLC 允许保存质量数据 + case "19": + fun_MesRead(e); + break; + //MES 保存数据完成 + case "20": + fun_MesReadOver(e); + break; + //PLC 申请上线 + case "43": + PartLoad(e); + break; + //PLC 传递机型 + case "44": + fun_EngineTypeGetOverPLC(e); + break; + //MES 合格放行 + case "51": + fun_ConfirmOkGo(e); + break; + //MES 不合格放行 + case "8": + fun_FalseGo(e); + break; + // PLC 系统健康心跳 + case "14": + fun_HeartBeatMIS(e); + break; + //空料握手plc + case "49": + fun_Handshake(e); + break; + // 写入托盘号后通知MES + case "48": + string write_Pallet_res; + MIS_BASE.Read_TagTypeID(48, m_OpName, out write_Pallet_res); + if (write_Pallet_res.ToLower() == "true" || write_Pallet_res.ToLower() == "1") + { + SendMessageFun.SendInfomation("writePallet", "1", m_OpName); + } + MIS_BASE.WritePLC(70, m_OpName, false); + break; + case "63": + PartLoadInPallet(e); + break; + //string S_plcStatus;//DBX501.5 PLC直通,1 强制放行 0 正常循环 + //MIS_BASE.Read_TagTypeID(63, m_OpName, out S_plcStatus); + //if (S_plcStatus.ToLower() != "true" || S_plcStatus.ToLower() == "1") + //{ + // SendMessageFun.SendInfomation("PlcStatus", "0", m_OpName); + //} + //else + //{ + // SendMessageFun.SendInfomation("PlcStatus", "1", m_OpName); + //} + //break; + } + break; + } + } + } + //public void FunWork(DoWhatPlc.CustomeEvetnArgs e) + //{ + // //lock1 = new object(); + // //lock (lock1) + // { + // switch (e.TagTypeCodeID.ToString()) + // { + // //PLC 工件到位 + // case "2": + // fun_WorkStart(e); + // break; + // //PLC 允许保存质量数据 + // case "19": + // fun_MesRead(e); + // break; + // //MES 保存数据完成 + // case "20": + // fun_MesReadOver(e); + // break; + // //PLC 传递机型 + // case "44": + // fun_EngineTypeGetOverPLC(e); + // break; + // //MES 合格放行 + // case "51": + // fun_ConfirmOkGo(e); + // break; + // //MES 不合格放行 + // case "8": + // fun_FalseGo(e); + // break; + // //MES 扫描条码 + // case "Barcode": + // fun_Barcode(e); + // break; + // //WEB 处理页面传递过来的数据 + // case "WebSubmit": + // fun_WebSubmit(e); + // break; + // } + // } + + //} + //1.工件到位后,PLC给MES传递机型(DBX0.4)(44), + //2.MES判断是否扫描完成 + //3.若扫描完成,则MES给出合格放行(DBX2.5)(51) + /// + /// 扫描条码 + /// + /// + /// + public void fun_Barcode(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(Barcode, e); + } + + + /// + /// 传递机型 + /// + /// + /// + public void fun_EngineTypeGetOverPLC(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(EngineTypeGetOver_PLC, e); + } + + /// + /// 合格放行 + /// + /// + /// + public void fun_ConfirmOkGo(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(ConfirmOkGo, e); + } + + /// + /// 不合格放行 + /// + /// + /// + public void fun_FalseGo(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(FalseGO, e); + } + + + /// + /// 保存完成 20 + /// + /// + /// + public void fun_MesReadOver(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(MesReadOver, e); + } + + /// + /// 空料握手plc + /// + public void fun_Handshake(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(Handshake_Fun, e); + } + + /// + /// 保存完成 19 + /// + /// + /// + public void fun_MesRead(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(MesRead, e); + } + + /// + /// 工件到位离开(清空所有的MES信号) + /// + /// + /// + public void fun_WorkStart(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(WorkStart, e); + } + + /// + /// 处理WEB页面发送过来的请求(m_Command + "|" + m_Value;) + /// + /// + /// + public void fun_WebSubmit(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(WebSubmit, e); + } + + public int fun_SubLineLoadPartCountMatch() + { + return SubLineLoadPartCountMatch; + } + + + /// + /// MES系统健康心跳监测 + /// + /// + /// + public void fun_HeartBeatMIS(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(HeartBeatMES, e); + } + /// + /// PLC系统健康心跳监测 + /// + /// + /// + public void fun_HeartBeatPLC(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(HeartBeatPLC, e); + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1051/MesServerFunction/vssver2.scc b/MisDataFunction/MesServer.Function/Function1051/MesServerFunction/vssver2.scc new file mode 100644 index 0000000..775bb6c Binary files /dev/null and b/MisDataFunction/MesServer.Function/Function1051/MesServerFunction/vssver2.scc differ diff --git a/MisDataFunction/MesServer.Function/Function1051/Methods/EngineGetOverBaseWork.cs b/MisDataFunction/MesServer.Function/Function1051/Methods/EngineGetOverBaseWork.cs new file mode 100644 index 0000000..a2070a6 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1051/Methods/EngineGetOverBaseWork.cs @@ -0,0 +1,345 @@ +using System; +using System.Data; +using System.Threading; +using bizFacade; +using MesServerWork; +//using SystemFramework; + + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 分线上总线的数量 + /// + public static int SubLineLoadPartCount = 2; + /// + /// 分线上总线已经匹配的数量 + /// + public static int SubLineLoadPartCountMatch = 0; + /// + /// 正常逻辑工作 + /// + /// + /// + /// + /// + /// + private void EngineTypeGetOver_PLC_Work(string OpName, int EngineTypeID, string EngineType, string EngineID, int PartPallet_Code,string OrderForm) + { + int IsAllowWork; + int RepairPartStatusPLC = 0; + int MES_QualityMask = 1; + + if (EngineTypeID <= 0 || EngineID.Length == 0 || EngineType.Length == 0) + { + MIS_BASE.WritePLC(34, OpName, true); + string msg = "【" + OpName + "】" + "PLC传递机型为空!"; + MyLog4Net.MyLogHelper.Error("EngineTypeGetOver", msg); + SendMessageFun.AsyncSendMessage_Notice(OpName, "PLC传递机型为空"); + return; + } + + MIS_BASE.Write_FixAllow(OpName, true); + + //初始化物料临时表 + //第二步,将零件信息转移到零件_临时表中(本地BOM与订单BOM的选择显示关系) + //BaseDataSystemMES.MesServer_Process_EngineTypeOver_BQ_FirstOP(OpName); + + ////5 显示订单、机型信息 线首工位用 + //SendMessage.ShowMoby_FirstOpName(OpName); + ////3显示操作指导图片 PicShow_String_FirstOpName + //SendMessage.PicShow_FirstOpName(OpName); + ////1(直接在界面通过选择机型确认工序内容) + //SendMessage.ProcessList_FirstOpName(OpName); + ////界面显示物料信息 + //SendMessage.MaterialList_FirstOpName(OpName); + + ////第四步,获取是否允许工作 + //BaseDataSystemMES.MesServer_Judge_IsCanWork(OpName, out IsAllowWork); + + // 暂时先定义为扫描完成才能进行压装工作,因为考虑到工作完成后,操作工未必会去扫描物料的情况 + //if (IsAllowWork == 1) + //{ + // //通知PLC允许工作,允许工作在保存完成时清空 + // MIS_BASE.Write_FixAllow(OpName, true); + //} + //else + //{ + // SendMessageFun.AsyncSendMessage_Notice(OpName, "请扫描物料!"); + //} + + } + + + /// + /// 保存MOBY信息 + /// + /// + /// + /// + /// + private void SaveMobyMessage(string OpName, int engineTypeID, string engineType, string engineID, string orderForm) + { + + if (MIS_BASE.hashtable_EngineGetOver_EngineTypeID == null) + { + MIS_BASE.InitHashtable_MesServerCode(); + } + if (MIS_BASE.hashtable_EngineGetOver_EngineTypeID.ContainsKey(OpName)) + { + MIS_BASE.hashtable_EngineGetOver_EngineTypeID[OpName] = engineTypeID; + } + if (MIS_BASE.hashtable_EngineGetOver_EngineType.ContainsKey(OpName)) + { + MIS_BASE.hashtable_EngineGetOver_EngineType[OpName] = engineType; + } + if (MIS_BASE.hashtable_EngineGetOver_EngineID.ContainsKey(OpName)) + { + MIS_BASE.hashtable_EngineGetOver_EngineID[OpName] = engineID; + } + if (MIS_BASE.hashtable_EngineGetOver_OrderForm.ContainsKey(OpName)) + { + MIS_BASE.hashtable_EngineGetOver_OrderForm[OpName] = orderForm; + } + } + + /// + /// 返修件需要工作 + /// + /// 工位号 + private void IsNeedRepaire_OK(string OpName) + { + + int isRepair; + int engineTypeID; + + string engineType = ""; + string engineID = ""; + string palletCode = ""; + string orderForm = ""; + string repairCode = ""; + //从监控系统中查询出本工位信息 + BaseDataSystemMES.OpName_MIS_Moby_Select(OpName, + out orderForm, out engineTypeID, out engineType, + out engineID, out palletCode, out isRepair, out repairCode); + + EngineTypeGetOver_PLC_Work(OpName, engineTypeID, engineType, engineID, Convert.ToInt32(palletCode),orderForm); + } + /// + /// 正常匹配分线和总线 + /// + /// + /// 总线工件号 + /// 总线工件机型代码 + /// 总线工件机型 + private void Match(string opName, string engineID, int engineTypeID, string engineType, int PartPallet_Code) + { + try + { + bool m_EngineGetOver_PLC_SubLine; + int engineTypeID_SubLine; + int partPallet_Code_SubLine; + int PalletInfo = 1;//总线托盘状态 + + string opName_SubLine = "";//分线工件信息 + string engineID_SubLine; + string engineType_SubLine; + string AlarmStr; + if (MIS_BASE.hashtable_OpNameRepair == null) + { + MIS_BASE.InitHashtable_MesServerCode(); + } + //第一步:获取分线中间交互工位号 + if (MIS_BASE.hashtable_OpNameRepair.ContainsKey(opName)) + { + opName_SubLine = MIS_BASE.hashtable_OpNameRepair[opName].ToString(); + } + if (opName_SubLine == "") + { + return; + } + + //第二步:获取分线传递机型信号 + MIS_BASE.Read_EngineGetOver_PLC(opName_SubLine, out m_EngineGetOver_PLC_SubLine); + if (!m_EngineGetOver_PLC_SubLine) return;//必须工件同时到位才能进行匹配 + + //第三步:判断合格标志 + MIS_BASE.Read_PalletInfo(opName_SubLine, out PalletInfo); + if (PalletInfo == 2) return; //若不合格则返回不进行匹配 + string OrderForm; + //第四步:获取分线的信息,匹配验证 + MIS_BASE.GetEngineTypeFromPLC(opName_SubLine, out engineTypeID_SubLine, out engineType_SubLine, out engineID_SubLine, out partPallet_Code_SubLine,out OrderForm); + //判断分线数据是否合格 + //if (!BaseDataSystemMES.QulityDataVerify(opName, engineID_SubLine, out AlarmStr) && !BaseDataSystemMES.QualityVerifyStatus_Hash_Read(opName)) + //{ + // SendInfomation("LineoutAlert", AlarmStr, opName); + // return; + //} + + if (engineTypeID_SubLine == engineTypeID) + { + BaseDataSystemMES.SubLineLoadPartCountMatch_Select(opName, out SubLineLoadPartCountMatch); + SubLineLoadPartCountMatch = SubLineLoadPartCountMatch + 1; + BaseDataSystemMES.SubLineLoadPartCountMatch_Update(opName, SubLineLoadPartCountMatch); + + + BaseDataSystemMES.MailLineAndSubLineData_Insert(engineID, engineTypeID, engineType, engineID_SubLine);//分线上总线数据转移 + MIS_BASE.Write_Match(opName, true);//匹配结果 + MIS_BASE.Write_MatchingCompleted(opName, true);//匹配完成 + if(SubLineLoadPartCountMatch== SubLineLoadPartCount) + { + MIS_BASE.Write_FixAllow(opName, true); + SubLineLoadPartCountMatch = 0; + BaseDataSystemMES.SubLineLoadPartCountMatch_Update(opName, SubLineLoadPartCountMatch); + + } + + SendMessageFun.SendInfomation("MatchSuccess", "1", opName); + sendmessage(opName, 1, "Match");//匹配结果 + } + else + { + MIS_BASE.Write_Match(opName, false);//匹配结果 + MIS_BASE.Write_MatchingCompleted(opName, true);//匹配完成//68:1、取消返修;2、匹配成功 自己监控发送 MES|MatchingCompleted + + //发送匹配完成和匹配结果信息 + SendMessageFun.AsyncSendMessage_Notice(opName,"匹配失败,工件型号不匹配!"); + SendMessageFun.SendInfomation("MatchSuccess", "0", opName); + sendmessage(opName, 0, "Match");//匹配结果 + } + + } + catch (Exception err) + { + ////ApplicationLog.WriteLog("Match:" + err.ToString()); + + } + } + + + + /// + /// 强制匹配分线和总线 + /// + /// + private void ForceMatch(string opName) + { + try + { + bool m_EngineGetOver_PLC_SubLine; + bool m_EngineGetOver_PLC; + + int engineTypeID_SubLine; + int engineTypeID; + int partPallet_Code_SubLine; + int partPallet_Code; + + string opName_SubLine = "";//分线工件信息 + string engineID_SubLine; + string engineType_SubLine; + string engineID; + string engineType; + if (MIS_BASE.hashtable_OpNameRepair == null) + { + MIS_BASE.InitHashtable_MesServerCode(); + } + //获取分线中间交互工位号 + if (MIS_BASE.hashtable_OpNameRepair.ContainsKey(opName)) + { + opName_SubLine = MIS_BASE.hashtable_OpNameRepair[opName].ToString(); + } + if (opName_SubLine == "") + { + return; + } + + MIS_BASE.Read_EngineGetOver_PLC(opName_SubLine, out m_EngineGetOver_PLC_SubLine);//1:读取分线工件到位的传递机型信号。 + + if (!m_EngineGetOver_PLC_SubLine) return;//必须工件同时到位才能进行匹配 + + MIS_BASE.Read_EngineGetOver_PLC(opName, out m_EngineGetOver_PLC);//2:读取总线工件到位的传递机型信号。 + + if (!m_EngineGetOver_PLC) return;//必须工件同时到位才能进行匹配 + string OrderForm; + MIS_BASE.GetEngineTypeFromPLC(opName_SubLine, out engineTypeID_SubLine, out engineType_SubLine, out engineID_SubLine, out partPallet_Code_SubLine,out OrderForm);//获取分线的信息 + MIS_BASE.GetEngineTypeFromPLC(opName, out engineTypeID, out engineType, out engineID, out partPallet_Code, out OrderForm); + + BaseDataSystemMES.MailLineAndSubLineData_Insert(engineID, engineTypeID, engineType, engineID_SubLine);//分线上总线数据转移 + + MIS_BASE.Write_Match(opName, true);//匹配结果 + MIS_BASE.Write_MatchingCompleted(opName, true);//匹配完成 + + SendMessageFun.SendInfomation("MatchSuccess", "1", opName);//界面显示匹配成功 + + MIS_BASE.Write_FixAllow(opName, true);//允许PLC工作 + + //发送匹配完成和匹配结果信息 + sendmessage(opName, 1, "MatchingComplete");//匹配完成 + sendmessage(opName, 1, "Match");//匹配结果 + } + catch + { + + } + } + + /// + /// 空料握手plc + /// + /// + private void Handshake_Fun(object e) + { + + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + + if (tagValue == 1) + { + int planCount = 0; // 计划上料数量 + int haveUplaodCount = 0; // 已上料数量 + int remainingQuantity = 0; // 待上料数量 + // 读取当前选择的计划中的机型,写入PLC + // 获取订单的机型 + string Program_No = ""; + Db.GetEngineType_Order(OpName, Program_No, out int EngineTypeID, out string EngineType, out string EngineID, out string OrderForm, out int isCheckOk, out planCount, out haveUplaodCount, out remainingQuantity); + if (isCheckOk == 2) + { + MIS_BASE.WritePLC(34, OpName, true); + + MIS_BASE.WritePLC(95, OpName, planCount); + MIS_BASE.WritePLC(96, OpName, haveUplaodCount); + MIS_BASE.WritePLC(97, OpName, remainingQuantity); + + MIS_BASE.WritePLC(35, OpName, true); + return; + } + else + { + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.EngineID_MES, EngineID); + + MIS_BASE.WritePLC(34, OpName, false); + + // 写入机型代码 (大机型) 机型 发动机号 订单号 + MIS_BASE.Write_EngineTypeID_MES(OpName, EngineTypeID); + MIS_BASE.Write_EngineType_MES(OpName, EngineType); + MIS_BASE.Write_EngineID_MES(OpName, EngineID); + MIS_BASE.Write_OrderForm_MES(OpName, OrderForm); + MIS_BASE.WritePLC(95, OpName, planCount); + MIS_BASE.WritePLC(96, OpName, haveUplaodCount); + MIS_BASE.WritePLC(97, OpName, remainingQuantity); + + Thread.Sleep(500); + // MES传递机型 + MIS_BASE.WritePLC(35, OpName, true); + } + } + else + { + MIS_BASE.WritePLC(35, OpName, false); + } + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1051/Methods/SubmitToMisweb.cs b/MisDataFunction/MesServer.Function/Function1051/Methods/SubmitToMisweb.cs new file mode 100644 index 0000000..8d84430 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1051/Methods/SubmitToMisweb.cs @@ -0,0 +1,145 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using bizFacade; +//using SystemFramework; + +namespace MesServerFunctions +{ + + /// + /// 此类用于向WEB发送各种类型消息 + /// + partial class FunctionMES + { + + + // /// + // /// 批量发送WEB消息(Value为BOOL值) + // /// + // /// 消息编号组合 + // /// 消息值组合 + // /// 工位号 + // void Sendmessage(string MessageNumm,string Value, string OpName) + //{ + // for (int i=0;i + // /// 选择发送给WEB的消息 + // /// + // /// 消息类型 + // /// 消息工位 + //void Sendmessage(char Num,string Value, string OpName) + //{ + // string SendMessage; + // switch (Num) + // { + // case '1': + // //1(直接在界面通过选择机型确认工序内容) + // SendMessage = "MES|ProcessList|" + OpName + "|" + Value; + // AsyncSendMessage(SendMessage); + // break; + + // case '2': + // //2显示物料 + // SendMessage = "MES|MaterialList|" + OpName + "|" + Value; + // AsyncSendMessage(SendMessage); + // break; + + // case '3': + + // //3显示操作指导图片 + // SendMessage = "MES|PicShow|" + OpName + "|" + Value; + // AsyncSendMessage(SendMessage); + // break; + // case '4': + // //3显示操作指导图片 + // SendMessage = "MES|OrderFormList|" + OpName + "|" + Value; + // AsyncSendMessage(SendMessage); + // break; + + // case '5': + // SendMessage = "MES|ShowMoby|" + OpName + "|" + Value; + // AsyncSendMessage(SendMessage); + // break; + // case '6': + // SendMessage = "MES|MaterialCheckPosition|" + OpName + "|" +Value; + // AsyncSendMessage(SendMessage); + // break; + // case '7': + // SendMessage = "MES|WorkStart|" + OpName + "|" + Value; + // AsyncSendMessage(SendMessage); + // break; + // case '8': + // SendMessage = "MES|OrderFormList|" + OpName + "|" + Value; + // AsyncSendMessage(SendMessage); + // break; + // case '9': + // SendMessage = "MES|ConfirmOkGo|" + OpName + "|" + Value; + // AsyncSendMessage(SendMessage); + // break; + // case 'a': + // SendMessage = "MES|FixAllow|" + OpName + "|" + Value; + // AsyncSendMessage(SendMessage); + // break; + // case 'b': + // SendMessage = "MES|ShaftPosition|" + OpName + "|" + Value; + // AsyncSendMessage(SendMessage); + // break; + // case 'c': + // SendMessage = "MES|ShowQuality|" + OpName + "|" + Value; + // AsyncSendMessage(SendMessage); + // break; + // } + //} + + /// + /// 向WEB发送信息(value为字符串) + /// + /// 消息种类 + /// 消息内容 + /// 工位号 + //void SendInfomation(string Command, string Value, string OpName) + //{ + + // string SendMessage = "MES|" + Command + "|" + OpName + "|" + Value; + // AsyncSendMessage(SendMessage); + //} + + + ///// + ///// 发送在线产量、在线节拍 + ///// + ///// + ///// + //private void SendActuallyCount(string OpName, int tagValue) + //{ + // //当工件离开时,更新在线产量、在线节拍 + // if (tagValue == 0) + // { + // try + // { + // int opNameCount = 0;//在线产量 + // int opNameCountTime = 0;//在线节拍 + + // BaseDataSystemMES.OpNameCount_New(OpName, out opNameCount, out opNameCountTime); //基本数据_工作日历_班次产量查询_New + + // SendInfomation("ActuallyCount", opNameCount.ToString() + "&" + opNameCountTime.ToString(), OpName); + + // } + // catch (Exception err) + // { + // ////ApplicationLog.WriteLog(err, "Function01:SendActuallyCount"); + // } + // } + //} + + + } +} diff --git a/MisDataFunction/MesServer.Function/Function1051/Methods/UDP.Send.cs b/MisDataFunction/MesServer.Function/Function1051/Methods/UDP.Send.cs new file mode 100644 index 0000000..26acece --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1051/Methods/UDP.Send.cs @@ -0,0 +1,62 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using MesServerWork; +//using BasicData; +using System.Collections; +using bizFacade; +//using SystemFramework; +using System.Data; +using System.Threading; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + ///// + ///// 发送信息到MES通讯服务器或者其他的 + ///// + ///// + //private void AsyncSendMessage(string Message) + //{ + // MIS_BASE.asyncSendMessage(Message); + //} + + /// + /// 发送提示消息 + /// + /// + //private void AsyncSendMessage_Notice(string opname, string notice) + //{ + // //通知Web界面 + // BaseDataSystemMES.Web_Notice_Insert(opname, notice); + // string SendMessage = "MES|Notice|" + opname + "|" + "1"; + // MIS_BASE.asyncSendMessage(SendMessage); + //} + + /// + /// 发送信息到打印机 + /// + /// + private void asyncSendMessageToMark(string Message) + { + string messageSend = (string)Message; + //UDPClientSend.Send_ALL(ApplicationConfig.MES_MarkPortNum, messageSend); + } + + /// + /// 发送信息到LED + /// + /// + private void asyncSendMessageLED(string OpName) + { + + //发送到大屏幕显示 41104 + string strMessage = "MIS|" + OpName + "|" + "0" + "|" + "1"; + //UDPClientSend.Send_ALL(ApplicationConfig.Port_ShowLED_ProductCount, strMessage); + + } + + } +} diff --git a/MisDataFunction/MesServer.Function/Function1051/Methods/vssver2.scc b/MisDataFunction/MesServer.Function/Function1051/Methods/vssver2.scc new file mode 100644 index 0000000..7b1a830 Binary files /dev/null and b/MisDataFunction/MesServer.Function/Function1051/Methods/vssver2.scc differ diff --git a/MisDataFunction/MesServer.Function/Function1051/OpcServer/Barcode.cs b/MisDataFunction/MesServer.Function/Function1051/OpcServer/Barcode.cs new file mode 100644 index 0000000..5a08a92 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1051/OpcServer/Barcode.cs @@ -0,0 +1,237 @@ +using System; +using System.Threading; +using System.Xml.Linq; +using bizFacade; + +//using SystemFramework; +using MesServerWork; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + object lockBarcode = new object(); + + ///第一步,判断条码类型,根据条码类型,执行对应的存储过程 + ///第二步,条码类型(将扫描的条码保存到对应的表中) + ///第三步,扫描完成之后给出允许工作信号 + /// 处理页面扫描条码 + /// + /// + /// + public void Barcode(object e) + { + lock(lockBarcode) + { + try + { + //DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + //string OpName = Convert.ToString(msgEvent.OpName); + ////+*************DbName***************** + //string DbName = Convert.ToString(msgEvent.OpName); + //string barcode = Convert.ToString(msgEvent.TagValue); + + //int EngineTypeID;//机型代码 + //string EngineType;//机型 + //string EngineID;//工件编号 + + //string OrderForm; + //int Recipe1; + //int Recipe2; + + //bool IsNotRepeatedNumber = false; + ////1:获得申请上线信息后,扫描条码才处理业务 + //bool ispartload; + ////(115) + //int PTO; + ////(118)0=不检测;1=24V,2=12V。检测线上线工位扫描总成条码,根据BOM,查出 + //int NgearSwitch; + ////(119)0=不检测;1=24V,2=12V。检测线上线工位扫描总成条码,根据BOM,查出 + //int RgearSwitch; + ////(120)0=不检测;1=检测。检测线上线工位扫描总成条码,根据BOM,查出 + //int SpeedSensor; + ////(121)例如:5S 400。检测线上线工位扫描总成条码,根据BOM,查出 + //string PartTypeMid; + ////(122) 0=不检测;1=24V,2=12V。检测线上线工位扫描总成条码,根据BOM,查出 + //int Tcu_V; + ////判断工件是否到位 + //MIS_BASE.Read_WorkStart(OpName, out ispartload); + //if (!ispartload) + //{ + // SendMessageFun.AsyncSendMessage_Notice(OpName, "请检查设备是否到位(DBX500.1=1)"); + // return; + //} + ////判断设备是否申请上线 + //MIS_BASE.Read_PartLoad(OpName, out ispartload); + //if (!ispartload) + //{ + // SendMessageFun.AsyncSendMessage_Notice(OpName, "请检查设备是否申请上线(DBX500.3=1)"); + // return; + //} + //// 判读条码是变速器序列号条码号还是物料号 小机型*日月年* 流水号(给起始号 + 数量) + //// 选小机型 从北汽福田BOM中选 得先维护BOM + //// 变速器序列号 '1333 050 062*16012023*30000001' + + ////扫描完变速器序列号条码号 true + //bool isGetOver_PLC = false; + ////判断上线工位,MES 是否将工件流水号、机型等信息已经写入到PLC了 + // MIS_BASE.Read_EngineGetOver_PLC(OpName, out isGetOver_PLC); + + ////如果工件流水号、机型等信息没有写入PLC,扫描的条码按工件流水号进行验证 + ////否则按装配物料进行验证 + //if (!isGetOver_PLC) + //{ + + // if (barcode.Split('*').Length > 2) + // { + // //2: 判断是否重号, 从数据库获得机型、机型代码等信息 + // string partSn = barcode; + // EngineID = barcode; + + // BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.EngineID_MES, EngineID); + + // //Db.GetEngineType( partSn, out EngineTypeID, out EngineType, out EngineID, out IsRepeatedNumber); + // //Db.GetEngineType( partSn, out EngineTypeID, out EngineType, out EngineID, out IsRepeatedNumber); + + // //IsRepeatedNumber true 不重号;false 重号; + // IsNotRepeatedNumber = BaseDataSystemMES.EngineTypeID_IsNotRepeatedNumber(partSn); + // if (IsNotRepeatedNumber) + // { + // BaseDataSystemMES.GetEngineTypeUpLoadOpName(partSn, OpName, out EngineTypeID, out EngineType, out OrderForm, out Recipe1, out Recipe2); + + // //MIS_BASE.Write_EngineID_MES(OpName, EngineID); + // //MIS_BASE.Write_EngineTypeID_MES(OpName, EngineTypeID); + // //MIS_BASE.Write_EngineType_MES(OpName, EngineType); + // //MIS_BASE.Write_OrderForm_MES(OpName, OrderForm); + + + // BaseDataSystemMES.UpLoadPTO(EngineType, out PTO, out NgearSwitch, out RgearSwitch, out SpeedSensor, out PartTypeMid, out Tcu_V); + // //PTO + // MIS_BASE.WritePLC(115, OpName, PTO); + // //空挡开关检测 + // MIS_BASE.WritePLC(95, OpName, NgearSwitch); + // //倒挡开关检测 + // MIS_BASE.WritePLC(96, OpName, RgearSwitch); + // //里程表检测 + // MIS_BASE.WritePLC(97, OpName, SpeedSensor); + // //大机型扩展 + // MIS_BASE.WritePLC(98, OpName, PartTypeMid); + // //TCU + // MIS_BASE.WritePLC(122, OpName, Tcu_V); + // string tagStartAdr;//= "DB411.10"; + + // // 先查询配方号 根据工位号 去moby表查配方号 + // // 根据配方号 去配方表查配方数据 + // // 写入配方数据 + // BaseDataSystemMES.PLCRcipeCurrent(OpName, out byte[] bytes, out tagStartAdr); + // DtWebApi.ReadWritePLC.Write_TagValueByTagTypeID("94", OpName, System.Text.Encoding.ASCII.GetString(bytes)); + // ////将产品信息写入PLC + // MIS_BASE.Write_EngineTypeID_MES(OpName, EngineTypeID); + // MIS_BASE.Write_EngineType_MES(OpName, EngineType); + // MIS_BASE.Write_EngineID_MES(OpName, EngineID); + // MIS_BASE.Write_OrderForm_MES(OpName, OrderForm); + + // //写入到数据库的[北汽福田工位状态监控MOBY]表中 + // //BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.EngineTypeID_MES, EngineTypeID.ToString()); + // //BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.EngineType_MES, EngineType); + // BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.EngineID_MES, EngineID); + // //BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.OrderForm_MES, OrderForm); + + + // // 工位号],[订单号],[产品型号代码],[变速器序列号],[发动机型号],[机型基本代码],[变速器总成号] ,[托盘号] + // // [产品型号代码_MES],[变速器序列号_MES],[发动机型号_MES] + // // [机床上电],[循环开始],[机床故障],[上料无件],[下料堵塞],[工件到位] + // // [传递机型],[申请上件],[允许保存],[保存完成],[合格标志],[前序合格] + // // [工号],[班次],[是否返修件],[合格放行],[不合格放行],[扫描条码] + + // //BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, "产品型号代码_MES", EngineTypeID.ToString()); + // //BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, "发动机型号_MES", EngineType); + + // MIS_BASE.Write_EngineTypeGetOver_MES(OpName, true); + + // //Thread.Sleep(5000); + // //MIS_BASE.Write_EngineTypeGetOver_MES(OpName, false); + + // //等待PLC将数据写入RFID;写入PLC的DB块,通知MES验证RFID机型数据是否正确传递 + + // //通知web显示 + // SendMessage.ShowMoby(OpName); + // //SendMessageFun.SendMessage("1235", "1111", OpName); + // } + // else + // { + // SendMessageFun.SendInfomation("EngineIDRepeat", "partSn", OpName); + // } + // } + // else + // { + // SendMessageFun.AsyncSendMessage_Notice(OpName, "变速器序列号格式不正确,请确认!"); + + // } + //} + //else//验证物料 + //{ + // //物料号 + // { + // //读取PLC的传递机型信号 + // bool tagValue; + // MIS_BASE.Read_EngineGetOver_PLC(OpName, out tagValue); + // if (tagValue) + // { + // //验证物料 + // BaseDataSystemMES.PartMaterial_DM_Update(OpName, barcode, out bool IsSuccess); + // if (!IsSuccess)//???? + // { + // SendMessageFun.AsyncSendMessage_Notice(OpName, "条码无效,请确认"); + // return; + // } + // else + // { + // SendMessageFun.SendInfomation("MaterialList", "1", OpName);//通知界面更新零件信息 + // } + // //判断物料是否验证完成 + // BaseDataSystemMES.MesServer_Judge_IsCanWork(OpName, out int IsAllowWork); + + + // if (IsSuccess) + // { + // if (IsAllowWork == 1) + // { + // //移到允许保存信号中 + // //BaseDataSystemMES.Material_Insert(OpName, 1); + + // ////更新订单完工数量及物料 + // SendMessageFun.SendMessage("24", "11", OpName); + + // //物料验证完成,通知PLC允许工作,允许工作在保存完成时清空 + // MIS_BASE.Write_FixAllow(OpName, true); + // } + // else + // { + // SendMessageFun.AsyncSendMessage_Notice(OpName, "请扫描物料!"); + // } + // } + // else + // { + // SendMessageFun.AsyncSendMessage_Notice(OpName, "PLC未传递机型"); + // } + // } + // else + // { + // SendMessage.AsyncSendMessage_Notice(OpName, "产品上线后,PLC获得变速器序列号后,再验证物料!"); + // } + + // } + //} + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function08:Barcode"); + } + } + + } + + + } +} diff --git a/MisDataFunction/MesServer.Function/Function1051/OpcServer/ConfirmOkGo.cs b/MisDataFunction/MesServer.Function/Function1051/OpcServer/ConfirmOkGo.cs new file mode 100644 index 0000000..a978c1f --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1051/OpcServer/ConfirmOkGo.cs @@ -0,0 +1,35 @@ +using System; +//using SystemFramework; +using MesServerWork; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 合格放行 + /// + /// + /// + private void ConfirmOkGo(object e) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + + if (tagValue == 1) + { + MIS_BASE.Write_MaterialVerifyOver(OpName, true);//工作完成 + SendMessageFun.SendInfomation("OrderFormList","1", OpName); + + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function08:ConfirmOkGo"); + } + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1051/OpcServer/EngineGetOver.cs b/MisDataFunction/MesServer.Function/Function1051/OpcServer/EngineGetOver.cs new file mode 100644 index 0000000..0976663 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1051/OpcServer/EngineGetOver.cs @@ -0,0 +1,99 @@ +using System; +using System.Data; +using bizFacade; +using MesServerWork; +//using SystemFramework; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + object lockBarcodeEngineTypeGetOver = new object(); + + + /// + /// PLC传递机型处理 + /// + /// + /// + private void EngineTypeGetOver_PLC(object e) + { + lock(lockBarcodeEngineTypeGetOver) + { + + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + //判断PLC机型与MES机型是否一致 + if (tagValue == 1) + { + bool MesRead = false; + + int EngineTypeID;//机型代码 + int PartPallet_Code;//托盘编号 + + string EngineType;//机型 + string EngineID;//工件编号 + + int EngineTypeID_MES;//机型代码 + string EngineType_MES;//机型 + string EngineID_MES;//工件编号 + + //上线工位清MES传递机型信号 + MIS_BASE.Write_EngineTypeGetOver_MES(OpName, false); + + MIS_BASE.Read_QualityData_Read_CF(OpName, out MesRead); + //第一步,判断允许保存和保存完成信号是否全部被清空,若未清空,则通知复位MES&PLC + if (MesRead) + { + //未能清空信号,请求复位 + string msg = "【" + OpName + "】" + "未能清空MesRead信号,请求复位!"; + SendMessageFun.SendInfomation("AskReset", "1", OpName); + MyLog4Net.MyLogHelper.Error("EngineTypeGetOver", msg); + return; + } + string OrderForm; + string OrderForm_MES; + MIS_BASE.GetEngineTypeFromPLC(OpName, out EngineTypeID, out EngineType, out EngineID, out PartPallet_Code, out OrderForm); + MIS_BASE.GetEngineTypeFromPLC_MES(OpName, out EngineTypeID_MES, out EngineType_MES, out EngineID_MES, out OrderForm_MES); + + if (EngineTypeID_MES == EngineTypeID & EngineID_MES == EngineID & EngineType_MES == EngineType & OrderForm_MES == OrderForm) + { + //写入到数据库的[北汽福田工位状态监控MOBY]表中 + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.EngineTypeID, EngineTypeID.ToString()); + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.EngineType, EngineType); + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.EngineID, EngineID); + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.OrderForm, OrderForm); + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.PartPallet_Code, PartPallet_Code.ToString()); + + EngineTypeGetOver_PLC_Work(OpName, EngineTypeID, EngineType, EngineID, PartPallet_Code, OrderForm); + return; + } + else + { + MIS_BASE.WritePLC(34, OpName, true); + string msg = "【" + OpName + "】" + "RFID机型与MES机型不匹配!"; + MyLog4Net.MyLogHelper.Error("EngineTypeGetOver", msg); + SendMessage.AsyncSendMessage_Notice(OpName, msg); + } + + } + else + { + MIS_BASE.Write_FixAllow(OpName, false); + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function08:EngineTypeGetOver_PLC"); + } + } + + } + + + + } +} diff --git a/MisDataFunction/MesServer.Function/Function1051/OpcServer/FalseGO.cs b/MisDataFunction/MesServer.Function/Function1051/OpcServer/FalseGO.cs new file mode 100644 index 0000000..54c73c7 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1051/OpcServer/FalseGO.cs @@ -0,0 +1,37 @@ +using System; +using MesServerWork; +//using SystemFramework; + + +namespace MesServerFunctions +{ + partial class FunctionMES + { + + /// + /// 返修放行 + /// + /// + /// + private void FalseGO(object e) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + + if (tagValue == 1) + { + MIS_BASE.Write_MaterialVerifyOver(OpName, true);//工作完成 + SendMessageFun.SendInfomation("OrderFormList", "1", OpName); + + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function08:FalseGO"); + } + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1051/OpcServer/HeartBeat.cs b/MisDataFunction/MesServer.Function/Function1051/OpcServer/HeartBeat.cs new file mode 100644 index 0000000..fdf985b --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1051/OpcServer/HeartBeat.cs @@ -0,0 +1,62 @@ +using bizFacade; +using MesServerWork; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// MES与PLC心跳监听 + /// + /// + /// + private void HeartBeatMES(object e) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + + //返写在MES心跳中 + MIS_BASE.WritePLC(15, OpName, tagValue); + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:FalseGO"); + } + } + + /// + /// MES与PLC心跳监听 + /// + /// + /// + private void HeartBeatPLC(object e) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + + int HeartBeatPLC; + //读取PLC心跳数据 + HeartBeatPLC = Convert.ToInt32(MIS_BASE.ReadPLC(14, OpName)); + //通知WEB修改状态 + string message = "MES|HeartBeatPLC|" + OpName + "|" + HeartBeatPLC.ToString(); + SendMessage.AsyncSendMessage(message); + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:FalseGO"); + } + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1051/OpcServer/MesRead.cs b/MisDataFunction/MesServer.Function/Function1051/OpcServer/MesRead.cs new file mode 100644 index 0000000..d309631 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1051/OpcServer/MesRead.cs @@ -0,0 +1,89 @@ +using System; +using bizFacade; +//using SystemFramework; +using MesServerWork; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + object lockMesRead = new object (); + /// + /// 保存完成(针对半自动和手动压装工位) + /// + /// + /// + private void MesRead(object e) + { + lock(lockMesRead) + { + try + { + int EngineTypeID; + string EngineType; + string EngineID; + int PartPallet_Code; + string OrderForm; + + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + + if (tagValue == 1) + { + int qualityMask; + + MIS_BASE.GetEngineTypeFromPLC(OpName, out EngineTypeID, out EngineType, out EngineID, out PartPallet_Code, out OrderForm); + //保存数据到线首表 先保存到 北汽福田变速器序列号总线上线 用于之前判断是否重号 + // 保存质量数据 + qualityMask = MisDataSaveDateMesRead.Funtion.MesRead(OpName, tagValue.ToString(), msgEvent.TagID.ToString()); + // 保存物料数据 + BaseDataSystemMES.Material_Insert(OpName, qualityMask); + + // 测量数据发动机在线状态 + BaseDataSystemMES.WorkStartInsert(OpName, qualityMask); + + // 推送质量数据到MES的页面 + SendMessageFun.SendInfomation("ShowTimelyQuality", "1&" + qualityMask.ToString(), OpName); + + // 记录手动存储的物料数据 + int byte1 = Convert.ToInt32(MIS_BASE.ReadPLC(211, OpName)); + int byte2 = Convert.ToInt32(MIS_BASE.ReadPLC(202, OpName)); + int byte3 = Convert.ToInt32(MIS_BASE.ReadPLC(203, OpName)); + int byte4 = Convert.ToInt32(MIS_BASE.ReadPLC(204, OpName)); + int byte5 = Convert.ToInt32(MIS_BASE.ReadPLC(205, OpName)); + int byte6 = Convert.ToInt32(MIS_BASE.ReadPLC(206, OpName)); + int byte7 = Convert.ToInt32(MIS_BASE.ReadPLC(207, OpName)); + int byte8 = Convert.ToInt32(MIS_BASE.ReadPLC(208, OpName)); + int byte9 = Convert.ToInt32(MIS_BASE.ReadPLC(209, OpName)); + int byte10 = Convert.ToInt32(MIS_BASE.ReadPLC(210, OpName)); + BaseDataSystemMES.HeLi_HMIMaterialFactory_Add(OpName, EngineID, OrderForm, byte1, byte2, byte3, byte4, byte5, byte6, byte7, byte8, byte9, byte10); + + //对应手动工位的 + //MIS_BASE.Write_ConfirmOkGo(OpName, true); + //通知设备,MES的质量数据(和物料数据)保存完成 + MIS_BASE.Write_MaterialVerifyOver(OpName, true); + MIS_BASE.Write_MesReadOver(OpName, true); + //统计在线产量,在线节拍 + SendMessage.SendActuallyCount(OpName, tagValue); + } + else + { + MIS_BASE.Write_MaterialVerifyOver(OpName, false); + MIS_BASE.Write_MesReadOver(OpName, false); + } + + } + + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function08:MesReadOver"); + } + + } + + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1051/OpcServer/MesReadOver.cs b/MisDataFunction/MesServer.Function/Function1051/OpcServer/MesReadOver.cs new file mode 100644 index 0000000..9b637f2 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1051/OpcServer/MesReadOver.cs @@ -0,0 +1,37 @@ +using System; +using bizFacade; +//using SystemFramework; +using MesServerWork; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 保存完成(针对半自动和手动压装工位) + /// + /// + /// + private void MesReadOver(object e) + { + try + { + //DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + //string OpName = Convert.ToString(msgEvent.OpName); + //int tagValue = Convert.ToInt32(msgEvent.TagValue); + + //if (tagValue == 1) + //{ + + // BaseDataSystemMES.Material_Insert(OpName, tagValue); + + // MIS_BASE.Write_ConfirmOkGo(OpName, true); + //} + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function08:MesReadOver"); + } + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1051/OpcServer/PartLoad.cs b/MisDataFunction/MesServer.Function/Function1051/OpcServer/PartLoad.cs new file mode 100644 index 0000000..677fe40 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1051/OpcServer/PartLoad.cs @@ -0,0 +1,88 @@ +using System; +using System.Threading; +using bizFacade; +//using SystemFramework; +using MesServerWork; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 申请上线(针对上线工位) + /// + /// + /// + private void PartLoad(object e) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + + + if (tagValue == 1) + { + // 读取当前选择的计划中的机型,写入PLC + // 获取订单的机型 + string Program_No = ""; + Db.GetEngineType_Order(OpName, Program_No, out int EngineTypeID, out string EngineType, out string EngineID, out string OrderForm, out int isCheckOk, out int planCount, out int haveUplaodCount, out int remainingQuantity); + if (isCheckOk == 2) + { + MIS_BASE.Write_EngineTypeID_MES(OpName, 0); + MIS_BASE.Write_EngineType_MES(OpName, ""); + MIS_BASE.Write_EngineID_MES(OpName, ""); + MIS_BASE.Write_OrderForm_MES(OpName, ""); + + MIS_BASE.WritePLC(95, OpName, planCount); + MIS_BASE.WritePLC(96, OpName, haveUplaodCount); + MIS_BASE.WritePLC(97, OpName, remainingQuantity); + + MIS_BASE.WritePLC(34, OpName, true); + string msg = "【" + OpName + "】" + "无上线订单,请下达新订单!"; + SendMessage.AsyncSendMessage_Notice(OpName, msg); + MyLog4Net.MyLogHelper.Error("PartLoad", msg); + return; + } + else + { + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.EngineID_MES, EngineID); + + MIS_BASE.WritePLC(34, OpName, false); + + // 写入机型代码 (大机型) 机型 发动机号 订单号 + MIS_BASE.Write_EngineTypeID_MES(OpName, EngineTypeID); + MIS_BASE.Write_EngineType_MES(OpName, EngineType); + MIS_BASE.Write_EngineID_MES(OpName, EngineID); + MIS_BASE.Write_OrderForm_MES(OpName, OrderForm); + MIS_BASE.WritePLC(95, OpName, planCount); + MIS_BASE.WritePLC(96, OpName, haveUplaodCount); + MIS_BASE.WritePLC(97, OpName, remainingQuantity); + + // 写入配方号 + string tagStartAdr; + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.EngineTypeID_MES, EngineTypeID.ToString()); + BaseDataSystemMES.PLCRcipeCurrent(OpName, out byte[] bytes, out tagStartAdr); + MIS_BASE.Write_TagValueByTagTypeID(94, OpName, System.Text.Encoding.ASCII.GetString(bytes)); + + Thread.Sleep(1000); + // MES传递机型 + MIS_BASE.Write_EngineTypeGetOver_MES(OpName, true); + // 通知web显示 + SendMessage.ShowMoby(OpName); + } + } + else + { + //上线工位清MES传递机型信号 + MIS_BASE.Write_EngineTypeGetOver_MES(OpName, false); + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function08:MesReadOver"); + } + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1051/OpcServer/PartLoadInPallet.cs b/MisDataFunction/MesServer.Function/Function1051/OpcServer/PartLoadInPallet.cs new file mode 100644 index 0000000..af9477a --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1051/OpcServer/PartLoadInPallet.cs @@ -0,0 +1,43 @@ +using System; +using bizFacade; +//using SystemFramework; +using MesServerWork; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 申请上线(针对上线工位) + /// + /// + /// + private void PartLoadInPallet(object e) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + + if (tagValue == 1) + { + // 读取上线轮毂号,进行确认上线的操作 + string EngineID_lungu; + MIS_BASE.Read_TagTypeID(40, OpName, out EngineID_lungu); + + Db.UpLoadOpNameInsert_Lungu(EngineID_lungu, OpName); + MIS_BASE.WritePLC(30, OpName, "1"); + } + else + { + MIS_BASE.WritePLC(30, OpName, "0"); + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function08:MesReadOver"); + } + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1051/OpcServer/WebSubmit.cs b/MisDataFunction/MesServer.Function/Function1051/OpcServer/WebSubmit.cs new file mode 100644 index 0000000..c76ad5f --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1051/OpcServer/WebSubmit.cs @@ -0,0 +1,383 @@ +using System; +using MesServerWork; +using bizFacade; +using System.Threading; +using MisDataSaveDate; +using System.Collections; +//using SystemFramework; + + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 处理WEB页面发送过来的请求(m_Command + "|" + m_Value;) + /// + /// + /// + private void WebSubmit(object e) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + string Content = Convert.ToString(msgEvent.TagValue); + + string opName_SubLine = ""; + string engineID = "";//工件信息 + string[] dataArray = Content.Split('|'); + + if (dataArray.Length != 2) + return; + + + string m_Command = dataArray[0].ToString();//消息类型 + string m_Value = dataArray[1].ToString();//消息参数 + string[] m_Value_array = m_Value.Split('&');//消息参数数量 + int m_Value_length = m_Value_array.Length; //消息参数长度 + + if (MIS_BASE.hashtable_EngineGetOver_EngineTypeID == null) + { + MIS_BASE.InitHashtable_MesServerCode(); + } + if (MIS_BASE.hashtable_EngineGetOver_EngineID.ContainsKey(OpName)) + { + engineID = MIS_BASE.hashtable_EngineGetOver_EngineID[OpName].ToString(); + } + if (MIS_BASE.hashtable_OpNameRepair == null) + { + MIS_BASE.InitHashtable_MesServerCode(); + } + DoWhatPlc.CustomeEvetnArgs _e = new DoWhatPlc.CustomeEvetnArgs(); + _e.OpName = OpName; + _e.TagValue = m_Value; + + //根据请求的命令处理逻辑 + switch (m_Command) + { + case "Barcode": + if (m_Value_length > 1) return; + fun_Barcode(_e); + break; + case "ConfirmOkGo"://合格放行 + //修改托盘状态 + + BaseDataSystemMES.BaseData_tagTable_Engine_IsNG_Delete(OpName, engineID); + MIS_BASE.Write_ConfirmOkGo(OpName, true); + MIS_BASE.Write_FalseGO(OpName, false); + Thread.Sleep(1000); + MIS_BASE.Write_ConfirmOkGo(OpName, false); + break; + case "FalseGO"://返修放行 + //修改托盘状态 + BaseDataSystemMES.BaseData_tagTable_Engine_IsNG_Delete(OpName, engineID); + MIS_BASE.Write_FalseGO(OpName, true); + MIS_BASE.Write_ConfirmOkGo(OpName, false); + Thread.Sleep(1000); + MIS_BASE.Write_FalseGO(OpName, false); + break; + case "NgGO"://不合格放行 + //修改托盘状态 + //保存不合格信息(必须保存不合格放行信息,由于B5A的Moby没有不合格标志位) + BaseDataSystemMES.BaseData_tagTable_Engine_IsNG_Insert(OpName, engineID, "", ""); + MIS_BASE.Write_FalseGO(OpName, true); + MIS_BASE.Write_ConfirmOkGo(OpName, false); + Thread.Sleep(1000); + MIS_BASE.Write_FalseGO(OpName, false); + break; + case "OnLineState"://在线0、离线1、屏蔽2 + try + { + if (m_Value_length > 1) return; + int a = Convert.ToInt32(m_Value); + if (a <= 2) + { + BaseDataSystemMES.IsOnLine_Update(OpName, m_Value.ToString()); + MIS_BASE.Write_OnLineState(OpName, Convert.ToInt32(m_Value)); + + if (a == 2) SendMessage.AsyncSendMessage_Notice(OpName, "屏蔽MES!"); + if (a == 0) SendMessage.AsyncSendMessage_Notice(OpName, "启用MES!"); + } + } + catch + { + + } + break; + + case "NullWorkGo"://空托盘放行 0不放行 1放行 + try + { + int a = Convert.ToInt32(m_Value); + //修改地址值 + MIS_BASE.Write_PartPalletGoOver(OpName, a); + if (a == 1) + { + SendMessage.AsyncSendMessage_Notice(OpName, "开启空托盘放行!"); + } + else + { + SendMessage.AsyncSendMessage_Notice(OpName, "关闭空托盘放行!"); + } + } + catch + { + + } + break; + case "Reset"://复位,将MES所有的信息都复位了 + SetMoby(OpName);//将MES所有信号清空 + + break; + case "FixAllow"://重新拧紧 + break; + case "IsAutoGetEngineID"://自动手动申请编号(线首) + if (m_Value_length > 1) return; + MIS_BASE.Write_IsAutoGetEngineID(OpName, Convert.ToInt32(m_Value)); + break; + case "PartPalletGoOver"://空托盘放行 + MIS_BASE.Write_RepairUpline_MES(opName_SubLine, true); + //MIS_BASE.Write_PalletInfo(opName_SubLine, 4); + //MIS_BASE.Write_UpdatePalletOK(opName_SubLine, true); + MIS_BASE.Write_MaterialVerifyOver(opName_SubLine, true); + break; + case "SetMoby"://清空托盘(线首) + SetMoby(OpName);//将MES所有信号清空 + break; + case "RepairUplineMES"://返修上线 + MIS_BASE.Write_RepairUpline_MES(OpName, true); + break; + case "CancelRepair"://将返修件置为正常件 + + break; + case "PartPalletCode"://申请写入托盘号 + //MIS_BASE.Write_PartPalletCode_PLC(OpName, 1); + break; + case "WritePartPalletCode"://写入托盘号 + if (m_Value_length > 1) return; + MIS_BASE.WritePLC(113, OpName, Convert.ToInt32(m_Value)); + Thread.Sleep(500); + MIS_BASE.WritePLC(70, OpName, true); + break; + case "Normal"://启用正常拧紧工位 + MIS_BASE.Write_Normal(OpName, 1); + MIS_BASE.Write_UnNormal(OpName, 0); + break; + case "UnNormal"://启用备用拧紧工位 + MIS_BASE.Write_Normal(OpName, 0); + MIS_BASE.Write_UnNormal(OpName, 1); + break; + case "ResetDevice"://复位设备 + MIS_BASE.Write_ResetDevice(OpName, true); + System.Threading.Thread.Sleep(1000); + MIS_BASE.Write_ResetDevice(OpName, false); + break; + case "IsNeedRepaire"://返修上线(返修上线点) + if (Convert.ToInt32(m_Value) == 1) + { + //修改托盘状态 + MIS_BASE.Write_PalletInfo(OpName, 3); + //通知修改成功 + MIS_BASE.Write_UpdatePalletOK(OpName, true); + IsNeedRepaire_OK(OpName); + } + else if (Convert.ToInt32(m_Value) == 0) + { + //直接给出工作完成 + MIS_BASE.Write_MaterialVerifyOver(OpName, true); + } + break; + //强制匹配 + case "ForceMatch": + if (Convert.ToInt32(m_Value) == 1) + { + ForceMatch(OpName); + } + break; + case "PalletGO": + + if (Convert.ToInt32(m_Value) == 1) + { + //直接给出工作完成 + MIS_BASE.Write_MaterialVerifyOver(opName_SubLine, true); + } + break; + case "ContinueMatch": + BaseDataSystemMES.QualityVerifyStatus_Hash_Write(OpName, true); + fun_EngineTypeGetOverPLC(_e); + break; + //初始化网页信号 + case "IniSingalToWeb": + InitializeSingalToWeb(OpName); + break; + //将指定托盘号写入托盘中(上线工位独有) + case "Write_WorkNumber": + //将工件号地址写入 + break; + //放行空托盘(上线工位独有) + ///case "Write_WorkNumber": + //将工件号地址写入 + // Convert.ToBoolean(m_Value) + // break; + default: break; + } + } + catch(Exception err) + { + ////ApplicationLog.WriteLog(err, "Function08:WebSubmit"); + } + } + + private void SetMoby(string OpName) + { + try + { + //清空Moby时,需要将MES信号清空 + MIS_BASE.Write_ClearMesMoby(OpName); + + BaseDataSystemMES.MesServer_Process_EngineTypeOver(OpName); + + SendMessageFun.SendMessage("5123", "1111", OpName); + + MIS_BASE.Write_ResetDevice(OpName, true); + System.Threading.Thread.Sleep(1000); + MIS_BASE.Write_ResetDevice(OpName, false); + } + catch + { + + } + } + + + /// + /// 网页重现登录,恢复关闭前的页面状态 + /// + /// 工位号 + private void InitializeSingalToWeb(string Opname) + { + bool S_WorkStart;//工件到位 DBX0.1 + bool S_EngineGetOver;//传递机型 DBX0.4 + bool S_FixAllow;//允许工作 DBX3.1 + bool S_MaterialVerifyOver;//工作完成 DBX2.3 + string S_plcStatus = "false";//DBX501.5 PLC直通,1 强制放行 0 正常循环 + + int IsCompleted = 0; + int S_Match = 0; + int PalletInfo_SubLine = 0;//显示分线托盘状态 + + MIS_BASE.Read_WorkStart(Opname, out S_WorkStart); + + if (S_WorkStart == true) + { + SendMessageFun.SendInfomation("WorkStart", Convert.ToString(Convert.ToInt32(S_WorkStart)), Opname); + //sendmessage(Opname, Convert.ToInt32(S_WorkStart), "WorkStart_Subline"); + } + + MIS_BASE.Read_EngineGetOver_PLC(Opname, out S_EngineGetOver); + if (S_EngineGetOver == true) + { + SendMessageFun.SendInfomation("EngineTypeGetOverPLC", Convert.ToString(Convert.ToInt32(S_EngineGetOver)), Opname); + //sendmessage(Opname, Convert.ToInt32(S_EngineGetOver), "EngineTypeGetOverMES_Subline"); + + //5 显示订单、机型信息 线首工位用 + SendMessage.ShowMoby_FirstOpName(Opname); + //界面显示物料信息 + SendMessage.MaterialList_FirstOpName(Opname); + } + + Thread.Sleep(1000); + + //3显示操作指导图片 PicShow_String_FirstOpName + SendMessage.PicShow_FirstOpName(Opname); + //1(直接在界面通过选择机型确认工序内容) + SendMessage.ProcessList_FirstOpName(Opname); + + + // 新增查询PLC直通状态 网页显示 + //MIS_BASE.Read_TagTypeID(63, Opname, out S_plcStatus); + + InitAlarm(Opname); + + if (S_plcStatus.ToLower() == "false") + { + SendMessageFun.SendInfomation("PlcStatus", "0", Opname); + } + else + { + SendMessageFun.SendInfomation("PlcStatus", "1", Opname); + } + + //sendmessage(Opname, Convert.ToInt32(S_WorkStart), "EngineTypeGetOverMES_Subline"); + + + + MIS_BASE.Read_FixAllow(Opname, out S_FixAllow); + + if (S_FixAllow == true) + { + SendMessageFun.SendInfomation("FixAllow", Convert.ToString(Convert.ToInt32(S_FixAllow)), Opname); + } + + MIS_BASE.Read_MaterialVerifyOver(Opname, out S_MaterialVerifyOver); + + if (S_MaterialVerifyOver == true) + { + SendMessageFun.SendInfomation("MaterialVerifyOver", Convert.ToString(Convert.ToInt32(S_MaterialVerifyOver)), Opname); + } + + //MIS_BASE.Read_MatchingCompleted(Opname, out IsCompleted); //DBX1.3 是否匹配 + //MIS_BASE.Read_Match(Opname, out S_Match); //DBX1.4 匹配结果 + + //if (IsCompleted == 1 && S_Match == 1)//发送匹配完成和匹配结果信息 + //{ + // SendMessageFun.SendInfomation("MatchingCompleted", "1", Opname); + // SendMessageFun.SendInfomation("Match", "1", Opname); + // SendMessageFun.SendInfomation("MatchSuccess", "1", Opname);//界面显示匹配成功 + //} + //else if (IsCompleted == 1 && S_Match == 0) + //{ + // SendMessageFun.SendInfomation("MatchSuccess", "0", Opname);//界面显示匹配失败 + //} + + //if (MIS_BASE.hashtable_OpNameRepair == null) + //{ + // MIS_BASE.InitHashtable_MesServerCode(); + //} + //string Opname_SubLine = ""; + //if (MIS_BASE.hashtable_OpNameRepair.ContainsKey(Opname)) + //{ + // Opname_SubLine = MIS_BASE.hashtable_OpNameRepair[Opname].ToString(); + //} + //if (Opname_SubLine == "") + //{ + // return; + //} + + //MIS_BASE.Read_PalletInfo(Opname, out PalletInfo_SubLine); + //sendmessage(Opname, PalletInfo_SubLine, "SubQualityMask"); + //SendMessageFun.SendInfomation("ShowMobySubLine", Opname_SubLine, Opname);//显示分线机型及流水号 + } + + //分线发送工件到位信号函数 + private void sendmessage(string OpName, int tagValue, string Command) + { + string SendMessage; + SendMessage = "MES|" + Command + "|" + OpName + "|" + tagValue; + SendMessageFun.AsyncSendMessage(SendMessage); + + } + private void InitAlarm(string Opname) + { + FuntionMesRead.Alarm_InitAlarm_Send(Opname, out Hashtable ht); + foreach (DictionaryEntry kv in ht) + { + var TagID = kv.Key.ToString(); + var TagValue = kv.Value.ToString(); + FuntionMesRead.Send_AlarmMsg(TagID, TagValue); + } + + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1051/OpcServer/WorkStart.cs b/MisDataFunction/MesServer.Function/Function1051/OpcServer/WorkStart.cs new file mode 100644 index 0000000..f16f3f2 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1051/OpcServer/WorkStart.cs @@ -0,0 +1,58 @@ +using System; +using bizFacade; +using MesServerWork; +//using SystemFramework; + + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 工件到位与离开时,清空MES自身信号 + /// + /// + /// + private void WorkStart(object e) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + + //线首显示订单信息 + + if (tagValue == 1) + { + MIS_BASE.Write_TagTypeID(115, OpName, 0); + MIS_BASE.Write_TagTypeID(95, OpName, 0); + MIS_BASE.Write_TagTypeID(96, OpName, 0); + MIS_BASE.Write_TagTypeID(97, OpName, 0); + MIS_BASE.Write_TagTypeID(98, OpName, ""); + //清空MOBY的产品流水号 + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.WorkStartIn, DateTime.Now.ToString()); + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.WorkStart, tagValue.ToString()); + } + else + { + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.WorkStartOut, DateTime.Now.ToString()); + MIS_BASE.Write_MesReadOver(OpName, false); + MIS_BASE.Write_ConfirmOkGo(OpName, false); + MIS_BASE.Write_FixAllow(OpName, false); + MIS_BASE.Write_EngineTypeGetOver_MES(OpName, false); + //工作完成 + MIS_BASE.Write_MaterialVerifyOver(OpName, false); + MIS_BASE.Write_EngineTypeID_MES(OpName, 0); + MIS_BASE.Write_EngineType_MES(OpName, ""); + MIS_BASE.Write_EngineID_MES(OpName, ""); + MIS_BASE.Write_OrderForm_MES(OpName, ""); + } + } + catch(Exception err) + { + ////ApplicationLog.WriteLog(err, "Function08:WorkStart"); + } + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1051/OpcServer/vssver2.scc b/MisDataFunction/MesServer.Function/Function1051/OpcServer/vssver2.scc new file mode 100644 index 0000000..e8dac03 Binary files /dev/null and b/MisDataFunction/MesServer.Function/Function1051/OpcServer/vssver2.scc differ diff --git a/MisDataFunction/MesServer.Function/Function1051/Properties/AssemblyInfo.cs b/MisDataFunction/MesServer.Function/Function1051/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..f3608c0 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1051/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// 有关程序集的常规信息通过以下 +// 特性集控制。更改这些特性值可修改 +// 与程序集关联的信息。 +[assembly: AssemblyTitle("Function08")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("苏州宏软信息技术有限公司")] +[assembly: AssemblyProduct("Function08")] +[assembly: AssemblyCopyright("Copyright © 苏州宏软信息技术有限公司 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// 将 ComVisible 设置为 false 使此程序集中的类型 +// 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型, +// 则将该类型上的 ComVisible 特性设置为 true。 +[assembly: ComVisible(false)] + +// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID +[assembly: Guid("47710f2c-e141-4252-8d13-701bf4c1c027")] + +// 程序集的版本信息由下面四个值组成: +// +// 主版本 +// 次版本 +// 内部版本号 +// 修订号 +// +// 可以指定所有这些值,也可以使用“内部版本号”和“修订号”的默认值, +// 方法是按如下所示使用“*”: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/MisDataFunction/MesServer.Function/Function1051/Properties/vssver2.scc b/MisDataFunction/MesServer.Function/Function1051/Properties/vssver2.scc new file mode 100644 index 0000000..87eebff Binary files /dev/null and b/MisDataFunction/MesServer.Function/Function1051/Properties/vssver2.scc differ diff --git a/MisDataFunction/MesServer.Function/Function1051/app.config b/MisDataFunction/MesServer.Function/Function1051/app.config new file mode 100644 index 0000000..b4c4daf --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1051/app.config @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + + + diff --git a/MisDataFunction/MesServer.Function/Function1051/mssccprj.scc b/MisDataFunction/MesServer.Function/Function1051/mssccprj.scc new file mode 100644 index 0000000..f184c61 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1051/mssccprj.scc @@ -0,0 +1,5 @@ +SCC = This is a Source Code Control file + +[Function08.csproj] +SCC_Aux_Path = "\\192.168.0.100\vss\MES4.0" +SCC_Project_Name = "$/MisData/MisData/MisData/MesServer.Function/Function08", KRHAAAAA diff --git a/MisDataFunction/MesServer.Function/Function1051/packages.config b/MisDataFunction/MesServer.Function/Function1051/packages.config new file mode 100644 index 0000000..b3e1761 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1051/packages.config @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/MisDataFunction/MesServer.Function/Function1051/vssver2.scc b/MisDataFunction/MesServer.Function/Function1051/vssver2.scc new file mode 100644 index 0000000..93af295 Binary files /dev/null and b/MisDataFunction/MesServer.Function/Function1051/vssver2.scc differ diff --git a/MisDataFunction/MesServer.Function/Function1052/DataAccess/DataAccess.cs b/MisDataFunction/MesServer.Function/Function1052/DataAccess/DataAccess.cs new file mode 100644 index 0000000..574d619 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1052/DataAccess/DataAccess.cs @@ -0,0 +1,15 @@ + +namespace MesServerFunctions +{ + partial class Function1052 + { + //针对“MIS.BizFacade.Dll”中没有的存储过程,在此类中新建 + //新建原则:所有的函数用private,只允许在内部使用 + //针对单个工艺特殊,需要新建存储过程,但是存储过程不能被加入到“MIS.BizFacade.Dll”中 + + private void aa() + { + + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1052/DataAccess/vssver2.scc b/MisDataFunction/MesServer.Function/Function1052/DataAccess/vssver2.scc new file mode 100644 index 0000000..d045c26 Binary files /dev/null and b/MisDataFunction/MesServer.Function/Function1052/DataAccess/vssver2.scc differ diff --git a/MisDataFunction/MesServer.Function/Function1052/Function02.csproj.vspscc b/MisDataFunction/MesServer.Function/Function1052/Function02.csproj.vspscc new file mode 100644 index 0000000..0f0f36c --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1052/Function02.csproj.vspscc @@ -0,0 +1,10 @@ +"" +{ +"FILE_VERSION" = "9237" +"ENLISTMENT_CHOICE" = "NEVER" +"PROJECT_FILE_RELATIVE_PATH" = "relative:MesServer.Function\\Function02" +"NUMBER_OF_EXCLUDED_FILES" = "0" +"ORIGINAL_PROJECT_FILE_PATH" = "" +"NUMBER_OF_NESTED_PROJECTS" = "0" +"SOURCE_CONTROL_SETTINGS_PROVIDER" = "PROVIDER" +} diff --git a/MisDataFunction/MesServer.Function/Function1052/Function1052.csproj b/MisDataFunction/MesServer.Function/Function1052/Function1052.csproj new file mode 100644 index 0000000..91da6dd --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1052/Function1052.csproj @@ -0,0 +1,171 @@ + + + + Debug + AnyCPU + 8.0.30703 + 2.0 + {5FEE5C91-8419-49FF-B2C2-47476F0B8C68} + Library + Properties + Function1052 + Function1052 + v4.8 + 512 + + + + + + + + + + + + + + true + full + false + ..\..\..\dll_fun\ + DEBUG;TRACE + prompt + 4 + false + false + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + false + + + + ..\..\..\Common\dll\MQTTnet.dll + + + ..\..\..\Common\dll\MQTTnet.Extensions.ManagedClient.dll + + + False + ..\..\..\Common\dll\Newtonsoft.Json.dll + + + + + + ..\..\DLL\System.Net.Http.dll + + + ..\..\packages\System.Net.Security.4.3.2\lib\net46\System.Net.Security.dll + + + ..\..\packages\System.Net.WebSockets.4.3.0\lib\net46\System.Net.WebSockets.dll + + + ..\..\packages\System.Net.WebSockets.Client.4.3.2\lib\net46\System.Net.WebSockets.Client.dll + + + ..\..\packages\System.Security.Cryptography.Algorithms.4.3.0\lib\net461\System.Security.Cryptography.Algorithms.dll + + + ..\..\packages\System.Security.Cryptography.Encoding.4.3.0\lib\net46\System.Security.Cryptography.Encoding.dll + + + ..\..\packages\System.Security.Cryptography.Primitives.4.3.0\lib\net46\System.Security.Cryptography.Primitives.dll + + + ..\..\packages\System.Security.Cryptography.X509Certificates.4.3.0\lib\net461\System.Security.Cryptography.X509Certificates.dll + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + {f55da1a0-a982-4479-8c47-0d9a5aaf3e18} + 00MesWorkMqtt + + + {0d1af432-439a-4920-8692-43ae139f5530} + 01_01DoWhatPlc + + + {f434e066-4c59-47c8-aa82-6f48cc84501a} + 04-DataBaseAccess + + + {f0a0c525-03fd-428a-9b17-7f54aa0e4475} + 07BusinessFacade + + + {d98be764-adeb-488d-9714-61e308aa8201} + 08-WebFun_base + + + {90e76fb4-646d-45e2-95db-0b8ab4e465d6} + 09-MesDataFunction + + + {e4eb6420-906d-4672-947a-ca33ddcdadfc} + 12SendMessageToWeb + + + {55b510c1-59e9-4bfd-ae84-d76d46f6e365} + 02-13.3MIS_FuntionSaveData + + + {1dc48c83-1842-4de8-acaf-26e1e7f7c58f} + 00_MyLog4Net + + + + + + + + + + 这台计算机上缺少此项目引用的 NuGet 程序包。使用“NuGet 程序包还原”可下载这些程序包。有关更多信息,请参见 http://go.microsoft.com/fwlink/?LinkID=322105。缺少的文件是 {0}。 + + + + + \ No newline at end of file diff --git a/MisDataFunction/MesServer.Function/Function1052/MesServerFunction/Fun_1052.cs b/MisDataFunction/MesServer.Function/Function1052/MesServerFunction/Fun_1052.cs new file mode 100644 index 0000000..1cc85e6 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1052/MesServerFunction/Fun_1052.cs @@ -0,0 +1,239 @@ +using MesServerWork; +using MisDataSaveDate; +using System.Collections.Generic; +using System.Threading; +using System.Xml.Linq; + +namespace MesServerFunctions +{ + public partial class FunctionMES + { + object lockFunWork; + //public void FunWork(DoWhatPlc.CustomeEvetnArgs e) + public void FunWork(string recData) + { + + + lockFunWork = new object(); + lock (lockFunWork) + { + List dataArray = DoWhatPlc.MessageText.GetCmdStringList(recData); + //string[] dataArray = recData.Split('|'); + //if (dataArray.Count != 4) + //return; + //消息来源 + string m_Source = dataArray[0].ToString(); + //消息类型 Barcode + string m_Command = dataArray[1].ToString(); + //工位号 + string m_OpName = dataArray[2].ToString(); + //消息参数 + string m_Value = dataArray[3].ToString(); + + DoWhatPlc.CustomeEvetnArgs e = new DoWhatPlc.CustomeEvetnArgs();// = Newtonsoft.Json.JsonConvert.DeserializeObject(m_Value); + string tagValue; + + switch (m_Source) + { + case "BarCode": + e.OpName = m_OpName; + e.TagValue = m_Value; + fun_Barcode(e); + break; + case "WEB": + e.OpName = m_OpName; + e.TagValue = m_Command + "|" + m_Value; + fun_WebSubmit(e); + break; + case "PLC": + e = Newtonsoft.Json.JsonConvert.DeserializeObject(m_Value); + string TagID = e.TagID.ToString(); + switch (e.TagValue.ToString().ToLower()) + { + case "false": + tagValue = "0"; + break; + case "true": + tagValue = "1"; + break; + default: + tagValue = e.TagValue.ToString(); + break; + } + e.TagValue = tagValue; + switch (e.TagTypeCodeID.ToString()) + { + //PLC 工件到位 + case "2": + fun_WorkStart(e); + break; + //PLC 允许保存质量数据 + case "19": + fun_MesRead(e); + break; + //MES 保存数据完成 + case "20": + fun_MesReadOver(e); + break; + //PLC 传递机型 + case "44": + fun_EngineTypeGetOverPLC(e); + break; + //MES 合格放行 + case "51": + fun_ConfirmOkGo(e); + break; + //MES 不合格放行 + case "8": + fun_FalseGo(e); + break; + //PLC 工位合格标志 + case "21": + fun_IsOk(e); + break; + //MES保存实时质量数据 + case "65": + fun_MesSaveNowData(e); + break; + //MES 系统健康心跳 + case "14": + fun_HeartBeatMIS(e); + break; + case "63": + string S_plcStatus;//DBX501.5 PLC直通,1 强制放行 0 正常循环 + MIS_BASE.Read_TagTypeID(63, m_OpName, out S_plcStatus); + if (S_plcStatus.ToLower() != "true" || S_plcStatus.ToLower() == "1") + { + SendMessageFun.SendInfomation("PlcStatus", "0", m_OpName); + } + else + { + SendMessageFun.SendInfomation("PlcStatus", "1", m_OpName); + } + break; + } + break; + } + } + } + + //1.工件到位后,PLC给MES传递机型(DBX0.4)(44), + //MES判断条码是否全部扫描完成 + //PLC给出允许保存(DBX100.2)(19),MES见到(DBX100.2)(19)为1后给出保存完成(DBX102.2)(20), + //PLC见到保存完成(DBX102.2)(20)为1后,清空允许保存(DBX100.2)(19), + //MES见到允许保存(DBX100.2)(19)为0后,清空保存完成(DBX102.2)(20) + //MES判断总合格标志(INT104)(21)为1后,给出合格放行(DBX2.5)(51) + /// + /// 扫描条码 + /// + /// + /// + public void fun_Barcode(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(Barcode, e); + } + + /// + /// 传递机型 + /// + /// + /// + public void fun_EngineTypeGetOverPLC(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(EngineTypeGetOver_PLC, e); + } + + /// + /// 合格放行 + /// + /// + /// + public void fun_ConfirmOkGo(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(ConfirmOkGo, e); + } + + /// + /// 不合格放行 + /// + /// + /// + public void fun_FalseGo(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(FalseGO, e); + } + + /// + /// 允许保存 + /// + /// + /// + public void fun_MesRead(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(MesRead, e); + } + + /// + /// 保存完成 + /// + /// + /// + public void fun_MesReadOver(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(MesReadOver, e); + } + + /// + /// 工件到位离开(清空所有的MES信号) + /// + /// + /// + public void fun_WorkStart(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(WorkStart, e); + } + + /// + /// 处理WEB页面发送过来的请求(m_Command + "|" + m_Value;) + /// + /// + /// + public void fun_WebSubmit(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(WebSubmit, e); + } + + + /// + /// 工位是否合格 + /// + /// + /// + public void fun_IsOk(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(IsOk, e); + } + + /// + /// 系统健康心跳监测 + /// + /// + /// + public void fun_HeartBeatMIS(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(HeartBeat, e); + } + + /// + /// MES实时保存质量数据 + /// + /// + /// + public void fun_MesSaveNowData(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(MesSaveNowData, e); + } + + + } +} diff --git a/MisDataFunction/MesServer.Function/Function1052/MesServerFunction/vssver2.scc b/MisDataFunction/MesServer.Function/Function1052/MesServerFunction/vssver2.scc new file mode 100644 index 0000000..a246f67 Binary files /dev/null and b/MisDataFunction/MesServer.Function/Function1052/MesServerFunction/vssver2.scc differ diff --git a/MisDataFunction/MesServer.Function/Function1052/Methods/EngineGetOverBaseWork.cs b/MisDataFunction/MesServer.Function/Function1052/Methods/EngineGetOverBaseWork.cs new file mode 100644 index 0000000..b6f3d24 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1052/Methods/EngineGetOverBaseWork.cs @@ -0,0 +1,123 @@ +using System; +using System.Data; +using bizFacade; +using MesServerWork; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 正常逻辑工作(传递机型) + /// + /// + /// + /// + /// + /// + private void EngineTypeGetOver_PLC_Work(string OpName, int EngineTypeID, string EngineType, string EngineID, int PartPallet_Code,string OrderForm) + { + int IsAllowWork; + int RepairPartStatusPLC = 0; + int MES_QualityMask = 1; + + if (EngineTypeID <= 0 || EngineID.Length == 0 || EngineType.Length == 0) + { + MIS_BASE.WritePLC(34, OpName, true); + string msg = "【" + OpName + "】" + "PLC传递机型为空!"; + MyLog4Net.MyLogHelper.Error("EngineTypeGetOver", msg); + SendMessageFun.AsyncSendMessage_Notice(OpName, "PLC传递机型为空"); + return; + } + + //电子看板_装配零件_临时表_增加_北汽 + //第二步,将零件信息转移到零件_临时表中 + BaseDataSystemMES.MesServer_Process_EngineTypeOverBQ(OpName); + + //通知web显示 + SendMessageFun.SendMessage("123", "111", OpName); + //MIS_BASE.Read_PalletInfo(OpName, out MES_QualityMask);//合格标志 合格标志暂时改为即时响应式的 + MIS_BASE.Read_RepairStatus_PLC(OpName, out RepairPartStatusPLC);//返修标志 + //SendMessageFun.SendInfomation("QualityMask", Convert.ToString(MES_QualityMask), OpName);//显示合格标志 + SendMessageFun.SendInfomation("RepairPartStatusPLC", Convert.ToString(RepairPartStatusPLC), OpName);//显示返修标志 + + if (MES_QualityMask == 2) + { + // 暂时先屏蔽掉 + ////工作完成 + //MIS_BASE.Write_MaterialVerifyOver(OpName, true); + //SendMessageFun.SendInfomation("NgGO", "1", OpName);//显示不合格标志 + //return; + } + + //第三步,用于工件离开后完工数量统计及工件编号追溯 + //BaseDataSystemMES.MaterialPush_EngineIDStatus_Insert(OpName);//更新订单产量 + + //第四步,获取是否允许工作 + BaseDataSystemMES.MesServer_Judge_IsCanWork(OpName, out IsAllowWork); + + //暂时先定义为扫描完成才能进行压装工作,因为考虑到工作完成后,操作工未必会去扫描物料的情况 + if (IsAllowWork == 1) + { + //通知PLC允许工作,允许工作在保存完成时清空 + MIS_BASE.Write_FixAllow(OpName, true); + } + else + { + SendMessageFun.AsyncSendMessage_Notice(OpName, "请扫描物料!"); + } + + } + + /// + /// 二次工作 + /// + /// + private void EngineTypeGetOver_PLC_Work_two(string OpName) + { + int EngineTypeID;//机型代码 + int PartPallet_Code;//托盘编号 + + string EngineType;//机型 + string EngineID;//工件编号 + string OrderForm; + MIS_BASE.GetEngineTypeFromPLC(OpName, out EngineTypeID, out EngineType, out EngineID, out PartPallet_Code, out OrderForm); + EngineTypeGetOver_PLC_Work(OpName, EngineTypeID, EngineType, EngineID, Convert.ToInt32(PartPallet_Code), OrderForm); + + } + /// + /// 跳过二次工作 + /// + /// + private void EngineTypeGetOver_PLC_Work_Skip(string OpName) + { + //MIS_BASE.Write_MesReadOver(OpName, true); + MIS_BASE.Write_MaterialVerifyOver(OpName, true); + } + + /// + /// 返修件需要工作 + /// + /// 工位号 + private void IsNeedRepaire_OK(string OpName) + { + string orderForm = ""; + int engineTypeID; + string engineType = ""; + string engineID = ""; + string palletCode = ""; + int isRepair; + string repairCode = ""; + //从监控系统中查询出本工位信息 + BaseDataSystemMES.OpName_MIS_Moby_Select(OpName, + out orderForm, out engineTypeID, out engineType, + out engineID, out palletCode, out isRepair, out repairCode); + + EngineTypeGetOver_PLC_Work(OpName, engineTypeID, engineType, engineID, Convert.ToInt32(palletCode),orderForm); + } + + + + + } +} diff --git a/MisDataFunction/MesServer.Function/Function1052/Methods/SubmitToMisweb.cs b/MisDataFunction/MesServer.Function/Function1052/Methods/SubmitToMisweb.cs new file mode 100644 index 0000000..52ce16f --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1052/Methods/SubmitToMisweb.cs @@ -0,0 +1,127 @@ +using System; +using bizFacade; +//using SystemFramework; + +namespace MesServerFunctions +{ + + /// + /// 此类用于向WEB发送各种类型消息 + /// + partial class FunctionMES + { + + /// + /// 批量发送WEB消息(Value为BOOL值) + /// + /// 消息编号组合 + /// 消息值组合 + /// 工位号 + void Sendmessage(string MessageNumm,string Value, string OpName) + { + for (int i=0;i + /// 选择发送给WEB的消息 + /// + /// 消息类型 + /// 消息工位 + string Sendmessage(char Num,string Value, string OpName) + { + string SendMessage; + string result = ""; + switch (Num) + { + case '1': + //1(直接在界面通过选择机型确认工序内容) + SendMessage = "MES|ProcessList|" + OpName + "|" + Value; + result = AsyncSendMessage(SendMessage); + break; + case '2': + //2显示物料 + SendMessage = "MES|MaterialList|" + OpName + "|" + Value; + result = AsyncSendMessage(SendMessage); + break; + case '3': + //3显示操作指导图片 + SendMessage = "MES|PicShow|" + OpName + "|" + Value; + result = AsyncSendMessage(SendMessage); + break; + case '4': + //4订单完工模块刷新完成数量 + SendMessage = "MES|OrderFormList|" + OpName + "|" + Value; + AsyncSendMessage(SendMessage); + break; + case '5': + SendMessage = "MES|ShowMoby|" + OpName + "|" + Value; + result = AsyncSendMessage(SendMessage); + break; + case '6': + SendMessage = "MES|MaterialCheckPosition|" + OpName + "|" +Value; + result = AsyncSendMessage(SendMessage); + break; + case '7': + SendMessage = "MES|WorkStart|" + OpName + "|" + Value; + result = AsyncSendMessage(SendMessage); + break; + case '8'://清除MES生成编号 + + break; + case '9': + SendMessage = "MES|ConfirmOkGo|" + OpName + "|" + Value; + result = AsyncSendMessage(SendMessage); + break; + case 'a': + SendMessage = "MES|FixAllow|" + OpName + "|" + Value; + result = AsyncSendMessage(SendMessage); + break; + } + return result; + } + /// + /// 向WEB发送信息(value为字符串) + /// + /// 消息种类 + /// 消息内容 + /// 工位号 + string SendInfomation(string Command, string Value, string OpName) + { + string SendMessage = "MES|" + Command + "|" + OpName + "|" + Value; + return AsyncSendMessage(SendMessage); + } + + + /// + /// 发送在线产量、在线节拍 + /// + /// + /// + private void SendActuallyCount(string OpName, int tagValue) + { + //当工件离开时,更新在线产量、在线节拍 + if (tagValue == 0) + { + try + { + int opNameCount = 0;//在线产量 + int opNameCountTime = 0;//在线节拍 + //基本数据_工作日历_班次产量查询_New + BaseDataSystemMES.OpNameCount_New(OpName, out opNameCount, out opNameCountTime); + string SendMessage; + SendMessage = "MES|ActuallyCount|" + OpName + "|" + opNameCount.ToString() + "&" + opNameCountTime.ToString(); + AsyncSendMessage(SendMessage); + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:SendActuallyCount"); + } + } + } + + + } +} diff --git a/MisDataFunction/MesServer.Function/Function1052/Methods/UDP.Send.cs b/MisDataFunction/MesServer.Function/Function1052/Methods/UDP.Send.cs new file mode 100644 index 0000000..aed7cc3 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1052/Methods/UDP.Send.cs @@ -0,0 +1,53 @@ +using bizFacade; +//using SystemFramework; +using MesServerWork; +using DataLinkMesWork; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 发送信息到MES通讯服务器或者其他的 + /// + /// + private string AsyncSendMessage(string Message) + { + return MIS_BASE.asyncSendMessage(Message); + } + + /// + /// 发送提示消息 + /// + /// + private void AsyncSendMessage_Notice(string opname, string notice) + { + //通知Web界面 + BaseDataSystemMES.Web_Notice_Insert(opname, notice); + string SendMessage = "MES|Notice|" + opname + "|" + "1"; + MIS_BASE.asyncSendMessage(SendMessage); + } + + /// + /// 发送信息到打印机 + /// + /// + private void asyncSendMessageToMark(string Message) + { + string messageSend = (string)Message; + //UDPClientSend.Send_ALL(ApplicationConfig.MES_MarkPortNum, messageSend); + } + + /// + /// 发送信息到LED + /// + /// + private void asyncSendMessageLED(string OpName) + { + //发送到大屏幕显示 41104 + string strMessage = "MIS|" + OpName + "|" + "0" + "|" + "1"; + //UDPClientSend.Send_ALL(ApplicationConfig.Port_ShowLED_ProductCount, strMessage); + + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1052/Methods/vssver2.scc b/MisDataFunction/MesServer.Function/Function1052/Methods/vssver2.scc new file mode 100644 index 0000000..7782f6f Binary files /dev/null and b/MisDataFunction/MesServer.Function/Function1052/Methods/vssver2.scc differ diff --git a/MisDataFunction/MesServer.Function/Function1052/OpcServer/Barcode.cs b/MisDataFunction/MesServer.Function/Function1052/OpcServer/Barcode.cs new file mode 100644 index 0000000..1f9ea05 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1052/OpcServer/Barcode.cs @@ -0,0 +1,90 @@ +using System; +using System.Windows.Forms; +using bizFacade; +//using SystemFramework; +using MesServerWork; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + ///1.扫描配送单号,用于接收物料,扫描单号的时候,将接收的物料信息显示在“物料拉动”Tab区域 + ///2.扫描料箱标签/看板卡,用于追溯物料批次信息 + ///3.扫描零件条码,根据零件图号进行防错 + ///第一步,判断条码类型,根据条码类型,执行对应的存储过程 + ///第二步,条码类型(将扫描的条码保存到对应的表中) + ///第三步,扫描完成之后给出允许工作信号 + /// 处理页面扫描条码 + /// + /// + /// + public void Barcode(object e) + { + + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + string barcode = Convert.ToString(msgEvent.TagValue); + string AlarmStr = ""; + + int IsAllowWork; + bool IsSuccess = false; + bool EngineGetOver_PLC_NextWorkStep; + //传递机型是否到位 + MIS_BASE.Read_EngineGetOver_PLC(OpName, out EngineGetOver_PLC_NextWorkStep); + if (!EngineGetOver_PLC_NextWorkStep) + { + SendMessageFun.AsyncSendMessage_Notice(OpName, "PLC未传递机型"); + return; + } + //物料验证 + BaseDataSystemMES.PartMaterial_DM_Update(OpName, barcode, out IsSuccess); + if (!IsSuccess) + { + SendMessageFun.AsyncSendMessage_Notice(OpName, "条码无效,请确认"); + return; + } + else + { + SendMessageFun.SendInfomation("MaterialList", "1", OpName);//通知界面更新零件信息 + } + + + + + //获取是否允许工作 + BaseDataSystemMES.MesServer_Judge_IsCanWork(OpName, out IsAllowWork); + + //此处逻辑有问题 需要考虑到批次扫描 提示PLC未传递机型的情况 + if (IsAllowWork == 1) + { + //BaseDataSystemMES.Material_Insert(OpName, 1); + + //更新订单完工数量及物料 + SendMessageFun.SendMessage("24", "11", OpName); + + //通知PLC允许工作,允许工作在保存完成时清空 + MIS_BASE.Write_FixAllow(OpName, true); + } + else + { + SendMessageFun.AsyncSendMessage_Notice(OpName, "请扫描物料!"); + } + + + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:Barcode"); + } + + } + + } + + + } +} diff --git a/MisDataFunction/MesServer.Function/Function1052/OpcServer/ConfirmOkGo.cs b/MisDataFunction/MesServer.Function/Function1052/OpcServer/ConfirmOkGo.cs new file mode 100644 index 0000000..06e6b33 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1052/OpcServer/ConfirmOkGo.cs @@ -0,0 +1,41 @@ +using System; +using bizFacade; +//using SystemFramework; +using MesServerWork; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 合格放行 + /// + /// + /// + private void ConfirmOkGo(object e) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + + if (tagValue == 1) + { + + BaseDataSystemMES.Material_Insert(OpName, 1); + + //更新订单完工数量及物料 + Sendmessage("24", "11", OpName); + + //工作完成 + MIS_BASE.Write_MaterialVerifyOver(OpName, true); + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:ConfirmOkGo"); + } + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1052/OpcServer/EngineGetOver.cs b/MisDataFunction/MesServer.Function/Function1052/OpcServer/EngineGetOver.cs new file mode 100644 index 0000000..3258e06 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1052/OpcServer/EngineGetOver.cs @@ -0,0 +1,83 @@ +using System; +using System.Data; +using System.Threading; +using System.Windows.Forms; +using System.Xml.Linq; +using bizFacade; +//using SystemFramework; +using MesServerWork; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// PLC传递机型处理 + /// + /// + /// + private void EngineTypeGetOver_PLC(object e) + { + + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + + if (tagValue == 1) + { + int EngineTypeID;//机型代码 + int PartPallet_Code;//托盘编号 + + string EngineType;//机型 + string EngineID;//工件编号 + string OrderForm; + //Thread.Sleep(6000); + MIS_BASE.GetEngineTypeFromPLC(OpName, out EngineTypeID, out EngineType, out EngineID, out PartPallet_Code, out OrderForm); + if (EngineTypeID <= 0 || EngineID.Length == 0 || EngineType.Length == 0) + { + MIS_BASE.WritePLC(34, OpName, true); + string msg = "【" + OpName + "】" + "PLC传递机型为空!EngineTypeID:"+EngineTypeID+",EngineID:"+EngineID+",EngineType:"+EngineType; + MyLog4Net.MyLogHelper.Error("EngineTypeGetOver", msg); + SendMessageFun.AsyncSendMessage_Notice(OpName, "PLC传递机型为空!"); + return; + } + + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.EngineTypeID, EngineTypeID.ToString()); + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.EngineType, EngineType); + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.EngineID, EngineID); + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.OrderForm, OrderForm); + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.PartPallet_Code, PartPallet_Code.ToString()); + + //显示当前订单信息 + SendMessage.ShowMoby(OpName); + //判断该订单数据是否已经工作过,有的话则在WEB跳出弹窗选择 并同时禁止工作 + //DataTable dt2 = BaseDataSystemMES.EngineIsTwoWork(OpName, OrderForm, EngineID); + //if (dt2.Rows[0]["result"].ToString() == "1") //已完成 + //{ + // //不允许工作 + // MIS_BASE.Write_FixAllow(OpName, false); + // //通知WEB校验重新工作还是跳过 点重新工作给允许工作,点跳过给工作完成 + // string message = "MES|Engine_Is_TwoWork|" + OpName + "|1"; + // SendMessage.AsyncSendMessage(message); + //} + //else + //{ + // EngineTypeGetOver_PLC_Work(OpName, EngineTypeID, EngineType, EngineID, PartPallet_Code, OrderForm); + //} + EngineTypeGetOver_PLC_Work(OpName, EngineTypeID, EngineType, EngineID, PartPallet_Code, OrderForm); + } + } + catch (Exception err) + { + MisDataSaveDate.FuntionMesRead.Alarm_SaveFileLog4Error(System.Reflection.MethodBase.GetCurrentMethod().Name, e, "Fun1052", err); + } + } + + + } + + } +} diff --git a/MisDataFunction/MesServer.Function/Function1052/OpcServer/FalseGO.cs b/MisDataFunction/MesServer.Function/Function1052/OpcServer/FalseGO.cs new file mode 100644 index 0000000..14b5771 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1052/OpcServer/FalseGO.cs @@ -0,0 +1,46 @@ +using System; +using System.Data; +using System.Windows.Forms; +using System.Xml.Linq; +using bizFacade; +//using SystemFramework; +using MesServerWork; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 不合格放行 + /// + /// + /// + private void FalseGO(object e) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + + if (tagValue == 1) + { + //不合格放行信号 + //MIS_BASE.Write_FalseGO(OpName, true); + //总合格标志2(不合格) + + BaseDataSystemMES.Material_Insert_NG(OpName, 2); + + Sendmessage("24", "11", OpName); + + //工作完成 + MIS_BASE.Write_MaterialVerifyOver(OpName, true); + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:FalseGO"); + } + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1052/OpcServer/HeartBeat.cs b/MisDataFunction/MesServer.Function/Function1052/OpcServer/HeartBeat.cs new file mode 100644 index 0000000..93affd3 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1052/OpcServer/HeartBeat.cs @@ -0,0 +1,35 @@ +using bizFacade; +using MesServerWork; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// MES与PLC心跳监听 + /// + /// + /// + private void HeartBeat(object e) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + + //返写在MES心跳中 + MIS_BASE.WritePLC(15, OpName, tagValue); + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:FalseGO"); + } + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1052/OpcServer/MesRead.cs b/MisDataFunction/MesServer.Function/Function1052/OpcServer/MesRead.cs new file mode 100644 index 0000000..c85fcb3 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1052/OpcServer/MesRead.cs @@ -0,0 +1,93 @@ +using bizFacade; +using MesServerWork; +using System; +//using SystemFramework; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 允许保存(针对半自动和手动压装工位) + /// + /// + /// + private void MesRead(object e) + { + { + try + { + + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + + if (tagValue == 1) + { + int EngineTypeID;//机型代码 + int PartPallet_Code;//托盘编号 + + string EngineType;//机型 + string EngineID;//工件编号 + string OrderForm; + MIS_BASE.GetEngineTypeFromPLC(OpName, out EngineTypeID, out EngineType, out EngineID, out PartPallet_Code, out OrderForm); + // 只有50工位有扫码记录 + if (OpName == "OP050") + { + string BarCode = MIS_BASE.ReadPLC(40, OpName).ToString(); + // 保存扫码结果 + BaseDataSystemMES.HeLi_BarCodeData_Add(OpName, EngineType, EngineID, OrderForm, BarCode); + } + + int qualityMask; + // 保存质量数据 + qualityMask = MisDataSaveDateMesRead.Funtion.MesRead(OpName, tagValue.ToString(), msgEvent.TagID.ToString()); + // 保存物料数据 + BaseDataSystemMES.Material_Insert(OpName, qualityMask); + + // 测量数据发动机在线状态 + BaseDataSystemMES.WorkStartInsert(OpName, qualityMask); + // 推送质量数据到MES的页面 + SendMessageFun.SendInfomation("ShowTimelyQuality", "1&" + qualityMask.ToString(), OpName); + + // 记录手动存储的物料数据 + int byte1 = Convert.ToInt32(MIS_BASE.ReadPLC(211, OpName)); + int byte2 = Convert.ToInt32(MIS_BASE.ReadPLC(202, OpName)); + int byte3 = Convert.ToInt32(MIS_BASE.ReadPLC(203, OpName)); + int byte4 = Convert.ToInt32(MIS_BASE.ReadPLC(204, OpName)); + int byte5 = Convert.ToInt32(MIS_BASE.ReadPLC(205, OpName)); + int byte6 = Convert.ToInt32(MIS_BASE.ReadPLC(206, OpName)); + int byte7 = Convert.ToInt32(MIS_BASE.ReadPLC(207, OpName)); + int byte8 = Convert.ToInt32(MIS_BASE.ReadPLC(208, OpName)); + int byte9 = Convert.ToInt32(MIS_BASE.ReadPLC(209, OpName)); + int byte10 = Convert.ToInt32(MIS_BASE.ReadPLC(210, OpName)); + BaseDataSystemMES.HeLi_HMIMaterialFactory_Add(OpName, EngineID, OrderForm, byte1, byte2, byte3, byte4, byte5, byte6, byte7, byte8, byte9, byte10); + + //对应手动工位的 + //MIS_BASE.Write_ConfirmOkGo(OpName, true); + //通知设备,MES的质量数据(和物料数据)保存完成 + MIS_BASE.Write_MesReadOver(OpName, true); + MIS_BASE.Write_MaterialVerifyOver(OpName, true); + //统计在线产量,在线节拍 + SendMessage.SendActuallyCount(OpName, tagValue); + } + else + { + MIS_BASE.Write_MesReadOver(OpName, false); + MIS_BASE.Write_MaterialVerifyOver(OpName, false); + } + } + + } + catch (Exception err) + { + // 保存出错日志 1.申请上线 2.传递机型 3.允许保存 4.扫码 + MisDataSaveDate.FuntionMesRead.Alarm_SaveFileLog4Error(System.Reflection.MethodBase.GetCurrentMethod().Name, e, "Fun1052", err); + } + } + + } + + } +} diff --git a/MisDataFunction/MesServer.Function/Function1052/OpcServer/MesReadOver.cs b/MisDataFunction/MesServer.Function/Function1052/OpcServer/MesReadOver.cs new file mode 100644 index 0000000..f96a7d3 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1052/OpcServer/MesReadOver.cs @@ -0,0 +1,55 @@ +using System; +//using SystemFramework; +using MesServerWork; +using bizFacade; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 保存完成(针对半自动和手动压装工位) + /// + /// + /// + private void MesReadOver(object e) + { + //try + //{ + // DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + // string OpName = Convert.ToString(msgEvent.OpName); + // var tagValue = msgEvent.TagValue.ToString (); + + // if (tagValue == "1" | tagValue.ToLower () == "true") + // { + // int qualityMask; + // MIS_BASE.Read_QualityMask(OpName, out qualityMask); + + // SendInfomation("ShowTimelyQuality", "1&" + qualityMask.ToString(), OpName);//发给Web页面显示质量数据 + + // if (qualityMask == 1)//全部OK,给出合格放行 + // { + // //如果存在线外扫描工位,根据扫描条码绑定线外数据 需要时解除禁用 + // //BaseDataSystemMES.TransLaunchDataByMainMaterial(OpName, EngineType, EngineID, EngineTypeID); + + // //如果存在线外排队工位,根据排队编号绑定线外数据 需要时解除禁用 + // ////BaseDataSystemMES.MailLineAndSubLineData_InsertByEngineID_Subline(OpName,EngineID, EngineTypeID, EngineType); + + // MIS_BASE.Write_ConfirmOkGo(OpName, true); + // //MIS_BASE.Write_FalseGO(OpName, false); + // } + // else + // { + // //MIS_BASE.Write_ConfirmOkGo(OpName, false); + // MIS_BASE.Write_FalseGO(OpName, true); + // } + + // } + //} + //catch (Exception err) + //{ + // ////ApplicationLog.WriteLog(err, "Function02:MesReadOver"); + //} + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1052/OpcServer/MesSaveNowData.cs b/MisDataFunction/MesServer.Function/Function1052/OpcServer/MesSaveNowData.cs new file mode 100644 index 0000000..63c11b3 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1052/OpcServer/MesSaveNowData.cs @@ -0,0 +1,40 @@ +using bizFacade; +using MesServerWork; +using System; +using System.Collections.Generic; +using System.Data; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; +using static System.Net.Mime.MediaTypeNames; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// MES保存实时质量数据 + /// + /// + /// + private void MesSaveNowData(object e) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + // 直接发送实时的 质量数据 + string message = MisDataSaveDateMesRead.Funtion.GetRealTimeQualityData(OpName); + //推送质量数据到MES的页面 + SendMessage.AsyncSendMessage("MES|ShowTimelyQuality_Resources|" + OpName + "|" + message); + //SendMessageFun.SendMessageMESToWEB("ShowTimelyQuality", "1&" + qualityMask.ToString(), OpName); + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:FalseGO"); + } + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1052/OpcServer/WebSubmit.cs b/MisDataFunction/MesServer.Function/Function1052/OpcServer/WebSubmit.cs new file mode 100644 index 0000000..d7ca28c --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1052/OpcServer/WebSubmit.cs @@ -0,0 +1,304 @@ +using System; +using MesServerWork; +using bizFacade; +using System.Threading; +using MisDataSaveDate; +using System.Collections; +//using SystemFramework; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 处理WEB页面发送过来的请求(m_Command + "|" + m_Value;) + /// + /// + /// + private void WebSubmit(object e) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName=Convert.ToString(msgEvent.OpName); + string Content = Convert.ToString(msgEvent.TagValue); + + string[] dataArray = Content.Split('|'); + if (dataArray.Length != 2) + return; + //消息类型 + string m_Command = dataArray[0].ToString(); + //消息参数 + string m_Value = dataArray[1].ToString(); + //消息参数数量 + string[] m_Value_array = m_Value.Split('&'); + //消息参数长度 + int m_Value_length = m_Value_array.Length; + + //工件信息 + string engineID = ""; + if (MIS_BASE.hashtable_EngineGetOver_EngineTypeID == null) + { + MIS_BASE.InitHashtable_MesServerCode(); + } + if (MIS_BASE.hashtable_EngineGetOver_EngineTypeID == null) + { + return; + } + if (MIS_BASE.hashtable_EngineGetOver_EngineID.ContainsKey(OpName)) + { + engineID = MIS_BASE.hashtable_EngineGetOver_EngineID[OpName].ToString(); + } + + DoWhatPlc.CustomeEvetnArgs _e = new DoWhatPlc.CustomeEvetnArgs(); + _e.OpName = OpName; + _e.TagValue = m_Value; + + //根据请求的命令处理逻辑 + switch (m_Command) + { + case "Barcode": + if (m_Value_length > 1) return; + fun_Barcode(_e); + break; + case "ConfirmOkGo"://合格放行 + //删除不合格放行记录 + //修改托盘状态 + //Update_PalletStatus(OpName, 1, false); + BaseDataSystemMES.BaseData_tagTable_Engine_IsNG_Delete(OpName, engineID); + MIS_BASE.Write_ConfirmOkGo(OpName, true); + MIS_BASE.Write_FalseGO(OpName, false); + + Thread.Sleep(1000); + MIS_BASE.Write_ConfirmOkGo(OpName, false); + break; + case "FalseGO"://返修放行 + //修改托盘状态 + //Update_PalletStatus(OpName, 3, false); + BaseDataSystemMES.BaseData_tagTable_Engine_IsNG_Delete(OpName, engineID); + MIS_BASE.Write_FalseGO(OpName, true); + MIS_BASE.Write_ConfirmOkGo(OpName, false); + + Thread.Sleep(1000); + MIS_BASE.Write_FalseGO(OpName, false); + break; + case "NgGO"://不合格放行 + //修改托盘状态 + //Update_PalletStatus(OpName, 2, false); + //保存不合格信息(必须保存不合格放行信息,由于B5A的Moby没有不合格标志位) + BaseDataSystemMES.BaseData_tagTable_Engine_IsNG_Insert(OpName, engineID, "", ""); + MIS_BASE.Write_FalseGO(OpName, true); + MIS_BASE.Write_ConfirmOkGo(OpName, false); + Thread.Sleep(1000); + MIS_BASE.Write_FalseGO(OpName, false); + break; + case "OnLineState"://在线0、离线1、屏蔽2 + try + { + if (m_Value_length > 1) return; + int a = Convert.ToInt32(m_Value); + if (a <= 2) + { + BaseDataSystemMES.IsOnLine_Update(OpName, m_Value.ToString()); + MIS_BASE.Write_OnLineState(OpName, Convert.ToInt32(m_Value)); + if (a == 2) SendMessage.AsyncSendMessage_Notice(OpName, "屏蔽MES!"); + if (a == 0) SendMessage.AsyncSendMessage_Notice(OpName, "启用MES!"); + } + } + catch + { + + } + break; + case "Reset"://复位,将MES所有的信息都复位了 + SetMoby(OpName);//将MES所有信号清空 + break; + case "FixAllow"://重新拧紧 + MIS_BASE.Write_FixAllow(OpName, false); + MIS_BASE.Write_FixAllow(OpName, true); + break; + case "IsAutoGetEngineID"://自动手动申请编号(线首) + if (m_Value_length > 1) return; + MIS_BASE.Write_IsAutoGetEngineID(OpName, Convert.ToInt32(m_Value)); + break; + case "PartPalletGoOver"://空托盘放行 + int Is_PartPalletGoOver; + MIS_BASE.Read_PartPalletGoOver(OpName, out Is_PartPalletGoOver); + if (Is_PartPalletGoOver == 1) + { + MIS_BASE.Write_PartPalletGoOver(OpName, 1); + } + else + { + MIS_BASE.Write_PartPalletGoOver(OpName,0); + } + break; + case "SetMoby"://清空托盘(线首) + SetMoby(OpName);//将MES所有信号清空 + //MIS_BASE.Write_PartPalletCode_PLC(OpName, 1); + break; + case "RepairUplineMES"://返修上线 + MIS_BASE.Write_RepairUpline_MES(OpName, true); + break; + case "CancelRepair"://将返修件置为正常件 + + break; + case "PartPalletCode"://申请写入托盘号 + //MIS_BASE.Write_PartPalletCode_PLC(OpName, 1); + break; + case "WritePartPalletCode"://写入托盘号 + if (m_Value_length > 1) return; + MIS_BASE.Write_PalletCode(OpName, Convert.ToInt32(m_Value)); + break; + case "Normal"://启用正常拧紧工位 + MIS_BASE.Write_Normal(OpName, 1); + MIS_BASE.Write_UnNormal(OpName, 0); + break; + case "UnNormal"://启用备用拧紧工位 + MIS_BASE.Write_Normal(OpName, 0); + MIS_BASE.Write_UnNormal(OpName, 1); + break; + case "ResetDevice"://复位设备 + MIS_BASE.Write_ResetDevice(OpName, true); + System.Threading.Thread.Sleep(1000); + MIS_BASE.Write_ResetDevice(OpName, false); + break; + case "IsNeedRepaire"://返修上线(返修上线点) + if (Convert.ToInt32(m_Value) == 1) + { + //修改托盘状态 + MIS_BASE.Write_PalletInfo(OpName, 3); + //通知修改成功 + MIS_BASE.Write_UpdatePalletOK(OpName, true); + IsNeedRepaire_OK(OpName); + + } + else if (Convert.ToInt32(m_Value) == 0) + { + //通知修改成功 + MIS_BASE.Write_UpdatePalletOK(OpName, true); + //直接给出工作完成 + MIS_BASE.Write_MaterialVerifyOver(OpName, true); + } + else + { } + + break; + case "ContinueMatch": + BaseDataSystemMES.QualityVerifyStatus_Hash_Write(OpName, true); + break; + //初始化网页信号 + case "IniSingalToWeb": + InitializeSingalToWeb(OpName); + break; + case "Reset_Engine"://返修上线(返修上线点) + SetMoby(OpName);//将MES所有信号清空 + //fun_EngineTypeGetOverPLC(OpName, 0); + //fun_EngineTypeGetOverPLC(OpName, 1); + break; + + case "twoWorkSkip"://重新工作工件跳过工作(重新工作工件) + //工作完成 + EngineTypeGetOver_PLC_Work_Skip(OpName); + break; + case "twoWork"://重新工作工件重新工作(重新工作工件) + //允许工作 + EngineTypeGetOver_PLC_Work_two(OpName); + break; + + default: break; + } + } + catch(Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:WebSubmit"); + } + } + private void SetMoby(string OpName) + { + try + { + //清空Moby时,需要将MES信号清空 + MIS_BASE.Write_ClearMesMoby(OpName); + + BaseDataSystemMES.MesServer_Process_EngineTypeOver(OpName); + + Sendmessage("5123", "1111", OpName); + + MIS_BASE.Write_ResetDevice(OpName, true); + System.Threading.Thread.Sleep(1000); + MIS_BASE.Write_ResetDevice(OpName, false); + } + catch + { + + } + } + /// 网页重现登录,恢复关闭前的页面状态 + /// + /// 工位号 + private void InitializeSingalToWeb(string Opname) + { + + //工件到位 DBX0.1 + bool S_WorkStart; + bool S_FixAllow; + bool S_EngineGetOver; + bool S_MaterialVerifyOver; + + MIS_BASE.Read_WorkStart(Opname, out S_WorkStart); + MIS_BASE.Read_FixAllow(Opname, out S_FixAllow); + MIS_BASE.Read_EngineGetOver_PLC(Opname, out S_EngineGetOver); + MIS_BASE.Read_MaterialVerifyOver(Opname, out S_MaterialVerifyOver); + + Sendmessage("13", "1111", Opname); + string S_plcStatus;//DBX501.5 PLC直通,1 强制放行 0 正常循环 + // 新增查询PLC直通状态 网页显示 + MIS_BASE.Read_TagTypeID(63, Opname, out S_plcStatus); + if (S_plcStatus.ToLower() == "false") + { + SendMessageFun.SendInfomation("PlcStatus", "0", Opname); + } + else + { + SendMessageFun.SendInfomation("PlcStatus", "1", Opname); + } + + if (S_WorkStart == true) + { + SendInfomation("WorkStart", Convert.ToString(Convert.ToInt32(S_WorkStart)), Opname); + } + if (S_FixAllow == true) + { + SendInfomation("FixAllow", Convert.ToString(Convert.ToInt32(S_FixAllow)), Opname); + } + if (S_MaterialVerifyOver == true) + { + SendInfomation("MaterialVerifyOver", Convert.ToString(Convert.ToInt32(S_MaterialVerifyOver)), Opname); + } + if (S_EngineGetOver == true) + { + SendInfomation("EngineTypeGetOverPLC", Convert.ToString(Convert.ToInt32(S_EngineGetOver)), Opname); + Sendmessage("2", "1111", Opname); + SendMessage.ShowMoby(Opname); + // 直接发送实时的 质量数据 + string message = MisDataSaveDateMesRead.Funtion.GetRealTimeQualityData(Opname); + //推送质量数据到MES的页面 + SendMessage.AsyncSendMessage("MES|ShowTimelyQuality_Resources|" + Opname + "|" + message); + } + InitAlarm(Opname); + } + + private void InitAlarm(string Opname) + { + FuntionMesRead.Alarm_InitAlarm_Send(Opname, out Hashtable ht); + foreach (DictionaryEntry kv in ht) + { + var TagID = kv.Key.ToString(); + var TagValue = kv.Value.ToString(); + FuntionMesRead.Send_AlarmMsg(TagID, TagValue); + } + + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1052/OpcServer/WorkIsOk.cs b/MisDataFunction/MesServer.Function/Function1052/OpcServer/WorkIsOk.cs new file mode 100644 index 0000000..08819e3 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1052/OpcServer/WorkIsOk.cs @@ -0,0 +1,45 @@ +using bizFacade; +using MesServerWork; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 工位合格标志 + /// + /// + /// + private void IsOk(object e) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + + int qualityMask; + MIS_BASE.Read_QualityMask(OpName, out qualityMask); + //判断是否合格 + if (qualityMask == 1) + { + qualityMask = 1; + } else { + qualityMask = 0; + } + //通知WEB修改状态 + string message = "MES|QualityMask|" + OpName + "|" + qualityMask.ToString(); + SendMessage.AsyncSendMessage(message); + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:FalseGO"); + } + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1052/OpcServer/WorkStart.cs b/MisDataFunction/MesServer.Function/Function1052/OpcServer/WorkStart.cs new file mode 100644 index 0000000..95692c0 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1052/OpcServer/WorkStart.cs @@ -0,0 +1,47 @@ +using bizFacade; +using MesServerWork; +using System; +using System.Threading; +//using SystemFramework; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 工件到位与离开时,清空MES自身信号 + /// + /// + /// + private void WorkStart(object e) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + if (tagValue > 0) + { + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.WorkStartIn, DateTime.Now.ToString()); + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.WorkStart, tagValue.ToString()); + } + else + { + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.WorkStartOut, DateTime.Now.ToString()); + MIS_BASE.Write_MesReadOver(OpName, false); + MIS_BASE.Write_ConfirmOkGo(OpName, false); + MIS_BASE.Write_FixAllow(OpName, false); + MIS_BASE.Write_ConfirmOkGo(OpName, false); + MIS_BASE.Write_EngineTypeGetOver_MES(OpName, false); + //工作完成 + MIS_BASE.Write_MaterialVerifyOver(OpName, false); + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:WorkStart"); + } + } + + } +} diff --git a/MisDataFunction/MesServer.Function/Function1052/OpcServer/vssver2.scc b/MisDataFunction/MesServer.Function/Function1052/OpcServer/vssver2.scc new file mode 100644 index 0000000..b884d13 Binary files /dev/null and b/MisDataFunction/MesServer.Function/Function1052/OpcServer/vssver2.scc differ diff --git a/MisDataFunction/MesServer.Function/Function1052/Properties/AssemblyInfo.cs b/MisDataFunction/MesServer.Function/Function1052/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..0bb79c4 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1052/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// 有关程序集的常规信息通过以下 +// 特性集控制。更改这些特性值可修改 +// 与程序集关联的信息。 +[assembly: AssemblyTitle("Function02")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("苏州宏软信息技术有限公司")] +[assembly: AssemblyProduct("Function02")] +[assembly: AssemblyCopyright("Copyright © 苏州宏软信息技术有限公司 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// 将 ComVisible 设置为 false 使此程序集中的类型 +// 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型, +// 则将该类型上的 ComVisible 特性设置为 true。 +[assembly: ComVisible(false)] + +// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID +[assembly: Guid("47710f2c-e141-4252-8d13-701bf4c1c027")] + +// 程序集的版本信息由下面四个值组成: +// +// 主版本 +// 次版本 +// 内部版本号 +// 修订号 +// +// 可以指定所有这些值,也可以使用“内部版本号”和“修订号”的默认值, +// 方法是按如下所示使用“*”: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/MisDataFunction/MesServer.Function/Function1052/Properties/vssver2.scc b/MisDataFunction/MesServer.Function/Function1052/Properties/vssver2.scc new file mode 100644 index 0000000..14e543b Binary files /dev/null and b/MisDataFunction/MesServer.Function/Function1052/Properties/vssver2.scc differ diff --git a/MisDataFunction/MesServer.Function/Function1052/app.config b/MisDataFunction/MesServer.Function/Function1052/app.config new file mode 100644 index 0000000..b4c4daf --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1052/app.config @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + + + diff --git a/MisDataFunction/MesServer.Function/Function1052/mssccprj.scc b/MisDataFunction/MesServer.Function/Function1052/mssccprj.scc new file mode 100644 index 0000000..119193d --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1052/mssccprj.scc @@ -0,0 +1,5 @@ +SCC = This is a Source Code Control file + +[Function02.csproj] +SCC_Aux_Path = "\\192.168.0.100\vss\MES4.0" +SCC_Project_Name = "$/MisData/MisData/MisData/MesServer.Function/Function02", ILHAAAAA diff --git a/MisDataFunction/MesServer.Function/Function1052/packages.config b/MisDataFunction/MesServer.Function/Function1052/packages.config new file mode 100644 index 0000000..b3e1761 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1052/packages.config @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/MisDataFunction/MesServer.Function/Function1052/vssver2.scc b/MisDataFunction/MesServer.Function/Function1052/vssver2.scc new file mode 100644 index 0000000..c770e28 Binary files /dev/null and b/MisDataFunction/MesServer.Function/Function1052/vssver2.scc differ diff --git a/MisDataFunction/MesServer.Function/Function1053/DataAccess/DataAccess.cs b/MisDataFunction/MesServer.Function/Function1053/DataAccess/DataAccess.cs new file mode 100644 index 0000000..cd36930 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1053/DataAccess/DataAccess.cs @@ -0,0 +1,15 @@ + +namespace MesServerFunctions +{ + partial class Function1053 + { + //针对“MIS.BizFacade.Dll”中没有的存储过程,在此类中新建 + //新建原则:所有的函数用private,只允许在内部使用 + //针对单个工艺特殊,需要新建存储过程,但是存储过程不能被加入到“MIS.BizFacade.Dll”中 + + private void aa() + { + + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1053/DataAccess/vssver2.scc b/MisDataFunction/MesServer.Function/Function1053/DataAccess/vssver2.scc new file mode 100644 index 0000000..d045c26 Binary files /dev/null and b/MisDataFunction/MesServer.Function/Function1053/DataAccess/vssver2.scc differ diff --git a/MisDataFunction/MesServer.Function/Function1053/Db.cs b/MisDataFunction/MesServer.Function/Function1053/Db.cs new file mode 100644 index 0000000..8b68b7c --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1053/Db.cs @@ -0,0 +1,109 @@ +using System; +using System.Collections.Generic; +using System.Data.SqlClient; +using System.Data; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using DataLinkMesWork; + +namespace MesServerFunctions +{ + public class Db + { + public static bool GetEngineType_Order(string opName, string Program_No, out int EngineTypeID, out string EngineType, out string EngineID, out string OrderForm, out int isCheckOk, out int planCount, out int haveUplaodCount, out int remainingQuantity) + { + DataTable dt = new DataTable(); + isCheckOk = 2; + EngineTypeID = 0; + EngineType = ""; + EngineID = ""; + OrderForm = ""; + planCount = 0; + haveUplaodCount = 0; + remainingQuantity = 0; + string produceName = "合力_生产上线_分线_判断机型订单是否匹配"; + SqlParameter[] thisParms = new SqlParameter[1]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + //thisParms[1] = new System.Data.SqlClient.SqlParameter("@PLC_机型代码", Program_No); + if (DataAccess.ExecuteStoredProcedure(produceName, ref thisParms, out dt)) + { + if (dt.Rows.Count > 0 && dt.Rows[0]["是否匹配"].ToString() == "1") + { + EngineTypeID = Convert.ToInt32(dt.Rows[0]["机型代码"]); + EngineType = dt.Rows[0]["机型"].ToString(); + EngineID = dt.Rows[0]["变速箱总成号"].ToString(); + OrderForm = dt.Rows[0]["订单号"].ToString(); + isCheckOk = Convert.ToInt32(dt.Rows[0]["是否匹配"]); + planCount = Convert.ToInt32(dt.Rows[0]["计划上料数量"]); + haveUplaodCount = Convert.ToInt32(dt.Rows[0]["已上料数量"]); + remainingQuantity = Convert.ToInt32(dt.Rows[0]["待上料数量"]); + return true; + } + } + return false; + } + + public static bool SubLine_WorkFinish(string EngineID, string opName, string OrderForm, int qualityMask) + { + DataTable dt = new DataTable(); + string produceName = "合力_分装线上线完成_扣数"; + SqlParameter[] thisParms = new SqlParameter[4]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@差速器总成号", EngineID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@订单号", OrderForm); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@合格标志", qualityMask); + if (DataAccess.ExecuteStoredProcedure(produceName, ref thisParms, out dt)) + { + return true; + } + return false; + } + public static bool UpdateWait_NUM_PLC(string opName, int Wait_NUM) + { + DataTable dt = new DataTable(); + string produceName = "合力_分装线PLC_更新待上线数量"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@待上线数量", Wait_NUM); + if (DataAccess.ExecuteStoredProcedure(produceName, ref thisParms, out dt)) + { + return true; + } + return false; + } + + + public static bool GethandType_Order(string opName, out int EngineTypeID, out string EngineType, out string EngineID, out string OrderForm, out int isCheckOk, out int planCount, out int haveUplaodCount, out int remainingQuantity) + { + DataTable dt = new DataTable(); + isCheckOk = 2; + EngineTypeID = 0; + EngineType = ""; + EngineID = ""; + OrderForm = ""; + planCount = 0; + haveUplaodCount = 0; + remainingQuantity = 0; + string produceName = "合力_生产上线_分线_判断机型订单是否匹配"; + SqlParameter[] thisParms = new SqlParameter[1]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + if (DataAccess.ExecuteStoredProcedure(produceName, ref thisParms, out dt)) + { + if (dt.Rows.Count > 0 && dt.Rows[0]["是否匹配"].ToString() == "1") + { + EngineTypeID = Convert.ToInt32(dt.Rows[0]["机型代码"]); + EngineType = dt.Rows[0]["机型"].ToString(); + EngineID = dt.Rows[0]["变速箱总成号"].ToString(); + OrderForm = dt.Rows[0]["订单号"].ToString(); + isCheckOk = Convert.ToInt32(dt.Rows[0]["是否匹配"]); + planCount = Convert.ToInt32(dt.Rows[0]["计划上料数量"]); + haveUplaodCount = Convert.ToInt32(dt.Rows[0]["已上料数量"]); + remainingQuantity = Convert.ToInt32(dt.Rows[0]["待上料数量"]); + return true; + } + } + return false; + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1053/Function02.csproj.vspscc b/MisDataFunction/MesServer.Function/Function1053/Function02.csproj.vspscc new file mode 100644 index 0000000..0f0f36c --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1053/Function02.csproj.vspscc @@ -0,0 +1,10 @@ +"" +{ +"FILE_VERSION" = "9237" +"ENLISTMENT_CHOICE" = "NEVER" +"PROJECT_FILE_RELATIVE_PATH" = "relative:MesServer.Function\\Function02" +"NUMBER_OF_EXCLUDED_FILES" = "0" +"ORIGINAL_PROJECT_FILE_PATH" = "" +"NUMBER_OF_NESTED_PROJECTS" = "0" +"SOURCE_CONTROL_SETTINGS_PROVIDER" = "PROVIDER" +} diff --git a/MisDataFunction/MesServer.Function/Function1053/Function1053.csproj b/MisDataFunction/MesServer.Function/Function1053/Function1053.csproj new file mode 100644 index 0000000..c1666b8 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1053/Function1053.csproj @@ -0,0 +1,176 @@ + + + + Debug + AnyCPU + 8.0.30703 + 2.0 + {CA8A12C5-7BF0-4489-93FA-180B1C492BBA} + Library + Properties + Function1053 + Function1053 + v4.8 + 512 + + + + + + + + + + + + + + true + full + false + ..\..\..\dll_fun\ + DEBUG;TRACE + prompt + 4 + false + false + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + false + + + + ..\..\..\Common\dll\MQTTnet.dll + + + ..\..\..\Common\dll\MQTTnet.Extensions.ManagedClient.dll + + + False + ..\..\..\Common\dll\Newtonsoft.Json.dll + + + + + + ..\..\DLL\System.Net.Http.dll + + + ..\..\packages\System.Net.Security.4.3.2\lib\net46\System.Net.Security.dll + + + ..\..\packages\System.Net.WebSockets.4.3.0\lib\net46\System.Net.WebSockets.dll + + + ..\..\packages\System.Net.WebSockets.Client.4.3.2\lib\net46\System.Net.WebSockets.Client.dll + + + ..\..\packages\System.Security.Cryptography.Algorithms.4.3.0\lib\net461\System.Security.Cryptography.Algorithms.dll + + + ..\..\packages\System.Security.Cryptography.Encoding.4.3.0\lib\net46\System.Security.Cryptography.Encoding.dll + + + ..\..\packages\System.Security.Cryptography.Primitives.4.3.0\lib\net46\System.Security.Cryptography.Primitives.dll + + + ..\..\packages\System.Security.Cryptography.X509Certificates.4.3.0\lib\net461\System.Security.Cryptography.X509Certificates.dll + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + {f55da1a0-a982-4479-8c47-0d9a5aaf3e18} + 00MesWorkMqtt + + + {0d1af432-439a-4920-8692-43ae139f5530} + 01_01DoWhatPlc + + + {3e6d1dd5-01c9-435f-9941-61f906ce35bb} + 02_02WebApiCallPLC + + + {f434e066-4c59-47c8-aa82-6f48cc84501a} + 04-DataBaseAccess + + + {f0a0c525-03fd-428a-9b17-7f54aa0e4475} + 07BusinessFacade + + + {d98be764-adeb-488d-9714-61e308aa8201} + 08-WebFun_base + + + {90e76fb4-646d-45e2-95db-0b8ab4e465d6} + 09-MesDataFunction + + + {e4eb6420-906d-4672-947a-ca33ddcdadfc} + 12SendMessageToWeb + + + {55b510c1-59e9-4bfd-ae84-d76d46f6e365} + 02-13.3MIS_FuntionSaveData + + + {1dc48c83-1842-4de8-acaf-26e1e7f7c58f} + 00_MyLog4Net + + + + + + + 这台计算机上缺少此项目引用的 NuGet 程序包。使用“NuGet 程序包还原”可下载这些程序包。有关更多信息,请参见 http://go.microsoft.com/fwlink/?LinkID=322105。缺少的文件是 {0}。 + + + + + \ No newline at end of file diff --git a/MisDataFunction/MesServer.Function/Function1053/MesServerFunction/Fun_1053.cs b/MisDataFunction/MesServer.Function/Function1053/MesServerFunction/Fun_1053.cs new file mode 100644 index 0000000..36bea9a --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1053/MesServerFunction/Fun_1053.cs @@ -0,0 +1,298 @@ +using MesServerWork; +using MisDataSaveDate; +using System.Collections.Generic; +using System.Threading; +using System.Xml.Linq; + +namespace MesServerFunctions +{ + public partial class FunctionMES + { + object lockFunWork; + //public void FunWork(DoWhatPlc.CustomeEvetnArgs e) + public void FunWork(string recData) + { + + + lockFunWork = new object(); + lock (lockFunWork) + { + List dataArray = DoWhatPlc.MessageText.GetCmdStringList(recData); + //string[] dataArray = recData.Split('|'); + //if (dataArray.Count != 4) + //return; + //消息来源 + string m_Source = dataArray[0].ToString(); + //消息类型 Barcode + string m_Command = dataArray[1].ToString(); + //工位号 + string m_OpName = dataArray[2].ToString(); + //消息参数 + string m_Value = dataArray[3].ToString(); + + DoWhatPlc.CustomeEvetnArgs e = new DoWhatPlc.CustomeEvetnArgs();// = Newtonsoft.Json.JsonConvert.DeserializeObject(m_Value); + string tagValue; + + switch (m_Source) + { + case "BarCode": + e.OpName = m_OpName; + e.TagValue = m_Value; + fun_Barcode(e); + break; + case "WEB": + e.OpName = m_OpName; + e.TagValue = m_Command + "|" + m_Value; + fun_WebSubmit(e); + break; + case "PLC": + e = Newtonsoft.Json.JsonConvert.DeserializeObject(m_Value); + string TagID = e.TagID.ToString(); + switch (e.TagValue.ToString().ToLower()) + { + case "false": + tagValue = "0"; + break; + case "true": + tagValue = "1"; + break; + default: + tagValue = e.TagValue.ToString(); + break; + } + e.TagValue = tagValue; + switch (e.TagTypeCodeID.ToString()) + { + //PLC 工件到位 + case "2": + fun_WorkStart(e); + break; + //PLC 允许保存质量数据 + case "19": + fun_MesRead(e); + break; + //MES 保存数据完成 + case "20": + fun_MesReadOver(e); + break; + //PLC 申请上线 + case "43": + PartLoad(e); + break; + //PLC 传递机型 + case "44": + fun_EngineTypeGetOverPLC(e); + break; + //MES 合格放行 + case "51": + fun_ConfirmOkGo(e); + break; + //MES 不合格放行 + case "8": + fun_FalseGo(e); + break; + //PLC 工位合格标志 + case "21": + fun_IsOk(e); + break; + //MES保存实时质量数据 + case "65": + fun_MesSaveNowData(e); + break; + //MES 系统健康心跳 + case "14": + fun_HeartBeatMIS(e); + break; + //空料握手plc + case "49": + fun_Handshake(e); + break; + //待上料数量plc + case "38": + UpdateWait_NUM_PLC(e); + break; + case "63": + string S_plcStatus;//DBX501.5 PLC直通,1 强制放行 0 正常循环 + MIS_BASE.Read_TagTypeID(63, m_OpName, out S_plcStatus); + if (S_plcStatus.ToLower() != "true" || S_plcStatus.ToLower() == "1") + { + SendMessageFun.SendInfomation("PlcStatus", "0", m_OpName); + } + else + { + SendMessageFun.SendInfomation("PlcStatus", "1", m_OpName); + } + break; + // 请求叫料 1 206 2 211 + // 请求退料 1 207 2 212 + // 允许进入 1 208 2 213 + // 退料类型 1 209 2 214 + // 叫料类型 1 210 2 215 + // 到料类型 1 202 2 205 + // 请求进入 1 200 2 203 + // AGV已离开1 201 2 204 + + // 请求叫料 + case "206": + case "211": + fun_CallMaterials(e); + break; + // 请求退料 + case "207": + case "212": + fun_QuitMaterials(e); + break; + } + break; + } + } + } + + //1.工件到位后,PLC给MES传递机型(DBX0.4)(44), + //MES判断条码是否全部扫描完成 + //PLC给出允许保存(DBX100.2)(19),MES见到(DBX100.2)(19)为1后给出保存完成(DBX102.2)(20), + //PLC见到保存完成(DBX102.2)(20)为1后,清空允许保存(DBX100.2)(19), + //MES见到允许保存(DBX100.2)(19)为0后,清空保存完成(DBX102.2)(20) + //MES判断总合格标志(INT104)(21)为1后,给出合格放行(DBX2.5)(51) + /// + /// 扫描条码 + /// + /// + /// + public void fun_Barcode(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(Barcode, e); + } + + /// + /// 请求叫料 + /// + /// + /// + public void fun_CallMaterials(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(CallMaterials, e); + } + /// + /// 请求离开 + /// + /// + public void fun_QuitMaterials(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(QuitMaterials, e); + } + + /// + /// 传递机型 + /// + /// + /// + public void fun_EngineTypeGetOverPLC(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(EngineTypeGetOver_PLC, e); + } + + /// + /// 合格放行 + /// + /// + /// + public void fun_ConfirmOkGo(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(ConfirmOkGo, e); + } + + /// + /// 不合格放行 + /// + /// + /// + public void fun_FalseGo(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(FalseGO, e); + } + + /// + /// 允许保存 + /// + /// + /// + public void fun_MesRead(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(MesRead, e); + } + + /// + /// 保存完成 + /// + /// + /// + public void fun_MesReadOver(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(MesReadOver, e); + } + + /// + /// 工件到位离开(清空所有的MES信号) + /// + /// + /// + public void fun_WorkStart(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(WorkStart, e); + } + + /// + /// 处理WEB页面发送过来的请求(m_Command + "|" + m_Value;) + /// + /// + /// + public void fun_WebSubmit(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(WebSubmit, e); + } + + + /// + /// 工位是否合格 + /// + /// + /// + public void fun_IsOk(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(IsOk, e); + } + + /// + /// 系统健康心跳监测 + /// + /// + /// + public void fun_HeartBeatMIS(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(HeartBeat, e); + } + + + /// + /// 空料握手plc + /// + public void fun_Handshake(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(Handshake_Fun, e); + } + + + /// + /// MES实时保存质量数据 + /// + /// + /// + public void fun_MesSaveNowData(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(MesSaveNowData, e); + } + + + } +} diff --git a/MisDataFunction/MesServer.Function/Function1053/MesServerFunction/vssver2.scc b/MisDataFunction/MesServer.Function/Function1053/MesServerFunction/vssver2.scc new file mode 100644 index 0000000..a246f67 Binary files /dev/null and b/MisDataFunction/MesServer.Function/Function1053/MesServerFunction/vssver2.scc differ diff --git a/MisDataFunction/MesServer.Function/Function1053/Methods/EngineGetOverBaseWork.cs b/MisDataFunction/MesServer.Function/Function1053/Methods/EngineGetOverBaseWork.cs new file mode 100644 index 0000000..ae598bc --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1053/Methods/EngineGetOverBaseWork.cs @@ -0,0 +1,214 @@ +using System; +using System.Data; +using bizFacade; +using MesServerWork; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 正常逻辑工作(传递机型) + /// + /// + /// + /// + /// + /// + private void EngineTypeGetOver_PLC_Work(string OpName, int EngineTypeID, string EngineType, string EngineID, int PartPallet_Code, string OrderForm) + { + int IsAllowWork; + int RepairPartStatusPLC = 0; + int MES_QualityMask = 1; + + if (EngineTypeID <= 0 || EngineID.Length == 0 || EngineType.Length == 0) + { + MIS_BASE.WritePLC(34, OpName, true); + string msg = "【" + OpName + "】" + "PLC传递机型为空!"; + MyLog4Net.MyLogHelper.Error("EngineTypeGetOver", msg); + SendMessageFun.AsyncSendMessage_Notice(OpName, msg); + return; + } + + MIS_BASE.Write_MesReadOver(OpName, false); //保存完成 + MIS_BASE.Write_MaterialVerifyOver(OpName, false); //工作完成信号 + MIS_BASE.Write_FixAllow(OpName, true); // 允许工作 + + //电子看板_装配零件_临时表_增加_北汽 + //第二步,将零件信息转移到零件_临时表中 + // BaseDataSystemMES.MesServer_Process_EngineTypeOverBQ(OpName); + + //通知web显示 + //SendMessageFun.SendMessage("123", "111", OpName); + //MIS_BASE.Read_PalletInfo(OpName, out MES_QualityMask);//合格标志 合格标志暂时改为即时响应式的 + //MIS_BASE.Read_RepairStatus_PLC(OpName, out RepairPartStatusPLC);//返修标志 + //SendMessageFun.SendInfomation("QualityMask", Convert.ToString(MES_QualityMask), OpName);//显示合格标志 + //SendMessageFun.SendInfomation("RepairPartStatusPLC", Convert.ToString(RepairPartStatusPLC), OpName);//显示返修标志 + + + + //if (MES_QualityMask == 2) + //{ + // 暂时先屏蔽掉 + ////工作完成 + //MIS_BASE.Write_MaterialVerifyOver(OpName, true); + //SendMessageFun.SendInfomation("NgGO", "1", OpName);//显示不合格标志 + //return; + // } + + //第三步,用于工件离开后完工数量统计及工件编号追溯 + //BaseDataSystemMES.MaterialPush_EngineIDStatus_Insert(OpName);//更新订单产量 + + //第四步,获取是否允许工作 + //BaseDataSystemMES.MesServer_Judge_IsCanWork(OpName, out IsAllowWork); + + //暂时先定义为扫描完成才能进行压装工作,因为考虑到工作完成后,操作工未必会去扫描物料的情况 + //if (IsAllowWork == 1) + //{ + // MIS_BASE.Write_MesReadOver(OpName, false); //允许保存信号 + // MIS_BASE.Write_MaterialVerifyOver(OpName, false); //工作完成信号 + // MIS_BASE.Write_FixAllow(OpName, true); + + // // 判断有没有PLC传递机型 没有就不给 + // //bool isEngine = Convert.ToBoolean(MIS_BASE.ReadPLC(44, OpName)); + // //if (isEngine) + // //{ + // // //通知PLC允许工作,允许工作在保存完成时清空 + // // MIS_BASE.Write_FixAllow(OpName, true); + // //} + // //else + // //{ + // // MyLog4Net.MyLogHelper.Error($"{OpName}给允许工作时无传递机型:", $"Message:"); + // //} + + //} + //else + //{ + // SendMessageFun.AsyncSendMessage_Notice(OpName, "请扫描物料!"); + //} + + } + + /// + /// 二次工作 + /// + /// + private void EngineTypeGetOver_PLC_Work_two(string OpName) + { + int EngineTypeID;//机型代码 + int PartPallet_Code;//托盘编号 + + string EngineType;//机型 + string EngineID;//工件编号 + string OrderForm; + MIS_BASE.GetEngineTypeFromPLC(OpName, out EngineTypeID, out EngineType, out EngineID, out PartPallet_Code, out OrderForm); + EngineTypeGetOver_PLC_Work(OpName, EngineTypeID, EngineType, EngineID, Convert.ToInt32(PartPallet_Code), OrderForm); + + } + /// + /// 跳过二次工作 + /// + /// + private void EngineTypeGetOver_PLC_Work_Skip(string OpName) + { + //MIS_BASE.Write_MesReadOver(OpName, true); + MIS_BASE.Write_MaterialVerifyOver(OpName, true); + } + + /// + /// 返修件需要工作 + /// + /// 工位号 + private void IsNeedRepaire_OK(string OpName) + { + string orderForm = ""; + int engineTypeID; + string engineType = ""; + string engineID = ""; + string palletCode = ""; + int isRepair; + string repairCode = ""; + //从监控系统中查询出本工位信息 + BaseDataSystemMES.OpName_MIS_Moby_Select(OpName, + out orderForm, out engineTypeID, out engineType, + out engineID, out palletCode, out isRepair, out repairCode); + + EngineTypeGetOver_PLC_Work(OpName, engineTypeID, engineType, engineID, Convert.ToInt32(palletCode), orderForm); + } + + /// + /// 更新待上料数量 + /// + /// + private void UpdateWait_NUM_PLC(object e) + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + // 更新待上料数量到数据库 + Db.UpdateWait_NUM_PLC(OpName, tagValue); + } + + + + /// + /// 空料握手plc + /// + /// + private void Handshake_Fun(object e) + { + + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + + if (tagValue == 1) + { + int planCount = 0; // 计划上料数量 + int haveUplaodCount = 0; // 已上料数量 + int remainingQuantity = 0; // 待上料数量 + Db.GethandType_Order(OpName, out int EngineTypeID, + out string EngineType, out string EngineID, out string OrderForm, + out int isCheckOk, out planCount, out haveUplaodCount, out remainingQuantity); + if (isCheckOk == 2) + { + + MIS_BASE.Write_EngineTypeID_MES(OpName, 0); + MIS_BASE.Write_EngineType_MES(OpName, ""); + MIS_BASE.Write_EngineID_MES(OpName, ""); + MIS_BASE.Write_OrderForm_MES(OpName, ""); + + // 写回空值 + MIS_BASE.WritePLC(95, OpName, planCount); + MIS_BASE.WritePLC(96, OpName, haveUplaodCount); + MIS_BASE.WritePLC(97, OpName, remainingQuantity); + // 发送MES握手 + MIS_BASE.WritePLC(35, OpName, true); + return; + } + else + { + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.EngineID_MES, EngineID); + + // 写入机型代码 (大机型) 机型 发动机号 订单号 + MIS_BASE.Write_EngineTypeID_MES(OpName, EngineTypeID); + MIS_BASE.Write_EngineType_MES(OpName, EngineType); + MIS_BASE.Write_EngineID_MES(OpName, EngineID); + MIS_BASE.Write_OrderForm_MES(OpName, OrderForm); + + MIS_BASE.WritePLC(95, OpName, planCount); + MIS_BASE.WritePLC(96, OpName, haveUplaodCount); + MIS_BASE.WritePLC(97, OpName, remainingQuantity); + + // 发送MES握手 + MIS_BASE.WritePLC(35, OpName, true); + } + } + else + { + MIS_BASE.WritePLC(35, OpName, false); + } + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1053/Methods/SubmitToMisweb.cs b/MisDataFunction/MesServer.Function/Function1053/Methods/SubmitToMisweb.cs new file mode 100644 index 0000000..52ce16f --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1053/Methods/SubmitToMisweb.cs @@ -0,0 +1,127 @@ +using System; +using bizFacade; +//using SystemFramework; + +namespace MesServerFunctions +{ + + /// + /// 此类用于向WEB发送各种类型消息 + /// + partial class FunctionMES + { + + /// + /// 批量发送WEB消息(Value为BOOL值) + /// + /// 消息编号组合 + /// 消息值组合 + /// 工位号 + void Sendmessage(string MessageNumm,string Value, string OpName) + { + for (int i=0;i + /// 选择发送给WEB的消息 + /// + /// 消息类型 + /// 消息工位 + string Sendmessage(char Num,string Value, string OpName) + { + string SendMessage; + string result = ""; + switch (Num) + { + case '1': + //1(直接在界面通过选择机型确认工序内容) + SendMessage = "MES|ProcessList|" + OpName + "|" + Value; + result = AsyncSendMessage(SendMessage); + break; + case '2': + //2显示物料 + SendMessage = "MES|MaterialList|" + OpName + "|" + Value; + result = AsyncSendMessage(SendMessage); + break; + case '3': + //3显示操作指导图片 + SendMessage = "MES|PicShow|" + OpName + "|" + Value; + result = AsyncSendMessage(SendMessage); + break; + case '4': + //4订单完工模块刷新完成数量 + SendMessage = "MES|OrderFormList|" + OpName + "|" + Value; + AsyncSendMessage(SendMessage); + break; + case '5': + SendMessage = "MES|ShowMoby|" + OpName + "|" + Value; + result = AsyncSendMessage(SendMessage); + break; + case '6': + SendMessage = "MES|MaterialCheckPosition|" + OpName + "|" +Value; + result = AsyncSendMessage(SendMessage); + break; + case '7': + SendMessage = "MES|WorkStart|" + OpName + "|" + Value; + result = AsyncSendMessage(SendMessage); + break; + case '8'://清除MES生成编号 + + break; + case '9': + SendMessage = "MES|ConfirmOkGo|" + OpName + "|" + Value; + result = AsyncSendMessage(SendMessage); + break; + case 'a': + SendMessage = "MES|FixAllow|" + OpName + "|" + Value; + result = AsyncSendMessage(SendMessage); + break; + } + return result; + } + /// + /// 向WEB发送信息(value为字符串) + /// + /// 消息种类 + /// 消息内容 + /// 工位号 + string SendInfomation(string Command, string Value, string OpName) + { + string SendMessage = "MES|" + Command + "|" + OpName + "|" + Value; + return AsyncSendMessage(SendMessage); + } + + + /// + /// 发送在线产量、在线节拍 + /// + /// + /// + private void SendActuallyCount(string OpName, int tagValue) + { + //当工件离开时,更新在线产量、在线节拍 + if (tagValue == 0) + { + try + { + int opNameCount = 0;//在线产量 + int opNameCountTime = 0;//在线节拍 + //基本数据_工作日历_班次产量查询_New + BaseDataSystemMES.OpNameCount_New(OpName, out opNameCount, out opNameCountTime); + string SendMessage; + SendMessage = "MES|ActuallyCount|" + OpName + "|" + opNameCount.ToString() + "&" + opNameCountTime.ToString(); + AsyncSendMessage(SendMessage); + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:SendActuallyCount"); + } + } + } + + + } +} diff --git a/MisDataFunction/MesServer.Function/Function1053/Methods/UDP.Send.cs b/MisDataFunction/MesServer.Function/Function1053/Methods/UDP.Send.cs new file mode 100644 index 0000000..aed7cc3 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1053/Methods/UDP.Send.cs @@ -0,0 +1,53 @@ +using bizFacade; +//using SystemFramework; +using MesServerWork; +using DataLinkMesWork; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 发送信息到MES通讯服务器或者其他的 + /// + /// + private string AsyncSendMessage(string Message) + { + return MIS_BASE.asyncSendMessage(Message); + } + + /// + /// 发送提示消息 + /// + /// + private void AsyncSendMessage_Notice(string opname, string notice) + { + //通知Web界面 + BaseDataSystemMES.Web_Notice_Insert(opname, notice); + string SendMessage = "MES|Notice|" + opname + "|" + "1"; + MIS_BASE.asyncSendMessage(SendMessage); + } + + /// + /// 发送信息到打印机 + /// + /// + private void asyncSendMessageToMark(string Message) + { + string messageSend = (string)Message; + //UDPClientSend.Send_ALL(ApplicationConfig.MES_MarkPortNum, messageSend); + } + + /// + /// 发送信息到LED + /// + /// + private void asyncSendMessageLED(string OpName) + { + //发送到大屏幕显示 41104 + string strMessage = "MIS|" + OpName + "|" + "0" + "|" + "1"; + //UDPClientSend.Send_ALL(ApplicationConfig.Port_ShowLED_ProductCount, strMessage); + + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1053/Methods/vssver2.scc b/MisDataFunction/MesServer.Function/Function1053/Methods/vssver2.scc new file mode 100644 index 0000000..7782f6f Binary files /dev/null and b/MisDataFunction/MesServer.Function/Function1053/Methods/vssver2.scc differ diff --git a/MisDataFunction/MesServer.Function/Function1053/OpcServer/Barcode.cs b/MisDataFunction/MesServer.Function/Function1053/OpcServer/Barcode.cs new file mode 100644 index 0000000..1f9ea05 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1053/OpcServer/Barcode.cs @@ -0,0 +1,90 @@ +using System; +using System.Windows.Forms; +using bizFacade; +//using SystemFramework; +using MesServerWork; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + ///1.扫描配送单号,用于接收物料,扫描单号的时候,将接收的物料信息显示在“物料拉动”Tab区域 + ///2.扫描料箱标签/看板卡,用于追溯物料批次信息 + ///3.扫描零件条码,根据零件图号进行防错 + ///第一步,判断条码类型,根据条码类型,执行对应的存储过程 + ///第二步,条码类型(将扫描的条码保存到对应的表中) + ///第三步,扫描完成之后给出允许工作信号 + /// 处理页面扫描条码 + /// + /// + /// + public void Barcode(object e) + { + + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + string barcode = Convert.ToString(msgEvent.TagValue); + string AlarmStr = ""; + + int IsAllowWork; + bool IsSuccess = false; + bool EngineGetOver_PLC_NextWorkStep; + //传递机型是否到位 + MIS_BASE.Read_EngineGetOver_PLC(OpName, out EngineGetOver_PLC_NextWorkStep); + if (!EngineGetOver_PLC_NextWorkStep) + { + SendMessageFun.AsyncSendMessage_Notice(OpName, "PLC未传递机型"); + return; + } + //物料验证 + BaseDataSystemMES.PartMaterial_DM_Update(OpName, barcode, out IsSuccess); + if (!IsSuccess) + { + SendMessageFun.AsyncSendMessage_Notice(OpName, "条码无效,请确认"); + return; + } + else + { + SendMessageFun.SendInfomation("MaterialList", "1", OpName);//通知界面更新零件信息 + } + + + + + //获取是否允许工作 + BaseDataSystemMES.MesServer_Judge_IsCanWork(OpName, out IsAllowWork); + + //此处逻辑有问题 需要考虑到批次扫描 提示PLC未传递机型的情况 + if (IsAllowWork == 1) + { + //BaseDataSystemMES.Material_Insert(OpName, 1); + + //更新订单完工数量及物料 + SendMessageFun.SendMessage("24", "11", OpName); + + //通知PLC允许工作,允许工作在保存完成时清空 + MIS_BASE.Write_FixAllow(OpName, true); + } + else + { + SendMessageFun.AsyncSendMessage_Notice(OpName, "请扫描物料!"); + } + + + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:Barcode"); + } + + } + + } + + + } +} diff --git a/MisDataFunction/MesServer.Function/Function1053/OpcServer/CallMaterials.cs b/MisDataFunction/MesServer.Function/Function1053/OpcServer/CallMaterials.cs new file mode 100644 index 0000000..4073dc5 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1053/OpcServer/CallMaterials.cs @@ -0,0 +1,88 @@ +using System; +using bizFacade; +using MesServerWork; +using WebApiCall; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 叫料 + /// + /// + /// + private void CallMaterials(object e) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + + // 信号名称、库位1变量号、库位2变量号 + // 请求叫料 1 206 2 211 + // 请求退料 1 207 2 212 + // 允许进入 1 208 2 213 + // 退料类型 1 209 2 214 + // 叫料类型 1 210 2 215 + // 到料类型 1 202 2 205 + // 请求进入 1 200 2 203 + // AGV已离开1 201 2 204 + + int tagType = Convert.ToInt32(msgEvent.TagType); + + if (tagValue == 1) + { + // 根据变量类型代码 获取 位置号 与 叫料类型 + string positionName = "-1"; // 位置号 + string engineType = "-1"; // 型号 1 3 吨 + string type = "叫料"; // 操作类型 分 叫料 退料 退余料 + + // 206 库位1 + if(tagType == 206) + { + positionName = "H1"; + engineType = MIS_BASE.ReadPLC(210,OpName).ToString(); + } + // 211 库位2 + else if (tagType == 211) + { + positionName = "H2"; + engineType = MIS_BASE.ReadPLC(215, OpName).ToString(); + } + + // 1.调用WebApi通知叫料 + bool isOk = AGVWebApiCall.MES_To_AGV_CallGoods(positionName,engineType); + + if (isOk) + { + // 2.叫料成功后 记录叫料日志 + BaseDataSystemMES.Get_AGV_CallRecord(OpName, positionName, engineType, type); + } + } + else + { + if (tagType == 206) + { + MIS_BASE.WritePLC(200,OpName,false); // AGV已离开 + MIS_BASE.WritePLC(201, OpName, false); // 请求进入 + MIS_BASE.WritePLC(202, OpName, false); // 叫料类型 + } + // 211 库位2 + else if (tagType == 211) + { + MIS_BASE.WritePLC(203, OpName, false); // AGV已离开 + MIS_BASE.WritePLC(204, OpName, false); // 请求进入 + MIS_BASE.WritePLC(205, OpName, false); // 叫料类型 + } + + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:ConfirmOkGo"); + } + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1053/OpcServer/ConfirmOkGo.cs b/MisDataFunction/MesServer.Function/Function1053/OpcServer/ConfirmOkGo.cs new file mode 100644 index 0000000..06e6b33 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1053/OpcServer/ConfirmOkGo.cs @@ -0,0 +1,41 @@ +using System; +using bizFacade; +//using SystemFramework; +using MesServerWork; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 合格放行 + /// + /// + /// + private void ConfirmOkGo(object e) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + + if (tagValue == 1) + { + + BaseDataSystemMES.Material_Insert(OpName, 1); + + //更新订单完工数量及物料 + Sendmessage("24", "11", OpName); + + //工作完成 + MIS_BASE.Write_MaterialVerifyOver(OpName, true); + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:ConfirmOkGo"); + } + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1053/OpcServer/EngineGetOver.cs b/MisDataFunction/MesServer.Function/Function1053/OpcServer/EngineGetOver.cs new file mode 100644 index 0000000..cb137a2 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1053/OpcServer/EngineGetOver.cs @@ -0,0 +1,86 @@ +using System; +using System.Data; +using System.Windows.Forms; +using System.Xml.Linq; +using bizFacade; +//using SystemFramework; +using MesServerWork; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// PLC传递机型处理 + /// + /// + /// + private void EngineTypeGetOver_PLC(object e) + { + + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + // 收到传递机型就不给允许工作了 + //MIS_BASE.Write_FixAllow(OpName, false); + + if (tagValue == 1) + { + int EngineTypeID;//机型代码 + int PartPallet_Code;//托盘编号 + + string EngineType;//机型 + string EngineID;//工件编号 + string OrderForm; + MIS_BASE.GetEngineTypeFromPLC(OpName, out EngineTypeID, out EngineType, out EngineID, out PartPallet_Code, out OrderForm); + + if (EngineTypeID <= 0 || EngineID.Length == 0 || EngineType.Length == 0) + { + MIS_BASE.WritePLC(34, OpName, true); + string msg = "【" + OpName + "】" + "PLC传递机型为空!"; + MyLog4Net.MyLogHelper.Error("EngineTypeGetOver", msg); + SendMessageFun.AsyncSendMessage_Notice(OpName, "PLC传递机型为空!"); + return; + } + + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.EngineTypeID, EngineTypeID.ToString()); + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.EngineType, EngineType); + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.EngineID, EngineID); + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.OrderForm, OrderForm); + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.PartPallet_Code, PartPallet_Code.ToString()); + + //显示当前订单信息 + SendMessage.ShowMoby(OpName); + //判断该订单数据是否已经工作过,有的话则在WEB跳出弹窗选择 并同时禁止工作 + //DataTable dt2 = BaseDataSystemMES.EngineIsTwoWork(OpName, OrderForm, EngineID); + //if (dt2.Rows[0]["result"].ToString() == "1") //已完成 + //{ + // //不允许工作 + // MIS_BASE.Write_FixAllow(OpName, false); + // //通知WEB校验重新工作还是跳过 点重新工作给允许工作,点跳过给工作完成 + // string message = "MES|Engine_Is_TwoWork|" + OpName + "|1"; + // SendMessage.AsyncSendMessage(message); + //} + //else + //{ + // EngineTypeGetOver_PLC_Work(OpName, EngineTypeID, EngineType, EngineID, PartPallet_Code, OrderForm); + //} + EngineTypeGetOver_PLC_Work(OpName, EngineTypeID, EngineType, EngineID, PartPallet_Code, OrderForm); + } + } + catch (Exception err) + { + // 保存出错日志 1.申请上线 2.传递机型 3.允许保存 4.扫码 + MisDataSaveDate.FuntionMesRead.Alarm_SaveFileLog4Error(System.Reflection.MethodBase.GetCurrentMethod().Name, e, "Fun1053", err); + ////ApplicationLog.WriteLog(err, "Function02:EngineTypeGetOver_PLC"); + } + } + + + } + + } +} diff --git a/MisDataFunction/MesServer.Function/Function1053/OpcServer/FalseGO.cs b/MisDataFunction/MesServer.Function/Function1053/OpcServer/FalseGO.cs new file mode 100644 index 0000000..14b5771 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1053/OpcServer/FalseGO.cs @@ -0,0 +1,46 @@ +using System; +using System.Data; +using System.Windows.Forms; +using System.Xml.Linq; +using bizFacade; +//using SystemFramework; +using MesServerWork; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 不合格放行 + /// + /// + /// + private void FalseGO(object e) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + + if (tagValue == 1) + { + //不合格放行信号 + //MIS_BASE.Write_FalseGO(OpName, true); + //总合格标志2(不合格) + + BaseDataSystemMES.Material_Insert_NG(OpName, 2); + + Sendmessage("24", "11", OpName); + + //工作完成 + MIS_BASE.Write_MaterialVerifyOver(OpName, true); + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:FalseGO"); + } + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1053/OpcServer/HeartBeat.cs b/MisDataFunction/MesServer.Function/Function1053/OpcServer/HeartBeat.cs new file mode 100644 index 0000000..93affd3 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1053/OpcServer/HeartBeat.cs @@ -0,0 +1,35 @@ +using bizFacade; +using MesServerWork; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// MES与PLC心跳监听 + /// + /// + /// + private void HeartBeat(object e) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + + //返写在MES心跳中 + MIS_BASE.WritePLC(15, OpName, tagValue); + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:FalseGO"); + } + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1053/OpcServer/MesRead.cs b/MisDataFunction/MesServer.Function/Function1053/OpcServer/MesRead.cs new file mode 100644 index 0000000..e0d63b3 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1053/OpcServer/MesRead.cs @@ -0,0 +1,156 @@ +using bizFacade; +using MesServerWork; +using MesWork; +using System; +using System.Threading; +//using SystemFramework; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 允许保存(针对半自动和手动压装工位) + /// + /// + /// + private void MesRead(object e) + { + { + try + { + + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + + MIS_BASE.Write_FixAllow(OpName, false); + + if (tagValue == 1) + { + int qualityMask; + // 保存质量数据 + qualityMask = MisDataSaveDateMesRead.Funtion.MesRead(OpName, tagValue.ToString(), msgEvent.TagID.ToString()); + + + MIS_BASE.Read_EngineID(OpName, out string EngineID); + MIS_BASE.Read_TagTypeID(39, OpName, out string OrderForm); + // 分装线保存 扣数 + Db.SubLine_WorkFinish(EngineID, OpName, OrderForm, qualityMask); + + + // 保存物料数据 + // BaseDataSystemMES.Material_Insert(OpName, qualityMask); + + // 测量数据发动机在线状态 过站信息 + + BaseDataSystemMES.WorkStartInsert(OpName, qualityMask); + + // 读取当前选择的计划中的机型,写入PLC + // 获取订单的机型 + string Program_No = ""; + int planCount = 0; // 计划上料数量 + int haveUplaodCount = 0; // 已上料数量 + int remainingQuantity = 0; // 待上料数量 + Db.GetEngineType_Order(OpName, Program_No, out int EngineTypeID_Program, + out string EngineType_Program, out string EngineID_Program, out string OrderForm_Program, + out int isCheckOk_Program, out planCount, out haveUplaodCount, out remainingQuantity); + if (isCheckOk_Program == 2) + { + MIS_BASE.Write_EngineTypeID_MES(OpName, 0); + MIS_BASE.Write_EngineType_MES(OpName, ""); + MIS_BASE.Write_EngineID_MES(OpName, ""); + MIS_BASE.Write_OrderForm_MES(OpName, ""); + + MIS_BASE.WritePLC(95, OpName, planCount); + MIS_BASE.WritePLC(96, OpName, haveUplaodCount); + MIS_BASE.WritePLC(97, OpName, remainingQuantity); + + //MIS_BASE.WritePLC(34, OpName, true); + string msg = "【" + OpName + "】" + "分装线无上线订单,请下达新订单!"; + MyLog4Net.MyLogHelper.Error("PartLoad", msg); + SendMessage.AsyncSendMessage_Notice(OpName, msg); + + Thread.Sleep(200); + MIS_BASE.Write_MaterialVerifyOver(OpName, true); + MIS_BASE.Write_MesReadOver(OpName, true); + } + else + { + // 写入机型代码 (大机型) 机型 发动机号 订单号 + MIS_BASE.Write_EngineTypeID_MES(OpName, EngineTypeID_Program); + MIS_BASE.Write_EngineType_MES(OpName, EngineID_Program); + MIS_BASE.Write_OrderForm_MES(OpName, OrderForm_Program); + + MIS_BASE.WritePLC(95, OpName, planCount); + MIS_BASE.WritePLC(96, OpName, haveUplaodCount); + MIS_BASE.WritePLC(97, OpName, remainingQuantity); + + // 通知web显示 + SendMessage.ShowMoby(OpName); + Thread.Sleep(200); + MIS_BASE.Write_MaterialVerifyOver(OpName, true); + MIS_BASE.Write_MesReadOver(OpName, true); + } + + // 记录手动存储的物料数据 + int byte1 = Convert.ToInt32(MIS_BASE.ReadPLC(211, OpName)); + int byte2 = Convert.ToInt32(MIS_BASE.ReadPLC(202, OpName)); + int byte3 = Convert.ToInt32(MIS_BASE.ReadPLC(203, OpName)); + int byte4 = Convert.ToInt32(MIS_BASE.ReadPLC(204, OpName)); + int byte5 = Convert.ToInt32(MIS_BASE.ReadPLC(205, OpName)); + int byte6 = Convert.ToInt32(MIS_BASE.ReadPLC(206, OpName)); + int byte7 = Convert.ToInt32(MIS_BASE.ReadPLC(207, OpName)); + int byte8 = Convert.ToInt32(MIS_BASE.ReadPLC(208, OpName)); + int byte9 = Convert.ToInt32(MIS_BASE.ReadPLC(209, OpName)); + int byte10 = Convert.ToInt32(MIS_BASE.ReadPLC(210, OpName)); + BaseDataSystemMES.HeLi_HMIMaterialFactory_Add(OpName, EngineID, OrderForm, byte1, byte2, byte3, byte4, byte5, byte6, byte7, byte8, byte9, byte10); + + // 推送质量数据到MES的页面 + // SendMessageFun.SendInfomation("ShowTimelyQuality", "1&" + qualityMask.ToString(), OpName); + // 对应手动工位的 + // MIS_BASE.Write_ConfirmOkGo(OpName, true); + + + // 通知设备,MES的质量数据(和物料数据)保存完成 + + //统计在线产量,在线节拍 + // SendMessage.SendActuallyCount(OpName, tagValue); + } + else + { + // 分装上线工位没有托盘到位离开,通过申请上线和保存完成代替 + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.WorkStartOut, DateTime.Now.ToString()); + MIS_BASE.Write_MaterialVerifyOver(OpName, false); + MIS_BASE.Write_MesReadOver(OpName, false); + MIS_BASE.Write_ConfirmOkGo(OpName, false); + MIS_BASE.Write_FixAllow(OpName, false); + MIS_BASE.Write_ConfirmOkGo(OpName, false); + + // 清传递机型时 去判断一下是否申请上线 还有 如果有就不清 + int isEngineGetOver = Convert.ToInt32(MIS_BASE.ReadPLC(19, OpName)); + if (isEngineGetOver == 0) + { + MIS_BASE.Write_EngineTypeGetOver_MES(OpName, false); + } + else + { + MyLog4Net.MyLogHelper.Error("MesRead", OpName + "清传递机型时存在申请上线!"); + } + } + } + + } + catch (Exception err) + { + // 保存出错日志 1.申请上线 2.传递机型 3.允许保存 4.扫码 + MisDataSaveDate.FuntionMesRead.Alarm_SaveFileLog4Error(System.Reflection.MethodBase.GetCurrentMethod().Name, e, "Fun1053", err); + ////ApplicationLog.WriteLog(err, "Function08:MesReadOver"); + } + } + + } + + } +} diff --git a/MisDataFunction/MesServer.Function/Function1053/OpcServer/MesReadOver.cs b/MisDataFunction/MesServer.Function/Function1053/OpcServer/MesReadOver.cs new file mode 100644 index 0000000..f96a7d3 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1053/OpcServer/MesReadOver.cs @@ -0,0 +1,55 @@ +using System; +//using SystemFramework; +using MesServerWork; +using bizFacade; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 保存完成(针对半自动和手动压装工位) + /// + /// + /// + private void MesReadOver(object e) + { + //try + //{ + // DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + // string OpName = Convert.ToString(msgEvent.OpName); + // var tagValue = msgEvent.TagValue.ToString (); + + // if (tagValue == "1" | tagValue.ToLower () == "true") + // { + // int qualityMask; + // MIS_BASE.Read_QualityMask(OpName, out qualityMask); + + // SendInfomation("ShowTimelyQuality", "1&" + qualityMask.ToString(), OpName);//发给Web页面显示质量数据 + + // if (qualityMask == 1)//全部OK,给出合格放行 + // { + // //如果存在线外扫描工位,根据扫描条码绑定线外数据 需要时解除禁用 + // //BaseDataSystemMES.TransLaunchDataByMainMaterial(OpName, EngineType, EngineID, EngineTypeID); + + // //如果存在线外排队工位,根据排队编号绑定线外数据 需要时解除禁用 + // ////BaseDataSystemMES.MailLineAndSubLineData_InsertByEngineID_Subline(OpName,EngineID, EngineTypeID, EngineType); + + // MIS_BASE.Write_ConfirmOkGo(OpName, true); + // //MIS_BASE.Write_FalseGO(OpName, false); + // } + // else + // { + // //MIS_BASE.Write_ConfirmOkGo(OpName, false); + // MIS_BASE.Write_FalseGO(OpName, true); + // } + + // } + //} + //catch (Exception err) + //{ + // ////ApplicationLog.WriteLog(err, "Function02:MesReadOver"); + //} + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1053/OpcServer/MesSaveNowData.cs b/MisDataFunction/MesServer.Function/Function1053/OpcServer/MesSaveNowData.cs new file mode 100644 index 0000000..63c11b3 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1053/OpcServer/MesSaveNowData.cs @@ -0,0 +1,40 @@ +using bizFacade; +using MesServerWork; +using System; +using System.Collections.Generic; +using System.Data; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; +using static System.Net.Mime.MediaTypeNames; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// MES保存实时质量数据 + /// + /// + /// + private void MesSaveNowData(object e) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + // 直接发送实时的 质量数据 + string message = MisDataSaveDateMesRead.Funtion.GetRealTimeQualityData(OpName); + //推送质量数据到MES的页面 + SendMessage.AsyncSendMessage("MES|ShowTimelyQuality_Resources|" + OpName + "|" + message); + //SendMessageFun.SendMessageMESToWEB("ShowTimelyQuality", "1&" + qualityMask.ToString(), OpName); + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:FalseGO"); + } + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1053/OpcServer/PartLoad.cs b/MisDataFunction/MesServer.Function/Function1053/OpcServer/PartLoad.cs new file mode 100644 index 0000000..fe2685f --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1053/OpcServer/PartLoad.cs @@ -0,0 +1,104 @@ +using System; +using bizFacade; +//using SystemFramework; +using MesServerWork; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 申请上线(针对上线工位) + /// + /// + /// + private void PartLoad(object e) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + + MIS_BASE.Write_FixAllow(OpName, false); + //上线工位清MES传递机型信号 + MIS_BASE.Write_EngineTypeGetOver_MES(OpName, false); + // 清除报警 + MIS_BASE.WritePLC(34, OpName, false); + + if (tagValue == 1) + { + int planCount = 0; // 计划上料数量 + int haveUplaodCount = 0; // 已上料数量 + int remainingQuantity = 0; // 待上料数量 + + // 分装上线工位没有托盘到位离开,通过申请上线和保存完成代替 + //MIS_BASE.Write_TagTypeID(115, OpName, 0); + //MIS_BASE.Write_TagTypeID(95, OpName, 0); + //MIS_BASE.Write_TagTypeID(96, OpName, 0); + //MIS_BASE.Write_TagTypeID(97, OpName, 0); + //MIS_BASE.Write_TagTypeID(98, OpName, ""); + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.WorkStartIn, DateTime.Now.ToString()); + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.WorkStart, tagValue.ToString()); + + // 读取当前选择的计划中的机型,写入PLC + // 获取订单的机型 + string Program_No = ""; + Db.GetEngineType_Order(OpName, Program_No, out int EngineTypeID, + out string EngineType, out string EngineID, out string OrderForm, + out int isCheckOk, out planCount, out haveUplaodCount, out remainingQuantity); + if (isCheckOk == 2) + { + MIS_BASE.Write_EngineTypeID_MES(OpName, 0); + MIS_BASE.Write_EngineType_MES(OpName, ""); + MIS_BASE.Write_EngineID_MES(OpName, ""); + MIS_BASE.Write_OrderForm_MES(OpName, ""); + + MIS_BASE.WritePLC(95, OpName, planCount); + MIS_BASE.WritePLC(96, OpName, haveUplaodCount); + MIS_BASE.WritePLC(97, OpName, remainingQuantity); + + MIS_BASE.WritePLC(34, OpName, true); + string msg = "【" + OpName + "】" + "分装线无上线订单,请下达新订单!"; + MyLog4Net.MyLogHelper.Error("PartLoad", msg); + SendMessage.AsyncSendMessage_Notice(OpName, msg); + return; + } + else + { + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.EngineID_MES, EngineID); + + // 写入机型代码 (大机型) 机型 发动机号 订单号 + MIS_BASE.Write_EngineTypeID_MES(OpName, EngineTypeID); + MIS_BASE.Write_EngineType_MES(OpName, EngineType); + MIS_BASE.Write_EngineID_MES(OpName, EngineID); + MIS_BASE.Write_OrderForm_MES(OpName, OrderForm); + + MIS_BASE.WritePLC(95, OpName, planCount); + MIS_BASE.WritePLC(96, OpName, haveUplaodCount); + MIS_BASE.WritePLC(97, OpName, remainingQuantity); + + + // MES传递机型 + MIS_BASE.Write_EngineTypeGetOver_MES(OpName, true); + // 通知web显示 + SendMessage.ShowMoby(OpName); + } + } + else + { + ////上线工位清MES传递机型信号 + //MIS_BASE.Write_EngineTypeGetOver_MES(OpName, false); + //// 清除报警 + //MIS_BASE.WritePLC(34, OpName, false); + } + } + catch (Exception err) + { + // 保存出错日志 1.申请上线 2.传递机型 3.允许保存 4.扫码 + MisDataSaveDate.FuntionMesRead.Alarm_SaveFileLog4Error(System.Reflection.MethodBase.GetCurrentMethod().Name, e, "Fun1053", err); + ////ApplicationLog.WriteLog(err, "Function08:MesReadOver"); + } + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1053/OpcServer/QuitMaterials.cs b/MisDataFunction/MesServer.Function/Function1053/OpcServer/QuitMaterials.cs new file mode 100644 index 0000000..b6e2542 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1053/OpcServer/QuitMaterials.cs @@ -0,0 +1,80 @@ +using System; +using bizFacade; +//using SystemFramework; +using MesServerWork; +using WebApiCall; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 请求退料 + /// + /// + /// + private void QuitMaterials(object e) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + + if (tagValue == 1) + { + int tagType = Convert.ToInt32(msgEvent.TagType); + // 根据变量类型代码 获取 位置号 与 叫料类型 + string positionName; // 位置号 + string engineType = "-1"; + string quitType; // 1 退空托 2 退1T余料 3 退3T余料 + string type = ""; // 操作类型 分 叫料 退料 退余料 + + // 206 库位1 + if (tagType == 207) + { + positionName = "H1"; + quitType = MIS_BASE.ReadPLC(209, OpName).ToString(); + } + // 211 库位2 212 + else + { + positionName = "H2"; + quitType = MIS_BASE.ReadPLC(214, OpName).ToString(); + } + + if (quitType == "1") + { + type = "退空托"; + } + if (quitType == "2") + { + type = "退余料"; + engineType = "1"; + } + if (quitType == "3") + { + type = "退余料"; + engineType = "3"; + } + + + // 1.调用WebApi通知退料 + int returnType = 0; // 默认空托退料 + if (quitType == "2" || quitType == "3") returnType = 1; // 余料退料 + bool isOk = AGVWebApiCall.MES_To_AGV_ReturnGoods(positionName, engineType, returnType); + + if (isOk) + { + // 2.叫料成功后 记录叫料日志 + BaseDataSystemMES.Get_AGV_CallRecord(OpName, positionName, engineType, type); + } + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:ConfirmOkGo"); + } + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1053/OpcServer/WebSubmit.cs b/MisDataFunction/MesServer.Function/Function1053/OpcServer/WebSubmit.cs new file mode 100644 index 0000000..d7ca28c --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1053/OpcServer/WebSubmit.cs @@ -0,0 +1,304 @@ +using System; +using MesServerWork; +using bizFacade; +using System.Threading; +using MisDataSaveDate; +using System.Collections; +//using SystemFramework; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 处理WEB页面发送过来的请求(m_Command + "|" + m_Value;) + /// + /// + /// + private void WebSubmit(object e) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName=Convert.ToString(msgEvent.OpName); + string Content = Convert.ToString(msgEvent.TagValue); + + string[] dataArray = Content.Split('|'); + if (dataArray.Length != 2) + return; + //消息类型 + string m_Command = dataArray[0].ToString(); + //消息参数 + string m_Value = dataArray[1].ToString(); + //消息参数数量 + string[] m_Value_array = m_Value.Split('&'); + //消息参数长度 + int m_Value_length = m_Value_array.Length; + + //工件信息 + string engineID = ""; + if (MIS_BASE.hashtable_EngineGetOver_EngineTypeID == null) + { + MIS_BASE.InitHashtable_MesServerCode(); + } + if (MIS_BASE.hashtable_EngineGetOver_EngineTypeID == null) + { + return; + } + if (MIS_BASE.hashtable_EngineGetOver_EngineID.ContainsKey(OpName)) + { + engineID = MIS_BASE.hashtable_EngineGetOver_EngineID[OpName].ToString(); + } + + DoWhatPlc.CustomeEvetnArgs _e = new DoWhatPlc.CustomeEvetnArgs(); + _e.OpName = OpName; + _e.TagValue = m_Value; + + //根据请求的命令处理逻辑 + switch (m_Command) + { + case "Barcode": + if (m_Value_length > 1) return; + fun_Barcode(_e); + break; + case "ConfirmOkGo"://合格放行 + //删除不合格放行记录 + //修改托盘状态 + //Update_PalletStatus(OpName, 1, false); + BaseDataSystemMES.BaseData_tagTable_Engine_IsNG_Delete(OpName, engineID); + MIS_BASE.Write_ConfirmOkGo(OpName, true); + MIS_BASE.Write_FalseGO(OpName, false); + + Thread.Sleep(1000); + MIS_BASE.Write_ConfirmOkGo(OpName, false); + break; + case "FalseGO"://返修放行 + //修改托盘状态 + //Update_PalletStatus(OpName, 3, false); + BaseDataSystemMES.BaseData_tagTable_Engine_IsNG_Delete(OpName, engineID); + MIS_BASE.Write_FalseGO(OpName, true); + MIS_BASE.Write_ConfirmOkGo(OpName, false); + + Thread.Sleep(1000); + MIS_BASE.Write_FalseGO(OpName, false); + break; + case "NgGO"://不合格放行 + //修改托盘状态 + //Update_PalletStatus(OpName, 2, false); + //保存不合格信息(必须保存不合格放行信息,由于B5A的Moby没有不合格标志位) + BaseDataSystemMES.BaseData_tagTable_Engine_IsNG_Insert(OpName, engineID, "", ""); + MIS_BASE.Write_FalseGO(OpName, true); + MIS_BASE.Write_ConfirmOkGo(OpName, false); + Thread.Sleep(1000); + MIS_BASE.Write_FalseGO(OpName, false); + break; + case "OnLineState"://在线0、离线1、屏蔽2 + try + { + if (m_Value_length > 1) return; + int a = Convert.ToInt32(m_Value); + if (a <= 2) + { + BaseDataSystemMES.IsOnLine_Update(OpName, m_Value.ToString()); + MIS_BASE.Write_OnLineState(OpName, Convert.ToInt32(m_Value)); + if (a == 2) SendMessage.AsyncSendMessage_Notice(OpName, "屏蔽MES!"); + if (a == 0) SendMessage.AsyncSendMessage_Notice(OpName, "启用MES!"); + } + } + catch + { + + } + break; + case "Reset"://复位,将MES所有的信息都复位了 + SetMoby(OpName);//将MES所有信号清空 + break; + case "FixAllow"://重新拧紧 + MIS_BASE.Write_FixAllow(OpName, false); + MIS_BASE.Write_FixAllow(OpName, true); + break; + case "IsAutoGetEngineID"://自动手动申请编号(线首) + if (m_Value_length > 1) return; + MIS_BASE.Write_IsAutoGetEngineID(OpName, Convert.ToInt32(m_Value)); + break; + case "PartPalletGoOver"://空托盘放行 + int Is_PartPalletGoOver; + MIS_BASE.Read_PartPalletGoOver(OpName, out Is_PartPalletGoOver); + if (Is_PartPalletGoOver == 1) + { + MIS_BASE.Write_PartPalletGoOver(OpName, 1); + } + else + { + MIS_BASE.Write_PartPalletGoOver(OpName,0); + } + break; + case "SetMoby"://清空托盘(线首) + SetMoby(OpName);//将MES所有信号清空 + //MIS_BASE.Write_PartPalletCode_PLC(OpName, 1); + break; + case "RepairUplineMES"://返修上线 + MIS_BASE.Write_RepairUpline_MES(OpName, true); + break; + case "CancelRepair"://将返修件置为正常件 + + break; + case "PartPalletCode"://申请写入托盘号 + //MIS_BASE.Write_PartPalletCode_PLC(OpName, 1); + break; + case "WritePartPalletCode"://写入托盘号 + if (m_Value_length > 1) return; + MIS_BASE.Write_PalletCode(OpName, Convert.ToInt32(m_Value)); + break; + case "Normal"://启用正常拧紧工位 + MIS_BASE.Write_Normal(OpName, 1); + MIS_BASE.Write_UnNormal(OpName, 0); + break; + case "UnNormal"://启用备用拧紧工位 + MIS_BASE.Write_Normal(OpName, 0); + MIS_BASE.Write_UnNormal(OpName, 1); + break; + case "ResetDevice"://复位设备 + MIS_BASE.Write_ResetDevice(OpName, true); + System.Threading.Thread.Sleep(1000); + MIS_BASE.Write_ResetDevice(OpName, false); + break; + case "IsNeedRepaire"://返修上线(返修上线点) + if (Convert.ToInt32(m_Value) == 1) + { + //修改托盘状态 + MIS_BASE.Write_PalletInfo(OpName, 3); + //通知修改成功 + MIS_BASE.Write_UpdatePalletOK(OpName, true); + IsNeedRepaire_OK(OpName); + + } + else if (Convert.ToInt32(m_Value) == 0) + { + //通知修改成功 + MIS_BASE.Write_UpdatePalletOK(OpName, true); + //直接给出工作完成 + MIS_BASE.Write_MaterialVerifyOver(OpName, true); + } + else + { } + + break; + case "ContinueMatch": + BaseDataSystemMES.QualityVerifyStatus_Hash_Write(OpName, true); + break; + //初始化网页信号 + case "IniSingalToWeb": + InitializeSingalToWeb(OpName); + break; + case "Reset_Engine"://返修上线(返修上线点) + SetMoby(OpName);//将MES所有信号清空 + //fun_EngineTypeGetOverPLC(OpName, 0); + //fun_EngineTypeGetOverPLC(OpName, 1); + break; + + case "twoWorkSkip"://重新工作工件跳过工作(重新工作工件) + //工作完成 + EngineTypeGetOver_PLC_Work_Skip(OpName); + break; + case "twoWork"://重新工作工件重新工作(重新工作工件) + //允许工作 + EngineTypeGetOver_PLC_Work_two(OpName); + break; + + default: break; + } + } + catch(Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:WebSubmit"); + } + } + private void SetMoby(string OpName) + { + try + { + //清空Moby时,需要将MES信号清空 + MIS_BASE.Write_ClearMesMoby(OpName); + + BaseDataSystemMES.MesServer_Process_EngineTypeOver(OpName); + + Sendmessage("5123", "1111", OpName); + + MIS_BASE.Write_ResetDevice(OpName, true); + System.Threading.Thread.Sleep(1000); + MIS_BASE.Write_ResetDevice(OpName, false); + } + catch + { + + } + } + /// 网页重现登录,恢复关闭前的页面状态 + /// + /// 工位号 + private void InitializeSingalToWeb(string Opname) + { + + //工件到位 DBX0.1 + bool S_WorkStart; + bool S_FixAllow; + bool S_EngineGetOver; + bool S_MaterialVerifyOver; + + MIS_BASE.Read_WorkStart(Opname, out S_WorkStart); + MIS_BASE.Read_FixAllow(Opname, out S_FixAllow); + MIS_BASE.Read_EngineGetOver_PLC(Opname, out S_EngineGetOver); + MIS_BASE.Read_MaterialVerifyOver(Opname, out S_MaterialVerifyOver); + + Sendmessage("13", "1111", Opname); + string S_plcStatus;//DBX501.5 PLC直通,1 强制放行 0 正常循环 + // 新增查询PLC直通状态 网页显示 + MIS_BASE.Read_TagTypeID(63, Opname, out S_plcStatus); + if (S_plcStatus.ToLower() == "false") + { + SendMessageFun.SendInfomation("PlcStatus", "0", Opname); + } + else + { + SendMessageFun.SendInfomation("PlcStatus", "1", Opname); + } + + if (S_WorkStart == true) + { + SendInfomation("WorkStart", Convert.ToString(Convert.ToInt32(S_WorkStart)), Opname); + } + if (S_FixAllow == true) + { + SendInfomation("FixAllow", Convert.ToString(Convert.ToInt32(S_FixAllow)), Opname); + } + if (S_MaterialVerifyOver == true) + { + SendInfomation("MaterialVerifyOver", Convert.ToString(Convert.ToInt32(S_MaterialVerifyOver)), Opname); + } + if (S_EngineGetOver == true) + { + SendInfomation("EngineTypeGetOverPLC", Convert.ToString(Convert.ToInt32(S_EngineGetOver)), Opname); + Sendmessage("2", "1111", Opname); + SendMessage.ShowMoby(Opname); + // 直接发送实时的 质量数据 + string message = MisDataSaveDateMesRead.Funtion.GetRealTimeQualityData(Opname); + //推送质量数据到MES的页面 + SendMessage.AsyncSendMessage("MES|ShowTimelyQuality_Resources|" + Opname + "|" + message); + } + InitAlarm(Opname); + } + + private void InitAlarm(string Opname) + { + FuntionMesRead.Alarm_InitAlarm_Send(Opname, out Hashtable ht); + foreach (DictionaryEntry kv in ht) + { + var TagID = kv.Key.ToString(); + var TagValue = kv.Value.ToString(); + FuntionMesRead.Send_AlarmMsg(TagID, TagValue); + } + + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1053/OpcServer/WorkIsOk.cs b/MisDataFunction/MesServer.Function/Function1053/OpcServer/WorkIsOk.cs new file mode 100644 index 0000000..08819e3 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1053/OpcServer/WorkIsOk.cs @@ -0,0 +1,45 @@ +using bizFacade; +using MesServerWork; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 工位合格标志 + /// + /// + /// + private void IsOk(object e) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + + int qualityMask; + MIS_BASE.Read_QualityMask(OpName, out qualityMask); + //判断是否合格 + if (qualityMask == 1) + { + qualityMask = 1; + } else { + qualityMask = 0; + } + //通知WEB修改状态 + string message = "MES|QualityMask|" + OpName + "|" + qualityMask.ToString(); + SendMessage.AsyncSendMessage(message); + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:FalseGO"); + } + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1053/OpcServer/WorkStart.cs b/MisDataFunction/MesServer.Function/Function1053/OpcServer/WorkStart.cs new file mode 100644 index 0000000..34c5803 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1053/OpcServer/WorkStart.cs @@ -0,0 +1,51 @@ +using bizFacade; +using MesServerWork; +using System; +using System.Threading; +//using SystemFramework; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 工件到位与离开时,清空MES自身信号 + /// + /// + /// + private void WorkStart(object e) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + if (tagValue > 0) + { + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.WorkStartIn, DateTime.Now.ToString()); + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.WorkStart, tagValue.ToString()); + } + else + { + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.WorkStartOut, DateTime.Now.ToString()); + MIS_BASE.Write_MesReadOver(OpName, false); + MIS_BASE.Write_ConfirmOkGo(OpName, false); + MIS_BASE.Write_FixAllow(OpName, false); + MIS_BASE.Write_ConfirmOkGo(OpName, false); + MIS_BASE.Write_EngineTypeGetOver_MES(OpName, false); + //工作完成 + MIS_BASE.Write_MaterialVerifyOver(OpName, false); + MIS_BASE.Write_EngineTypeID_MES(OpName, 0); + MIS_BASE.Write_EngineType_MES(OpName, ""); + MIS_BASE.Write_EngineID_MES(OpName, ""); + MIS_BASE.Write_OrderForm_MES(OpName, ""); + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:WorkStart"); + } + } + + } +} diff --git a/MisDataFunction/MesServer.Function/Function1053/OpcServer/vssver2.scc b/MisDataFunction/MesServer.Function/Function1053/OpcServer/vssver2.scc new file mode 100644 index 0000000..b884d13 Binary files /dev/null and b/MisDataFunction/MesServer.Function/Function1053/OpcServer/vssver2.scc differ diff --git a/MisDataFunction/MesServer.Function/Function1053/Properties/AssemblyInfo.cs b/MisDataFunction/MesServer.Function/Function1053/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..0bb79c4 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1053/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// 有关程序集的常规信息通过以下 +// 特性集控制。更改这些特性值可修改 +// 与程序集关联的信息。 +[assembly: AssemblyTitle("Function02")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("苏州宏软信息技术有限公司")] +[assembly: AssemblyProduct("Function02")] +[assembly: AssemblyCopyright("Copyright © 苏州宏软信息技术有限公司 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// 将 ComVisible 设置为 false 使此程序集中的类型 +// 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型, +// 则将该类型上的 ComVisible 特性设置为 true。 +[assembly: ComVisible(false)] + +// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID +[assembly: Guid("47710f2c-e141-4252-8d13-701bf4c1c027")] + +// 程序集的版本信息由下面四个值组成: +// +// 主版本 +// 次版本 +// 内部版本号 +// 修订号 +// +// 可以指定所有这些值,也可以使用“内部版本号”和“修订号”的默认值, +// 方法是按如下所示使用“*”: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/MisDataFunction/MesServer.Function/Function1053/Properties/vssver2.scc b/MisDataFunction/MesServer.Function/Function1053/Properties/vssver2.scc new file mode 100644 index 0000000..14e543b Binary files /dev/null and b/MisDataFunction/MesServer.Function/Function1053/Properties/vssver2.scc differ diff --git a/MisDataFunction/MesServer.Function/Function1053/app.config b/MisDataFunction/MesServer.Function/Function1053/app.config new file mode 100644 index 0000000..b4c4daf --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1053/app.config @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + + + diff --git a/MisDataFunction/MesServer.Function/Function1053/mssccprj.scc b/MisDataFunction/MesServer.Function/Function1053/mssccprj.scc new file mode 100644 index 0000000..119193d --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1053/mssccprj.scc @@ -0,0 +1,5 @@ +SCC = This is a Source Code Control file + +[Function02.csproj] +SCC_Aux_Path = "\\192.168.0.100\vss\MES4.0" +SCC_Project_Name = "$/MisData/MisData/MisData/MesServer.Function/Function02", ILHAAAAA diff --git a/MisDataFunction/MesServer.Function/Function1053/packages.config b/MisDataFunction/MesServer.Function/Function1053/packages.config new file mode 100644 index 0000000..b3e1761 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1053/packages.config @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/MisDataFunction/MesServer.Function/Function1053/vssver2.scc b/MisDataFunction/MesServer.Function/Function1053/vssver2.scc new file mode 100644 index 0000000..c770e28 Binary files /dev/null and b/MisDataFunction/MesServer.Function/Function1053/vssver2.scc differ diff --git a/MisDataFunction/MesServer.Function/Function1054/DataAccess/DataAccess.cs b/MisDataFunction/MesServer.Function/Function1054/DataAccess/DataAccess.cs new file mode 100644 index 0000000..574d619 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1054/DataAccess/DataAccess.cs @@ -0,0 +1,15 @@ + +namespace MesServerFunctions +{ + partial class Function1052 + { + //针对“MIS.BizFacade.Dll”中没有的存储过程,在此类中新建 + //新建原则:所有的函数用private,只允许在内部使用 + //针对单个工艺特殊,需要新建存储过程,但是存储过程不能被加入到“MIS.BizFacade.Dll”中 + + private void aa() + { + + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1054/DataAccess/vssver2.scc b/MisDataFunction/MesServer.Function/Function1054/DataAccess/vssver2.scc new file mode 100644 index 0000000..d045c26 Binary files /dev/null and b/MisDataFunction/MesServer.Function/Function1054/DataAccess/vssver2.scc differ diff --git a/MisDataFunction/MesServer.Function/Function1054/Db.cs b/MisDataFunction/MesServer.Function/Function1054/Db.cs new file mode 100644 index 0000000..4bac3f6 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1054/Db.cs @@ -0,0 +1,84 @@ +using System; +using System.Collections.Generic; +using System.Data.SqlClient; +using System.Data; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using DataLinkMesWork; + +namespace MesServerFunctions +{ + public class Db + { + /// + /// 合力_OPA90是否允许工作_判断 如果允许工作则将两个轮毂状态设为待匹配 + /// + /// + /// + /// + /// + /// + /// + /// + public static bool OP50_OPA90_MatchResult(int EngineTypeID, int EngineTypeID_QiaoKe, string EngineID, string OrderForm, out int MatchResult, out string MatchResultStr) + { + DataTable dt = new DataTable(); + MatchResult = 3;// 默认是报警 程序出错 + MatchResultStr = "默认是报警 程序出错";// 默认是报警 程序出错 + string produceName = "合力_OPA90是否允许工作_判断"; + SqlParameter[] thisParms = new SqlParameter[4]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@轮毂机型", EngineTypeID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@轮毂总成号", EngineID); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@桥壳_机型", EngineTypeID_QiaoKe); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@订单号", OrderForm); + if (DataAccess.ExecuteStoredProcedure(produceName, ref thisParms, out dt)) + { + if (dt.Rows.Count > 0) + { + MatchResult = Convert.ToInt32(dt.Rows[0]["最终结果"]); + MatchResultStr = dt.Rows[0]["最终结果说明"].ToString(); + return true; + } + } + return false; + } + /// + /// 合力_转线_OPA90_TO_OP050 + /// + /// + /// + /// + public static bool OPA90_TO_OP50_WorkFinish(string partSn_Main, string partSn_Sub) + { + + string produceName = "合力_转线_OPA90_TO_OP050"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@轮毂总成号", partSn_Sub); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@桥壳总成号", partSn_Main); + return DataAccess.ExecuteStoredProcedure(produceName, ref thisParms); + } + + /// + /// 合力_OP050是否允许工作_判断 + /// + /// + /// + public static bool OPA90_TO_OP50_CheckTwoFinish(out int MainLineAllowWork) + { + DataTable dt; + MainLineAllowWork = 2; + string produceName = "合力_OP050是否允许工作_判断"; + SqlParameter[] thisParms = new SqlParameter[0]; + if (DataAccess.ExecuteStoredProcedure(produceName, ref thisParms, out dt)) + { + if (dt.Rows.Count > 0) + { + MainLineAllowWork = Convert.ToInt32(dt.Rows[0]["是否允许工作"]); + return true; + } + } + return false; + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1054/Function02.csproj.vspscc b/MisDataFunction/MesServer.Function/Function1054/Function02.csproj.vspscc new file mode 100644 index 0000000..0f0f36c --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1054/Function02.csproj.vspscc @@ -0,0 +1,10 @@ +"" +{ +"FILE_VERSION" = "9237" +"ENLISTMENT_CHOICE" = "NEVER" +"PROJECT_FILE_RELATIVE_PATH" = "relative:MesServer.Function\\Function02" +"NUMBER_OF_EXCLUDED_FILES" = "0" +"ORIGINAL_PROJECT_FILE_PATH" = "" +"NUMBER_OF_NESTED_PROJECTS" = "0" +"SOURCE_CONTROL_SETTINGS_PROVIDER" = "PROVIDER" +} diff --git a/MisDataFunction/MesServer.Function/Function1054/Function1054.csproj b/MisDataFunction/MesServer.Function/Function1054/Function1054.csproj new file mode 100644 index 0000000..b234e0d --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1054/Function1054.csproj @@ -0,0 +1,169 @@ + + + + Debug + AnyCPU + 8.0.30703 + 2.0 + {CC45D613-11B9-48AF-B073-6523D6273525} + Library + Properties + Function1054 + Function1054 + v4.8 + 512 + + + + + + + + + + + + + + true + full + false + ..\..\..\dll_fun\ + DEBUG;TRACE + prompt + 4 + false + false + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + false + + + + ..\..\..\Common\dll\MQTTnet.dll + + + ..\..\..\Common\dll\MQTTnet.Extensions.ManagedClient.dll + + + False + ..\..\..\Common\dll\Newtonsoft.Json.dll + + + + + + ..\..\DLL\System.Net.Http.dll + + + ..\..\packages\System.Net.Security.4.3.2\lib\net46\System.Net.Security.dll + + + ..\..\packages\System.Net.WebSockets.4.3.0\lib\net46\System.Net.WebSockets.dll + + + ..\..\packages\System.Net.WebSockets.Client.4.3.2\lib\net46\System.Net.WebSockets.Client.dll + + + ..\..\packages\System.Security.Cryptography.Algorithms.4.3.0\lib\net461\System.Security.Cryptography.Algorithms.dll + + + ..\..\packages\System.Security.Cryptography.Encoding.4.3.0\lib\net46\System.Security.Cryptography.Encoding.dll + + + ..\..\packages\System.Security.Cryptography.Primitives.4.3.0\lib\net46\System.Security.Cryptography.Primitives.dll + + + ..\..\packages\System.Security.Cryptography.X509Certificates.4.3.0\lib\net461\System.Security.Cryptography.X509Certificates.dll + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + {f55da1a0-a982-4479-8c47-0d9a5aaf3e18} + 00MesWorkMqtt + + + {0d1af432-439a-4920-8692-43ae139f5530} + 01_01DoWhatPlc + + + {3e6d1dd5-01c9-435f-9941-61f906ce35bb} + 02_02WebApiCallPLC + + + {f434e066-4c59-47c8-aa82-6f48cc84501a} + 04-DataBaseAccess + + + {f0a0c525-03fd-428a-9b17-7f54aa0e4475} + 07BusinessFacade + + + {d98be764-adeb-488d-9714-61e308aa8201} + 08-WebFun_base + + + {90e76fb4-646d-45e2-95db-0b8ab4e465d6} + 09-MesDataFunction + + + {e4eb6420-906d-4672-947a-ca33ddcdadfc} + 12SendMessageToWeb + + + {55b510c1-59e9-4bfd-ae84-d76d46f6e365} + 02-13.3MIS_FuntionSaveData + + + + + + + 这台计算机上缺少此项目引用的 NuGet 程序包。使用“NuGet 程序包还原”可下载这些程序包。有关更多信息,请参见 http://go.microsoft.com/fwlink/?LinkID=322105。缺少的文件是 {0}。 + + + + + \ No newline at end of file diff --git a/MisDataFunction/MesServer.Function/Function1054/MesServerFunction/Fun_1054.cs b/MisDataFunction/MesServer.Function/Function1054/MesServerFunction/Fun_1054.cs new file mode 100644 index 0000000..bafbff6 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1054/MesServerFunction/Fun_1054.cs @@ -0,0 +1,237 @@ +using MesServerWork; +using System.Collections.Generic; +using System.Threading; +using System.Xml.Linq; + +namespace MesServerFunctions +{ + public partial class FunctionMES + { + object lockFunWork; + //public void FunWork(DoWhatPlc.CustomeEvetnArgs e) + public void FunWork(string recData) + { + + + lockFunWork = new object(); + lock (lockFunWork) + { + List dataArray = DoWhatPlc.MessageText.GetCmdStringList(recData); + //string[] dataArray = recData.Split('|'); + //if (dataArray.Count != 4) + //return; + //消息来源 + string m_Source = dataArray[0].ToString(); + //消息类型 Barcode + string m_Command = dataArray[1].ToString(); + //工位号 + string m_OpName = dataArray[2].ToString(); + //消息参数 + string m_Value = dataArray[3].ToString(); + + DoWhatPlc.CustomeEvetnArgs e = new DoWhatPlc.CustomeEvetnArgs();// = Newtonsoft.Json.JsonConvert.DeserializeObject(m_Value); + string tagValue; + + switch (m_Source) + { + case "BarCode": + e.OpName = m_OpName; + e.TagValue = m_Value; + fun_Barcode(e); + break; + case "WEB": + e.OpName = m_OpName; + e.TagValue = m_Command + "|" + m_Value; + fun_WebSubmit(e); + break; + case "PLC": + e = Newtonsoft.Json.JsonConvert.DeserializeObject(m_Value); + switch (e.TagValue.ToString().ToLower()) + { + case "false": + tagValue = "0"; + break; + case "true": + tagValue = "1"; + break; + default: + tagValue = e.TagValue.ToString(); + break; + } + e.TagValue = tagValue; + switch (e.TagTypeCodeID.ToString()) + { + //PLC 工件到位 + case "2": + fun_WorkStart(e); + break; + //PLC 允许保存质量数据 + case "19": + fun_MesRead(e); + break; + //MES 保存数据完成 + case "20": + fun_MesReadOver(e); + break; + //PLC 传递机型 + case "44": + fun_EngineTypeGetOverPLC(e); + break; + //MES 合格放行 + case "51": + fun_ConfirmOkGo(e); + break; + //MES 不合格放行 + case "8": + fun_FalseGo(e); + break; + //PLC 工位合格标志 + case "21": + fun_IsOk(e); + break; + //MES保存实时质量数据 + case "65": + fun_MesSaveNowData(e); + break; + //MES 系统健康心跳 + case "14": + fun_HeartBeatMIS(e); + break; + case "63": + string S_plcStatus;//DBX501.5 PLC直通,1 强制放行 0 正常循环 + MIS_BASE.Read_TagTypeID(63, m_OpName, out S_plcStatus); + if (S_plcStatus.ToLower() != "true" || S_plcStatus.ToLower() == "1") + { + SendMessageFun.SendInfomation("PlcStatus", "0", m_OpName); + } + else + { + SendMessageFun.SendInfomation("PlcStatus", "1", m_OpName); + } + break; + } + break; + } + } + } + + //1.工件到位后,PLC给MES传递机型(DBX0.4)(44), + //MES判断条码是否全部扫描完成 + //PLC给出允许保存(DBX100.2)(19),MES见到(DBX100.2)(19)为1后给出保存完成(DBX102.2)(20), + //PLC见到保存完成(DBX102.2)(20)为1后,清空允许保存(DBX100.2)(19), + //MES见到允许保存(DBX100.2)(19)为0后,清空保存完成(DBX102.2)(20) + //MES判断总合格标志(INT104)(21)为1后,给出合格放行(DBX2.5)(51) + /// + /// 扫描条码 + /// + /// + /// + public void fun_Barcode(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(Barcode, e); + } + + /// + /// 传递机型 + /// + /// + /// + public void fun_EngineTypeGetOverPLC(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(EngineTypeGetOver_PLC, e); + } + + /// + /// 合格放行 + /// + /// + /// + public void fun_ConfirmOkGo(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(ConfirmOkGo, e); + } + + /// + /// 不合格放行 + /// + /// + /// + public void fun_FalseGo(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(FalseGO, e); + } + + /// + /// 允许保存 + /// + /// + /// + public void fun_MesRead(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(MesRead, e); + } + + /// + /// 保存完成 + /// + /// + /// + public void fun_MesReadOver(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(MesReadOver, e); + } + + /// + /// 工件到位离开(清空所有的MES信号) + /// + /// + /// + public void fun_WorkStart(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(WorkStart, e); + } + + /// + /// 处理WEB页面发送过来的请求(m_Command + "|" + m_Value;) + /// + /// + /// + public void fun_WebSubmit(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(WebSubmit, e); + } + + + /// + /// 工位是否合格 + /// + /// + /// + public void fun_IsOk(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(IsOk, e); + } + + /// + /// 系统健康心跳监测 + /// + /// + /// + public void fun_HeartBeatMIS(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(HeartBeat, e); + } + + /// + /// MES实时保存质量数据 + /// + /// + /// + public void fun_MesSaveNowData(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(MesSaveNowData, e); + } + + + } +} diff --git a/MisDataFunction/MesServer.Function/Function1054/MesServerFunction/vssver2.scc b/MisDataFunction/MesServer.Function/Function1054/MesServerFunction/vssver2.scc new file mode 100644 index 0000000..a246f67 Binary files /dev/null and b/MisDataFunction/MesServer.Function/Function1054/MesServerFunction/vssver2.scc differ diff --git a/MisDataFunction/MesServer.Function/Function1054/Methods/EngineGetOverBaseWork.cs b/MisDataFunction/MesServer.Function/Function1054/Methods/EngineGetOverBaseWork.cs new file mode 100644 index 0000000..e82998c --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1054/Methods/EngineGetOverBaseWork.cs @@ -0,0 +1,181 @@ +using System; +using System.Data; +using bizFacade; +using MesServerWork; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 正常逻辑工作(传递机型) + /// + /// + /// + /// + /// + /// + private void EngineTypeGetOver_PLC_Work(string OpName, int EngineTypeID, string EngineType, string EngineID, int PartPallet_Code, string OrderForm) + { + int IsAllowWork; + int RepairPartStatusPLC = 0; + int MES_QualityMask = 1; + + + + //电子看板_装配零件_临时表_增加_北汽 + //第二步,将零件信息转移到零件_临时表中 + BaseDataSystemMES.MesServer_Process_EngineTypeOverBQ(OpName); + + //通知web显示 + SendMessageFun.SendMessage("123", "111", OpName); + //MIS_BASE.Read_PalletInfo(OpName, out MES_QualityMask);//合格标志 合格标志暂时改为即时响应式的 + //MIS_BASE.Read_RepairStatus_PLC(OpName, out RepairPartStatusPLC);//返修标志 + //SendMessageFun.SendInfomation("QualityMask", Convert.ToString(MES_QualityMask), OpName);//显示合格标志 + //SendMessageFun.SendInfomation("RepairPartStatusPLC", Convert.ToString(RepairPartStatusPLC), OpName);//显示返修标志 + MIS_BASE.Read_TagTypeID(201, OpName, out string EngineTypeID_QiaoKe); + + Db.OP50_OPA90_MatchResult(EngineTypeID, Convert.ToInt32(EngineTypeID_QiaoKe), EngineID, OrderForm, out int MatchResult, out string MatchResultStr); + if (MatchResult == 1) + { + // 轮毂线 + MIS_BASE.Write_Match(OpName, true);// 匹配结果 + MIS_BASE.Write_MatchingCompleted(OpName, true);// 匹配完成 + MIS_BASE.Write_FixAllow(OpName, true); // 允许工作 + return; + } + else if (MatchResult == 2) // 分等待状态 与 报警状态 等待的话就等A60 工作完成时判断清除等待 写入A90 的匹配结果 匹配完成 允许工作 + { + MIS_BASE.WritePLC(29, OpName, true); // 开始等待 通知A60 保存完成时更新下等待状态与匹配状态 + return; + } + else + { + // 将根据轮毂号 工位号 时间 报错内容 存储到数据库中供查询 + BaseDataSystemMES.HeLi_OoNameAlarmRecord_Add(OpName, EngineID, MatchResultStr); + // 匹配结果不成功 + MIS_BASE.Write_Match(OpName, false);// 匹配结果 + MIS_BASE.Write_MatchingCompleted(OpName, true);// 匹配完成 + return; + } + + + + + + //// 判断分线是否 传递机型 + //if (EngineGetOver_SubLine) + //{ + // string EngineTypeID_MainLine; + // int EngineTypeID_MainLineQiaoKe; + // // 读取主线桥壳机型 + // MIS_BASE.Read_EngineTypeID(OpName_MainLine, out EngineTypeID_MainLineQiaoKe); + // // 读取分线存储的桥壳机型 + // MIS_BASE.Read_TagTypeID(38, OpName_SubLine, out EngineTypeID_MainLine); + + // if (Convert.ToInt32(EngineTypeID_MainLine) == EngineTypeID) + // { + // Db.OP50_OPA90_MatchResult(EngineTypeID, Convert.ToInt32(EngineTypeID_MainLine), EngineTypeID_MainLineQiaoKe, out int MatchResult); + + // if (MatchResult == 0) // 不匹配 + // { + // // 主线 + // MIS_BASE.Write_Match(OpName_MainLine, false);// 匹配结果 + // MIS_BASE.Write_MatchingCompleted(OpName_MainLine, false);// 匹配完成 + // MIS_BASE.Write_FixAllow(OpName_MainLine, false); // 允许工作 + // // 分线 + // MIS_BASE.Write_Match(OpName_SubLine, false);// 匹配结果 + // MIS_BASE.Write_MatchingCompleted(OpName_SubLine, false);// 匹配完成 + // MIS_BASE.Write_FixAllow(OpName_SubLine, false); // 允许工作 + + // // 写入分线 等待 0 + // MIS_BASE.WritePLC(29, OpName_SubLine, "0"); + // } + // if (MatchResult == 1) // 允许抓 + // { + // // 主线 + // MIS_BASE.Write_Match(OpName_MainLine, true);// 匹配结果 + // MIS_BASE.Write_MatchingCompleted(OpName_MainLine, true);// 匹配完成 + // // 分线 + // MIS_BASE.Write_Match(OpName_SubLine, true);// 匹配结果 + // MIS_BASE.Write_MatchingCompleted(OpName_SubLine, true);// 匹配完成 + // MIS_BASE.Write_FixAllow(OpName_MainLine, true); // 允许工作 + + // // 写入分线 等待 0 + // MIS_BASE.WritePLC(29, OpName_SubLine, "0"); + // } + // if (MatchResult == 2) // 等待 + // { + // // 写入分线 等待 1 + // MIS_BASE.WritePLC(29, OpName_SubLine, "1"); + // } + // } + // else // 不匹配 + // { + // // 主线 + // MIS_BASE.Write_Match(OpName_MainLine, false);// 匹配结果 + // MIS_BASE.Write_MatchingCompleted(OpName_MainLine, false);// 匹配完成 + // MIS_BASE.Write_FixAllow(OpName_MainLine, false); // 允许工作 + // // 分线 + // MIS_BASE.Write_Match(OpName_SubLine, false);// 匹配结果 + // MIS_BASE.Write_MatchingCompleted(OpName_SubLine, false);// 匹配完成 + // MIS_BASE.Write_FixAllow(OpName_SubLine, false); // 允许工作 + + // // 写入分线 等待 0 + // MIS_BASE.WritePLC(29, OpName_SubLine, "0"); + // } + //} + } + + /// + /// 二次工作 + /// + /// + private void EngineTypeGetOver_PLC_Work_two(string OpName) + { + int EngineTypeID;//机型代码 + int PartPallet_Code;//托盘编号 + + string EngineType;//机型 + string EngineID;//工件编号 + string OrderForm; + MIS_BASE.GetEngineTypeFromPLC(OpName, out EngineTypeID, out EngineType, out EngineID, out PartPallet_Code, out OrderForm); + EngineTypeGetOver_PLC_Work(OpName, EngineTypeID, EngineType, EngineID, Convert.ToInt32(PartPallet_Code), OrderForm); + + } + /// + /// 跳过二次工作 + /// + /// + private void EngineTypeGetOver_PLC_Work_Skip(string OpName) + { + MIS_BASE.Write_MesReadOver(OpName, true); + MIS_BASE.Write_MaterialVerifyOver(OpName, true); + } + + /// + /// 返修件需要工作 + /// + /// 工位号 + private void IsNeedRepaire_OK(string OpName) + { + string orderForm = ""; + int engineTypeID; + string engineType = ""; + string engineID = ""; + string palletCode = ""; + int isRepair; + string repairCode = ""; + //从监控系统中查询出本工位信息 + BaseDataSystemMES.OpName_MIS_Moby_Select(OpName, + out orderForm, out engineTypeID, out engineType, + out engineID, out palletCode, out isRepair, out repairCode); + + EngineTypeGetOver_PLC_Work(OpName, engineTypeID, engineType, engineID, Convert.ToInt32(palletCode), orderForm); + } + + + + + } +} diff --git a/MisDataFunction/MesServer.Function/Function1054/Methods/SubmitToMisweb.cs b/MisDataFunction/MesServer.Function/Function1054/Methods/SubmitToMisweb.cs new file mode 100644 index 0000000..52ce16f --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1054/Methods/SubmitToMisweb.cs @@ -0,0 +1,127 @@ +using System; +using bizFacade; +//using SystemFramework; + +namespace MesServerFunctions +{ + + /// + /// 此类用于向WEB发送各种类型消息 + /// + partial class FunctionMES + { + + /// + /// 批量发送WEB消息(Value为BOOL值) + /// + /// 消息编号组合 + /// 消息值组合 + /// 工位号 + void Sendmessage(string MessageNumm,string Value, string OpName) + { + for (int i=0;i + /// 选择发送给WEB的消息 + /// + /// 消息类型 + /// 消息工位 + string Sendmessage(char Num,string Value, string OpName) + { + string SendMessage; + string result = ""; + switch (Num) + { + case '1': + //1(直接在界面通过选择机型确认工序内容) + SendMessage = "MES|ProcessList|" + OpName + "|" + Value; + result = AsyncSendMessage(SendMessage); + break; + case '2': + //2显示物料 + SendMessage = "MES|MaterialList|" + OpName + "|" + Value; + result = AsyncSendMessage(SendMessage); + break; + case '3': + //3显示操作指导图片 + SendMessage = "MES|PicShow|" + OpName + "|" + Value; + result = AsyncSendMessage(SendMessage); + break; + case '4': + //4订单完工模块刷新完成数量 + SendMessage = "MES|OrderFormList|" + OpName + "|" + Value; + AsyncSendMessage(SendMessage); + break; + case '5': + SendMessage = "MES|ShowMoby|" + OpName + "|" + Value; + result = AsyncSendMessage(SendMessage); + break; + case '6': + SendMessage = "MES|MaterialCheckPosition|" + OpName + "|" +Value; + result = AsyncSendMessage(SendMessage); + break; + case '7': + SendMessage = "MES|WorkStart|" + OpName + "|" + Value; + result = AsyncSendMessage(SendMessage); + break; + case '8'://清除MES生成编号 + + break; + case '9': + SendMessage = "MES|ConfirmOkGo|" + OpName + "|" + Value; + result = AsyncSendMessage(SendMessage); + break; + case 'a': + SendMessage = "MES|FixAllow|" + OpName + "|" + Value; + result = AsyncSendMessage(SendMessage); + break; + } + return result; + } + /// + /// 向WEB发送信息(value为字符串) + /// + /// 消息种类 + /// 消息内容 + /// 工位号 + string SendInfomation(string Command, string Value, string OpName) + { + string SendMessage = "MES|" + Command + "|" + OpName + "|" + Value; + return AsyncSendMessage(SendMessage); + } + + + /// + /// 发送在线产量、在线节拍 + /// + /// + /// + private void SendActuallyCount(string OpName, int tagValue) + { + //当工件离开时,更新在线产量、在线节拍 + if (tagValue == 0) + { + try + { + int opNameCount = 0;//在线产量 + int opNameCountTime = 0;//在线节拍 + //基本数据_工作日历_班次产量查询_New + BaseDataSystemMES.OpNameCount_New(OpName, out opNameCount, out opNameCountTime); + string SendMessage; + SendMessage = "MES|ActuallyCount|" + OpName + "|" + opNameCount.ToString() + "&" + opNameCountTime.ToString(); + AsyncSendMessage(SendMessage); + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:SendActuallyCount"); + } + } + } + + + } +} diff --git a/MisDataFunction/MesServer.Function/Function1054/Methods/UDP.Send.cs b/MisDataFunction/MesServer.Function/Function1054/Methods/UDP.Send.cs new file mode 100644 index 0000000..aed7cc3 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1054/Methods/UDP.Send.cs @@ -0,0 +1,53 @@ +using bizFacade; +//using SystemFramework; +using MesServerWork; +using DataLinkMesWork; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 发送信息到MES通讯服务器或者其他的 + /// + /// + private string AsyncSendMessage(string Message) + { + return MIS_BASE.asyncSendMessage(Message); + } + + /// + /// 发送提示消息 + /// + /// + private void AsyncSendMessage_Notice(string opname, string notice) + { + //通知Web界面 + BaseDataSystemMES.Web_Notice_Insert(opname, notice); + string SendMessage = "MES|Notice|" + opname + "|" + "1"; + MIS_BASE.asyncSendMessage(SendMessage); + } + + /// + /// 发送信息到打印机 + /// + /// + private void asyncSendMessageToMark(string Message) + { + string messageSend = (string)Message; + //UDPClientSend.Send_ALL(ApplicationConfig.MES_MarkPortNum, messageSend); + } + + /// + /// 发送信息到LED + /// + /// + private void asyncSendMessageLED(string OpName) + { + //发送到大屏幕显示 41104 + string strMessage = "MIS|" + OpName + "|" + "0" + "|" + "1"; + //UDPClientSend.Send_ALL(ApplicationConfig.Port_ShowLED_ProductCount, strMessage); + + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1054/Methods/vssver2.scc b/MisDataFunction/MesServer.Function/Function1054/Methods/vssver2.scc new file mode 100644 index 0000000..7782f6f Binary files /dev/null and b/MisDataFunction/MesServer.Function/Function1054/Methods/vssver2.scc differ diff --git a/MisDataFunction/MesServer.Function/Function1054/OpcServer/Barcode.cs b/MisDataFunction/MesServer.Function/Function1054/OpcServer/Barcode.cs new file mode 100644 index 0000000..1f9ea05 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1054/OpcServer/Barcode.cs @@ -0,0 +1,90 @@ +using System; +using System.Windows.Forms; +using bizFacade; +//using SystemFramework; +using MesServerWork; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + ///1.扫描配送单号,用于接收物料,扫描单号的时候,将接收的物料信息显示在“物料拉动”Tab区域 + ///2.扫描料箱标签/看板卡,用于追溯物料批次信息 + ///3.扫描零件条码,根据零件图号进行防错 + ///第一步,判断条码类型,根据条码类型,执行对应的存储过程 + ///第二步,条码类型(将扫描的条码保存到对应的表中) + ///第三步,扫描完成之后给出允许工作信号 + /// 处理页面扫描条码 + /// + /// + /// + public void Barcode(object e) + { + + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + string barcode = Convert.ToString(msgEvent.TagValue); + string AlarmStr = ""; + + int IsAllowWork; + bool IsSuccess = false; + bool EngineGetOver_PLC_NextWorkStep; + //传递机型是否到位 + MIS_BASE.Read_EngineGetOver_PLC(OpName, out EngineGetOver_PLC_NextWorkStep); + if (!EngineGetOver_PLC_NextWorkStep) + { + SendMessageFun.AsyncSendMessage_Notice(OpName, "PLC未传递机型"); + return; + } + //物料验证 + BaseDataSystemMES.PartMaterial_DM_Update(OpName, barcode, out IsSuccess); + if (!IsSuccess) + { + SendMessageFun.AsyncSendMessage_Notice(OpName, "条码无效,请确认"); + return; + } + else + { + SendMessageFun.SendInfomation("MaterialList", "1", OpName);//通知界面更新零件信息 + } + + + + + //获取是否允许工作 + BaseDataSystemMES.MesServer_Judge_IsCanWork(OpName, out IsAllowWork); + + //此处逻辑有问题 需要考虑到批次扫描 提示PLC未传递机型的情况 + if (IsAllowWork == 1) + { + //BaseDataSystemMES.Material_Insert(OpName, 1); + + //更新订单完工数量及物料 + SendMessageFun.SendMessage("24", "11", OpName); + + //通知PLC允许工作,允许工作在保存完成时清空 + MIS_BASE.Write_FixAllow(OpName, true); + } + else + { + SendMessageFun.AsyncSendMessage_Notice(OpName, "请扫描物料!"); + } + + + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:Barcode"); + } + + } + + } + + + } +} diff --git a/MisDataFunction/MesServer.Function/Function1054/OpcServer/ConfirmOkGo.cs b/MisDataFunction/MesServer.Function/Function1054/OpcServer/ConfirmOkGo.cs new file mode 100644 index 0000000..06e6b33 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1054/OpcServer/ConfirmOkGo.cs @@ -0,0 +1,41 @@ +using System; +using bizFacade; +//using SystemFramework; +using MesServerWork; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 合格放行 + /// + /// + /// + private void ConfirmOkGo(object e) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + + if (tagValue == 1) + { + + BaseDataSystemMES.Material_Insert(OpName, 1); + + //更新订单完工数量及物料 + Sendmessage("24", "11", OpName); + + //工作完成 + MIS_BASE.Write_MaterialVerifyOver(OpName, true); + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:ConfirmOkGo"); + } + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1054/OpcServer/EngineGetOver.cs b/MisDataFunction/MesServer.Function/Function1054/OpcServer/EngineGetOver.cs new file mode 100644 index 0000000..59d2445 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1054/OpcServer/EngineGetOver.cs @@ -0,0 +1,79 @@ +using System; +using System.Data; +using System.Windows.Forms; +using System.Xml.Linq; +using bizFacade; +//using SystemFramework; +using MesServerWork; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// PLC传递机型处理 + /// + /// + /// + private void EngineTypeGetOver_PLC(object e) + { + + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + + if (tagValue == 1) + { + int EngineTypeID;//机型代码 + int PartPallet_Code;//托盘编号 + + string EngineType;//机型 + string EngineID;//工件编号 + string OrderForm; + MIS_BASE.GetEngineTypeFromPLC(OpName, out EngineTypeID, out EngineType, out EngineID, out PartPallet_Code, out OrderForm); + + if (EngineTypeID <= 0 || EngineID.Length == 0 || EngineType.Length == 0) + { + SendMessageFun.AsyncSendMessage_Notice(OpName, "PLC传递机型为空"); + return; + } + + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.EngineTypeID, EngineTypeID.ToString()); + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.EngineType, EngineType); + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.EngineID, EngineID); + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.OrderForm, OrderForm); + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.PartPallet_Code, PartPallet_Code.ToString()); + + //显示当前订单信息 + SendMessage.ShowMoby(OpName); + //判断该订单数据是否已经工作过,有的话则在WEB跳出弹窗选择 并同时禁止工作 + //DataTable dt2 = BaseDataSystemMES.EngineIsTwoWork(OpName, OrderForm, EngineID); + //if (dt2.Rows[0]["result"].ToString() == "1") //已完成 + //{ + // //不允许工作 + // MIS_BASE.Write_FixAllow(OpName, false); + // //通知WEB校验重新工作还是跳过 点重新工作给允许工作,点跳过给工作完成 + // string message = "MES|Engine_Is_TwoWork|" + OpName + "|1"; + // SendMessage.AsyncSendMessage(message); + //} + //else + //{ + // EngineTypeGetOver_PLC_Work(OpName, EngineTypeID, EngineType, EngineID, PartPallet_Code, OrderForm); + //} + EngineTypeGetOver_PLC_Work(OpName, EngineTypeID, EngineType, EngineID, PartPallet_Code, OrderForm); + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:EngineTypeGetOver_PLC"); + } + } + + + } + + } +} diff --git a/MisDataFunction/MesServer.Function/Function1054/OpcServer/FalseGO.cs b/MisDataFunction/MesServer.Function/Function1054/OpcServer/FalseGO.cs new file mode 100644 index 0000000..14b5771 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1054/OpcServer/FalseGO.cs @@ -0,0 +1,46 @@ +using System; +using System.Data; +using System.Windows.Forms; +using System.Xml.Linq; +using bizFacade; +//using SystemFramework; +using MesServerWork; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 不合格放行 + /// + /// + /// + private void FalseGO(object e) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + + if (tagValue == 1) + { + //不合格放行信号 + //MIS_BASE.Write_FalseGO(OpName, true); + //总合格标志2(不合格) + + BaseDataSystemMES.Material_Insert_NG(OpName, 2); + + Sendmessage("24", "11", OpName); + + //工作完成 + MIS_BASE.Write_MaterialVerifyOver(OpName, true); + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:FalseGO"); + } + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1054/OpcServer/HeartBeat.cs b/MisDataFunction/MesServer.Function/Function1054/OpcServer/HeartBeat.cs new file mode 100644 index 0000000..93affd3 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1054/OpcServer/HeartBeat.cs @@ -0,0 +1,35 @@ +using bizFacade; +using MesServerWork; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// MES与PLC心跳监听 + /// + /// + /// + private void HeartBeat(object e) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + + //返写在MES心跳中 + MIS_BASE.WritePLC(15, OpName, tagValue); + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:FalseGO"); + } + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1054/OpcServer/MesRead.cs b/MisDataFunction/MesServer.Function/Function1054/OpcServer/MesRead.cs new file mode 100644 index 0000000..f2065d0 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1054/OpcServer/MesRead.cs @@ -0,0 +1,68 @@ +using bizFacade; +using MesServerWork; +using System; +//using SystemFramework; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 允许保存(针对半自动和手动压装工位) + /// + /// + /// + private void MesRead(object e) + { + { + try + { + + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + + if (tagValue == 1) + { + MIS_BASE.Read_EngineID(OpName, out string EngineID); + int qualityMask; + // 保存质量数据 + qualityMask = MisDataSaveDateMesRead.Funtion.MesRead(OpName, tagValue.ToString(), msgEvent.TagID.ToString()); + // 保存物料数据 + BaseDataSystemMES.Material_Insert(OpName, qualityMask); + + // 测量数据发动机在线状态 + BaseDataSystemMES.WorkStartInsert(OpName, qualityMask); + + // 推送质量数据到MES的页面 + SendMessageFun.SendInfomation("ShowTimelyQuality", "1&" + qualityMask.ToString(), OpName); + + //对应手动工位的 + //MIS_BASE.Write_ConfirmOkGo(OpName, true); + //通知设备,MES的质量数据(和物料数据)保存完成 + MIS_BASE.Write_MesReadOver(OpName, true); + MIS_BASE.Write_MaterialVerifyOver(OpName, true); + //统计在线产量,在线节拍 + //SendMessage.SendActuallyCount(OpName, tagValue); + + MesFunctions.EnginePart_OutStation(OpName, EngineID, qualityMask); + } + else + { + MIS_BASE.Write_MesReadOver(OpName, false); + + } + } + + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function08:MesReadOver"); + } + } + + } + + } +} diff --git a/MisDataFunction/MesServer.Function/Function1054/OpcServer/MesReadOver.cs b/MisDataFunction/MesServer.Function/Function1054/OpcServer/MesReadOver.cs new file mode 100644 index 0000000..f96a7d3 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1054/OpcServer/MesReadOver.cs @@ -0,0 +1,55 @@ +using System; +//using SystemFramework; +using MesServerWork; +using bizFacade; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 保存完成(针对半自动和手动压装工位) + /// + /// + /// + private void MesReadOver(object e) + { + //try + //{ + // DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + // string OpName = Convert.ToString(msgEvent.OpName); + // var tagValue = msgEvent.TagValue.ToString (); + + // if (tagValue == "1" | tagValue.ToLower () == "true") + // { + // int qualityMask; + // MIS_BASE.Read_QualityMask(OpName, out qualityMask); + + // SendInfomation("ShowTimelyQuality", "1&" + qualityMask.ToString(), OpName);//发给Web页面显示质量数据 + + // if (qualityMask == 1)//全部OK,给出合格放行 + // { + // //如果存在线外扫描工位,根据扫描条码绑定线外数据 需要时解除禁用 + // //BaseDataSystemMES.TransLaunchDataByMainMaterial(OpName, EngineType, EngineID, EngineTypeID); + + // //如果存在线外排队工位,根据排队编号绑定线外数据 需要时解除禁用 + // ////BaseDataSystemMES.MailLineAndSubLineData_InsertByEngineID_Subline(OpName,EngineID, EngineTypeID, EngineType); + + // MIS_BASE.Write_ConfirmOkGo(OpName, true); + // //MIS_BASE.Write_FalseGO(OpName, false); + // } + // else + // { + // //MIS_BASE.Write_ConfirmOkGo(OpName, false); + // MIS_BASE.Write_FalseGO(OpName, true); + // } + + // } + //} + //catch (Exception err) + //{ + // ////ApplicationLog.WriteLog(err, "Function02:MesReadOver"); + //} + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1054/OpcServer/MesSaveNowData.cs b/MisDataFunction/MesServer.Function/Function1054/OpcServer/MesSaveNowData.cs new file mode 100644 index 0000000..63c11b3 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1054/OpcServer/MesSaveNowData.cs @@ -0,0 +1,40 @@ +using bizFacade; +using MesServerWork; +using System; +using System.Collections.Generic; +using System.Data; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; +using static System.Net.Mime.MediaTypeNames; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// MES保存实时质量数据 + /// + /// + /// + private void MesSaveNowData(object e) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + // 直接发送实时的 质量数据 + string message = MisDataSaveDateMesRead.Funtion.GetRealTimeQualityData(OpName); + //推送质量数据到MES的页面 + SendMessage.AsyncSendMessage("MES|ShowTimelyQuality_Resources|" + OpName + "|" + message); + //SendMessageFun.SendMessageMESToWEB("ShowTimelyQuality", "1&" + qualityMask.ToString(), OpName); + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:FalseGO"); + } + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1054/OpcServer/WebSubmit.cs b/MisDataFunction/MesServer.Function/Function1054/OpcServer/WebSubmit.cs new file mode 100644 index 0000000..d7ca28c --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1054/OpcServer/WebSubmit.cs @@ -0,0 +1,304 @@ +using System; +using MesServerWork; +using bizFacade; +using System.Threading; +using MisDataSaveDate; +using System.Collections; +//using SystemFramework; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 处理WEB页面发送过来的请求(m_Command + "|" + m_Value;) + /// + /// + /// + private void WebSubmit(object e) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName=Convert.ToString(msgEvent.OpName); + string Content = Convert.ToString(msgEvent.TagValue); + + string[] dataArray = Content.Split('|'); + if (dataArray.Length != 2) + return; + //消息类型 + string m_Command = dataArray[0].ToString(); + //消息参数 + string m_Value = dataArray[1].ToString(); + //消息参数数量 + string[] m_Value_array = m_Value.Split('&'); + //消息参数长度 + int m_Value_length = m_Value_array.Length; + + //工件信息 + string engineID = ""; + if (MIS_BASE.hashtable_EngineGetOver_EngineTypeID == null) + { + MIS_BASE.InitHashtable_MesServerCode(); + } + if (MIS_BASE.hashtable_EngineGetOver_EngineTypeID == null) + { + return; + } + if (MIS_BASE.hashtable_EngineGetOver_EngineID.ContainsKey(OpName)) + { + engineID = MIS_BASE.hashtable_EngineGetOver_EngineID[OpName].ToString(); + } + + DoWhatPlc.CustomeEvetnArgs _e = new DoWhatPlc.CustomeEvetnArgs(); + _e.OpName = OpName; + _e.TagValue = m_Value; + + //根据请求的命令处理逻辑 + switch (m_Command) + { + case "Barcode": + if (m_Value_length > 1) return; + fun_Barcode(_e); + break; + case "ConfirmOkGo"://合格放行 + //删除不合格放行记录 + //修改托盘状态 + //Update_PalletStatus(OpName, 1, false); + BaseDataSystemMES.BaseData_tagTable_Engine_IsNG_Delete(OpName, engineID); + MIS_BASE.Write_ConfirmOkGo(OpName, true); + MIS_BASE.Write_FalseGO(OpName, false); + + Thread.Sleep(1000); + MIS_BASE.Write_ConfirmOkGo(OpName, false); + break; + case "FalseGO"://返修放行 + //修改托盘状态 + //Update_PalletStatus(OpName, 3, false); + BaseDataSystemMES.BaseData_tagTable_Engine_IsNG_Delete(OpName, engineID); + MIS_BASE.Write_FalseGO(OpName, true); + MIS_BASE.Write_ConfirmOkGo(OpName, false); + + Thread.Sleep(1000); + MIS_BASE.Write_FalseGO(OpName, false); + break; + case "NgGO"://不合格放行 + //修改托盘状态 + //Update_PalletStatus(OpName, 2, false); + //保存不合格信息(必须保存不合格放行信息,由于B5A的Moby没有不合格标志位) + BaseDataSystemMES.BaseData_tagTable_Engine_IsNG_Insert(OpName, engineID, "", ""); + MIS_BASE.Write_FalseGO(OpName, true); + MIS_BASE.Write_ConfirmOkGo(OpName, false); + Thread.Sleep(1000); + MIS_BASE.Write_FalseGO(OpName, false); + break; + case "OnLineState"://在线0、离线1、屏蔽2 + try + { + if (m_Value_length > 1) return; + int a = Convert.ToInt32(m_Value); + if (a <= 2) + { + BaseDataSystemMES.IsOnLine_Update(OpName, m_Value.ToString()); + MIS_BASE.Write_OnLineState(OpName, Convert.ToInt32(m_Value)); + if (a == 2) SendMessage.AsyncSendMessage_Notice(OpName, "屏蔽MES!"); + if (a == 0) SendMessage.AsyncSendMessage_Notice(OpName, "启用MES!"); + } + } + catch + { + + } + break; + case "Reset"://复位,将MES所有的信息都复位了 + SetMoby(OpName);//将MES所有信号清空 + break; + case "FixAllow"://重新拧紧 + MIS_BASE.Write_FixAllow(OpName, false); + MIS_BASE.Write_FixAllow(OpName, true); + break; + case "IsAutoGetEngineID"://自动手动申请编号(线首) + if (m_Value_length > 1) return; + MIS_BASE.Write_IsAutoGetEngineID(OpName, Convert.ToInt32(m_Value)); + break; + case "PartPalletGoOver"://空托盘放行 + int Is_PartPalletGoOver; + MIS_BASE.Read_PartPalletGoOver(OpName, out Is_PartPalletGoOver); + if (Is_PartPalletGoOver == 1) + { + MIS_BASE.Write_PartPalletGoOver(OpName, 1); + } + else + { + MIS_BASE.Write_PartPalletGoOver(OpName,0); + } + break; + case "SetMoby"://清空托盘(线首) + SetMoby(OpName);//将MES所有信号清空 + //MIS_BASE.Write_PartPalletCode_PLC(OpName, 1); + break; + case "RepairUplineMES"://返修上线 + MIS_BASE.Write_RepairUpline_MES(OpName, true); + break; + case "CancelRepair"://将返修件置为正常件 + + break; + case "PartPalletCode"://申请写入托盘号 + //MIS_BASE.Write_PartPalletCode_PLC(OpName, 1); + break; + case "WritePartPalletCode"://写入托盘号 + if (m_Value_length > 1) return; + MIS_BASE.Write_PalletCode(OpName, Convert.ToInt32(m_Value)); + break; + case "Normal"://启用正常拧紧工位 + MIS_BASE.Write_Normal(OpName, 1); + MIS_BASE.Write_UnNormal(OpName, 0); + break; + case "UnNormal"://启用备用拧紧工位 + MIS_BASE.Write_Normal(OpName, 0); + MIS_BASE.Write_UnNormal(OpName, 1); + break; + case "ResetDevice"://复位设备 + MIS_BASE.Write_ResetDevice(OpName, true); + System.Threading.Thread.Sleep(1000); + MIS_BASE.Write_ResetDevice(OpName, false); + break; + case "IsNeedRepaire"://返修上线(返修上线点) + if (Convert.ToInt32(m_Value) == 1) + { + //修改托盘状态 + MIS_BASE.Write_PalletInfo(OpName, 3); + //通知修改成功 + MIS_BASE.Write_UpdatePalletOK(OpName, true); + IsNeedRepaire_OK(OpName); + + } + else if (Convert.ToInt32(m_Value) == 0) + { + //通知修改成功 + MIS_BASE.Write_UpdatePalletOK(OpName, true); + //直接给出工作完成 + MIS_BASE.Write_MaterialVerifyOver(OpName, true); + } + else + { } + + break; + case "ContinueMatch": + BaseDataSystemMES.QualityVerifyStatus_Hash_Write(OpName, true); + break; + //初始化网页信号 + case "IniSingalToWeb": + InitializeSingalToWeb(OpName); + break; + case "Reset_Engine"://返修上线(返修上线点) + SetMoby(OpName);//将MES所有信号清空 + //fun_EngineTypeGetOverPLC(OpName, 0); + //fun_EngineTypeGetOverPLC(OpName, 1); + break; + + case "twoWorkSkip"://重新工作工件跳过工作(重新工作工件) + //工作完成 + EngineTypeGetOver_PLC_Work_Skip(OpName); + break; + case "twoWork"://重新工作工件重新工作(重新工作工件) + //允许工作 + EngineTypeGetOver_PLC_Work_two(OpName); + break; + + default: break; + } + } + catch(Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:WebSubmit"); + } + } + private void SetMoby(string OpName) + { + try + { + //清空Moby时,需要将MES信号清空 + MIS_BASE.Write_ClearMesMoby(OpName); + + BaseDataSystemMES.MesServer_Process_EngineTypeOver(OpName); + + Sendmessage("5123", "1111", OpName); + + MIS_BASE.Write_ResetDevice(OpName, true); + System.Threading.Thread.Sleep(1000); + MIS_BASE.Write_ResetDevice(OpName, false); + } + catch + { + + } + } + /// 网页重现登录,恢复关闭前的页面状态 + /// + /// 工位号 + private void InitializeSingalToWeb(string Opname) + { + + //工件到位 DBX0.1 + bool S_WorkStart; + bool S_FixAllow; + bool S_EngineGetOver; + bool S_MaterialVerifyOver; + + MIS_BASE.Read_WorkStart(Opname, out S_WorkStart); + MIS_BASE.Read_FixAllow(Opname, out S_FixAllow); + MIS_BASE.Read_EngineGetOver_PLC(Opname, out S_EngineGetOver); + MIS_BASE.Read_MaterialVerifyOver(Opname, out S_MaterialVerifyOver); + + Sendmessage("13", "1111", Opname); + string S_plcStatus;//DBX501.5 PLC直通,1 强制放行 0 正常循环 + // 新增查询PLC直通状态 网页显示 + MIS_BASE.Read_TagTypeID(63, Opname, out S_plcStatus); + if (S_plcStatus.ToLower() == "false") + { + SendMessageFun.SendInfomation("PlcStatus", "0", Opname); + } + else + { + SendMessageFun.SendInfomation("PlcStatus", "1", Opname); + } + + if (S_WorkStart == true) + { + SendInfomation("WorkStart", Convert.ToString(Convert.ToInt32(S_WorkStart)), Opname); + } + if (S_FixAllow == true) + { + SendInfomation("FixAllow", Convert.ToString(Convert.ToInt32(S_FixAllow)), Opname); + } + if (S_MaterialVerifyOver == true) + { + SendInfomation("MaterialVerifyOver", Convert.ToString(Convert.ToInt32(S_MaterialVerifyOver)), Opname); + } + if (S_EngineGetOver == true) + { + SendInfomation("EngineTypeGetOverPLC", Convert.ToString(Convert.ToInt32(S_EngineGetOver)), Opname); + Sendmessage("2", "1111", Opname); + SendMessage.ShowMoby(Opname); + // 直接发送实时的 质量数据 + string message = MisDataSaveDateMesRead.Funtion.GetRealTimeQualityData(Opname); + //推送质量数据到MES的页面 + SendMessage.AsyncSendMessage("MES|ShowTimelyQuality_Resources|" + Opname + "|" + message); + } + InitAlarm(Opname); + } + + private void InitAlarm(string Opname) + { + FuntionMesRead.Alarm_InitAlarm_Send(Opname, out Hashtable ht); + foreach (DictionaryEntry kv in ht) + { + var TagID = kv.Key.ToString(); + var TagValue = kv.Value.ToString(); + FuntionMesRead.Send_AlarmMsg(TagID, TagValue); + } + + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1054/OpcServer/WorkIsOk.cs b/MisDataFunction/MesServer.Function/Function1054/OpcServer/WorkIsOk.cs new file mode 100644 index 0000000..08819e3 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1054/OpcServer/WorkIsOk.cs @@ -0,0 +1,45 @@ +using bizFacade; +using MesServerWork; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 工位合格标志 + /// + /// + /// + private void IsOk(object e) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + + int qualityMask; + MIS_BASE.Read_QualityMask(OpName, out qualityMask); + //判断是否合格 + if (qualityMask == 1) + { + qualityMask = 1; + } else { + qualityMask = 0; + } + //通知WEB修改状态 + string message = "MES|QualityMask|" + OpName + "|" + qualityMask.ToString(); + SendMessage.AsyncSendMessage(message); + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:FalseGO"); + } + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1054/OpcServer/WorkStart.cs b/MisDataFunction/MesServer.Function/Function1054/OpcServer/WorkStart.cs new file mode 100644 index 0000000..14c05a5 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1054/OpcServer/WorkStart.cs @@ -0,0 +1,50 @@ +using bizFacade; +using MesServerWork; +using System; +using System.Threading; +//using SystemFramework; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 工件到位与离开时,清空MES自身信号 + /// + /// + /// + private void WorkStart(object e) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + if (tagValue > 0) + { + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.WorkStartIn, DateTime.Now.ToString()); + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.WorkStart, tagValue.ToString()); + } + else + { + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.WorkStartOut, DateTime.Now.ToString()); + MIS_BASE.Write_MesReadOver(OpName, false); + MIS_BASE.Write_ConfirmOkGo(OpName, false); + MIS_BASE.Write_FixAllow(OpName, false); + MIS_BASE.Write_ConfirmOkGo(OpName, false); + MIS_BASE.Write_EngineTypeGetOver_MES(OpName, false); + //工作完成 + MIS_BASE.Write_MaterialVerifyOver(OpName, false); + + // 写入分线 等待 0 + MIS_BASE.WritePLC(29, "OPA90", "0"); + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:WorkStart"); + } + } + + } +} diff --git a/MisDataFunction/MesServer.Function/Function1054/OpcServer/vssver2.scc b/MisDataFunction/MesServer.Function/Function1054/OpcServer/vssver2.scc new file mode 100644 index 0000000..b884d13 Binary files /dev/null and b/MisDataFunction/MesServer.Function/Function1054/OpcServer/vssver2.scc differ diff --git a/MisDataFunction/MesServer.Function/Function1054/Properties/AssemblyInfo.cs b/MisDataFunction/MesServer.Function/Function1054/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..0bb79c4 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1054/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// 有关程序集的常规信息通过以下 +// 特性集控制。更改这些特性值可修改 +// 与程序集关联的信息。 +[assembly: AssemblyTitle("Function02")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("苏州宏软信息技术有限公司")] +[assembly: AssemblyProduct("Function02")] +[assembly: AssemblyCopyright("Copyright © 苏州宏软信息技术有限公司 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// 将 ComVisible 设置为 false 使此程序集中的类型 +// 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型, +// 则将该类型上的 ComVisible 特性设置为 true。 +[assembly: ComVisible(false)] + +// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID +[assembly: Guid("47710f2c-e141-4252-8d13-701bf4c1c027")] + +// 程序集的版本信息由下面四个值组成: +// +// 主版本 +// 次版本 +// 内部版本号 +// 修订号 +// +// 可以指定所有这些值,也可以使用“内部版本号”和“修订号”的默认值, +// 方法是按如下所示使用“*”: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/MisDataFunction/MesServer.Function/Function1054/Properties/vssver2.scc b/MisDataFunction/MesServer.Function/Function1054/Properties/vssver2.scc new file mode 100644 index 0000000..14e543b Binary files /dev/null and b/MisDataFunction/MesServer.Function/Function1054/Properties/vssver2.scc differ diff --git a/MisDataFunction/MesServer.Function/Function1054/app.config b/MisDataFunction/MesServer.Function/Function1054/app.config new file mode 100644 index 0000000..b4c4daf --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1054/app.config @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + + + diff --git a/MisDataFunction/MesServer.Function/Function1054/mssccprj.scc b/MisDataFunction/MesServer.Function/Function1054/mssccprj.scc new file mode 100644 index 0000000..119193d --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1054/mssccprj.scc @@ -0,0 +1,5 @@ +SCC = This is a Source Code Control file + +[Function02.csproj] +SCC_Aux_Path = "\\192.168.0.100\vss\MES4.0" +SCC_Project_Name = "$/MisData/MisData/MisData/MesServer.Function/Function02", ILHAAAAA diff --git a/MisDataFunction/MesServer.Function/Function1054/packages.config b/MisDataFunction/MesServer.Function/Function1054/packages.config new file mode 100644 index 0000000..b3e1761 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1054/packages.config @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/MisDataFunction/MesServer.Function/Function1054/vssver2.scc b/MisDataFunction/MesServer.Function/Function1054/vssver2.scc new file mode 100644 index 0000000..c770e28 Binary files /dev/null and b/MisDataFunction/MesServer.Function/Function1054/vssver2.scc differ diff --git a/MisDataFunction/MesServer.Function/Function1055/DataAccess/DataAccess.cs b/MisDataFunction/MesServer.Function/Function1055/DataAccess/DataAccess.cs new file mode 100644 index 0000000..68cdca4 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1055/DataAccess/DataAccess.cs @@ -0,0 +1,15 @@ + +namespace MesServerFunctions +{ + partial class FunctionMES + { + //针对“MIS.BizFacade.Dll”中没有的存储过程,在此类中新建 + //新建原则:所有的函数用private,只允许在内部使用 + //针对单个工艺特殊,需要新建存储过程,但是存储过程不能被加入到“MIS.BizFacade.Dll”中 + + private void aa() + { + + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1055/DataAccess/vssver2.scc b/MisDataFunction/MesServer.Function/Function1055/DataAccess/vssver2.scc new file mode 100644 index 0000000..d045c26 Binary files /dev/null and b/MisDataFunction/MesServer.Function/Function1055/DataAccess/vssver2.scc differ diff --git a/MisDataFunction/MesServer.Function/Function1055/Db.cs b/MisDataFunction/MesServer.Function/Function1055/Db.cs new file mode 100644 index 0000000..03abc44 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1055/Db.cs @@ -0,0 +1,60 @@ +using System; +using System.Collections.Generic; +using System.Data.SqlClient; +using System.Data; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using DataLinkMesWork; +using System.Net.NetworkInformation; + +namespace MesServerFunctions +{ + public class Db + { + public static bool OP051_OP050_NeedWork(string EngineID, string opName,string orderForm, out int MatchResult) + { + DataTable dt = new DataTable(); + MatchResult = 0; + string produceName = "合力_OP050前停判断_下工位是否需要工作"; + SqlParameter[] thisParms = new SqlParameter[3]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@桥壳总成号", EngineID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@订单号", orderForm); + if (DataAccess.ExecuteStoredProcedure(produceName, ref thisParms, out dt)) + { + if (dt.Rows.Count > 0) + { + MatchResult = Convert.ToInt32(dt.Rows[0]["是否需要工作"]); + return true; + } + } + return false; + } + public static bool OP051_OP050_NeedWork_Save(string EngineID, int MatchResult) + { + + string produceName = "合力_OP050是否需要工作_插入"; + SqlParameter[] thisParms = new SqlParameter[2]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@桥壳总成号", EngineID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@是否需要工作", MatchResult); + return DataAccess.ExecuteStoredProcedure(produceName, ref thisParms); + } + public static bool OPA90_TO_OP50_CheckTwoFinish(out int MainLineAllowWork) + { + DataTable dt; + MainLineAllowWork = 2; + string produceName = "合力_OP050是否允许工作_判断"; + SqlParameter[] thisParms = new SqlParameter[0]; + if (DataAccess.ExecuteStoredProcedure(produceName, ref thisParms, out dt)) + { + if (dt.Rows.Count > 0) + { + MainLineAllowWork = Convert.ToInt32(dt.Rows[0]["是否允许工作"]); + return true; + } + } + return false; + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1055/Function02.csproj.vspscc b/MisDataFunction/MesServer.Function/Function1055/Function02.csproj.vspscc new file mode 100644 index 0000000..0f0f36c --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1055/Function02.csproj.vspscc @@ -0,0 +1,10 @@ +"" +{ +"FILE_VERSION" = "9237" +"ENLISTMENT_CHOICE" = "NEVER" +"PROJECT_FILE_RELATIVE_PATH" = "relative:MesServer.Function\\Function02" +"NUMBER_OF_EXCLUDED_FILES" = "0" +"ORIGINAL_PROJECT_FILE_PATH" = "" +"NUMBER_OF_NESTED_PROJECTS" = "0" +"SOURCE_CONTROL_SETTINGS_PROVIDER" = "PROVIDER" +} diff --git a/MisDataFunction/MesServer.Function/Function1055/Function1055.csproj b/MisDataFunction/MesServer.Function/Function1055/Function1055.csproj new file mode 100644 index 0000000..215c483 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1055/Function1055.csproj @@ -0,0 +1,169 @@ + + + + Debug + AnyCPU + 8.0.30703 + 2.0 + {9DAFA1E7-0DD9-4B59-944B-B03065DAAFF1} + Library + Properties + Function1055 + Function1055 + v4.8 + 512 + + + + + + + + + + + + + + true + full + false + ..\..\..\dll_fun\ + DEBUG;TRACE + prompt + 4 + false + false + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + false + + + + ..\..\..\Common\dll\MQTTnet.dll + + + ..\..\..\Common\dll\MQTTnet.Extensions.ManagedClient.dll + + + False + ..\..\..\Common\dll\Newtonsoft.Json.dll + + + + + + ..\..\DLL\System.Net.Http.dll + + + ..\..\packages\System.Net.Security.4.3.2\lib\net46\System.Net.Security.dll + + + ..\..\packages\System.Net.WebSockets.4.3.0\lib\net46\System.Net.WebSockets.dll + + + ..\..\packages\System.Net.WebSockets.Client.4.3.2\lib\net46\System.Net.WebSockets.Client.dll + + + ..\..\packages\System.Security.Cryptography.Algorithms.4.3.0\lib\net461\System.Security.Cryptography.Algorithms.dll + + + ..\..\packages\System.Security.Cryptography.Encoding.4.3.0\lib\net46\System.Security.Cryptography.Encoding.dll + + + ..\..\packages\System.Security.Cryptography.Primitives.4.3.0\lib\net46\System.Security.Cryptography.Primitives.dll + + + ..\..\packages\System.Security.Cryptography.X509Certificates.4.3.0\lib\net461\System.Security.Cryptography.X509Certificates.dll + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + {f55da1a0-a982-4479-8c47-0d9a5aaf3e18} + 00MesWorkMqtt + + + {0d1af432-439a-4920-8692-43ae139f5530} + 01_01DoWhatPlc + + + {3e6d1dd5-01c9-435f-9941-61f906ce35bb} + 02_02WebApiCallPLC + + + {f434e066-4c59-47c8-aa82-6f48cc84501a} + 04-DataBaseAccess + + + {f0a0c525-03fd-428a-9b17-7f54aa0e4475} + 07BusinessFacade + + + {d98be764-adeb-488d-9714-61e308aa8201} + 08-WebFun_base + + + {90e76fb4-646d-45e2-95db-0b8ab4e465d6} + 09-MesDataFunction + + + {e4eb6420-906d-4672-947a-ca33ddcdadfc} + 12SendMessageToWeb + + + {55b510c1-59e9-4bfd-ae84-d76d46f6e365} + 02-13.3MIS_FuntionSaveData + + + + + + + 这台计算机上缺少此项目引用的 NuGet 程序包。使用“NuGet 程序包还原”可下载这些程序包。有关更多信息,请参见 http://go.microsoft.com/fwlink/?LinkID=322105。缺少的文件是 {0}。 + + + + + \ No newline at end of file diff --git a/MisDataFunction/MesServer.Function/Function1055/MesServerFunction/Fun_1055.cs b/MisDataFunction/MesServer.Function/Function1055/MesServerFunction/Fun_1055.cs new file mode 100644 index 0000000..bd3e090 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1055/MesServerFunction/Fun_1055.cs @@ -0,0 +1,242 @@ +using MesServerWork; +using System.Collections.Generic; +using System.Threading; +using System.Xml.Linq; + +namespace MesServerFunctions +{ + public partial class FunctionMES + { + object lockFunWork; + //public void FunWork(DoWhatPlc.CustomeEvetnArgs e) + public void FunWork(string recData) + { + + + lockFunWork = new object(); + lock (lockFunWork) + { + List dataArray = DoWhatPlc.MessageText.GetCmdStringList(recData); + //string[] dataArray = recData.Split('|'); + //if (dataArray.Count != 4) + //return; + //消息来源 + string m_Source = dataArray[0].ToString(); + //消息类型 Barcode + string m_Command = dataArray[1].ToString(); + //工位号 + string m_OpName = dataArray[2].ToString(); + //消息参数 + string m_Value = dataArray[3].ToString(); + + DoWhatPlc.CustomeEvetnArgs e = new DoWhatPlc.CustomeEvetnArgs();// = Newtonsoft.Json.JsonConvert.DeserializeObject(m_Value); + string tagValue; + + switch (m_Source) + { + case "BarCode": + e.OpName = m_OpName; + e.TagValue = m_Value; + fun_Barcode(e); + break; + case "WEB": + e.OpName = m_OpName; + e.TagValue = m_Command + "|" + m_Value; + fun_WebSubmit(e); + break; + case "PLC": + e = Newtonsoft.Json.JsonConvert.DeserializeObject(m_Value); + switch (e.TagValue.ToString().ToLower()) + { + case "false": + tagValue = "0"; + break; + case "true": + tagValue = "1"; + break; + default: + tagValue = e.TagValue.ToString(); + break; + } + e.TagValue = tagValue; + switch (e.TagTypeCodeID.ToString()) + { + //PLC 工件到位 + case "2": + fun_WorkStart(e); + break; + //PLC 允许保存质量数据 + case "19": + fun_MesRead(e); + break; + //MES 保存数据完成 + case "20": + fun_MesReadOver(e); + break; + //PLC 传递机型 + case "44": + fun_EngineTypeGetOverPLC(e); + break; + //MES 合格放行 + case "51": + fun_ConfirmOkGo(e); + break; + //MES 不合格放行 + case "8": + fun_FalseGo(e); + break; + //PLC 工位合格标志 + case "21": + fun_IsOk(e); + break; + //MES保存实时质量数据 + case "65": + fun_MesSaveNowData(e); + break; + //MES 系统健康心跳 + case "14": + fun_HeartBeatMIS(e); + break; + case "63": + string S_plcStatus;//DBX501.5 PLC直通,1 强制放行 0 正常循环 + MIS_BASE.Read_TagTypeID(63, m_OpName, out S_plcStatus); + if (S_plcStatus.ToLower() != "true" || S_plcStatus.ToLower() == "1") + { + SendMessageFun.SendInfomation("PlcStatus", "0", m_OpName); + } + else + { + SendMessageFun.SendInfomation("PlcStatus", "1", m_OpName); + } + break; + //MES 将MES传递的数据回传到这个变量,如果是人为修改的,也需要更新到这个变量 (DBX589 37) + case "37": + MIS_BASE.WritePLC(77, m_OpName, m_Value); // 回写到MES托盘状态 + MIS_BASE.Write_FixAllow(m_OpName, true); // 允许工作 + break; + } + break; + } + } + } + + //1.工件到位后,PLC给MES传递机型(DBX0.4)(44), + //MES判断条码是否全部扫描完成 + //PLC给出允许保存(DBX100.2)(19),MES见到(DBX100.2)(19)为1后给出保存完成(DBX102.2)(20), + //PLC见到保存完成(DBX102.2)(20)为1后,清空允许保存(DBX100.2)(19), + //MES见到允许保存(DBX100.2)(19)为0后,清空保存完成(DBX102.2)(20) + //MES判断总合格标志(INT104)(21)为1后,给出合格放行(DBX2.5)(51) + /// + /// 扫描条码 + /// + /// + /// + public void fun_Barcode(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(Barcode, e); + } + + /// + /// 传递机型 + /// + /// + /// + public void fun_EngineTypeGetOverPLC(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(EngineTypeGetOver_PLC, e); + } + + /// + /// 合格放行 + /// + /// + /// + public void fun_ConfirmOkGo(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(ConfirmOkGo, e); + } + + /// + /// 不合格放行 + /// + /// + /// + public void fun_FalseGo(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(FalseGO, e); + } + + /// + /// 允许保存 + /// + /// + /// + public void fun_MesRead(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(MesRead, e); + } + + /// + /// 保存完成 + /// + /// + /// + public void fun_MesReadOver(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(MesReadOver, e); + } + + /// + /// 工件到位离开(清空所有的MES信号) + /// + /// + /// + public void fun_WorkStart(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(WorkStart, e); + } + + /// + /// 处理WEB页面发送过来的请求(m_Command + "|" + m_Value;) + /// + /// + /// + public void fun_WebSubmit(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(WebSubmit, e); + } + + + /// + /// 工位是否合格 + /// + /// + /// + public void fun_IsOk(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(IsOk, e); + } + + /// + /// 系统健康心跳监测 + /// + /// + /// + public void fun_HeartBeatMIS(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(HeartBeat, e); + } + + /// + /// MES实时保存质量数据 + /// + /// + /// + public void fun_MesSaveNowData(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(MesSaveNowData, e); + } + + + } +} diff --git a/MisDataFunction/MesServer.Function/Function1055/MesServerFunction/vssver2.scc b/MisDataFunction/MesServer.Function/Function1055/MesServerFunction/vssver2.scc new file mode 100644 index 0000000..a246f67 Binary files /dev/null and b/MisDataFunction/MesServer.Function/Function1055/MesServerFunction/vssver2.scc differ diff --git a/MisDataFunction/MesServer.Function/Function1055/Methods/EngineGetOverBaseWork.cs b/MisDataFunction/MesServer.Function/Function1055/Methods/EngineGetOverBaseWork.cs new file mode 100644 index 0000000..ab76f41 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1055/Methods/EngineGetOverBaseWork.cs @@ -0,0 +1,120 @@ +using System; +using System.Data; +using bizFacade; +using MesServerWork; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 正常逻辑工作(传递机型) + /// + /// + /// + /// + /// + /// + private void EngineTypeGetOver_PLC_Work(string OpName, int EngineTypeID, string EngineType, string EngineID, int PartPallet_Code, string OrderForm) + { + int IsAllowWork; + int RepairPartStatusPLC = 0; + int MES_QualityMask = 1; + + //电子看板_装配零件_临时表_增加_北汽 + //第二步,将零件信息转移到零件_临时表中 + BaseDataSystemMES.MesServer_Process_EngineTypeOverBQ(OpName); + + //通知web显示 + SendMessageFun.SendMessage("123", "111", OpName); + //MIS_BASE.Read_PalletInfo(OpName, out MES_QualityMask);//合格标志 合格标志暂时改为即时响应式的 + //MIS_BASE.Read_RepairStatus_PLC(OpName, out RepairPartStatusPLC);//返修标志 + //SendMessageFun.SendInfomation("QualityMask", Convert.ToString(MES_QualityMask), OpName);//显示合格标志 + //SendMessageFun.SendInfomation("RepairPartStatusPLC", Convert.ToString(RepairPartStatusPLC), OpName);//显示返修标志 + + if (MES_QualityMask == 2) + { + // 暂时先屏蔽掉 + ////工作完成 + //MIS_BASE.Write_MaterialVerifyOver(OpName, true); + //SendMessageFun.SendInfomation("NgGO", "1", OpName);//显示不合格标志 + //return; + } + + //第三步,用于工件离开后完工数量统计及工件编号追溯 + //BaseDataSystemMES.MaterialPush_EngineIDStatus_Insert(OpName);//更新订单产量 + //MIS_BASE.Read_TagTypeID(201, OpName, out string EngineTypeID_QiaoKe); + Db.OP051_OP050_NeedWork(EngineID, OpName, OrderForm, out int MatchResult); + + if (MatchResult == 2) // 不匹配 没有需要装配的轮毂了 + { + MIS_BASE.Write_Match(OpName, false);// 匹配结果 + MIS_BASE.Write_MatchingCompleted(OpName, false);// 匹配完成 + MIS_BASE.WritePLC(77, OpName, "2"); ;// 托盘是否需要工作 1:需要工作 2:不需要工作 + + } + else if (MatchResult == 1) //匹配 有需要装配的轮毂 + { + MIS_BASE.Write_Match(OpName, true);// 匹配结果 + MIS_BASE.Write_MatchingCompleted(OpName, true);// 匹配完成 + MIS_BASE.WritePLC(77, OpName, "1");// 托盘是否需要工作 1:需要工作 2:不需要工作 + MIS_BASE.Write_FixAllow(OpName, true); // 允许工作 + } + else + { + MIS_BASE.WritePLC(29, OpName, true); // 开始等待 通知A60 保存完成时更新下等待状态与匹配状态 + } + } + + /// + /// 二次工作 + /// + /// + private void EngineTypeGetOver_PLC_Work_two(string OpName) + { + int EngineTypeID;//机型代码 + int PartPallet_Code;//托盘编号 + + string EngineType;//机型 + string EngineID;//工件编号 + string OrderForm; + MIS_BASE.GetEngineTypeFromPLC(OpName, out EngineTypeID, out EngineType, out EngineID, out PartPallet_Code, out OrderForm); + EngineTypeGetOver_PLC_Work(OpName, EngineTypeID, EngineType, EngineID, Convert.ToInt32(PartPallet_Code), OrderForm); + + } + /// + /// 跳过二次工作 + /// + /// + private void EngineTypeGetOver_PLC_Work_Skip(string OpName) + { + MIS_BASE.Write_MesReadOver(OpName, true); + MIS_BASE.Write_MaterialVerifyOver(OpName, true); + } + + /// + /// 返修件需要工作 + /// + /// 工位号 + private void IsNeedRepaire_OK(string OpName) + { + string orderForm = ""; + int engineTypeID; + string engineType = ""; + string engineID = ""; + string palletCode = ""; + int isRepair; + string repairCode = ""; + //从监控系统中查询出本工位信息 + BaseDataSystemMES.OpName_MIS_Moby_Select(OpName, + out orderForm, out engineTypeID, out engineType, + out engineID, out palletCode, out isRepair, out repairCode); + + EngineTypeGetOver_PLC_Work(OpName, engineTypeID, engineType, engineID, Convert.ToInt32(palletCode), orderForm); + } + + + + + } +} diff --git a/MisDataFunction/MesServer.Function/Function1055/Methods/SubmitToMisweb.cs b/MisDataFunction/MesServer.Function/Function1055/Methods/SubmitToMisweb.cs new file mode 100644 index 0000000..52ce16f --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1055/Methods/SubmitToMisweb.cs @@ -0,0 +1,127 @@ +using System; +using bizFacade; +//using SystemFramework; + +namespace MesServerFunctions +{ + + /// + /// 此类用于向WEB发送各种类型消息 + /// + partial class FunctionMES + { + + /// + /// 批量发送WEB消息(Value为BOOL值) + /// + /// 消息编号组合 + /// 消息值组合 + /// 工位号 + void Sendmessage(string MessageNumm,string Value, string OpName) + { + for (int i=0;i + /// 选择发送给WEB的消息 + /// + /// 消息类型 + /// 消息工位 + string Sendmessage(char Num,string Value, string OpName) + { + string SendMessage; + string result = ""; + switch (Num) + { + case '1': + //1(直接在界面通过选择机型确认工序内容) + SendMessage = "MES|ProcessList|" + OpName + "|" + Value; + result = AsyncSendMessage(SendMessage); + break; + case '2': + //2显示物料 + SendMessage = "MES|MaterialList|" + OpName + "|" + Value; + result = AsyncSendMessage(SendMessage); + break; + case '3': + //3显示操作指导图片 + SendMessage = "MES|PicShow|" + OpName + "|" + Value; + result = AsyncSendMessage(SendMessage); + break; + case '4': + //4订单完工模块刷新完成数量 + SendMessage = "MES|OrderFormList|" + OpName + "|" + Value; + AsyncSendMessage(SendMessage); + break; + case '5': + SendMessage = "MES|ShowMoby|" + OpName + "|" + Value; + result = AsyncSendMessage(SendMessage); + break; + case '6': + SendMessage = "MES|MaterialCheckPosition|" + OpName + "|" +Value; + result = AsyncSendMessage(SendMessage); + break; + case '7': + SendMessage = "MES|WorkStart|" + OpName + "|" + Value; + result = AsyncSendMessage(SendMessage); + break; + case '8'://清除MES生成编号 + + break; + case '9': + SendMessage = "MES|ConfirmOkGo|" + OpName + "|" + Value; + result = AsyncSendMessage(SendMessage); + break; + case 'a': + SendMessage = "MES|FixAllow|" + OpName + "|" + Value; + result = AsyncSendMessage(SendMessage); + break; + } + return result; + } + /// + /// 向WEB发送信息(value为字符串) + /// + /// 消息种类 + /// 消息内容 + /// 工位号 + string SendInfomation(string Command, string Value, string OpName) + { + string SendMessage = "MES|" + Command + "|" + OpName + "|" + Value; + return AsyncSendMessage(SendMessage); + } + + + /// + /// 发送在线产量、在线节拍 + /// + /// + /// + private void SendActuallyCount(string OpName, int tagValue) + { + //当工件离开时,更新在线产量、在线节拍 + if (tagValue == 0) + { + try + { + int opNameCount = 0;//在线产量 + int opNameCountTime = 0;//在线节拍 + //基本数据_工作日历_班次产量查询_New + BaseDataSystemMES.OpNameCount_New(OpName, out opNameCount, out opNameCountTime); + string SendMessage; + SendMessage = "MES|ActuallyCount|" + OpName + "|" + opNameCount.ToString() + "&" + opNameCountTime.ToString(); + AsyncSendMessage(SendMessage); + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:SendActuallyCount"); + } + } + } + + + } +} diff --git a/MisDataFunction/MesServer.Function/Function1055/Methods/UDP.Send.cs b/MisDataFunction/MesServer.Function/Function1055/Methods/UDP.Send.cs new file mode 100644 index 0000000..aed7cc3 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1055/Methods/UDP.Send.cs @@ -0,0 +1,53 @@ +using bizFacade; +//using SystemFramework; +using MesServerWork; +using DataLinkMesWork; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 发送信息到MES通讯服务器或者其他的 + /// + /// + private string AsyncSendMessage(string Message) + { + return MIS_BASE.asyncSendMessage(Message); + } + + /// + /// 发送提示消息 + /// + /// + private void AsyncSendMessage_Notice(string opname, string notice) + { + //通知Web界面 + BaseDataSystemMES.Web_Notice_Insert(opname, notice); + string SendMessage = "MES|Notice|" + opname + "|" + "1"; + MIS_BASE.asyncSendMessage(SendMessage); + } + + /// + /// 发送信息到打印机 + /// + /// + private void asyncSendMessageToMark(string Message) + { + string messageSend = (string)Message; + //UDPClientSend.Send_ALL(ApplicationConfig.MES_MarkPortNum, messageSend); + } + + /// + /// 发送信息到LED + /// + /// + private void asyncSendMessageLED(string OpName) + { + //发送到大屏幕显示 41104 + string strMessage = "MIS|" + OpName + "|" + "0" + "|" + "1"; + //UDPClientSend.Send_ALL(ApplicationConfig.Port_ShowLED_ProductCount, strMessage); + + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1055/Methods/vssver2.scc b/MisDataFunction/MesServer.Function/Function1055/Methods/vssver2.scc new file mode 100644 index 0000000..7782f6f Binary files /dev/null and b/MisDataFunction/MesServer.Function/Function1055/Methods/vssver2.scc differ diff --git a/MisDataFunction/MesServer.Function/Function1055/OpcServer/Barcode.cs b/MisDataFunction/MesServer.Function/Function1055/OpcServer/Barcode.cs new file mode 100644 index 0000000..1f9ea05 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1055/OpcServer/Barcode.cs @@ -0,0 +1,90 @@ +using System; +using System.Windows.Forms; +using bizFacade; +//using SystemFramework; +using MesServerWork; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + ///1.扫描配送单号,用于接收物料,扫描单号的时候,将接收的物料信息显示在“物料拉动”Tab区域 + ///2.扫描料箱标签/看板卡,用于追溯物料批次信息 + ///3.扫描零件条码,根据零件图号进行防错 + ///第一步,判断条码类型,根据条码类型,执行对应的存储过程 + ///第二步,条码类型(将扫描的条码保存到对应的表中) + ///第三步,扫描完成之后给出允许工作信号 + /// 处理页面扫描条码 + /// + /// + /// + public void Barcode(object e) + { + + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + string barcode = Convert.ToString(msgEvent.TagValue); + string AlarmStr = ""; + + int IsAllowWork; + bool IsSuccess = false; + bool EngineGetOver_PLC_NextWorkStep; + //传递机型是否到位 + MIS_BASE.Read_EngineGetOver_PLC(OpName, out EngineGetOver_PLC_NextWorkStep); + if (!EngineGetOver_PLC_NextWorkStep) + { + SendMessageFun.AsyncSendMessage_Notice(OpName, "PLC未传递机型"); + return; + } + //物料验证 + BaseDataSystemMES.PartMaterial_DM_Update(OpName, barcode, out IsSuccess); + if (!IsSuccess) + { + SendMessageFun.AsyncSendMessage_Notice(OpName, "条码无效,请确认"); + return; + } + else + { + SendMessageFun.SendInfomation("MaterialList", "1", OpName);//通知界面更新零件信息 + } + + + + + //获取是否允许工作 + BaseDataSystemMES.MesServer_Judge_IsCanWork(OpName, out IsAllowWork); + + //此处逻辑有问题 需要考虑到批次扫描 提示PLC未传递机型的情况 + if (IsAllowWork == 1) + { + //BaseDataSystemMES.Material_Insert(OpName, 1); + + //更新订单完工数量及物料 + SendMessageFun.SendMessage("24", "11", OpName); + + //通知PLC允许工作,允许工作在保存完成时清空 + MIS_BASE.Write_FixAllow(OpName, true); + } + else + { + SendMessageFun.AsyncSendMessage_Notice(OpName, "请扫描物料!"); + } + + + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:Barcode"); + } + + } + + } + + + } +} diff --git a/MisDataFunction/MesServer.Function/Function1055/OpcServer/ConfirmOkGo.cs b/MisDataFunction/MesServer.Function/Function1055/OpcServer/ConfirmOkGo.cs new file mode 100644 index 0000000..06e6b33 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1055/OpcServer/ConfirmOkGo.cs @@ -0,0 +1,41 @@ +using System; +using bizFacade; +//using SystemFramework; +using MesServerWork; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 合格放行 + /// + /// + /// + private void ConfirmOkGo(object e) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + + if (tagValue == 1) + { + + BaseDataSystemMES.Material_Insert(OpName, 1); + + //更新订单完工数量及物料 + Sendmessage("24", "11", OpName); + + //工作完成 + MIS_BASE.Write_MaterialVerifyOver(OpName, true); + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:ConfirmOkGo"); + } + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1055/OpcServer/EngineGetOver.cs b/MisDataFunction/MesServer.Function/Function1055/OpcServer/EngineGetOver.cs new file mode 100644 index 0000000..59d2445 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1055/OpcServer/EngineGetOver.cs @@ -0,0 +1,79 @@ +using System; +using System.Data; +using System.Windows.Forms; +using System.Xml.Linq; +using bizFacade; +//using SystemFramework; +using MesServerWork; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// PLC传递机型处理 + /// + /// + /// + private void EngineTypeGetOver_PLC(object e) + { + + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + + if (tagValue == 1) + { + int EngineTypeID;//机型代码 + int PartPallet_Code;//托盘编号 + + string EngineType;//机型 + string EngineID;//工件编号 + string OrderForm; + MIS_BASE.GetEngineTypeFromPLC(OpName, out EngineTypeID, out EngineType, out EngineID, out PartPallet_Code, out OrderForm); + + if (EngineTypeID <= 0 || EngineID.Length == 0 || EngineType.Length == 0) + { + SendMessageFun.AsyncSendMessage_Notice(OpName, "PLC传递机型为空"); + return; + } + + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.EngineTypeID, EngineTypeID.ToString()); + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.EngineType, EngineType); + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.EngineID, EngineID); + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.OrderForm, OrderForm); + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.PartPallet_Code, PartPallet_Code.ToString()); + + //显示当前订单信息 + SendMessage.ShowMoby(OpName); + //判断该订单数据是否已经工作过,有的话则在WEB跳出弹窗选择 并同时禁止工作 + //DataTable dt2 = BaseDataSystemMES.EngineIsTwoWork(OpName, OrderForm, EngineID); + //if (dt2.Rows[0]["result"].ToString() == "1") //已完成 + //{ + // //不允许工作 + // MIS_BASE.Write_FixAllow(OpName, false); + // //通知WEB校验重新工作还是跳过 点重新工作给允许工作,点跳过给工作完成 + // string message = "MES|Engine_Is_TwoWork|" + OpName + "|1"; + // SendMessage.AsyncSendMessage(message); + //} + //else + //{ + // EngineTypeGetOver_PLC_Work(OpName, EngineTypeID, EngineType, EngineID, PartPallet_Code, OrderForm); + //} + EngineTypeGetOver_PLC_Work(OpName, EngineTypeID, EngineType, EngineID, PartPallet_Code, OrderForm); + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:EngineTypeGetOver_PLC"); + } + } + + + } + + } +} diff --git a/MisDataFunction/MesServer.Function/Function1055/OpcServer/FalseGO.cs b/MisDataFunction/MesServer.Function/Function1055/OpcServer/FalseGO.cs new file mode 100644 index 0000000..14b5771 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1055/OpcServer/FalseGO.cs @@ -0,0 +1,46 @@ +using System; +using System.Data; +using System.Windows.Forms; +using System.Xml.Linq; +using bizFacade; +//using SystemFramework; +using MesServerWork; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 不合格放行 + /// + /// + /// + private void FalseGO(object e) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + + if (tagValue == 1) + { + //不合格放行信号 + //MIS_BASE.Write_FalseGO(OpName, true); + //总合格标志2(不合格) + + BaseDataSystemMES.Material_Insert_NG(OpName, 2); + + Sendmessage("24", "11", OpName); + + //工作完成 + MIS_BASE.Write_MaterialVerifyOver(OpName, true); + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:FalseGO"); + } + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1055/OpcServer/HeartBeat.cs b/MisDataFunction/MesServer.Function/Function1055/OpcServer/HeartBeat.cs new file mode 100644 index 0000000..93affd3 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1055/OpcServer/HeartBeat.cs @@ -0,0 +1,35 @@ +using bizFacade; +using MesServerWork; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// MES与PLC心跳监听 + /// + /// + /// + private void HeartBeat(object e) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + + //返写在MES心跳中 + MIS_BASE.WritePLC(15, OpName, tagValue); + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:FalseGO"); + } + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1055/OpcServer/MesRead.cs b/MisDataFunction/MesServer.Function/Function1055/OpcServer/MesRead.cs new file mode 100644 index 0000000..5fe6452 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1055/OpcServer/MesRead.cs @@ -0,0 +1,77 @@ +using bizFacade; +using MesServerWork; +using System; +//using SystemFramework; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 允许保存(针对半自动和手动压装工位) + /// + /// + /// + private void MesRead(object e) + { + { + try + { + + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + int EngineTypeID;//机型代码 + int PartPallet_Code;//托盘编号 + + string EngineType;//机型 + string EngineID;//工件编号 + string OrderForm; + string NeedWork; + + if (tagValue == 1) + { + // 记录050前停工位的是否需要工作 + MIS_BASE.GetEngineTypeFromPLC(OpName, out EngineTypeID, out EngineType, out EngineID, out PartPallet_Code, out OrderForm); + MIS_BASE.Read_TagTypeID(37, OpName, out NeedWork); + Db.OP051_OP050_NeedWork_Save(EngineID, Convert.ToInt32(NeedWork)); + + int qualityMask; + // 保存质量数据 + qualityMask = MisDataSaveDateMesRead.Funtion.MesRead(OpName, tagValue.ToString(), msgEvent.TagID.ToString()); + // 保存物料数据 + BaseDataSystemMES.Material_Insert(OpName, qualityMask); + + // 测量数据发动机在线状态 + BaseDataSystemMES.WorkStartInsert(OpName, qualityMask); + + // 推送质量数据到MES的页面 + SendMessageFun.SendInfomation("ShowTimelyQuality", "1&" + qualityMask.ToString(), OpName); + + //对应手动工位的 + //MIS_BASE.Write_ConfirmOkGo(OpName, true); + //通知设备,MES的质量数据(和物料数据)保存完成 + MIS_BASE.Write_MesReadOver(OpName, true); + MIS_BASE.Write_MaterialVerifyOver(OpName, true); + //统计在线产量,在线节拍 + //SendMessage.SendActuallyCount(OpName, tagValue); + var result = MesFunctions.EnginePart_OutStation(OpName, EngineID, qualityMask); + } + else + { + MIS_BASE.Write_MesReadOver(OpName, false); + + } + } + + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function08:MesReadOver"); + } + } + + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1055/OpcServer/MesReadOver.cs b/MisDataFunction/MesServer.Function/Function1055/OpcServer/MesReadOver.cs new file mode 100644 index 0000000..f96a7d3 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1055/OpcServer/MesReadOver.cs @@ -0,0 +1,55 @@ +using System; +//using SystemFramework; +using MesServerWork; +using bizFacade; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 保存完成(针对半自动和手动压装工位) + /// + /// + /// + private void MesReadOver(object e) + { + //try + //{ + // DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + // string OpName = Convert.ToString(msgEvent.OpName); + // var tagValue = msgEvent.TagValue.ToString (); + + // if (tagValue == "1" | tagValue.ToLower () == "true") + // { + // int qualityMask; + // MIS_BASE.Read_QualityMask(OpName, out qualityMask); + + // SendInfomation("ShowTimelyQuality", "1&" + qualityMask.ToString(), OpName);//发给Web页面显示质量数据 + + // if (qualityMask == 1)//全部OK,给出合格放行 + // { + // //如果存在线外扫描工位,根据扫描条码绑定线外数据 需要时解除禁用 + // //BaseDataSystemMES.TransLaunchDataByMainMaterial(OpName, EngineType, EngineID, EngineTypeID); + + // //如果存在线外排队工位,根据排队编号绑定线外数据 需要时解除禁用 + // ////BaseDataSystemMES.MailLineAndSubLineData_InsertByEngineID_Subline(OpName,EngineID, EngineTypeID, EngineType); + + // MIS_BASE.Write_ConfirmOkGo(OpName, true); + // //MIS_BASE.Write_FalseGO(OpName, false); + // } + // else + // { + // //MIS_BASE.Write_ConfirmOkGo(OpName, false); + // MIS_BASE.Write_FalseGO(OpName, true); + // } + + // } + //} + //catch (Exception err) + //{ + // ////ApplicationLog.WriteLog(err, "Function02:MesReadOver"); + //} + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1055/OpcServer/MesSaveNowData.cs b/MisDataFunction/MesServer.Function/Function1055/OpcServer/MesSaveNowData.cs new file mode 100644 index 0000000..63c11b3 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1055/OpcServer/MesSaveNowData.cs @@ -0,0 +1,40 @@ +using bizFacade; +using MesServerWork; +using System; +using System.Collections.Generic; +using System.Data; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; +using static System.Net.Mime.MediaTypeNames; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// MES保存实时质量数据 + /// + /// + /// + private void MesSaveNowData(object e) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + // 直接发送实时的 质量数据 + string message = MisDataSaveDateMesRead.Funtion.GetRealTimeQualityData(OpName); + //推送质量数据到MES的页面 + SendMessage.AsyncSendMessage("MES|ShowTimelyQuality_Resources|" + OpName + "|" + message); + //SendMessageFun.SendMessageMESToWEB("ShowTimelyQuality", "1&" + qualityMask.ToString(), OpName); + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:FalseGO"); + } + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1055/OpcServer/WebSubmit.cs b/MisDataFunction/MesServer.Function/Function1055/OpcServer/WebSubmit.cs new file mode 100644 index 0000000..d7ca28c --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1055/OpcServer/WebSubmit.cs @@ -0,0 +1,304 @@ +using System; +using MesServerWork; +using bizFacade; +using System.Threading; +using MisDataSaveDate; +using System.Collections; +//using SystemFramework; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 处理WEB页面发送过来的请求(m_Command + "|" + m_Value;) + /// + /// + /// + private void WebSubmit(object e) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName=Convert.ToString(msgEvent.OpName); + string Content = Convert.ToString(msgEvent.TagValue); + + string[] dataArray = Content.Split('|'); + if (dataArray.Length != 2) + return; + //消息类型 + string m_Command = dataArray[0].ToString(); + //消息参数 + string m_Value = dataArray[1].ToString(); + //消息参数数量 + string[] m_Value_array = m_Value.Split('&'); + //消息参数长度 + int m_Value_length = m_Value_array.Length; + + //工件信息 + string engineID = ""; + if (MIS_BASE.hashtable_EngineGetOver_EngineTypeID == null) + { + MIS_BASE.InitHashtable_MesServerCode(); + } + if (MIS_BASE.hashtable_EngineGetOver_EngineTypeID == null) + { + return; + } + if (MIS_BASE.hashtable_EngineGetOver_EngineID.ContainsKey(OpName)) + { + engineID = MIS_BASE.hashtable_EngineGetOver_EngineID[OpName].ToString(); + } + + DoWhatPlc.CustomeEvetnArgs _e = new DoWhatPlc.CustomeEvetnArgs(); + _e.OpName = OpName; + _e.TagValue = m_Value; + + //根据请求的命令处理逻辑 + switch (m_Command) + { + case "Barcode": + if (m_Value_length > 1) return; + fun_Barcode(_e); + break; + case "ConfirmOkGo"://合格放行 + //删除不合格放行记录 + //修改托盘状态 + //Update_PalletStatus(OpName, 1, false); + BaseDataSystemMES.BaseData_tagTable_Engine_IsNG_Delete(OpName, engineID); + MIS_BASE.Write_ConfirmOkGo(OpName, true); + MIS_BASE.Write_FalseGO(OpName, false); + + Thread.Sleep(1000); + MIS_BASE.Write_ConfirmOkGo(OpName, false); + break; + case "FalseGO"://返修放行 + //修改托盘状态 + //Update_PalletStatus(OpName, 3, false); + BaseDataSystemMES.BaseData_tagTable_Engine_IsNG_Delete(OpName, engineID); + MIS_BASE.Write_FalseGO(OpName, true); + MIS_BASE.Write_ConfirmOkGo(OpName, false); + + Thread.Sleep(1000); + MIS_BASE.Write_FalseGO(OpName, false); + break; + case "NgGO"://不合格放行 + //修改托盘状态 + //Update_PalletStatus(OpName, 2, false); + //保存不合格信息(必须保存不合格放行信息,由于B5A的Moby没有不合格标志位) + BaseDataSystemMES.BaseData_tagTable_Engine_IsNG_Insert(OpName, engineID, "", ""); + MIS_BASE.Write_FalseGO(OpName, true); + MIS_BASE.Write_ConfirmOkGo(OpName, false); + Thread.Sleep(1000); + MIS_BASE.Write_FalseGO(OpName, false); + break; + case "OnLineState"://在线0、离线1、屏蔽2 + try + { + if (m_Value_length > 1) return; + int a = Convert.ToInt32(m_Value); + if (a <= 2) + { + BaseDataSystemMES.IsOnLine_Update(OpName, m_Value.ToString()); + MIS_BASE.Write_OnLineState(OpName, Convert.ToInt32(m_Value)); + if (a == 2) SendMessage.AsyncSendMessage_Notice(OpName, "屏蔽MES!"); + if (a == 0) SendMessage.AsyncSendMessage_Notice(OpName, "启用MES!"); + } + } + catch + { + + } + break; + case "Reset"://复位,将MES所有的信息都复位了 + SetMoby(OpName);//将MES所有信号清空 + break; + case "FixAllow"://重新拧紧 + MIS_BASE.Write_FixAllow(OpName, false); + MIS_BASE.Write_FixAllow(OpName, true); + break; + case "IsAutoGetEngineID"://自动手动申请编号(线首) + if (m_Value_length > 1) return; + MIS_BASE.Write_IsAutoGetEngineID(OpName, Convert.ToInt32(m_Value)); + break; + case "PartPalletGoOver"://空托盘放行 + int Is_PartPalletGoOver; + MIS_BASE.Read_PartPalletGoOver(OpName, out Is_PartPalletGoOver); + if (Is_PartPalletGoOver == 1) + { + MIS_BASE.Write_PartPalletGoOver(OpName, 1); + } + else + { + MIS_BASE.Write_PartPalletGoOver(OpName,0); + } + break; + case "SetMoby"://清空托盘(线首) + SetMoby(OpName);//将MES所有信号清空 + //MIS_BASE.Write_PartPalletCode_PLC(OpName, 1); + break; + case "RepairUplineMES"://返修上线 + MIS_BASE.Write_RepairUpline_MES(OpName, true); + break; + case "CancelRepair"://将返修件置为正常件 + + break; + case "PartPalletCode"://申请写入托盘号 + //MIS_BASE.Write_PartPalletCode_PLC(OpName, 1); + break; + case "WritePartPalletCode"://写入托盘号 + if (m_Value_length > 1) return; + MIS_BASE.Write_PalletCode(OpName, Convert.ToInt32(m_Value)); + break; + case "Normal"://启用正常拧紧工位 + MIS_BASE.Write_Normal(OpName, 1); + MIS_BASE.Write_UnNormal(OpName, 0); + break; + case "UnNormal"://启用备用拧紧工位 + MIS_BASE.Write_Normal(OpName, 0); + MIS_BASE.Write_UnNormal(OpName, 1); + break; + case "ResetDevice"://复位设备 + MIS_BASE.Write_ResetDevice(OpName, true); + System.Threading.Thread.Sleep(1000); + MIS_BASE.Write_ResetDevice(OpName, false); + break; + case "IsNeedRepaire"://返修上线(返修上线点) + if (Convert.ToInt32(m_Value) == 1) + { + //修改托盘状态 + MIS_BASE.Write_PalletInfo(OpName, 3); + //通知修改成功 + MIS_BASE.Write_UpdatePalletOK(OpName, true); + IsNeedRepaire_OK(OpName); + + } + else if (Convert.ToInt32(m_Value) == 0) + { + //通知修改成功 + MIS_BASE.Write_UpdatePalletOK(OpName, true); + //直接给出工作完成 + MIS_BASE.Write_MaterialVerifyOver(OpName, true); + } + else + { } + + break; + case "ContinueMatch": + BaseDataSystemMES.QualityVerifyStatus_Hash_Write(OpName, true); + break; + //初始化网页信号 + case "IniSingalToWeb": + InitializeSingalToWeb(OpName); + break; + case "Reset_Engine"://返修上线(返修上线点) + SetMoby(OpName);//将MES所有信号清空 + //fun_EngineTypeGetOverPLC(OpName, 0); + //fun_EngineTypeGetOverPLC(OpName, 1); + break; + + case "twoWorkSkip"://重新工作工件跳过工作(重新工作工件) + //工作完成 + EngineTypeGetOver_PLC_Work_Skip(OpName); + break; + case "twoWork"://重新工作工件重新工作(重新工作工件) + //允许工作 + EngineTypeGetOver_PLC_Work_two(OpName); + break; + + default: break; + } + } + catch(Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:WebSubmit"); + } + } + private void SetMoby(string OpName) + { + try + { + //清空Moby时,需要将MES信号清空 + MIS_BASE.Write_ClearMesMoby(OpName); + + BaseDataSystemMES.MesServer_Process_EngineTypeOver(OpName); + + Sendmessage("5123", "1111", OpName); + + MIS_BASE.Write_ResetDevice(OpName, true); + System.Threading.Thread.Sleep(1000); + MIS_BASE.Write_ResetDevice(OpName, false); + } + catch + { + + } + } + /// 网页重现登录,恢复关闭前的页面状态 + /// + /// 工位号 + private void InitializeSingalToWeb(string Opname) + { + + //工件到位 DBX0.1 + bool S_WorkStart; + bool S_FixAllow; + bool S_EngineGetOver; + bool S_MaterialVerifyOver; + + MIS_BASE.Read_WorkStart(Opname, out S_WorkStart); + MIS_BASE.Read_FixAllow(Opname, out S_FixAllow); + MIS_BASE.Read_EngineGetOver_PLC(Opname, out S_EngineGetOver); + MIS_BASE.Read_MaterialVerifyOver(Opname, out S_MaterialVerifyOver); + + Sendmessage("13", "1111", Opname); + string S_plcStatus;//DBX501.5 PLC直通,1 强制放行 0 正常循环 + // 新增查询PLC直通状态 网页显示 + MIS_BASE.Read_TagTypeID(63, Opname, out S_plcStatus); + if (S_plcStatus.ToLower() == "false") + { + SendMessageFun.SendInfomation("PlcStatus", "0", Opname); + } + else + { + SendMessageFun.SendInfomation("PlcStatus", "1", Opname); + } + + if (S_WorkStart == true) + { + SendInfomation("WorkStart", Convert.ToString(Convert.ToInt32(S_WorkStart)), Opname); + } + if (S_FixAllow == true) + { + SendInfomation("FixAllow", Convert.ToString(Convert.ToInt32(S_FixAllow)), Opname); + } + if (S_MaterialVerifyOver == true) + { + SendInfomation("MaterialVerifyOver", Convert.ToString(Convert.ToInt32(S_MaterialVerifyOver)), Opname); + } + if (S_EngineGetOver == true) + { + SendInfomation("EngineTypeGetOverPLC", Convert.ToString(Convert.ToInt32(S_EngineGetOver)), Opname); + Sendmessage("2", "1111", Opname); + SendMessage.ShowMoby(Opname); + // 直接发送实时的 质量数据 + string message = MisDataSaveDateMesRead.Funtion.GetRealTimeQualityData(Opname); + //推送质量数据到MES的页面 + SendMessage.AsyncSendMessage("MES|ShowTimelyQuality_Resources|" + Opname + "|" + message); + } + InitAlarm(Opname); + } + + private void InitAlarm(string Opname) + { + FuntionMesRead.Alarm_InitAlarm_Send(Opname, out Hashtable ht); + foreach (DictionaryEntry kv in ht) + { + var TagID = kv.Key.ToString(); + var TagValue = kv.Value.ToString(); + FuntionMesRead.Send_AlarmMsg(TagID, TagValue); + } + + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1055/OpcServer/WorkIsOk.cs b/MisDataFunction/MesServer.Function/Function1055/OpcServer/WorkIsOk.cs new file mode 100644 index 0000000..08819e3 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1055/OpcServer/WorkIsOk.cs @@ -0,0 +1,45 @@ +using bizFacade; +using MesServerWork; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 工位合格标志 + /// + /// + /// + private void IsOk(object e) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + + int qualityMask; + MIS_BASE.Read_QualityMask(OpName, out qualityMask); + //判断是否合格 + if (qualityMask == 1) + { + qualityMask = 1; + } else { + qualityMask = 0; + } + //通知WEB修改状态 + string message = "MES|QualityMask|" + OpName + "|" + qualityMask.ToString(); + SendMessage.AsyncSendMessage(message); + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:FalseGO"); + } + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1055/OpcServer/WorkStart.cs b/MisDataFunction/MesServer.Function/Function1055/OpcServer/WorkStart.cs new file mode 100644 index 0000000..a0905d5 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1055/OpcServer/WorkStart.cs @@ -0,0 +1,53 @@ +using bizFacade; +using MesServerWork; +using System; +using System.Threading; +//using SystemFramework; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 工件到位与离开时,清空MES自身信号 + /// + /// + /// + private void WorkStart(object e) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + if (tagValue == 1) + { + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.WorkStartIn, DateTime.Now.ToString()); + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.WorkStart, tagValue.ToString()); + } + else + { + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.WorkStartOut, DateTime.Now.ToString()); + Thread.Sleep(500); + MIS_BASE.Write_MesReadOver(OpName, false); + MIS_BASE.Write_ConfirmOkGo(OpName, false); + MIS_BASE.Write_FixAllow(OpName, false); + MIS_BASE.Write_ConfirmOkGo(OpName, false); + MIS_BASE.Write_EngineTypeGetOver_MES(OpName, false); + //工作完成 + MIS_BASE.Write_MaterialVerifyOver(OpName, false); + + MIS_BASE.Write_MatchingCompleted(OpName, false);// 匹配完成 + MIS_BASE.Write_Match(OpName, false);// 匹配结果 + MIS_BASE.WritePLC(77, OpName, "0"); ;// 托盘是否需要工作 1:需要工作 2:不需要工作 + + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:WorkStart"); + } + } + + } +} diff --git a/MisDataFunction/MesServer.Function/Function1055/OpcServer/vssver2.scc b/MisDataFunction/MesServer.Function/Function1055/OpcServer/vssver2.scc new file mode 100644 index 0000000..b884d13 Binary files /dev/null and b/MisDataFunction/MesServer.Function/Function1055/OpcServer/vssver2.scc differ diff --git a/MisDataFunction/MesServer.Function/Function1055/Properties/AssemblyInfo.cs b/MisDataFunction/MesServer.Function/Function1055/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..0bb79c4 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1055/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// 有关程序集的常规信息通过以下 +// 特性集控制。更改这些特性值可修改 +// 与程序集关联的信息。 +[assembly: AssemblyTitle("Function02")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("苏州宏软信息技术有限公司")] +[assembly: AssemblyProduct("Function02")] +[assembly: AssemblyCopyright("Copyright © 苏州宏软信息技术有限公司 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// 将 ComVisible 设置为 false 使此程序集中的类型 +// 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型, +// 则将该类型上的 ComVisible 特性设置为 true。 +[assembly: ComVisible(false)] + +// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID +[assembly: Guid("47710f2c-e141-4252-8d13-701bf4c1c027")] + +// 程序集的版本信息由下面四个值组成: +// +// 主版本 +// 次版本 +// 内部版本号 +// 修订号 +// +// 可以指定所有这些值,也可以使用“内部版本号”和“修订号”的默认值, +// 方法是按如下所示使用“*”: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/MisDataFunction/MesServer.Function/Function1055/Properties/vssver2.scc b/MisDataFunction/MesServer.Function/Function1055/Properties/vssver2.scc new file mode 100644 index 0000000..14e543b Binary files /dev/null and b/MisDataFunction/MesServer.Function/Function1055/Properties/vssver2.scc differ diff --git a/MisDataFunction/MesServer.Function/Function1055/app.config b/MisDataFunction/MesServer.Function/Function1055/app.config new file mode 100644 index 0000000..b4c4daf --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1055/app.config @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + + + diff --git a/MisDataFunction/MesServer.Function/Function1055/mssccprj.scc b/MisDataFunction/MesServer.Function/Function1055/mssccprj.scc new file mode 100644 index 0000000..119193d --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1055/mssccprj.scc @@ -0,0 +1,5 @@ +SCC = This is a Source Code Control file + +[Function02.csproj] +SCC_Aux_Path = "\\192.168.0.100\vss\MES4.0" +SCC_Project_Name = "$/MisData/MisData/MisData/MesServer.Function/Function02", ILHAAAAA diff --git a/MisDataFunction/MesServer.Function/Function1055/packages.config b/MisDataFunction/MesServer.Function/Function1055/packages.config new file mode 100644 index 0000000..b3e1761 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1055/packages.config @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/MisDataFunction/MesServer.Function/Function1055/vssver2.scc b/MisDataFunction/MesServer.Function/Function1055/vssver2.scc new file mode 100644 index 0000000..c770e28 Binary files /dev/null and b/MisDataFunction/MesServer.Function/Function1055/vssver2.scc differ diff --git a/MisDataFunction/MesServer.Function/Function1056/DataAccess/DataAccess.cs b/MisDataFunction/MesServer.Function/Function1056/DataAccess/DataAccess.cs new file mode 100644 index 0000000..68cdca4 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1056/DataAccess/DataAccess.cs @@ -0,0 +1,15 @@ + +namespace MesServerFunctions +{ + partial class FunctionMES + { + //针对“MIS.BizFacade.Dll”中没有的存储过程,在此类中新建 + //新建原则:所有的函数用private,只允许在内部使用 + //针对单个工艺特殊,需要新建存储过程,但是存储过程不能被加入到“MIS.BizFacade.Dll”中 + + private void aa() + { + + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1056/DataAccess/vssver2.scc b/MisDataFunction/MesServer.Function/Function1056/DataAccess/vssver2.scc new file mode 100644 index 0000000..d045c26 Binary files /dev/null and b/MisDataFunction/MesServer.Function/Function1056/DataAccess/vssver2.scc differ diff --git a/MisDataFunction/MesServer.Function/Function1056/Db.cs b/MisDataFunction/MesServer.Function/Function1056/Db.cs new file mode 100644 index 0000000..23ab541 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1056/Db.cs @@ -0,0 +1,57 @@ +using System; +using System.Collections.Generic; +using System.Data.SqlClient; +using System.Data; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using DataLinkMesWork; + +namespace MesServerFunctions +{ + public class Db + { + /// + /// 合力_转线_A92判断工件状态 + /// + /// + /// + /// + /// + /// + /// + /// + public static bool OPA92_EngineGetOverCheckWorkType(string EngineID, out int MatchResult, out string MatchResultStr) + { + DataTable dt = new DataTable(); + MatchResult = 2;// 默认是报警 程序出错 + MatchResultStr = "默认是报警 程序出错";// 默认是报警 程序出错 + string produceName = "合力_转线_A92判断工件状态"; + SqlParameter[] thisParms = new SqlParameter[1]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@轮毂总成号", EngineID); + if (DataAccess.ExecuteStoredProcedure(produceName, ref thisParms, out dt)) + { + if (dt.Rows.Count > 0) + { + MatchResult = Convert.ToInt32(dt.Rows[0]["result"]); + MatchResultStr = dt.Rows[0]["msg"].ToString(); + return true; + } + } + return false; + } + + /// + /// 合力_转线_删除记录数据 同时保存 轮毂 桥壳 关系 + /// + /// + public static void OPA92_DeleteLineData(string EngineID_QiaoKe) + { + DataTable dt = new DataTable(); + string produceName = "合力_转线_删除记录数据"; + SqlParameter[] thisParms = new SqlParameter[1]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@桥壳总成号", EngineID_QiaoKe); + DataAccess.ExecuteStoredProcedure(produceName, ref thisParms, out dt); + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1056/Function02.csproj.vspscc b/MisDataFunction/MesServer.Function/Function1056/Function02.csproj.vspscc new file mode 100644 index 0000000..0f0f36c --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1056/Function02.csproj.vspscc @@ -0,0 +1,10 @@ +"" +{ +"FILE_VERSION" = "9237" +"ENLISTMENT_CHOICE" = "NEVER" +"PROJECT_FILE_RELATIVE_PATH" = "relative:MesServer.Function\\Function02" +"NUMBER_OF_EXCLUDED_FILES" = "0" +"ORIGINAL_PROJECT_FILE_PATH" = "" +"NUMBER_OF_NESTED_PROJECTS" = "0" +"SOURCE_CONTROL_SETTINGS_PROVIDER" = "PROVIDER" +} diff --git a/MisDataFunction/MesServer.Function/Function1056/Function1056.csproj b/MisDataFunction/MesServer.Function/Function1056/Function1056.csproj new file mode 100644 index 0000000..550ad79 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1056/Function1056.csproj @@ -0,0 +1,169 @@ + + + + Debug + AnyCPU + 8.0.30703 + 2.0 + {72659518-D67A-4A49-875D-E4B038CDF32B} + Library + Properties + Function1056 + Function1056 + v4.8 + 512 + + + + + + + + + + + + + + true + full + false + ..\..\..\dll_fun\ + DEBUG;TRACE + prompt + 4 + false + false + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + false + + + + ..\..\..\Common\dll\MQTTnet.dll + + + ..\..\..\Common\dll\MQTTnet.Extensions.ManagedClient.dll + + + False + ..\..\..\Common\dll\Newtonsoft.Json.dll + + + + + + ..\..\DLL\System.Net.Http.dll + + + ..\..\packages\System.Net.Security.4.3.2\lib\net46\System.Net.Security.dll + + + ..\..\packages\System.Net.WebSockets.4.3.0\lib\net46\System.Net.WebSockets.dll + + + ..\..\packages\System.Net.WebSockets.Client.4.3.2\lib\net46\System.Net.WebSockets.Client.dll + + + ..\..\packages\System.Security.Cryptography.Algorithms.4.3.0\lib\net461\System.Security.Cryptography.Algorithms.dll + + + ..\..\packages\System.Security.Cryptography.Encoding.4.3.0\lib\net46\System.Security.Cryptography.Encoding.dll + + + ..\..\packages\System.Security.Cryptography.Primitives.4.3.0\lib\net46\System.Security.Cryptography.Primitives.dll + + + ..\..\packages\System.Security.Cryptography.X509Certificates.4.3.0\lib\net461\System.Security.Cryptography.X509Certificates.dll + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + {f55da1a0-a982-4479-8c47-0d9a5aaf3e18} + 00MesWorkMqtt + + + {0d1af432-439a-4920-8692-43ae139f5530} + 01_01DoWhatPlc + + + {3e6d1dd5-01c9-435f-9941-61f906ce35bb} + 02_02WebApiCallPLC + + + {f434e066-4c59-47c8-aa82-6f48cc84501a} + 04-DataBaseAccess + + + {f0a0c525-03fd-428a-9b17-7f54aa0e4475} + 07BusinessFacade + + + {d98be764-adeb-488d-9714-61e308aa8201} + 08-WebFun_base + + + {90e76fb4-646d-45e2-95db-0b8ab4e465d6} + 09-MesDataFunction + + + {e4eb6420-906d-4672-947a-ca33ddcdadfc} + 12SendMessageToWeb + + + {55b510c1-59e9-4bfd-ae84-d76d46f6e365} + 02-13.3MIS_FuntionSaveData + + + + + + + 这台计算机上缺少此项目引用的 NuGet 程序包。使用“NuGet 程序包还原”可下载这些程序包。有关更多信息,请参见 http://go.microsoft.com/fwlink/?LinkID=322105。缺少的文件是 {0}。 + + + + + \ No newline at end of file diff --git a/MisDataFunction/MesServer.Function/Function1056/MesServerFunction/Fun_1056.cs b/MisDataFunction/MesServer.Function/Function1056/MesServerFunction/Fun_1056.cs new file mode 100644 index 0000000..a6ed400 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1056/MesServerFunction/Fun_1056.cs @@ -0,0 +1,223 @@ +using MesServerWork; +using System.Collections.Generic; +using System.Threading; + +namespace MesServerFunctions +{ + public partial class FunctionMES + { + object lockFunWork; + //public void FunWork(DoWhatPlc.CustomeEvetnArgs e) + public void FunWork(string recData) + { + + + lockFunWork = new object(); + lock (lockFunWork) + { + List dataArray = DoWhatPlc.MessageText.GetCmdStringList(recData); + //string[] dataArray = recData.Split('|'); + //if (dataArray.Count != 4) + //return; + //消息来源 + string m_Source = dataArray[0].ToString(); + //消息类型 Barcode + string m_Command = dataArray[1].ToString(); + //工位号 + string m_OpName = dataArray[2].ToString(); + //消息参数 + string m_Value = dataArray[3].ToString(); + + DoWhatPlc.CustomeEvetnArgs e = new DoWhatPlc.CustomeEvetnArgs();// = Newtonsoft.Json.JsonConvert.DeserializeObject(m_Value); + string tagValue; + + switch (m_Source) + { + case "BarCode": + e.OpName = m_OpName; + e.TagValue = m_Value; + fun_Barcode(e); + break; + case "WEB": + e.OpName = m_OpName; + e.TagValue = m_Command + "|" + m_Value; + fun_WebSubmit(e); + break; + // case "MES": + case "PLC": + e = Newtonsoft.Json.JsonConvert.DeserializeObject(m_Value); + switch (e.TagValue.ToString().ToLower()) + { + case "false": + tagValue = "0"; + break; + case "true": + tagValue = "1"; + break; + default: + tagValue = e.TagValue.ToString(); + break; + } + e.TagValue = tagValue; + switch (e.TagTypeCodeID.ToString()) + { + //PLC 工件到位 + case "2": + fun_WorkStart(e); + break; + //PLC 允许保存质量数据 + case "19": + fun_MesRead(e); + break; + //MES 保存数据完成 + case "20": + fun_MesReadOver(e); + break; + //PLC 传递机型 + case "44": + fun_EngineTypeGetOverPLC(e); + break; + //MES 合格放行 + case "51": + fun_ConfirmOkGo(e); + break; + //MES 不合格放行 + case "8": + fun_FalseGo(e); + break; + //MES保存实时质量数据 + case "65": + fun_MesSaveNowData(e); + break; + //MES 系统健康心跳 + case "15": + fun_HeartBeatMIS(e); + break; + case "63": + string S_plcStatus;//DBX501.5 PLC直通,1 强制放行 0 正常循环 + MIS_BASE.Read_TagTypeID(63, m_OpName, out S_plcStatus); + if (S_plcStatus.ToLower() != "true" || S_plcStatus.ToLower() == "1") + { + SendMessageFun.SendInfomation("PlcStatus", "0", m_OpName); + } + else + { + SendMessageFun.SendInfomation("PlcStatus", "1", m_OpName); + } + break; + } + break; + } + } + } + + //1.工件到位后,PLC给MES传递机型(DBX0.4)(44), + //MES判断条码是否全部扫描完成 + //PLC给出允许保存(DBX100.2)(19),MES见到(DBX100.2)(19)为1后给出保存完成(DBX102.2)(20), + //PLC见到保存完成(DBX102.2)(20)为1后,清空允许保存(DBX100.2)(19), + //MES见到允许保存(DBX100.2)(19)为0后,清空保存完成(DBX102.2)(20) + //MES判断总合格标志(INT104)(21)为1后,给出合格放行(DBX2.5)(51) + /// + /// 扫描条码 + /// + /// + /// + public void fun_Barcode(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(Barcode, e); + } + /// + /// 系统健康心跳监测 + /// + /// + /// + public void fun_HeartBeatMIS(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(HeartBeat, e); + } + public void fun_WritePLC(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(WritePLC, e); + } + /// + /// 传递机型 + /// + /// + /// + public void fun_EngineTypeGetOverPLC(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(EngineTypeGetOver_PLC, e); + } + + /// + /// 合格放行 + /// + /// + /// + public void fun_ConfirmOkGo(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(ConfirmOkGo, e); + } + + /// + /// 不合格放行 + /// + /// + /// + public void fun_FalseGo(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(FalseGO, e); + } + + /// + /// 允许保存 + /// + /// + /// + public void fun_MesRead(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(MesRead, e); + } + + /// + /// 保存完成 + /// + /// + /// + public void fun_MesReadOver(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(MesReadOver, e); + } + + /// + /// 工件到位离开(清空所有的MES信号) + /// + /// + /// + public void fun_WorkStart(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(WorkStart, e); + } + + /// + /// 处理WEB页面发送过来的请求(m_Command + "|" + m_Value;) + /// + /// + /// + public void fun_WebSubmit(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(WebSubmit, e); + } + + /// + /// MES实时保存质量数据 + /// + /// + /// + public void fun_MesSaveNowData(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(MesSaveNowData, e); + } + + } +} diff --git a/MisDataFunction/MesServer.Function/Function1056/MesServerFunction/vssver2.scc b/MisDataFunction/MesServer.Function/Function1056/MesServerFunction/vssver2.scc new file mode 100644 index 0000000..a246f67 Binary files /dev/null and b/MisDataFunction/MesServer.Function/Function1056/MesServerFunction/vssver2.scc differ diff --git a/MisDataFunction/MesServer.Function/Function1056/Methods/EngineGetOverBaseWork.cs b/MisDataFunction/MesServer.Function/Function1056/Methods/EngineGetOverBaseWork.cs new file mode 100644 index 0000000..bd32165 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1056/Methods/EngineGetOverBaseWork.cs @@ -0,0 +1,109 @@ +using System; +using System.Data; +using bizFacade; +using MesServerWork; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 正常逻辑工作(传递机型) + /// + /// + /// + /// + /// + /// + private void EngineTypeGetOver_PLC_Work(string OpName, int EngineTypeID, string EngineType, string EngineID, int PartPallet_Code,string OrderForm) + { + int IsAllowWork; + int RepairPartStatusPLC = 0; + int MES_QualityMask = 1; + DataTable dt; + dt = BaseDataSystemMES.EngineTypeChange(OpName, EngineType); + + //通知web显示 + SendMessageFun.SendMessage("123", "111", OpName); + MIS_BASE.Read_PalletInfo(OpName, out MES_QualityMask);//合格标志 + SendMessageFun.SendInfomation("QualityMask", Convert.ToString(MES_QualityMask), OpName);//显示合格标志 + + MIS_BASE.Write_FixAllow(OpName, true); + + // 当A92 到位时表示当前一定是第二个件 先判断当前工件是否为已匹配的第二个工件 是的话是工作,不是报警 + Db.OPA92_EngineGetOverCheckWorkType(EngineID, out int MatchResult, out string MatchResultStr); + if (MatchResult == 1) + { + // 轮毂线 + MIS_BASE.Write_Match(OpName, true);// 匹配结果 + MIS_BASE.Write_MatchingCompleted(OpName, true);// 匹配完成 + MIS_BASE.Write_FixAllow(OpName, true); // 允许工作 + + return; + } + else + { + // 将根据轮毂号 工位号 时间 报错内容 存储到数据库中供查询 + // 匹配结果不成功 + MIS_BASE.Write_Match(OpName, false);// 匹配结果 + MIS_BASE.Write_MatchingCompleted(OpName, true);// 匹配完成 + return; + } + + //if (MES_QualityMask == 2) + //{ + // //工作完成 + // //MIS_BASE.Write_MaterialVerifyOver(OpName, true); + // //SendMessageFun.SendInfomation("NgGO", "1", OpName);//显示不合格标志 + // //return; + //} + + + //第三步,用于工件离开后完工数量统计及工件编号追溯 + //BaseDataSystemMES.MaterialPush_EngineIDStatus_Insert(OpName);//更新订单产量 + + ////第四步,获取是否允许工作 + //BaseDataSystemMES.MesServer_Judge_IsCanWork(OpName, out IsAllowWork); + + ////暂时先定义为扫描完成才能进行压装工作,因为考虑到工作完成后,操作工未必会去扫描物料的情况 + //if (IsAllowWork == 1) + //{ + // //通知PLC允许工作,允许工作在保存完成时清空 + // MIS_BASE.Write_FixAllow(OpName, true); + //} + //else + //{ + // SendMessageFun.AsyncSendMessage_Notice(OpName, "请扫描物料!"); + //} + + + + } + + + /// + /// 返修件需要工作 + /// + /// 工位号 + private void IsNeedRepaire_OK(string OpName) + { + string orderForm = ""; + int engineTypeID; + string engineType = ""; + string engineID = ""; + string palletCode = ""; + int isRepair; + string repairCode = ""; + //从监控系统中查询出本工位信息 + BaseDataSystemMES.OpName_MIS_Moby_Select(OpName, + out orderForm, out engineTypeID, out engineType, + out engineID, out palletCode, out isRepair, out repairCode); + + EngineTypeGetOver_PLC_Work(OpName, engineTypeID, engineType, engineID, Convert.ToInt32(palletCode),orderForm); + } + + + + + } +} diff --git a/MisDataFunction/MesServer.Function/Function1056/Methods/SubmitToMisweb.cs b/MisDataFunction/MesServer.Function/Function1056/Methods/SubmitToMisweb.cs new file mode 100644 index 0000000..52ce16f --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1056/Methods/SubmitToMisweb.cs @@ -0,0 +1,127 @@ +using System; +using bizFacade; +//using SystemFramework; + +namespace MesServerFunctions +{ + + /// + /// 此类用于向WEB发送各种类型消息 + /// + partial class FunctionMES + { + + /// + /// 批量发送WEB消息(Value为BOOL值) + /// + /// 消息编号组合 + /// 消息值组合 + /// 工位号 + void Sendmessage(string MessageNumm,string Value, string OpName) + { + for (int i=0;i + /// 选择发送给WEB的消息 + /// + /// 消息类型 + /// 消息工位 + string Sendmessage(char Num,string Value, string OpName) + { + string SendMessage; + string result = ""; + switch (Num) + { + case '1': + //1(直接在界面通过选择机型确认工序内容) + SendMessage = "MES|ProcessList|" + OpName + "|" + Value; + result = AsyncSendMessage(SendMessage); + break; + case '2': + //2显示物料 + SendMessage = "MES|MaterialList|" + OpName + "|" + Value; + result = AsyncSendMessage(SendMessage); + break; + case '3': + //3显示操作指导图片 + SendMessage = "MES|PicShow|" + OpName + "|" + Value; + result = AsyncSendMessage(SendMessage); + break; + case '4': + //4订单完工模块刷新完成数量 + SendMessage = "MES|OrderFormList|" + OpName + "|" + Value; + AsyncSendMessage(SendMessage); + break; + case '5': + SendMessage = "MES|ShowMoby|" + OpName + "|" + Value; + result = AsyncSendMessage(SendMessage); + break; + case '6': + SendMessage = "MES|MaterialCheckPosition|" + OpName + "|" +Value; + result = AsyncSendMessage(SendMessage); + break; + case '7': + SendMessage = "MES|WorkStart|" + OpName + "|" + Value; + result = AsyncSendMessage(SendMessage); + break; + case '8'://清除MES生成编号 + + break; + case '9': + SendMessage = "MES|ConfirmOkGo|" + OpName + "|" + Value; + result = AsyncSendMessage(SendMessage); + break; + case 'a': + SendMessage = "MES|FixAllow|" + OpName + "|" + Value; + result = AsyncSendMessage(SendMessage); + break; + } + return result; + } + /// + /// 向WEB发送信息(value为字符串) + /// + /// 消息种类 + /// 消息内容 + /// 工位号 + string SendInfomation(string Command, string Value, string OpName) + { + string SendMessage = "MES|" + Command + "|" + OpName + "|" + Value; + return AsyncSendMessage(SendMessage); + } + + + /// + /// 发送在线产量、在线节拍 + /// + /// + /// + private void SendActuallyCount(string OpName, int tagValue) + { + //当工件离开时,更新在线产量、在线节拍 + if (tagValue == 0) + { + try + { + int opNameCount = 0;//在线产量 + int opNameCountTime = 0;//在线节拍 + //基本数据_工作日历_班次产量查询_New + BaseDataSystemMES.OpNameCount_New(OpName, out opNameCount, out opNameCountTime); + string SendMessage; + SendMessage = "MES|ActuallyCount|" + OpName + "|" + opNameCount.ToString() + "&" + opNameCountTime.ToString(); + AsyncSendMessage(SendMessage); + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:SendActuallyCount"); + } + } + } + + + } +} diff --git a/MisDataFunction/MesServer.Function/Function1056/Methods/UDP.Send.cs b/MisDataFunction/MesServer.Function/Function1056/Methods/UDP.Send.cs new file mode 100644 index 0000000..aed7cc3 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1056/Methods/UDP.Send.cs @@ -0,0 +1,53 @@ +using bizFacade; +//using SystemFramework; +using MesServerWork; +using DataLinkMesWork; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 发送信息到MES通讯服务器或者其他的 + /// + /// + private string AsyncSendMessage(string Message) + { + return MIS_BASE.asyncSendMessage(Message); + } + + /// + /// 发送提示消息 + /// + /// + private void AsyncSendMessage_Notice(string opname, string notice) + { + //通知Web界面 + BaseDataSystemMES.Web_Notice_Insert(opname, notice); + string SendMessage = "MES|Notice|" + opname + "|" + "1"; + MIS_BASE.asyncSendMessage(SendMessage); + } + + /// + /// 发送信息到打印机 + /// + /// + private void asyncSendMessageToMark(string Message) + { + string messageSend = (string)Message; + //UDPClientSend.Send_ALL(ApplicationConfig.MES_MarkPortNum, messageSend); + } + + /// + /// 发送信息到LED + /// + /// + private void asyncSendMessageLED(string OpName) + { + //发送到大屏幕显示 41104 + string strMessage = "MIS|" + OpName + "|" + "0" + "|" + "1"; + //UDPClientSend.Send_ALL(ApplicationConfig.Port_ShowLED_ProductCount, strMessage); + + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1056/Methods/vssver2.scc b/MisDataFunction/MesServer.Function/Function1056/Methods/vssver2.scc new file mode 100644 index 0000000..7782f6f Binary files /dev/null and b/MisDataFunction/MesServer.Function/Function1056/Methods/vssver2.scc differ diff --git a/MisDataFunction/MesServer.Function/Function1056/OpcServer/Barcode.cs b/MisDataFunction/MesServer.Function/Function1056/OpcServer/Barcode.cs new file mode 100644 index 0000000..10a0ee6 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1056/OpcServer/Barcode.cs @@ -0,0 +1,98 @@ +using System; +using System.Windows.Forms; +using bizFacade; +//using SystemFramework; +using MesServerWork; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + ///1.扫描配送单号,用于接收物料,扫描单号的时候,将接收的物料信息显示在“物料拉动”Tab区域 + ///2.扫描料箱标签/看板卡,用于追溯物料批次信息 + ///3.扫描零件条码,根据零件图号进行防错 + ///第一步,判断条码类型,根据条码类型,执行对应的存储过程 + ///第二步,条码类型(将扫描的条码保存到对应的表中) + ///第三步,扫描完成之后给出允许工作信号 + /// 处理页面扫描条码 + /// + /// + /// + public void Barcode(object e) + { + + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + string barcode = Convert.ToString(msgEvent.TagValue); + string AlarmStr = ""; + + int IsAllowWork; + bool IsSuccess = false; + bool EngineGetOver_PLC_NextWorkStep; + //传递机型是否到位 + MIS_BASE.Read_EngineGetOver_PLC(OpName, out EngineGetOver_PLC_NextWorkStep); + if (!EngineGetOver_PLC_NextWorkStep) + { + SendMessageFun.AsyncSendMessage_Notice(OpName, "PLC未传递机型"); + return; + } + //物料验证 + BaseDataSystemMES.PartMaterial_DM_Update(OpName, barcode, out IsSuccess); + if (!IsSuccess) + { + SendMessageFun.AsyncSendMessage_Notice(OpName, "条码无效,请确认"); + return; + } + else + { + SendMessageFun.SendInfomation("MaterialList", "1", OpName);//通知界面更新零件信息 + } + + //获取是否允许工作 + BaseDataSystemMES.MesServer_Judge_IsCanWork(OpName, out IsAllowWork); + + //此处逻辑有问题 需要考虑到批次扫描 提示PLC未传递机型的情况 + if (IsAllowWork == 1) + { + //BaseDataSystemMES.Material_Insert(OpName, 1); + + //更新订单完工数量及物料 + SendMessageFun.SendMessage("24", "11", OpName); + + //工作完成 + //MIS_BASE.Write_MaterialVerifyOver(OpName, true); + //if (!BaseDataSystemMES.QualityVerifyStatusOutline(OpName, out AlarmStr)) + //{ + // SendInfomation("LineoutAlert", AlarmStr, OpName); + // return; + //} + //通知PLC允许工作,允许工作在保存完成时清空 + + //将机型信息传递给刷写站工控机 + + + MIS_BASE.Write_FixAllow(OpName, true); + } + else + { + SendMessageFun.AsyncSendMessage_Notice(OpName, "请扫描物料!"); + } + + + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:Barcode"); + } + + } + + } + + + } +} diff --git a/MisDataFunction/MesServer.Function/Function1056/OpcServer/ConfirmOkGo.cs b/MisDataFunction/MesServer.Function/Function1056/OpcServer/ConfirmOkGo.cs new file mode 100644 index 0000000..06e6b33 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1056/OpcServer/ConfirmOkGo.cs @@ -0,0 +1,41 @@ +using System; +using bizFacade; +//using SystemFramework; +using MesServerWork; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 合格放行 + /// + /// + /// + private void ConfirmOkGo(object e) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + + if (tagValue == 1) + { + + BaseDataSystemMES.Material_Insert(OpName, 1); + + //更新订单完工数量及物料 + Sendmessage("24", "11", OpName); + + //工作完成 + MIS_BASE.Write_MaterialVerifyOver(OpName, true); + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:ConfirmOkGo"); + } + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1056/OpcServer/EngineGetOver.cs b/MisDataFunction/MesServer.Function/Function1056/OpcServer/EngineGetOver.cs new file mode 100644 index 0000000..c5b6d6f --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1056/OpcServer/EngineGetOver.cs @@ -0,0 +1,67 @@ +using System; +using System.Data; +using System.Windows.Forms; +using System.Xml.Linq; +using bizFacade; +//using SystemFramework; +using MesServerWork; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// PLC传递机型处理 + /// + /// + /// + private void EngineTypeGetOver_PLC(object e) + { + + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + + if (tagValue == 1) + { + int EngineTypeID;//机型代码 + int PartPallet_Code;//托盘编号 + + string EngineType;//机型 + string EngineID;//工件编号 + string OrderForm; + MIS_BASE.GetEngineTypeFromPLC(OpName, out EngineTypeID, out EngineType, out EngineID, out PartPallet_Code, out OrderForm); + + if (EngineTypeID <= 0 || EngineID.Length == 0 || EngineType.Length == 0 || OrderForm.Length == 0) + { + SendMessageFun.AsyncSendMessage_Notice(OpName, "PLC传递机型为空"); + return; + } + + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.EngineTypeID, EngineTypeID.ToString()); + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.EngineType, EngineType); + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.EngineID, EngineID); + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.OrderForm, OrderForm); + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.PartPallet_Code, PartPallet_Code.ToString()); + //显示当前订单信息 + SendMessage.ShowMoby(OpName); + + EngineTypeGetOver_PLC_Work(OpName, EngineTypeID, EngineType, EngineID, PartPallet_Code, OrderForm); + + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:EngineTypeGetOver_PLC"); + } + } + + + } + + + } +} diff --git a/MisDataFunction/MesServer.Function/Function1056/OpcServer/FalseGO.cs b/MisDataFunction/MesServer.Function/Function1056/OpcServer/FalseGO.cs new file mode 100644 index 0000000..4ad2665 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1056/OpcServer/FalseGO.cs @@ -0,0 +1,41 @@ +using System; +using bizFacade; +//using SystemFramework; +using MesServerWork; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 不合格放行 + /// + /// + /// + private void FalseGO(object e) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + + if (tagValue == 1) + { + //总合格标志2(不合格) + + BaseDataSystemMES.Material_Insert_NG(OpName, 2); + + Sendmessage("24", "11", OpName); + + //工作完成 + MIS_BASE.Write_MaterialVerifyOver(OpName, true); + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:FalseGO"); + } + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1056/OpcServer/HeartBeat.cs b/MisDataFunction/MesServer.Function/Function1056/OpcServer/HeartBeat.cs new file mode 100644 index 0000000..93affd3 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1056/OpcServer/HeartBeat.cs @@ -0,0 +1,35 @@ +using bizFacade; +using MesServerWork; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// MES与PLC心跳监听 + /// + /// + /// + private void HeartBeat(object e) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + + //返写在MES心跳中 + MIS_BASE.WritePLC(15, OpName, tagValue); + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:FalseGO"); + } + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1056/OpcServer/MesRead.cs b/MisDataFunction/MesServer.Function/Function1056/OpcServer/MesRead.cs new file mode 100644 index 0000000..a577ea9 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1056/OpcServer/MesRead.cs @@ -0,0 +1,92 @@ +using bizFacade; +using MesServerWork; +using System; +//using SystemFramework; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 允许保存(针对半自动和手动压装工位) + /// + /// + /// + private void MesRead(object e) + { + { + try + { + + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + + if (tagValue == 1) + { + int qualityMask; + + //保存质量数据 + qualityMask = MisDataSaveDateMesRead.Funtion.MesRead(OpName, tagValue.ToString(), msgEvent.TagID.ToString()); + //保存物料数据 + BaseDataSystemMES.Material_Insert(OpName, qualityMask); + + //测量数据发动机在线状态 + BaseDataSystemMES.WorkStartInsert(OpName, qualityMask); + + //推送质量数据到MES的页面 + SendMessageFun.SendInfomation("ShowTimelyQuality", "1&" + qualityMask.ToString(), OpName); + + + //对应手动工位的 + //MIS_BASE.Write_ConfirmOkGo(OpName, true); + + + //MIS_BASE.Write_FixAllow(OpName, false); + + //MIS_BASE.Write_ConfirmOkGo(OpName, false); + + + //MIS_BASE.Write_FixOver(OpName, false); + //MIS_BASE.Write_MaterialVerifyOver(OpName, false); + + + //统计在线产量,在线节拍 + // SendMessage.SendActuallyCount(OpName, tagValue); + + // 判断050 工位是否有传递机型 有的话 允许050工作 同时删除记录表中轮毂号 + MIS_BASE.Read_EngineGetOver_PLC("OP050", out bool EngineGetOver_PLC_NextWorkStep); + if (EngineGetOver_PLC_NextWorkStep) + { + MIS_BASE.Write_FixAllow("OP050", true); + // 查询050 工位当前到位的工件编号 + MIS_BASE.Read_EngineID("OP050", out string OP050_EngineID); + // 绑定关系 同时 删除记录 + Db.OPA92_DeleteLineData(OP050_EngineID); + } + + //通知设备,MES的质量数据(和物料数据)保存完成 + MIS_BASE.Write_MesReadOver(OpName, true); + } + else + { + MIS_BASE.Write_MesReadOver(OpName, false); + MIS_BASE.Write_ConfirmOkGo(OpName, false); + MIS_BASE.Write_FixAllow(OpName, false); + MIS_BASE.Write_ConfirmOkGo(OpName, false); + //工作完成 + MIS_BASE.Write_MaterialVerifyOver(OpName, false); + } + } + + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function08:MesReadOver"); + } + } + + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1056/OpcServer/MesReadOver.cs b/MisDataFunction/MesServer.Function/Function1056/OpcServer/MesReadOver.cs new file mode 100644 index 0000000..f96a7d3 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1056/OpcServer/MesReadOver.cs @@ -0,0 +1,55 @@ +using System; +//using SystemFramework; +using MesServerWork; +using bizFacade; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 保存完成(针对半自动和手动压装工位) + /// + /// + /// + private void MesReadOver(object e) + { + //try + //{ + // DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + // string OpName = Convert.ToString(msgEvent.OpName); + // var tagValue = msgEvent.TagValue.ToString (); + + // if (tagValue == "1" | tagValue.ToLower () == "true") + // { + // int qualityMask; + // MIS_BASE.Read_QualityMask(OpName, out qualityMask); + + // SendInfomation("ShowTimelyQuality", "1&" + qualityMask.ToString(), OpName);//发给Web页面显示质量数据 + + // if (qualityMask == 1)//全部OK,给出合格放行 + // { + // //如果存在线外扫描工位,根据扫描条码绑定线外数据 需要时解除禁用 + // //BaseDataSystemMES.TransLaunchDataByMainMaterial(OpName, EngineType, EngineID, EngineTypeID); + + // //如果存在线外排队工位,根据排队编号绑定线外数据 需要时解除禁用 + // ////BaseDataSystemMES.MailLineAndSubLineData_InsertByEngineID_Subline(OpName,EngineID, EngineTypeID, EngineType); + + // MIS_BASE.Write_ConfirmOkGo(OpName, true); + // //MIS_BASE.Write_FalseGO(OpName, false); + // } + // else + // { + // //MIS_BASE.Write_ConfirmOkGo(OpName, false); + // MIS_BASE.Write_FalseGO(OpName, true); + // } + + // } + //} + //catch (Exception err) + //{ + // ////ApplicationLog.WriteLog(err, "Function02:MesReadOver"); + //} + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1056/OpcServer/MesSaveNowData.cs b/MisDataFunction/MesServer.Function/Function1056/OpcServer/MesSaveNowData.cs new file mode 100644 index 0000000..63c11b3 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1056/OpcServer/MesSaveNowData.cs @@ -0,0 +1,40 @@ +using bizFacade; +using MesServerWork; +using System; +using System.Collections.Generic; +using System.Data; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; +using static System.Net.Mime.MediaTypeNames; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// MES保存实时质量数据 + /// + /// + /// + private void MesSaveNowData(object e) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + // 直接发送实时的 质量数据 + string message = MisDataSaveDateMesRead.Funtion.GetRealTimeQualityData(OpName); + //推送质量数据到MES的页面 + SendMessage.AsyncSendMessage("MES|ShowTimelyQuality_Resources|" + OpName + "|" + message); + //SendMessageFun.SendMessageMESToWEB("ShowTimelyQuality", "1&" + qualityMask.ToString(), OpName); + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:FalseGO"); + } + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1056/OpcServer/WebSubmit.cs b/MisDataFunction/MesServer.Function/Function1056/OpcServer/WebSubmit.cs new file mode 100644 index 0000000..6a088b5 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1056/OpcServer/WebSubmit.cs @@ -0,0 +1,294 @@ +using System; +using MesServerWork; +using bizFacade; +using System.Threading; +using MisDataSaveDate; +using System.Collections; +//using SystemFramework; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 处理WEB页面发送过来的请求(m_Command + "|" + m_Value;) + /// + /// + /// + private void WebSubmit(object e) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName=Convert.ToString(msgEvent.OpName); + string Content = Convert.ToString(msgEvent.TagValue); + + string[] dataArray = Content.Split('|'); + if (dataArray.Length != 2) + return; + //消息类型 + string m_Command = dataArray[0].ToString(); + //消息参数 + string m_Value = dataArray[1].ToString(); + //消息参数数量 + string[] m_Value_array = m_Value.Split('&'); + //消息参数长度 + int m_Value_length = m_Value_array.Length; + + //工件信息 + string engineID = ""; + if (MIS_BASE.hashtable_EngineGetOver_EngineTypeID == null) + { + MIS_BASE.InitHashtable_MesServerCode(); + } + if (MIS_BASE.hashtable_EngineGetOver_EngineID.ContainsKey(OpName)) + { + engineID = MIS_BASE.hashtable_EngineGetOver_EngineID[OpName].ToString(); + } + + DoWhatPlc.CustomeEvetnArgs _e = new DoWhatPlc.CustomeEvetnArgs(); + _e.OpName = OpName; + _e.TagValue = m_Value; + + //根据请求的命令处理逻辑 + switch (m_Command) + { + case "WritePLC": + if (m_Value_length > 1) return; + fun_WritePLC(_e); + break; + case "Barcode": + if (m_Value_length > 1) return; + fun_Barcode(_e); + break; + case "ConfirmOkGo"://合格放行 + //删除不合格放行记录 + //修改托盘状态 + //Update_PalletStatus(OpName, 1, false); + BaseDataSystemMES.BaseData_tagTable_Engine_IsNG_Delete(OpName, engineID); + MIS_BASE.Write_ConfirmOkGo(OpName, true); + MIS_BASE.Write_FalseGO(OpName, false); + Thread.Sleep(1000); + MIS_BASE.Write_ConfirmOkGo(OpName, false); + break; + case "FalseGO"://返修放行 + //修改托盘状态 + //Update_PalletStatus(OpName, 3, false); + BaseDataSystemMES.BaseData_tagTable_Engine_IsNG_Delete(OpName, engineID); + MIS_BASE.Write_FalseGO(OpName, true); + MIS_BASE.Write_ConfirmOkGo(OpName, false); + Thread.Sleep(1000); + MIS_BASE.Write_FalseGO(OpName, false); + break; + case "NgGO"://不合格放行 + //修改托盘状态 + //Update_PalletStatus(OpName, 2, false); + //保存不合格信息(必须保存不合格放行信息,由于B5A的Moby没有不合格标志位) + BaseDataSystemMES.BaseData_tagTable_Engine_IsNG_Insert(OpName, engineID, "", ""); + MIS_BASE.Write_FalseGO(OpName, true); + MIS_BASE.Write_ConfirmOkGo(OpName, false); + Thread.Sleep(1000); + MIS_BASE.Write_FalseGO(OpName, false); + break; + case "OnLineState"://在线0、离线1、屏蔽2 + try + { + if (m_Value_length > 1) return; + int a = Convert.ToInt32(m_Value); + if (a <= 2) + { + BaseDataSystemMES.IsOnLine_Update(OpName, m_Value.ToString()); + MIS_BASE.Write_OnLineState(OpName, Convert.ToInt32(m_Value)); + if (a == 2) SendMessage.AsyncSendMessage_Notice(OpName, "屏蔽MES!"); + if (a == 0) SendMessage.AsyncSendMessage_Notice(OpName, "启用MES!"); + } + } + catch + { + + } + break; + case "Reset"://复位,将MES所有的信息都复位了 + SetMoby(OpName);//将MES所有信号清空 + break; + case "FixAllow"://重新拧紧 + MIS_BASE.Write_FixAllow(OpName, false); + MIS_BASE.Write_FixAllow(OpName, true); + break; + case "IsAutoGetEngineID"://自动手动申请编号(线首) + if (m_Value_length > 1) return; + MIS_BASE.Write_IsAutoGetEngineID(OpName, Convert.ToInt32(m_Value)); + break; + case "PartPalletGoOver"://空托盘放行 + int Is_PartPalletGoOver; + MIS_BASE.Read_PartPalletGoOver(OpName, out Is_PartPalletGoOver); + if (Is_PartPalletGoOver == 1) + { + MIS_BASE.Write_PartPalletGoOver(OpName, 1); + } + else + { + MIS_BASE.Write_PartPalletGoOver(OpName,0); + } + break; + case "SetMoby"://清空托盘(线首) + SetMoby(OpName);//将MES所有信号清空 + //MIS_BASE.Write_PartPalletCode_PLC(OpName, 1); + break; + case "RepairUplineMES"://返修上线 + MIS_BASE.Write_RepairUpline_MES(OpName, true); + break; + case "CancelRepair"://将返修件置为正常件 + + break; + case "PartPalletCode"://申请写入托盘号 + //MIS_BASE.Write_PartPalletCode_PLC(OpName, 1); + break; + case "WritePartPalletCode"://写入托盘号 + if (m_Value_length > 1) return; + MIS_BASE.Write_PalletCode(OpName, Convert.ToInt32(m_Value)); + break; + case "Normal"://启用正常拧紧工位 + MIS_BASE.Write_Normal(OpName, 1); + MIS_BASE.Write_UnNormal(OpName, 0); + break; + case "UnNormal"://启用备用拧紧工位 + MIS_BASE.Write_Normal(OpName, 0); + MIS_BASE.Write_UnNormal(OpName, 1); + break; + case "ResetDevice"://复位设备 + MIS_BASE.Write_ResetDevice(OpName, true); + System.Threading.Thread.Sleep(1000); + MIS_BASE.Write_ResetDevice(OpName, false); + break; + case "IsNeedRepaire"://返修上线(返修上线点) + if (Convert.ToInt32(m_Value) == 1) + { + //修改托盘状态 + MIS_BASE.Write_PalletInfo(OpName, 3); + //通知修改成功 + MIS_BASE.Write_UpdatePalletOK(OpName, true); + IsNeedRepaire_OK(OpName); + + } + else if (Convert.ToInt32(m_Value) == 0) + { + //通知修改成功 + MIS_BASE.Write_UpdatePalletOK(OpName, true); + //直接给出工作完成 + MIS_BASE.Write_MaterialVerifyOver(OpName, true); + } + else + { } + + break; + case "ContinueMatch": + BaseDataSystemMES.QualityVerifyStatus_Hash_Write(OpName, true); + break; + //初始化网页信号 + case "IniSingalToWeb": + InitializeSingalToWeb(OpName); + break; + case "Reset_Engine"://返修上线(返修上线点) + SetMoby(OpName);//将MES所有信号清空 + //fun_EngineTypeGetOverPLC(OpName, 0); + //fun_EngineTypeGetOverPLC(OpName, 1); + break; + + + default: break; + } + } + catch(Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:WebSubmit"); + } + } + private void SetMoby(string OpName) + { + try + { + //清空Moby时,需要将MES信号清空 + MIS_BASE.Write_ClearMesMoby(OpName); + + BaseDataSystemMES.MesServer_Process_EngineTypeOver(OpName); + + Sendmessage("5123", "1111", OpName); + + MIS_BASE.Write_ResetDevice(OpName, true); + System.Threading.Thread.Sleep(1000); + MIS_BASE.Write_ResetDevice(OpName, false); + } + catch + { + + } + } + /// 网页重现登录,恢复关闭前的页面状态 + /// + /// 工位号 + private void InitializeSingalToWeb(string Opname) + { + + //工件到位 DBX0.1 + bool S_WorkStart; + bool S_FixAllow; + bool S_EngineGetOver; + bool S_MaterialVerifyOver; + + MIS_BASE.Read_WorkStart(Opname, out S_WorkStart); + MIS_BASE.Read_FixAllow(Opname, out S_FixAllow); + MIS_BASE.Read_EngineGetOver_PLC(Opname, out S_EngineGetOver); + MIS_BASE.Read_MaterialVerifyOver(Opname, out S_MaterialVerifyOver); + + Sendmessage("13", "1111", Opname); + string S_plcStatus;//DBX501.5 PLC直通,1 强制放行 0 正常循环 + // 新增查询PLC直通状态 网页显示 + MIS_BASE.Read_TagTypeID(63, Opname, out S_plcStatus); + if (S_plcStatus.ToLower() == "false") + { + SendMessageFun.SendInfomation("PlcStatus", "0", Opname); + } + else + { + SendMessageFun.SendInfomation("PlcStatus", "1", Opname); + } + + if (S_WorkStart == true) + { + SendInfomation("WorkStart", Convert.ToString(Convert.ToInt32(S_WorkStart)), Opname); + } + + if (S_FixAllow == true) + { + SendInfomation("FixAllow", Convert.ToString(Convert.ToInt32(S_FixAllow)), Opname); + } + if (S_MaterialVerifyOver == true) + { + SendInfomation("MaterialVerifyOver", Convert.ToString(Convert.ToInt32(S_MaterialVerifyOver)), Opname); + } + if (S_EngineGetOver == true) + { + SendInfomation("EngineTypeGetOverPLC", Convert.ToString(Convert.ToInt32(S_EngineGetOver)), Opname); + Sendmessage("2", "1111", Opname); + SendMessage.ShowMoby(Opname); + // 直接发送实时的 质量数据 + string message = MisDataSaveDateMesRead.Funtion.GetRealTimeQualityData(Opname); + //推送质量数据到MES的页面 + SendMessage.AsyncSendMessage("MES|ShowTimelyQuality_Resources|" + Opname + "|" + message); + } + InitAlarm(Opname); + } + private void InitAlarm(string Opname) + { + FuntionMesRead.Alarm_InitAlarm_Send(Opname, out Hashtable ht); + foreach (DictionaryEntry kv in ht) + { + var TagID = kv.Key.ToString(); + var TagValue = kv.Value.ToString(); + FuntionMesRead.Send_AlarmMsg(TagID, TagValue); + } + + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1056/OpcServer/WorkStart.cs b/MisDataFunction/MesServer.Function/Function1056/OpcServer/WorkStart.cs new file mode 100644 index 0000000..da1ef0a --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1056/OpcServer/WorkStart.cs @@ -0,0 +1,46 @@ +using bizFacade; +using MesServerWork; +using System; +//using SystemFramework; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 工件到位与离开时,清空MES自身信号 + /// + /// + /// + private void WorkStart(object e) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + if (tagValue > 0) + { + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.WorkStartIn, DateTime.Now.ToString()); + } + else + { + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.WorkStartOut, DateTime.Now.ToString()); + //后加,清空信号 + MIS_BASE.Write_MesReadOver(OpName, false); + MIS_BASE.Write_ConfirmOkGo(OpName, false); + MIS_BASE.Write_FixAllow(OpName, false); + MIS_BASE.Write_ConfirmOkGo(OpName, false); + MIS_BASE.Write_EngineTypeGetOver_MES(OpName, false); + //工作完成 + MIS_BASE.Write_MaterialVerifyOver(OpName, false); + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:WorkStart"); + } + } + + } +} diff --git a/MisDataFunction/MesServer.Function/Function1056/OpcServer/WritePLC.cs b/MisDataFunction/MesServer.Function/Function1056/OpcServer/WritePLC.cs new file mode 100644 index 0000000..83ede7c --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1056/OpcServer/WritePLC.cs @@ -0,0 +1,41 @@ +using System; +using System.Windows.Forms; +using bizFacade; +//using SystemFramework; +using MesServerWork; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + ///1.扫描配送单号,用于接收物料,扫描单号的时候,将接收的物料信息显示在“物料拉动”Tab区域 + ///2.扫描料箱标签/看板卡,用于追溯物料批次信息 + ///3.扫描零件条码,根据零件图号进行防错 + ///第一步,判断条码类型,根据条码类型,执行对应的存储过程 + ///第二步,条码类型(将扫描的条码保存到对应的表中) + ///第三步,扫描完成之后给出允许工作信号 + /// 处理页面扫描条码 + /// + /// + /// + public void WritePLC(object e) + { + + { + try + { + + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:Barcode"); + } + + } + + } + + + } +} diff --git a/MisDataFunction/MesServer.Function/Function1056/OpcServer/vssver2.scc b/MisDataFunction/MesServer.Function/Function1056/OpcServer/vssver2.scc new file mode 100644 index 0000000..b884d13 Binary files /dev/null and b/MisDataFunction/MesServer.Function/Function1056/OpcServer/vssver2.scc differ diff --git a/MisDataFunction/MesServer.Function/Function1056/Properties/AssemblyInfo.cs b/MisDataFunction/MesServer.Function/Function1056/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..0bb79c4 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1056/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// 有关程序集的常规信息通过以下 +// 特性集控制。更改这些特性值可修改 +// 与程序集关联的信息。 +[assembly: AssemblyTitle("Function02")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("苏州宏软信息技术有限公司")] +[assembly: AssemblyProduct("Function02")] +[assembly: AssemblyCopyright("Copyright © 苏州宏软信息技术有限公司 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// 将 ComVisible 设置为 false 使此程序集中的类型 +// 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型, +// 则将该类型上的 ComVisible 特性设置为 true。 +[assembly: ComVisible(false)] + +// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID +[assembly: Guid("47710f2c-e141-4252-8d13-701bf4c1c027")] + +// 程序集的版本信息由下面四个值组成: +// +// 主版本 +// 次版本 +// 内部版本号 +// 修订号 +// +// 可以指定所有这些值,也可以使用“内部版本号”和“修订号”的默认值, +// 方法是按如下所示使用“*”: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/MisDataFunction/MesServer.Function/Function1056/Properties/vssver2.scc b/MisDataFunction/MesServer.Function/Function1056/Properties/vssver2.scc new file mode 100644 index 0000000..14e543b Binary files /dev/null and b/MisDataFunction/MesServer.Function/Function1056/Properties/vssver2.scc differ diff --git a/MisDataFunction/MesServer.Function/Function1056/app.config b/MisDataFunction/MesServer.Function/Function1056/app.config new file mode 100644 index 0000000..b4c4daf --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1056/app.config @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + + + diff --git a/MisDataFunction/MesServer.Function/Function1056/mssccprj.scc b/MisDataFunction/MesServer.Function/Function1056/mssccprj.scc new file mode 100644 index 0000000..119193d --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1056/mssccprj.scc @@ -0,0 +1,5 @@ +SCC = This is a Source Code Control file + +[Function02.csproj] +SCC_Aux_Path = "\\192.168.0.100\vss\MES4.0" +SCC_Project_Name = "$/MisData/MisData/MisData/MesServer.Function/Function02", ILHAAAAA diff --git a/MisDataFunction/MesServer.Function/Function1056/packages.config b/MisDataFunction/MesServer.Function/Function1056/packages.config new file mode 100644 index 0000000..b3e1761 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1056/packages.config @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/MisDataFunction/MesServer.Function/Function1056/vssver2.scc b/MisDataFunction/MesServer.Function/Function1056/vssver2.scc new file mode 100644 index 0000000..c770e28 Binary files /dev/null and b/MisDataFunction/MesServer.Function/Function1056/vssver2.scc differ diff --git a/MisDataFunction/MesServer.Function/Function1057/DataAccess/DataAccess.cs b/MisDataFunction/MesServer.Function/Function1057/DataAccess/DataAccess.cs new file mode 100644 index 0000000..574d619 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1057/DataAccess/DataAccess.cs @@ -0,0 +1,15 @@ + +namespace MesServerFunctions +{ + partial class Function1052 + { + //针对“MIS.BizFacade.Dll”中没有的存储过程,在此类中新建 + //新建原则:所有的函数用private,只允许在内部使用 + //针对单个工艺特殊,需要新建存储过程,但是存储过程不能被加入到“MIS.BizFacade.Dll”中 + + private void aa() + { + + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1057/DataAccess/vssver2.scc b/MisDataFunction/MesServer.Function/Function1057/DataAccess/vssver2.scc new file mode 100644 index 0000000..d045c26 Binary files /dev/null and b/MisDataFunction/MesServer.Function/Function1057/DataAccess/vssver2.scc differ diff --git a/MisDataFunction/MesServer.Function/Function1057/Db.cs b/MisDataFunction/MesServer.Function/Function1057/Db.cs new file mode 100644 index 0000000..0e1fdc9 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1057/Db.cs @@ -0,0 +1,67 @@ +using System; +using System.Collections.Generic; +using System.Data.SqlClient; +using System.Data; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using DataLinkMesWork; + +namespace MesServerFunctions +{ + public class Db + { + /// + /// 合力_OPA90是否允许工作_判断 如果允许工作则将两个轮毂状态设为待匹配 + /// + /// + /// + /// + /// + /// + /// + /// + public static bool OP50_OPA90_MatchResult(int EngineTypeID, int EngineTypeID_QiaoKe, string EngineID, string OrderForm, out int MatchResult, out string MatchResultStr) + { + DataTable dt = new DataTable(); + MatchResult = 3;// 默认是报警 程序出错 + MatchResultStr = "默认是报警 程序出错";// 默认是报警 程序出错 + string produceName = "合力_OPA90是否允许工作_判断"; + SqlParameter[] thisParms = new SqlParameter[4]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@轮毂机型", EngineTypeID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@轮毂总成号", EngineID); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@桥壳_机型", EngineTypeID_QiaoKe); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@订单号", OrderForm); + if (DataAccess.ExecuteStoredProcedure(produceName, ref thisParms, out dt)) + { + if (dt.Rows.Count > 0) + { + MatchResult = Convert.ToInt32(dt.Rows[0]["最终结果"]); + MatchResultStr = dt.Rows[0]["最终结果说明"].ToString(); + return true; + } + } + return false; + } + + public static bool OP051_OP050_NeedWork(string EngineID, string opName, string orderForm, out int MatchResult) + { + DataTable dt = new DataTable(); + MatchResult = 0; + string produceName = "合力_OP050前停判断_下工位是否需要工作"; + SqlParameter[] thisParms = new SqlParameter[3]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@桥壳总成号", EngineID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@订单号", orderForm); + if (DataAccess.ExecuteStoredProcedure(produceName, ref thisParms, out dt)) + { + if (dt.Rows.Count > 0) + { + MatchResult = Convert.ToInt32(dt.Rows[0]["是否需要工作"]); + return true; + } + } + return false; + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1057/Function02.csproj.vspscc b/MisDataFunction/MesServer.Function/Function1057/Function02.csproj.vspscc new file mode 100644 index 0000000..0f0f36c --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1057/Function02.csproj.vspscc @@ -0,0 +1,10 @@ +"" +{ +"FILE_VERSION" = "9237" +"ENLISTMENT_CHOICE" = "NEVER" +"PROJECT_FILE_RELATIVE_PATH" = "relative:MesServer.Function\\Function02" +"NUMBER_OF_EXCLUDED_FILES" = "0" +"ORIGINAL_PROJECT_FILE_PATH" = "" +"NUMBER_OF_NESTED_PROJECTS" = "0" +"SOURCE_CONTROL_SETTINGS_PROVIDER" = "PROVIDER" +} diff --git a/MisDataFunction/MesServer.Function/Function1057/Function1057.csproj b/MisDataFunction/MesServer.Function/Function1057/Function1057.csproj new file mode 100644 index 0000000..ad1f4d9 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1057/Function1057.csproj @@ -0,0 +1,167 @@ + + + + Debug + AnyCPU + 8.0.30703 + 2.0 + {5FC3B1B6-B5BB-423E-AF5B-60A115507594} + Library + Properties + Function1057 + Function1057 + v4.8 + 512 + + + + + + + + + + + + + + true + full + false + ..\..\..\dll_fun\ + DEBUG;TRACE + prompt + 4 + false + false + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + false + + + + ..\..\..\Common\dll\MQTTnet.dll + + + ..\..\..\Common\dll\MQTTnet.Extensions.ManagedClient.dll + + + False + ..\..\..\Common\dll\Newtonsoft.Json.dll + + + + + + ..\..\DLL\System.Net.Http.dll + + + ..\..\packages\System.Net.Security.4.3.2\lib\net46\System.Net.Security.dll + + + ..\..\packages\System.Net.WebSockets.4.3.0\lib\net46\System.Net.WebSockets.dll + + + ..\..\packages\System.Net.WebSockets.Client.4.3.2\lib\net46\System.Net.WebSockets.Client.dll + + + ..\..\packages\System.Security.Cryptography.Algorithms.4.3.0\lib\net461\System.Security.Cryptography.Algorithms.dll + + + ..\..\packages\System.Security.Cryptography.Encoding.4.3.0\lib\net46\System.Security.Cryptography.Encoding.dll + + + ..\..\packages\System.Security.Cryptography.Primitives.4.3.0\lib\net46\System.Security.Cryptography.Primitives.dll + + + ..\..\packages\System.Security.Cryptography.X509Certificates.4.3.0\lib\net461\System.Security.Cryptography.X509Certificates.dll + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + {f55da1a0-a982-4479-8c47-0d9a5aaf3e18} + 00MesWorkMqtt + + + {0d1af432-439a-4920-8692-43ae139f5530} + 01_01DoWhatPlc + + + {3e6d1dd5-01c9-435f-9941-61f906ce35bb} + 02_02WebApiCallPLC + + + {f434e066-4c59-47c8-aa82-6f48cc84501a} + 04-DataBaseAccess + + + {f0a0c525-03fd-428a-9b17-7f54aa0e4475} + 07BusinessFacade + + + {d98be764-adeb-488d-9714-61e308aa8201} + 08-WebFun_base + + + {90e76fb4-646d-45e2-95db-0b8ab4e465d6} + 09-MesDataFunction + + + {e4eb6420-906d-4672-947a-ca33ddcdadfc} + 12SendMessageToWeb + + + {55b510c1-59e9-4bfd-ae84-d76d46f6e365} + 02-13.3MIS_FuntionSaveData + + + + + + + 这台计算机上缺少此项目引用的 NuGet 程序包。使用“NuGet 程序包还原”可下载这些程序包。有关更多信息,请参见 http://go.microsoft.com/fwlink/?LinkID=322105。缺少的文件是 {0}。 + + + + + \ No newline at end of file diff --git a/MisDataFunction/MesServer.Function/Function1057/MesServerFunction/Fun_1057.cs b/MisDataFunction/MesServer.Function/Function1057/MesServerFunction/Fun_1057.cs new file mode 100644 index 0000000..6a943b5 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1057/MesServerFunction/Fun_1057.cs @@ -0,0 +1,206 @@ +using MesServerWork; +using System.Collections.Generic; +using System.Threading; +using System.Xml.Linq; + +namespace MesServerFunctions +{ + public partial class FunctionMES + { + object lockFunWork; + //public void FunWork(DoWhatPlc.CustomeEvetnArgs e) + public void FunWork(string recData) + { + + + lockFunWork = new object(); + lock (lockFunWork) + { + List dataArray = DoWhatPlc.MessageText.GetCmdStringList(recData); + //string[] dataArray = recData.Split('|'); + //if (dataArray.Count != 4) + //return; + //消息来源 + string m_Source = dataArray[0].ToString(); + //消息类型 Barcode + string m_Command = dataArray[1].ToString(); + //工位号 + string m_OpName = dataArray[2].ToString(); + //消息参数 + string m_Value = dataArray[3].ToString(); + + DoWhatPlc.CustomeEvetnArgs e = new DoWhatPlc.CustomeEvetnArgs();// = Newtonsoft.Json.JsonConvert.DeserializeObject(m_Value); + string tagValue; + + switch (m_Source) + { + case "BarCode": + e.OpName = m_OpName; + e.TagValue = m_Value; + fun_Barcode(e); + break; + case "WEB": + e.OpName = m_OpName; + e.TagValue = m_Command + "|" + m_Value; + fun_WebSubmit(e); + break; + case "PLC": + e = Newtonsoft.Json.JsonConvert.DeserializeObject(m_Value); + switch (e.TagValue.ToString().ToLower()) + { + case "false": + tagValue = "0"; + break; + case "true": + tagValue = "1"; + break; + default: + tagValue = e.TagValue.ToString(); + break; + } + e.TagValue = tagValue; + switch (e.TagTypeCodeID.ToString()) + { + //PLC 工件到位 + case "2": + fun_WorkStart(e); + break; + //PLC 允许保存质量数据 + case "19": + fun_MesRead(e); + break; + //MES 保存数据完成 + case "20": + fun_MesReadOver(e); + break; + //PLC 传递机型 + case "44": + fun_EngineTypeGetOverPLC(e); + break; + //MES 合格放行 + case "51": + fun_ConfirmOkGo(e); + break; + //MES 不合格放行 + case "8": + fun_FalseGo(e); + break; + //MES 系统健康心跳 + case "14": + fun_HeartBeatMIS(e); + break; + case "63": + string S_plcStatus;//DBX501.5 PLC直通,1 强制放行 0 正常循环 + MIS_BASE.Read_TagTypeID(63, m_OpName, out S_plcStatus); + if (S_plcStatus.ToLower() != "true" || S_plcStatus.ToLower() == "1") + { + SendMessageFun.SendInfomation("PlcStatus", "0", m_OpName); + } + else + { + SendMessageFun.SendInfomation("PlcStatus", "1", m_OpName); + } + break; + } + break; + } + } + } + + //1.工件到位后,PLC给MES传递机型(DBX0.4)(44), + //MES判断条码是否全部扫描完成 + //PLC给出允许保存(DBX100.2)(19),MES见到(DBX100.2)(19)为1后给出保存完成(DBX102.2)(20), + //PLC见到保存完成(DBX102.2)(20)为1后,清空允许保存(DBX100.2)(19), + //MES见到允许保存(DBX100.2)(19)为0后,清空保存完成(DBX102.2)(20) + //MES判断总合格标志(INT104)(21)为1后,给出合格放行(DBX2.5)(51) + /// + /// 扫描条码 + /// + /// + /// + public void fun_Barcode(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(Barcode, e); + } + + /// + /// 传递机型 + /// + /// + /// + public void fun_EngineTypeGetOverPLC(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(EngineTypeGetOver_PLC, e); + } + /// + /// 系统健康心跳监测 + /// + /// + /// + public void fun_HeartBeatMIS(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(HeartBeat, e); + } + /// + /// 合格放行 + /// + /// + /// + public void fun_ConfirmOkGo(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(ConfirmOkGo, e); + } + + /// + /// 不合格放行 + /// + /// + /// + public void fun_FalseGo(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(FalseGO, e); + } + + /// + /// 允许保存 + /// + /// + /// + public void fun_MesRead(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(MesRead, e); + } + + /// + /// 保存完成 + /// + /// + /// + public void fun_MesReadOver(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(MesReadOver, e); + } + + /// + /// 工件到位离开(清空所有的MES信号) + /// + /// + /// + public void fun_WorkStart(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(WorkStart, e); + } + + /// + /// 处理WEB页面发送过来的请求(m_Command + "|" + m_Value;) + /// + /// + /// + public void fun_WebSubmit(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(WebSubmit, e); + } + + + } +} diff --git a/MisDataFunction/MesServer.Function/Function1057/MesServerFunction/vssver2.scc b/MisDataFunction/MesServer.Function/Function1057/MesServerFunction/vssver2.scc new file mode 100644 index 0000000..a246f67 Binary files /dev/null and b/MisDataFunction/MesServer.Function/Function1057/MesServerFunction/vssver2.scc differ diff --git a/MisDataFunction/MesServer.Function/Function1057/Methods/EngineGetOverBaseWork.cs b/MisDataFunction/MesServer.Function/Function1057/Methods/EngineGetOverBaseWork.cs new file mode 100644 index 0000000..edaa222 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1057/Methods/EngineGetOverBaseWork.cs @@ -0,0 +1,98 @@ +using System; +using System.Data; +using bizFacade; +using MesServerWork; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 正常逻辑工作(传递机型) + /// + /// + /// + /// + /// + /// + private void EngineTypeGetOver_PLC_Work(string OpName, int EngineTypeID, string EngineType, string EngineID, int PartPallet_Code,string OrderForm) + { + int IsAllowWork; + int RepairPartStatusPLC = 0; + int MES_QualityMask = 1; + DataTable dt; + dt = BaseDataSystemMES.EngineTypeChange(OpName, EngineType); + //提示机型发生变化 + if (dt.Rows.Count > 0) + { + string mesValue = Newtonsoft.Json.JsonConvert.SerializeObject(dt);//(recData); + string message = "MES|MaterialList_Dif_Resources|" + OpName + "|" + mesValue; + SendMessage.AsyncSendMessage(message); + } + + //电子看板_装配零件_临时表_增加_北汽 + //第二步,将零件信息转移到零件_临时表中 + BaseDataSystemMES.MesServer_Process_EngineTypeOverBQ(OpName); + + //通知web显示 + SendMessageFun.SendMessage("123", "111", OpName); + MIS_BASE.Read_PalletInfo(OpName, out MES_QualityMask);//合格标志 + MIS_BASE.Read_RepairStatus_PLC(OpName, out RepairPartStatusPLC);//返修标志 + SendMessageFun.SendInfomation("QualityMask", Convert.ToString(MES_QualityMask), OpName);//显示合格标志 + SendMessageFun.SendInfomation("RepairPartStatusPLC", Convert.ToString(RepairPartStatusPLC), OpName);//显示返修标志 + + if (MES_QualityMask == 2) + { + ////工作完成 + //MIS_BASE.Write_MaterialVerifyOver(OpName, true); + //SendMessageFun.SendInfomation("NgGO", "1", OpName);//显示不合格标志 + //return; + } + + + //第三步,用于工件离开后完工数量统计及工件编号追溯 + //BaseDataSystemMES.MaterialPush_EngineIDStatus_Insert(OpName);//更新订单产量 + + //第四步,获取是否允许工作 + BaseDataSystemMES.MesServer_Judge_IsCanWork(OpName, out IsAllowWork); + + //暂时先定义为扫描完成才能进行压装工作,因为考虑到工作完成后,操作工未必会去扫描物料的情况 + if (IsAllowWork == 1) + { + //通知PLC允许工作,允许工作在保存完成时清空 + MIS_BASE.Write_FixAllow(OpName, true); + } + else + { + SendMessageFun.AsyncSendMessage_Notice(OpName, "请扫描物料!"); + } + + } + + + /// + /// 返修件需要工作 + /// + /// 工位号 + private void IsNeedRepaire_OK(string OpName) + { + string orderForm = ""; + int engineTypeID; + string engineType = ""; + string engineID = ""; + string palletCode = ""; + int isRepair; + string repairCode = ""; + //从监控系统中查询出本工位信息 + BaseDataSystemMES.OpName_MIS_Moby_Select(OpName, + out orderForm, out engineTypeID, out engineType, + out engineID, out palletCode, out isRepair, out repairCode); + + EngineTypeGetOver_PLC_Work(OpName, engineTypeID, engineType, engineID, Convert.ToInt32(palletCode),orderForm); + } + + + + + } +} diff --git a/MisDataFunction/MesServer.Function/Function1057/Methods/SubmitToMisweb.cs b/MisDataFunction/MesServer.Function/Function1057/Methods/SubmitToMisweb.cs new file mode 100644 index 0000000..52ce16f --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1057/Methods/SubmitToMisweb.cs @@ -0,0 +1,127 @@ +using System; +using bizFacade; +//using SystemFramework; + +namespace MesServerFunctions +{ + + /// + /// 此类用于向WEB发送各种类型消息 + /// + partial class FunctionMES + { + + /// + /// 批量发送WEB消息(Value为BOOL值) + /// + /// 消息编号组合 + /// 消息值组合 + /// 工位号 + void Sendmessage(string MessageNumm,string Value, string OpName) + { + for (int i=0;i + /// 选择发送给WEB的消息 + /// + /// 消息类型 + /// 消息工位 + string Sendmessage(char Num,string Value, string OpName) + { + string SendMessage; + string result = ""; + switch (Num) + { + case '1': + //1(直接在界面通过选择机型确认工序内容) + SendMessage = "MES|ProcessList|" + OpName + "|" + Value; + result = AsyncSendMessage(SendMessage); + break; + case '2': + //2显示物料 + SendMessage = "MES|MaterialList|" + OpName + "|" + Value; + result = AsyncSendMessage(SendMessage); + break; + case '3': + //3显示操作指导图片 + SendMessage = "MES|PicShow|" + OpName + "|" + Value; + result = AsyncSendMessage(SendMessage); + break; + case '4': + //4订单完工模块刷新完成数量 + SendMessage = "MES|OrderFormList|" + OpName + "|" + Value; + AsyncSendMessage(SendMessage); + break; + case '5': + SendMessage = "MES|ShowMoby|" + OpName + "|" + Value; + result = AsyncSendMessage(SendMessage); + break; + case '6': + SendMessage = "MES|MaterialCheckPosition|" + OpName + "|" +Value; + result = AsyncSendMessage(SendMessage); + break; + case '7': + SendMessage = "MES|WorkStart|" + OpName + "|" + Value; + result = AsyncSendMessage(SendMessage); + break; + case '8'://清除MES生成编号 + + break; + case '9': + SendMessage = "MES|ConfirmOkGo|" + OpName + "|" + Value; + result = AsyncSendMessage(SendMessage); + break; + case 'a': + SendMessage = "MES|FixAllow|" + OpName + "|" + Value; + result = AsyncSendMessage(SendMessage); + break; + } + return result; + } + /// + /// 向WEB发送信息(value为字符串) + /// + /// 消息种类 + /// 消息内容 + /// 工位号 + string SendInfomation(string Command, string Value, string OpName) + { + string SendMessage = "MES|" + Command + "|" + OpName + "|" + Value; + return AsyncSendMessage(SendMessage); + } + + + /// + /// 发送在线产量、在线节拍 + /// + /// + /// + private void SendActuallyCount(string OpName, int tagValue) + { + //当工件离开时,更新在线产量、在线节拍 + if (tagValue == 0) + { + try + { + int opNameCount = 0;//在线产量 + int opNameCountTime = 0;//在线节拍 + //基本数据_工作日历_班次产量查询_New + BaseDataSystemMES.OpNameCount_New(OpName, out opNameCount, out opNameCountTime); + string SendMessage; + SendMessage = "MES|ActuallyCount|" + OpName + "|" + opNameCount.ToString() + "&" + opNameCountTime.ToString(); + AsyncSendMessage(SendMessage); + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:SendActuallyCount"); + } + } + } + + + } +} diff --git a/MisDataFunction/MesServer.Function/Function1057/Methods/UDP.Send.cs b/MisDataFunction/MesServer.Function/Function1057/Methods/UDP.Send.cs new file mode 100644 index 0000000..aed7cc3 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1057/Methods/UDP.Send.cs @@ -0,0 +1,53 @@ +using bizFacade; +//using SystemFramework; +using MesServerWork; +using DataLinkMesWork; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 发送信息到MES通讯服务器或者其他的 + /// + /// + private string AsyncSendMessage(string Message) + { + return MIS_BASE.asyncSendMessage(Message); + } + + /// + /// 发送提示消息 + /// + /// + private void AsyncSendMessage_Notice(string opname, string notice) + { + //通知Web界面 + BaseDataSystemMES.Web_Notice_Insert(opname, notice); + string SendMessage = "MES|Notice|" + opname + "|" + "1"; + MIS_BASE.asyncSendMessage(SendMessage); + } + + /// + /// 发送信息到打印机 + /// + /// + private void asyncSendMessageToMark(string Message) + { + string messageSend = (string)Message; + //UDPClientSend.Send_ALL(ApplicationConfig.MES_MarkPortNum, messageSend); + } + + /// + /// 发送信息到LED + /// + /// + private void asyncSendMessageLED(string OpName) + { + //发送到大屏幕显示 41104 + string strMessage = "MIS|" + OpName + "|" + "0" + "|" + "1"; + //UDPClientSend.Send_ALL(ApplicationConfig.Port_ShowLED_ProductCount, strMessage); + + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1057/Methods/vssver2.scc b/MisDataFunction/MesServer.Function/Function1057/Methods/vssver2.scc new file mode 100644 index 0000000..7782f6f Binary files /dev/null and b/MisDataFunction/MesServer.Function/Function1057/Methods/vssver2.scc differ diff --git a/MisDataFunction/MesServer.Function/Function1057/OpcServer/Barcode.cs b/MisDataFunction/MesServer.Function/Function1057/OpcServer/Barcode.cs new file mode 100644 index 0000000..d9f59f8 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1057/OpcServer/Barcode.cs @@ -0,0 +1,228 @@ +using System; +using System.Threading; +using System.Windows.Forms; +using bizFacade; +//using SystemFramework; +using MesServerWork; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + ///1.扫描配送单号,用于接收物料,扫描单号的时候,将接收的物料信息显示在“物料拉动”Tab区域 + ///2.扫描料箱标签/看板卡,用于追溯物料批次信息 + ///3.扫描零件条码,根据零件图号进行防错 + ///第一步,判断条码类型,根据条码类型,执行对应的存储过程 + ///第二步,条码类型(将扫描的条码保存到对应的表中) + ///第三步,扫描完成之后给出允许工作信号 + /// 处理页面扫描条码 + /// + /// + /// + public void Barcode(object e) + { + + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + string barcode = Convert.ToString(msgEvent.TagValue); + + int EngineTypeID;//机型代码 + string EngineType;//机型 + string EngineID;//工件编号 + + string OrderForm; + int Recipe1; + int Recipe2; + + bool IsNotRepeatedNumber = false; + //1:获得申请上线信息后,扫描条码才处理业务 + bool ispartload; + //(115) + int PTO; + //(118)0=不检测;1=24V,2=12V。检测线上线工位扫描总成条码,根据BOM,查出 + int NgearSwitch; + //(119)0=不检测;1=24V,2=12V。检测线上线工位扫描总成条码,根据BOM,查出 + int RgearSwitch; + //(120)0=不检测;1=检测。检测线上线工位扫描总成条码,根据BOM,查出 + int SpeedSensor; + //(121)例如:5S 400。检测线上线工位扫描总成条码,根据BOM,查出 + string PartTypeMid; + //(122) 0=不检测;1=24V,2=12V。检测线上线工位扫描总成条码,根据BOM,查出 + int Tcu_V; + + //判断是否开启线外上线 + if (!Convert.ToBoolean(MIS_BASE.ReadPLC(64, OpName))) + { + SendMessageFun.AsyncSendMessage_Notice(OpName, "若转线上线工件请在系统选择转线工件选项"); + return; + } + + //判断工件是否到位 + MIS_BASE.Read_WorkStart(OpName, out ispartload); + if (!ispartload) + { + SendMessageFun.AsyncSendMessage_Notice(OpName, "请检查设备是否到位(DBX500.1=1)"); + return; + } + //判断设备是否申请上线 + MIS_BASE.Read_UpdatePalletOK(OpName, out ispartload); + if (!ispartload) + { + SendMessageFun.AsyncSendMessage_Notice(OpName, "请检查设备是否申请上线(DBX500.3=1)"); + return; + } + // 判读条码是变速器序列号条码号还是物料号 小机型*日月年* 流水号(给起始号 + 数量) + // 选小机型 从北汽福田BOM中选 得先维护BOM + // 变速器序列号 '1333 050 062*16012023*30000001' + + //扫描完变速器序列号条码号 true + bool isGetOver_PLC = false; + //判断上线工位,MES 是否将工件流水号、机型等信息已经写入到PLC了 + MIS_BASE.Read_EngineGetOver_PLC(OpName, out isGetOver_PLC); + //如果工件流水号、机型等信息没有写入PLC,扫描的条码按工件流水号进行验证 + //否则按装配物料进行验证 + if (!isGetOver_PLC) + { + + if (barcode.Split('*').Length > 2) + { + //2: 判断是否重号, 从数据库获得机型、机型代码等信息 + string partSn = barcode; + EngineID = barcode; + + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.EngineID_MES, EngineID); + + //IsRepeatedNumber true 不重号;false 重号; + IsNotRepeatedNumber = BaseDataSystemMES.EngineTypeID_IsNotRepeatedNumber(partSn); + if (IsNotRepeatedNumber) + { + BaseDataSystemMES.GetEngineTypeUpLoadOpName(partSn, OpName, out EngineTypeID, out EngineType, out OrderForm, out Recipe1, out Recipe2); + + + BaseDataSystemMES.UpLoadPTO(EngineType, out PTO, out NgearSwitch, out RgearSwitch, out SpeedSensor, out PartTypeMid, out Tcu_V); + //PTO + MIS_BASE.WritePLC(115, OpName, PTO); + //空挡开关检测 + MIS_BASE.WritePLC(95, OpName, NgearSwitch); + //倒挡开关检测 + MIS_BASE.WritePLC(96, OpName, RgearSwitch); + //里程表检测 + MIS_BASE.WritePLC(97, OpName, SpeedSensor); + //大机型扩展 + MIS_BASE.WritePLC(98, OpName, PartTypeMid); + //TCU + MIS_BASE.WritePLC(122, OpName, Tcu_V); + string tagStartAdr;//= "DB411.10"; + + // 先查询配方号 根据工位号 去moby表查配方号 + // 根据配方号 去配方表查配方数据 + // 写入配方数据 + BaseDataSystemMES.PLCRcipeCurrent(OpName, out byte[] bytes, out tagStartAdr); + DtWebApi.ReadWritePLC.Write_TagValueByTagTypeID("94", OpName, System.Text.Encoding.ASCII.GetString(bytes)); + ////将产品信息写入PLC + MIS_BASE.Write_EngineTypeID_MES(OpName, EngineTypeID); + MIS_BASE.Write_EngineType_MES(OpName, EngineType); + MIS_BASE.Write_EngineID_MES(OpName, EngineID); + MIS_BASE.Write_OrderForm_MES(OpName, OrderForm); + + //写入到数据库的[北汽福田工位状态监控MOBY]表中 + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.EngineTypeID_MES, EngineTypeID.ToString()); + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.EngineType_MES, EngineType); + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.EngineID_MES, EngineID); + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.OrderForm_MES, OrderForm); + + //通知web显示 + SendMessage.ShowMoby(OpName); + //在PLC传递机型后进行允许工作 + //MIS_BASE.Write_FixAllow(OpName, true); + SendMessageFun.AsyncSendMessage_Notice(OpName, "扫码成功,请开始工作!"); + //SendMessageFun.SendMessage("1235", "1111", OpName); + + MIS_BASE.Write_EngineTypeGetOver_MES(OpName, true); + //Thread.Sleep(1000); + //MIS_BASE.Write_EngineTypeGetOver_MES(OpName, false); + } + else + { + SendMessageFun.AsyncSendMessage_Notice(OpName, "变速器序列号 重号,请确认!"); + } + } + else + { + SendMessageFun.AsyncSendMessage_Notice(OpName, "变速器序列号格式不正确,请确认!"); + + } + } + else//验证物料 + { + //物料号 + { + //读取PLC的传递机型信号 + bool tagValue; + MIS_BASE.Read_EngineGetOver_PLC(OpName, out tagValue); + if (tagValue) + { + //验证物料 + BaseDataSystemMES.PartMaterial_DM_Update(OpName, barcode, out bool IsSuccess); + if (!IsSuccess)//???? + { + SendMessageFun.AsyncSendMessage_Notice(OpName, "条码无效,请确认"); + return; + } + else + { + SendMessageFun.SendInfomation("MaterialList", "1", OpName);//通知界面更新零件信息 + } + //判断物料是否验证完成 + BaseDataSystemMES.MesServer_Judge_IsCanWork(OpName, out int IsAllowWork); + + + if (IsSuccess) + { + if (IsAllowWork == 1) + { + //移到允许保存信号中 + //BaseDataSystemMES.Material_Insert(OpName, 1); + + ////更新订单完工数量及物料 + SendMessageFun.SendMessage("24", "11", OpName); + + //物料验证完成,通知PLC允许工作,允许工作在保存完成时清空 + MIS_BASE.Write_FixAllow(OpName, true); + } + else + { + SendMessageFun.AsyncSendMessage_Notice(OpName, "请扫描物料!"); + } + } + else + { + SendMessageFun.AsyncSendMessage_Notice(OpName, "PLC未传递机型"); + } + } + else + { + SendMessage.AsyncSendMessage_Notice(OpName, "产品上线后,PLC获得变速器序列号后,再验证物料!"); + } + + } + } + + + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:Barcode"); + } + + } + + } + + + } +} diff --git a/MisDataFunction/MesServer.Function/Function1057/OpcServer/ConfirmOkGo.cs b/MisDataFunction/MesServer.Function/Function1057/OpcServer/ConfirmOkGo.cs new file mode 100644 index 0000000..06e6b33 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1057/OpcServer/ConfirmOkGo.cs @@ -0,0 +1,41 @@ +using System; +using bizFacade; +//using SystemFramework; +using MesServerWork; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 合格放行 + /// + /// + /// + private void ConfirmOkGo(object e) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + + if (tagValue == 1) + { + + BaseDataSystemMES.Material_Insert(OpName, 1); + + //更新订单完工数量及物料 + Sendmessage("24", "11", OpName); + + //工作完成 + MIS_BASE.Write_MaterialVerifyOver(OpName, true); + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:ConfirmOkGo"); + } + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1057/OpcServer/EngineGetOver.cs b/MisDataFunction/MesServer.Function/Function1057/OpcServer/EngineGetOver.cs new file mode 100644 index 0000000..fd4ae58 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1057/OpcServer/EngineGetOver.cs @@ -0,0 +1,79 @@ +using System; +using System.Data; +using System.Windows.Forms; +using System.Xml.Linq; +using bizFacade; +//using SystemFramework; +using MesServerWork; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// PLC传递机型处理 + /// + /// + /// + private void EngineTypeGetOver_PLC(object e) + { + + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + + if (tagValue == 1) + { + int EngineTypeID;//机型代码 + int PartPallet_Code;//托盘编号 + + string EngineType;//机型 + string EngineID;//工件编号 + string OrderForm; + MIS_BASE.GetEngineTypeFromPLC(OpName, out EngineTypeID, out EngineType, out EngineID, out PartPallet_Code, out OrderForm); + + if (EngineTypeID <= 0 || EngineID.Length == 0 || EngineType.Length == 0 || OrderForm.Length == 0) + { + SendMessageFun.AsyncSendMessage_Notice(OpName, "PLC传递机型为空"); + return; + } + + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.EngineTypeID, EngineTypeID.ToString()); + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.EngineType, EngineType); + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.EngineID, EngineID); + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.OrderForm, OrderForm); + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.PartPallet_Code, PartPallet_Code.ToString()); + //显示当前订单信息 + SendMessage.ShowMoby(OpName); + //判断该订单数据是否已经工作过,有的话则在WEB跳出弹窗选择 并同时禁止工作 + //DataTable dt2 = BaseDataSystemMES.EngineIsTwoWork(OpName, OrderForm, EngineID); + //if (dt2.Rows[0]["result"].ToString() == "1") //已完成 + //{ + // //不允许工作 + // MIS_BASE.Write_FixAllow(OpName, false); + // //通知WEB校验重新工作还是跳过 点重新工作给允许工作,点跳过给工作完成 + // string message = "MES|Engine_Is_TwoWork|" + OpName + "|1"; + // SendMessage.AsyncSendMessage(message); + //} + //else + //{ + // EngineTypeGetOver_PLC_Work(OpName, EngineTypeID, EngineType, EngineID, PartPallet_Code, OrderForm); + //} + EngineTypeGetOver_PLC_Work(OpName, EngineTypeID, EngineType, EngineID, PartPallet_Code, OrderForm); + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:EngineTypeGetOver_PLC"); + } + } + + + } + + + } +} diff --git a/MisDataFunction/MesServer.Function/Function1057/OpcServer/FalseGO.cs b/MisDataFunction/MesServer.Function/Function1057/OpcServer/FalseGO.cs new file mode 100644 index 0000000..4ad2665 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1057/OpcServer/FalseGO.cs @@ -0,0 +1,41 @@ +using System; +using bizFacade; +//using SystemFramework; +using MesServerWork; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 不合格放行 + /// + /// + /// + private void FalseGO(object e) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + + if (tagValue == 1) + { + //总合格标志2(不合格) + + BaseDataSystemMES.Material_Insert_NG(OpName, 2); + + Sendmessage("24", "11", OpName); + + //工作完成 + MIS_BASE.Write_MaterialVerifyOver(OpName, true); + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:FalseGO"); + } + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1057/OpcServer/HeartBeat.cs b/MisDataFunction/MesServer.Function/Function1057/OpcServer/HeartBeat.cs new file mode 100644 index 0000000..93affd3 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1057/OpcServer/HeartBeat.cs @@ -0,0 +1,35 @@ +using bizFacade; +using MesServerWork; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// MES与PLC心跳监听 + /// + /// + /// + private void HeartBeat(object e) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + + //返写在MES心跳中 + MIS_BASE.WritePLC(15, OpName, tagValue); + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:FalseGO"); + } + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1057/OpcServer/MesRead.cs b/MisDataFunction/MesServer.Function/Function1057/OpcServer/MesRead.cs new file mode 100644 index 0000000..2496314 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1057/OpcServer/MesRead.cs @@ -0,0 +1,123 @@ +using bizFacade; +using MesServerWork; +using System; +//using SystemFramework; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 允许保存(针对半自动和手动压装工位) + /// + /// + /// + private void MesRead(object e) + { + { + try + { + + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + + if (tagValue == 1) + { + int qualityMask; + + //保存质量数据 + qualityMask = MisDataSaveDateMesRead.Funtion.MesRead_J07MA150(OpName, tagValue.ToString(), msgEvent.TagID.ToString()); + //保存物料数据 + BaseDataSystemMES.Material_Insert(OpName, qualityMask); + + //测量数据发动机在线状态 + BaseDataSystemMES.WorkStartInsert(OpName, qualityMask); + + //推送质量数据到MES的页面d + SendMessageFun.SendInfomation("ShowTimelyQuality", "1&" + qualityMask.ToString(), OpName); + + int EngineTypeID;//机型代码 + int PartPallet_Code;//托盘编号 + string EngineType;//机型 + string EngineID;//工件编号 + string OrderForm; + MIS_BASE.GetEngineTypeFromPLC(OpName, out EngineTypeID, out EngineType, out EngineID, out PartPallet_Code, out OrderForm); + string SLResult = MIS_BASE.ReadPLC(41, OpName).ToString(); //试漏结果 + int TurnLineWork = Convert.ToInt32(MIS_BASE.ReadPLC(64, OpName)); //是否转线 + // 保存150工位试漏结果 + BaseDataSystemMES.SLResult_Add( SLResult, EngineID, EngineType, EngineTypeID, TurnLineWork); + + //通知设备,MES的质量数据(和物料数据)保存完成 + MIS_BASE.Write_MesReadOver(OpName, true); + MIS_BASE.Write_MaterialVerifyOver(OpName, true); + + //统计在线产量,在线节拍 + SendMessage.SendActuallyCount(OpName, tagValue); + + string awaitOpName = "OPA90"; + // 读取A90 是否在等待 + int isAwait = Convert.ToInt32(MIS_BASE.ReadPLC(29, awaitOpName)); + // 如果是OPA60 的话去再次判断工件匹配状态 + if (isAwait == 1) + { + MIS_BASE.Read_TagTypeID(201, awaitOpName, out string EngineTypeID_QiaoKe); + + string await_EngineID = MIS_BASE.ReadPLC(10, awaitOpName).ToString(); // 读取A90等待工件的工件编号 + int await_EngineTypeID = Convert.ToInt32(MIS_BASE.ReadPLC(9, awaitOpName)); // 读取A90等待工件的机型编号 + string await_OrderForm = MIS_BASE.ReadPLC(39, awaitOpName).ToString(); // 读取A90等待工件的订单号 + Db.OP50_OPA90_MatchResult(await_EngineTypeID, Convert.ToInt32(EngineTypeID_QiaoKe), await_EngineID, await_OrderForm, out int MatchResult, out string MatchResultStr); + if (MatchResult == 1) + { + // 轮毂线 + MIS_BASE.Write_Match(awaitOpName, true);// 匹配结果 + MIS_BASE.Write_MatchingCompleted(awaitOpName, true);// 匹配完成 + MIS_BASE.Write_FixAllow(awaitOpName, true); // 允许工作 + MIS_BASE.WritePLC(29, awaitOpName, false); // 取消等待 + return; + } + } + + string awaitOpName2 = "OP051"; + // 读取A90 是否在等待 + int isAwait2 = Convert.ToInt32(MIS_BASE.ReadPLC(29, awaitOpName2)); + if (isAwait2 == 1 && OpName == "OPA60") + { + string await2_EngineID = MIS_BASE.ReadPLC(10, awaitOpName2).ToString(); // 读取051等待工件的工件编号 + string await2_OrderForm = MIS_BASE.ReadPLC(39, awaitOpName2).ToString(); // 读取051等待工件的订单号 + + + Db.OP051_OP050_NeedWork(await2_EngineID, awaitOpName2, await2_OrderForm, out int MatchResult); + + if (MatchResult == 1) //匹配 有需要装配的轮毂 + { + MIS_BASE.Write_Match(awaitOpName2, true);// 匹配结果 + MIS_BASE.Write_MatchingCompleted(awaitOpName2, true);// 匹配完成 + MIS_BASE.WritePLC(77, awaitOpName2, "1");// 托盘是否需要工作 1:需要工作 2:不需要工作 + MIS_BASE.Write_FixAllow(awaitOpName2, true); // 允许工作 + MIS_BASE.WritePLC(29, awaitOpName2, false); // 取消等待 + } + } + } + else + { + MIS_BASE.Write_MesReadOver(OpName, false); + MIS_BASE.Write_ConfirmOkGo(OpName, false); + MIS_BASE.Write_FixAllow(OpName, false); + MIS_BASE.Write_ConfirmOkGo(OpName, false); + //工作完成 + MIS_BASE.Write_MaterialVerifyOver(OpName, false); + } + } + + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function08:MesReadOver"); + } + } + + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1057/OpcServer/MesReadOver.cs b/MisDataFunction/MesServer.Function/Function1057/OpcServer/MesReadOver.cs new file mode 100644 index 0000000..f96a7d3 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1057/OpcServer/MesReadOver.cs @@ -0,0 +1,55 @@ +using System; +//using SystemFramework; +using MesServerWork; +using bizFacade; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 保存完成(针对半自动和手动压装工位) + /// + /// + /// + private void MesReadOver(object e) + { + //try + //{ + // DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + // string OpName = Convert.ToString(msgEvent.OpName); + // var tagValue = msgEvent.TagValue.ToString (); + + // if (tagValue == "1" | tagValue.ToLower () == "true") + // { + // int qualityMask; + // MIS_BASE.Read_QualityMask(OpName, out qualityMask); + + // SendInfomation("ShowTimelyQuality", "1&" + qualityMask.ToString(), OpName);//发给Web页面显示质量数据 + + // if (qualityMask == 1)//全部OK,给出合格放行 + // { + // //如果存在线外扫描工位,根据扫描条码绑定线外数据 需要时解除禁用 + // //BaseDataSystemMES.TransLaunchDataByMainMaterial(OpName, EngineType, EngineID, EngineTypeID); + + // //如果存在线外排队工位,根据排队编号绑定线外数据 需要时解除禁用 + // ////BaseDataSystemMES.MailLineAndSubLineData_InsertByEngineID_Subline(OpName,EngineID, EngineTypeID, EngineType); + + // MIS_BASE.Write_ConfirmOkGo(OpName, true); + // //MIS_BASE.Write_FalseGO(OpName, false); + // } + // else + // { + // //MIS_BASE.Write_ConfirmOkGo(OpName, false); + // MIS_BASE.Write_FalseGO(OpName, true); + // } + + // } + //} + //catch (Exception err) + //{ + // ////ApplicationLog.WriteLog(err, "Function02:MesReadOver"); + //} + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1057/OpcServer/WebSubmit.cs b/MisDataFunction/MesServer.Function/Function1057/OpcServer/WebSubmit.cs new file mode 100644 index 0000000..fc79ae5 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1057/OpcServer/WebSubmit.cs @@ -0,0 +1,307 @@ +using System; +using MesServerWork; +using bizFacade; +using System.Threading; +using MisDataSaveDate; +using System.Collections; +//using SystemFramework; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 处理WEB页面发送过来的请求(m_Command + "|" + m_Value;) + /// + /// + /// + private void WebSubmit(object e) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName=Convert.ToString(msgEvent.OpName); + string Content = Convert.ToString(msgEvent.TagValue); + + string[] dataArray = Content.Split('|'); + if (dataArray.Length != 2) + return; + //消息类型 + string m_Command = dataArray[0].ToString(); + //消息参数 + string m_Value = dataArray[1].ToString(); + //消息参数数量 + string[] m_Value_array = m_Value.Split('&'); + //消息参数长度 + int m_Value_length = m_Value_array.Length; + + //工件信息 + string engineID = ""; + if (MIS_BASE.hashtable_EngineGetOver_EngineTypeID == null) + { + MIS_BASE.InitHashtable_MesServerCode(); + } + if (MIS_BASE.hashtable_EngineGetOver_EngineID.ContainsKey(OpName)) + { + engineID = MIS_BASE.hashtable_EngineGetOver_EngineID[OpName].ToString(); + } + + DoWhatPlc.CustomeEvetnArgs _e = new DoWhatPlc.CustomeEvetnArgs(); + _e.OpName = OpName; + _e.TagValue = m_Value; + + //根据请求的命令处理逻辑 + switch (m_Command) + { + case "Barcode": + if (m_Value_length > 1) return; + fun_Barcode(_e); + break; + case "ConfirmOkGo"://合格放行 + //删除不合格放行记录 + //修改托盘状态 + //Update_PalletStatus(OpName, 1, false); + BaseDataSystemMES.BaseData_tagTable_Engine_IsNG_Delete(OpName, engineID); + MIS_BASE.Write_ConfirmOkGo(OpName, true); + MIS_BASE.Write_FalseGO(OpName, false); + + Thread.Sleep(1000); + MIS_BASE.Write_ConfirmOkGo(OpName, false); + break; + case "FalseGO"://返修放行 + //修改托盘状态 + //Update_PalletStatus(OpName, 3, false); + BaseDataSystemMES.BaseData_tagTable_Engine_IsNG_Delete(OpName, engineID); + MIS_BASE.Write_FalseGO(OpName, true); + MIS_BASE.Write_ConfirmOkGo(OpName, false); + + Thread.Sleep(1000); + MIS_BASE.Write_FalseGO(OpName, false); + break; + case "NgGO"://不合格放行 + //修改托盘状态 + //Update_PalletStatus(OpName, 2, false); + //保存不合格信息(必须保存不合格放行信息,由于B5A的Moby没有不合格标志位) + BaseDataSystemMES.BaseData_tagTable_Engine_IsNG_Insert(OpName, engineID, "", ""); + MIS_BASE.Write_FalseGO(OpName, true); + MIS_BASE.Write_ConfirmOkGo(OpName, false); + Thread.Sleep(1000); + MIS_BASE.Write_FalseGO(OpName, false); + break; + case "OnLineState"://在线0、离线1、屏蔽2 + try + { + if (m_Value_length > 1) return; + int a = Convert.ToInt32(m_Value); + if (a <= 2) + { + BaseDataSystemMES.IsOnLine_Update(OpName, m_Value.ToString()); + MIS_BASE.Write_OnLineState(OpName, Convert.ToInt32(m_Value)); + if (a == 2) SendMessage.AsyncSendMessage_Notice(OpName, "屏蔽MES!"); + if (a == 0) SendMessage.AsyncSendMessage_Notice(OpName, "启用MES!"); + } + } + catch + { + + } + break; + case "Reset"://复位,将MES所有的信息都复位了 + SetMoby(OpName);//将MES所有信号清空 + break; + case "TurnLineWork"://150工位独有,转线上线标志 + SendMessage.AsyncSendMessage_Notice(OpName, "切换成功!"); + if (Convert.ToInt32(m_Value) == 1) //(0 正常工件 ,1 转线工件) + { + //写入转线标识点 (64)501.6 + MIS_BASE.WritePLC(64, OpName, true); + } + else + { + MIS_BASE.WritePLC(64, OpName, false); + } + break; + case "FixAllow"://重新拧紧 + MIS_BASE.Write_FixAllow(OpName, false); + MIS_BASE.Write_FixAllow(OpName, true); + break; + case "IsAutoGetEngineID"://自动手动申请编号(线首) + if (m_Value_length > 1) return; + MIS_BASE.Write_IsAutoGetEngineID(OpName, Convert.ToInt32(m_Value)); + break; + case "PartPalletGoOver"://空托盘放行 + int Is_PartPalletGoOver; + MIS_BASE.Read_PartPalletGoOver(OpName, out Is_PartPalletGoOver); + if (Is_PartPalletGoOver == 1) + { + MIS_BASE.Write_PartPalletGoOver(OpName, 1); + } + else + { + MIS_BASE.Write_PartPalletGoOver(OpName,0); + } + break; + case "SetMoby"://清空托盘(线首) + SetMoby(OpName);//将MES所有信号清空 + //MIS_BASE.Write_PartPalletCode_PLC(OpName, 1); + break; + case "RepairUplineMES"://返修上线 + MIS_BASE.Write_RepairUpline_MES(OpName, true); + break; + case "CancelRepair"://将返修件置为正常件 + + break; + case "PartPalletCode"://申请写入托盘号 + //MIS_BASE.Write_PartPalletCode_PLC(OpName, 1); + break; + case "WritePartPalletCode"://写入托盘号 + if (m_Value_length > 1) return; + MIS_BASE.Write_PalletCode(OpName, Convert.ToInt32(m_Value)); + break; + case "Normal"://启用正常拧紧工位 + MIS_BASE.Write_Normal(OpName, 1); + MIS_BASE.Write_UnNormal(OpName, 0); + break; + case "UnNormal"://启用备用拧紧工位 + MIS_BASE.Write_Normal(OpName, 0); + MIS_BASE.Write_UnNormal(OpName, 1); + break; + case "ResetDevice"://复位设备 + MIS_BASE.Write_ResetDevice(OpName, true); + System.Threading.Thread.Sleep(1000); + MIS_BASE.Write_ResetDevice(OpName, false); + break; + case "IsNeedRepaire"://返修上线(返修上线点) + if (Convert.ToInt32(m_Value) == 1) + { + //修改托盘状态 + MIS_BASE.Write_PalletInfo(OpName, 3); + //通知修改成功 + MIS_BASE.Write_UpdatePalletOK(OpName, true); + IsNeedRepaire_OK(OpName); + + } + else if (Convert.ToInt32(m_Value) == 0) + { + //通知修改成功 + MIS_BASE.Write_UpdatePalletOK(OpName, true); + //直接给出工作完成 + MIS_BASE.Write_MaterialVerifyOver(OpName, true); + } + else + { } + + break; + case "ContinueMatch": + BaseDataSystemMES.QualityVerifyStatus_Hash_Write(OpName, true); + break; + //初始化网页信号 + case "IniSingalToWeb": + InitializeSingalToWeb(OpName); + break; + case "Reset_Engine"://返修上线(返修上线点) + SetMoby(OpName);//将MES所有信号清空 + //fun_EngineTypeGetOverPLC(OpName, 0); + //fun_EngineTypeGetOverPLC(OpName, 1); + break; + + + default: break; + } + } + catch(Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:WebSubmit"); + } + } + private void SetMoby(string OpName) + { + try + { + //清空Moby时,需要将MES信号清空 + MIS_BASE.Write_ClearMesMoby(OpName); + + BaseDataSystemMES.MesServer_Process_EngineTypeOver(OpName); + + Sendmessage("5123", "1111", OpName); + + MIS_BASE.Write_ResetDevice(OpName, true); + System.Threading.Thread.Sleep(1000); + MIS_BASE.Write_ResetDevice(OpName, false); + } + catch + { + + } + } + /// 网页重现登录,恢复关闭前的页面状态 + /// + /// 工位号 + private void InitializeSingalToWeb(string Opname) + { + try + { + //工件到位 DBX0.1 + bool S_WorkStart; + bool S_FixAllow; + bool S_EngineGetOver; + bool S_MaterialVerifyOver; + + MIS_BASE.Read_WorkStart(Opname, out S_WorkStart); + MIS_BASE.Read_FixAllow(Opname, out S_FixAllow); + MIS_BASE.Read_EngineGetOver_PLC(Opname, out S_EngineGetOver); + MIS_BASE.Read_MaterialVerifyOver(Opname, out S_MaterialVerifyOver); + + Sendmessage("13", "1111", Opname); + string S_plcStatus;//DBX501.5 PLC直通,1 强制放行 0 正常循环 + // 新增查询PLC直通状态 网页显示 + MIS_BASE.Read_TagTypeID(63, Opname, out S_plcStatus); + if (S_plcStatus.ToLower() == "false") + { + SendMessageFun.SendInfomation("PlcStatus", "0", Opname); + } + else + { + SendMessageFun.SendInfomation("PlcStatus", "1", Opname); + } + + if (S_WorkStart == true) + { + SendInfomation("WorkStart", Convert.ToString(Convert.ToInt32(S_WorkStart)), Opname); + } + + if (S_EngineGetOver == true) + { + SendInfomation("EngineTypeGetOverPLC", Convert.ToString(Convert.ToInt32(S_EngineGetOver)), Opname); + Sendmessage("2", "1111", Opname); + SendMessage.ShowMoby(Opname); + } + if (S_FixAllow == true) + { + SendInfomation("FixAllow", Convert.ToString(Convert.ToInt32(S_FixAllow)), Opname); + } + if (S_MaterialVerifyOver == true) + { + SendInfomation("MaterialVerifyOver", Convert.ToString(Convert.ToInt32(S_MaterialVerifyOver)), Opname); + } + InitAlarm(Opname); + } + catch (Exception err) + { + + } + + } + private void InitAlarm(string Opname) + { + FuntionMesRead.Alarm_InitAlarm_Send(Opname, out Hashtable ht); + foreach (DictionaryEntry kv in ht) + { + var TagID = kv.Key.ToString(); + var TagValue = kv.Value.ToString(); + FuntionMesRead.Send_AlarmMsg(TagID, TagValue); + } + + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1057/OpcServer/WorkStart.cs b/MisDataFunction/MesServer.Function/Function1057/OpcServer/WorkStart.cs new file mode 100644 index 0000000..5739456 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1057/OpcServer/WorkStart.cs @@ -0,0 +1,44 @@ +using bizFacade; +using MesServerWork; +using System; +//using SystemFramework; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 工件到位与离开时,清空MES自身信号 + /// + /// + /// + private void WorkStart(object e) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + if (tagValue > 0) + { + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.WorkStartIn, DateTime.Now.ToString()); + } + else + { + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.WorkStartOut, DateTime.Now.ToString()); + MIS_BASE.Write_MesReadOver(OpName, false); + MIS_BASE.Write_ConfirmOkGo(OpName, false); + MIS_BASE.Write_FixAllow(OpName, false); + MIS_BASE.Write_EngineTypeGetOver_MES(OpName, false); + //工作完成 + MIS_BASE.Write_MaterialVerifyOver(OpName, false); + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:WorkStart"); + } + } + + } +} diff --git a/MisDataFunction/MesServer.Function/Function1057/OpcServer/vssver2.scc b/MisDataFunction/MesServer.Function/Function1057/OpcServer/vssver2.scc new file mode 100644 index 0000000..b884d13 Binary files /dev/null and b/MisDataFunction/MesServer.Function/Function1057/OpcServer/vssver2.scc differ diff --git a/MisDataFunction/MesServer.Function/Function1057/Properties/AssemblyInfo.cs b/MisDataFunction/MesServer.Function/Function1057/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..0bb79c4 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1057/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// 有关程序集的常规信息通过以下 +// 特性集控制。更改这些特性值可修改 +// 与程序集关联的信息。 +[assembly: AssemblyTitle("Function02")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("苏州宏软信息技术有限公司")] +[assembly: AssemblyProduct("Function02")] +[assembly: AssemblyCopyright("Copyright © 苏州宏软信息技术有限公司 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// 将 ComVisible 设置为 false 使此程序集中的类型 +// 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型, +// 则将该类型上的 ComVisible 特性设置为 true。 +[assembly: ComVisible(false)] + +// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID +[assembly: Guid("47710f2c-e141-4252-8d13-701bf4c1c027")] + +// 程序集的版本信息由下面四个值组成: +// +// 主版本 +// 次版本 +// 内部版本号 +// 修订号 +// +// 可以指定所有这些值,也可以使用“内部版本号”和“修订号”的默认值, +// 方法是按如下所示使用“*”: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/MisDataFunction/MesServer.Function/Function1057/Properties/vssver2.scc b/MisDataFunction/MesServer.Function/Function1057/Properties/vssver2.scc new file mode 100644 index 0000000..14e543b Binary files /dev/null and b/MisDataFunction/MesServer.Function/Function1057/Properties/vssver2.scc differ diff --git a/MisDataFunction/MesServer.Function/Function1057/app.config b/MisDataFunction/MesServer.Function/Function1057/app.config new file mode 100644 index 0000000..b4c4daf --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1057/app.config @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + + + diff --git a/MisDataFunction/MesServer.Function/Function1057/mssccprj.scc b/MisDataFunction/MesServer.Function/Function1057/mssccprj.scc new file mode 100644 index 0000000..119193d --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1057/mssccprj.scc @@ -0,0 +1,5 @@ +SCC = This is a Source Code Control file + +[Function02.csproj] +SCC_Aux_Path = "\\192.168.0.100\vss\MES4.0" +SCC_Project_Name = "$/MisData/MisData/MisData/MesServer.Function/Function02", ILHAAAAA diff --git a/MisDataFunction/MesServer.Function/Function1057/packages.config b/MisDataFunction/MesServer.Function/Function1057/packages.config new file mode 100644 index 0000000..b3e1761 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1057/packages.config @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/MisDataFunction/MesServer.Function/Function1057/vssver2.scc b/MisDataFunction/MesServer.Function/Function1057/vssver2.scc new file mode 100644 index 0000000..c770e28 Binary files /dev/null and b/MisDataFunction/MesServer.Function/Function1057/vssver2.scc differ diff --git a/MisDataFunction/MesServer.Function/Function1058/DataAccess/DataAccess.cs b/MisDataFunction/MesServer.Function/Function1058/DataAccess/DataAccess.cs new file mode 100644 index 0000000..a7f91fa --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1058/DataAccess/DataAccess.cs @@ -0,0 +1,16 @@ + + +namespace MesServerFunctions +{ + partial class FunctionMES + { + //针对“MIS.BizFacade.Dll”中没有的存储过程,在此类中新建 + //新建原则:所有的函数用private,只允许在内部使用 + //针对单个工艺特殊,需要新建存储过程,但是存储过程不能被加入到“MIS.BizFacade.Dll”中 + + private void aa() + { + + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1058/DataAccess/vssver2.scc b/MisDataFunction/MesServer.Function/Function1058/DataAccess/vssver2.scc new file mode 100644 index 0000000..1083b3a Binary files /dev/null and b/MisDataFunction/MesServer.Function/Function1058/DataAccess/vssver2.scc differ diff --git a/MisDataFunction/MesServer.Function/Function1058/Db.cs b/MisDataFunction/MesServer.Function/Function1058/Db.cs new file mode 100644 index 0000000..64286ed --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1058/Db.cs @@ -0,0 +1,74 @@ +using System; +using System.Collections.Generic; +using System.Data.SqlClient; +using System.Data; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using DataLinkMesWork; + +namespace MesServerFunctions +{ + public class Db + { + /// + /// 北汽福田变速器序列号总线上线_获得机型信息 + /// + /// + /// + /// + /// + /// 0 不重号;1 重号;2:失败 + /// + public static bool GetEngineType(string partSn, out int EngineTypeID, out string EngineType, out string EngineID,out int IsRepeatedNumber) + { + DataTable dt = new DataTable(); + EngineTypeID = 0; + EngineType = ""; + EngineID = ""; + IsRepeatedNumber = 2; + string produceName = "北汽福田变速器序列号总线上线_获得机型信息"; + SqlParameter[] thisParms = new SqlParameter[1]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@变速器序列号", partSn); + + thisParms[2].Direction = ParameterDirection.Output; + if (DataAccess.ExecuteStoredProcedure(produceName, ref thisParms,out dt)) + { + if(dt.Rows.Count > 0) + { + IsRepeatedNumber = Convert.ToInt32( dt.Rows[0]["IsRepeatedNumber"]); + EngineTypeID = Convert.ToInt32(dt.Rows[0]["EngineTypeID"]); + EngineType = dt.Rows[0]["EngineType"].ToString(); + EngineID = partSn; + return true; + } + } + return false; + } + /// + /// 北汽福田变速器序列号总线上线_增加 + /// + /// + /// + /// + /// + /// + public static bool UpLoadOpNameInsert(string partSn, int EngineTypeID, string EngineType, string OpName) + { + + string produceName = "北汽福田变速器序列号总线上线_增加"; + SqlParameter[] thisParms = new SqlParameter[4]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@变速器序列号", partSn); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@基本型号代码", EngineTypeID); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@基本型号", EngineType); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@工位号", OpName); + return DataAccess.ExecuteStoredProcedure(produceName, ref thisParms); + } + + // ALTER PROCEDURE[dbo].[北汽福田变速器序列号总线上线_增加] + // @变速器序列号 nvarchar(50)='1333 050 062 0001*146012023*12345678',--'1333 050 062 0001' + //@基本型号代码 int=1, + //@基本型号 nvarchar(50)='1333 050 062 0001', + //@工位号 nvarchar(50) = 'J05PA010' + } +} diff --git a/MisDataFunction/MesServer.Function/Function1058/Function08.csproj.vspscc b/MisDataFunction/MesServer.Function/Function1058/Function08.csproj.vspscc new file mode 100644 index 0000000..82c6db2 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1058/Function08.csproj.vspscc @@ -0,0 +1,10 @@ +"" +{ +"FILE_VERSION" = "9237" +"ENLISTMENT_CHOICE" = "NEVER" +"PROJECT_FILE_RELATIVE_PATH" = "relative:MesServer.Function\\Function08" +"NUMBER_OF_EXCLUDED_FILES" = "0" +"ORIGINAL_PROJECT_FILE_PATH" = "" +"NUMBER_OF_NESTED_PROJECTS" = "0" +"SOURCE_CONTROL_SETTINGS_PROVIDER" = "PROVIDER" +} diff --git a/MisDataFunction/MesServer.Function/Function1058/Function1058.csproj b/MisDataFunction/MesServer.Function/Function1058/Function1058.csproj new file mode 100644 index 0000000..1c5612b --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1058/Function1058.csproj @@ -0,0 +1,168 @@ + + + + Debug + AnyCPU + 8.0.30703 + 2.0 + {E446FCEB-055D-495C-8773-407419AE3B31} + Library + Properties + Function1058 + Function1058 + v4.8 + 512 + + + + + + + + + + + + + + true + full + false + ..\..\..\dll_fun\ + DEBUG;TRACE + prompt + 4 + AnyCPU + false + false + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + false + + + + ..\..\..\Common\dll\MQTTnet.dll + + + ..\..\..\Common\dll\MQTTnet.Extensions.ManagedClient.dll + + + False + ..\..\..\Common\dll\Newtonsoft.Json.dll + + + + + + ..\..\DLL\System.Net.Http.dll + + + ..\..\packages\System.Net.Security.4.3.2\lib\net46\System.Net.Security.dll + + + ..\..\packages\System.Net.WebSockets.4.3.0\lib\net46\System.Net.WebSockets.dll + + + ..\..\packages\System.Net.WebSockets.Client.4.3.2\lib\net46\System.Net.WebSockets.Client.dll + + + ..\..\packages\System.Security.Cryptography.Algorithms.4.3.0\lib\net461\System.Security.Cryptography.Algorithms.dll + + + ..\..\packages\System.Security.Cryptography.Encoding.4.3.0\lib\net46\System.Security.Cryptography.Encoding.dll + + + ..\..\packages\System.Security.Cryptography.Primitives.4.3.0\lib\net46\System.Security.Cryptography.Primitives.dll + + + ..\..\packages\System.Security.Cryptography.X509Certificates.4.3.0\lib\net461\System.Security.Cryptography.X509Certificates.dll + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + {f55da1a0-a982-4479-8c47-0d9a5aaf3e18} + 00MesWorkMqtt + + + {0d1af432-439a-4920-8692-43ae139f5530} + 01_01DoWhatPlc + + + {3e6d1dd5-01c9-435f-9941-61f906ce35bb} + 02_02WebApiCallPLC + + + {f434e066-4c59-47c8-aa82-6f48cc84501a} + 04-DataBaseAccess + + + {f0a0c525-03fd-428a-9b17-7f54aa0e4475} + 07BusinessFacade + + + {d98be764-adeb-488d-9714-61e308aa8201} + 08-WebFun_base + + + {90e76fb4-646d-45e2-95db-0b8ab4e465d6} + 09-MesDataFunction + + + {e4eb6420-906d-4672-947a-ca33ddcdadfc} + 12SendMessageToWeb + + + {55b510c1-59e9-4bfd-ae84-d76d46f6e365} + 02-13.3MIS_FuntionSaveData + + + + + + + 这台计算机上缺少此项目引用的 NuGet 程序包。使用“NuGet 程序包还原”可下载这些程序包。有关更多信息,请参见 http://go.microsoft.com/fwlink/?LinkID=322105。缺少的文件是 {0}。 + + + + + \ No newline at end of file diff --git a/MisDataFunction/MesServer.Function/Function1058/MesServerFunction/Function1058.cs b/MisDataFunction/MesServer.Function/Function1058/MesServerFunction/Function1058.cs new file mode 100644 index 0000000..1c5713d --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1058/MesServerFunction/Function1058.cs @@ -0,0 +1,253 @@ + +using MesServerWork; +using System; +using System.Collections.Generic; +using System.Threading; + +namespace MesServerFunctions +{ + public partial class FunctionMES + { + object lockFunWork; + //public void FunWork(DoWhatPlc.CustomeEvetnArgs e) + public void FunWork(string recData) + { + + + lockFunWork = new object(); + lock (lockFunWork) + { + List dataArray = DoWhatPlc.MessageText.GetCmdStringList(recData); + //string[] dataArray = recData.Split('|'); + //if (dataArray.Count != 4) + //return; + //消息来源 + string m_Source = dataArray[0].ToString(); + //消息类型 Barcode + string m_Command = dataArray[1].ToString(); + //工位号 + string m_OpName = dataArray[2].ToString(); + //消息参数 + string m_Value = dataArray[3].ToString(); + + DoWhatPlc.CustomeEvetnArgs e =new DoWhatPlc.CustomeEvetnArgs();// = Newtonsoft.Json.JsonConvert.DeserializeObject(m_Value); + string tagValue; + + switch (m_Source) + { + case "BarCode": + e.OpName = m_OpName; + e.TagValue = m_Value; + fun_Barcode(e); + + break; + case "WEB": + e.OpName = m_OpName; + e.TagValue = m_Command + "|" + m_Value; + fun_WebSubmit(e); + break; + case "PLC": + e = Newtonsoft.Json.JsonConvert.DeserializeObject(m_Value); + switch (e.TagValue.ToString().ToLower()) + { + case "false": + tagValue = "0"; + break; + case "true": + tagValue = "1"; + break; + default: + tagValue = e.TagValue.ToString(); + break; + } + e.TagValue = tagValue; + switch (e.TagTypeCodeID.ToString()) + { + //PLC 工件到位 + case "2": + fun_WorkStart(e); + break; + //PLC 允许保存质量数据 + case "19": + fun_MesRead(e); + break; + //MES 保存数据完成 + case "20": + fun_MesReadOver(e); + break; + //PLC 传递机型 + case "44": + fun_EngineTypeGetOverPLC(e); + break; + //MES 合格放行 + case "51": + fun_ConfirmOkGo(e); + break; + //MES 不合格放行 + case "8": + fun_FalseGo(e); + break; + //MES 系统健康心跳 + case "14": + fun_HeartBeatMIS(e); + break; + case "63": + string S_plcStatus;//DBX501.5 PLC直通,1 强制放行 0 正常循环 + MIS_BASE.Read_TagTypeID(63, m_OpName, out S_plcStatus); + if (S_plcStatus.ToLower() != "true" || S_plcStatus.ToLower() == "1") + { + SendMessageFun.SendInfomation("PlcStatus", "0", m_OpName); + } + else + { + SendMessageFun.SendInfomation("PlcStatus", "1", m_OpName); + } + break; + } + break; + } + } + } + //public void FunWork(DoWhatPlc.CustomeEvetnArgs e) + //{ + // //lock1 = new object(); + // //lock (lock1) + // { + // switch (e.TagTypeCodeID.ToString()) + // { + // //PLC 工件到位 + // case "2": + // fun_WorkStart(e); + // break; + // //PLC 允许保存质量数据 + // case "19": + // fun_MesRead(e); + // break; + // //MES 保存数据完成 + // case "20": + // fun_MesReadOver(e); + // break; + // //PLC 传递机型 + // case "44": + // fun_EngineTypeGetOverPLC(e); + // break; + // //MES 合格放行 + // case "51": + // fun_ConfirmOkGo(e); + // break; + // //MES 不合格放行 + // case "8": + // fun_FalseGo(e); + // break; + // //MES 扫描条码 + // case "Barcode": + // fun_Barcode(e); + // break; + // //WEB 处理页面传递过来的数据 + // case "WebSubmit": + // fun_WebSubmit(e); + // break; + // } + // } + + //} + //1.工件到位后,PLC给MES传递机型(DBX0.4)(44), + //2.MES判断是否扫描完成 + //3.若扫描完成,则MES给出合格放行(DBX2.5)(51) + /// + /// 扫描条码 + /// + /// + /// + public void fun_Barcode(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(Barcode, e); + } + + + /// + /// 传递机型 + /// + /// + /// + public void fun_EngineTypeGetOverPLC(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(EngineTypeGetOver_PLC, e); + } + + /// + /// 合格放行 + /// + /// + /// + public void fun_ConfirmOkGo(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(ConfirmOkGo, e); + } + /// + /// 系统健康心跳监测 + /// + /// + /// + public void fun_HeartBeatMIS(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(HeartBeat, e); + } + /// + /// 不合格放行 + /// + /// + /// + public void fun_FalseGo(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(FalseGO, e); + } + + + /// + /// 保存完成 20 + /// + /// + /// + public void fun_MesReadOver(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(MesReadOver, e); + } + + /// + /// 保存完成 19 + /// + /// + /// + public void fun_MesRead(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(MesRead, e); + } + + /// + /// 工件到位离开(清空所有的MES信号) + /// + /// + /// + public void fun_WorkStart(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(WorkStart, e); + } + + /// + /// 处理WEB页面发送过来的请求(m_Command + "|" + m_Value;) + /// + /// + /// + public void fun_WebSubmit(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(WebSubmit, e); + } + + public int fun_SubLineLoadPartCountMatch() + { + return SubLineLoadPartCountMatch; + } + + } +} diff --git a/MisDataFunction/MesServer.Function/Function1058/MesServerFunction/vssver2.scc b/MisDataFunction/MesServer.Function/Function1058/MesServerFunction/vssver2.scc new file mode 100644 index 0000000..775bb6c Binary files /dev/null and b/MisDataFunction/MesServer.Function/Function1058/MesServerFunction/vssver2.scc differ diff --git a/MisDataFunction/MesServer.Function/Function1058/Methods/EngineGetOverBaseWork.cs b/MisDataFunction/MesServer.Function/Function1058/Methods/EngineGetOverBaseWork.cs new file mode 100644 index 0000000..5c44814 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1058/Methods/EngineGetOverBaseWork.cs @@ -0,0 +1,288 @@ +using System; +using System.Data; +using bizFacade; +using MesServerWork; +//using SystemFramework; + + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 分线上总线的数量 + /// + public static int SubLineLoadPartCount = 2; + /// + /// 分线上总线已经匹配的数量 + /// + public static int SubLineLoadPartCountMatch = 0; + /// + /// 正常逻辑工作 + /// + /// + /// + /// + /// + /// + private void EngineTypeGetOver_PLC_Work(string OpName, int EngineTypeID, string EngineType, string EngineID, int PartPallet_Code,string OrderForm) + { + int IsAllowWork; + int RepairPartStatusPLC = 0; + int MES_QualityMask = 1; + + if (EngineTypeID <= 0 || EngineID.Length == 0 || EngineType.Length == 0 || OrderForm.Length == 0) + { + SendMessageFun.AsyncSendMessage_Notice(OpName, "PLC传递机型为空"); + return; + } + + //初始化物料临时表 + //第二步,将零件信息转移到零件_临时表中(本地BOM与订单BOM的选择显示关系) + BaseDataSystemMES.MesServer_Process_EngineTypeOver_BQ_FirstOP(OpName); + + //5 显示订单、机型信息 线首工位用 + SendMessage.ShowMoby_FirstOpName(OpName); + //3显示操作指导图片 PicShow_String_FirstOpName + SendMessage.PicShow_FirstOpName(OpName); + //1(直接在界面通过选择机型确认工序内容) + SendMessage.ProcessList_FirstOpName(OpName); + //界面显示物料信息 + SendMessage.MaterialList_FirstOpName(OpName); + + //电子看板_装配零件_临时表_增加_北汽 + //第二步,将零件信息转移到零件_临时表中 + // BaseDataSystemMES.MesServer_Process_EngineTypeOverBQ(OpName); + + //通知web显示 + //SendMessageFun.SendMessage("123", "111", OpName); + + //第四步,获取是否允许工作 + BaseDataSystemMES.MesServer_Judge_IsCanWork(OpName, out IsAllowWork); + + // 暂时先定义为扫描完成才能进行压装工作,因为考虑到工作完成后,操作工未必会去扫描物料的情况 + if (IsAllowWork == 1) + { + //通知PLC允许工作,允许工作在保存完成时清空 + MIS_BASE.Write_FixAllow(OpName, true); + } + else + { + SendMessageFun.AsyncSendMessage_Notice(OpName, "请扫描物料!"); + } + } + + + /// + /// 保存MOBY信息 + /// + /// + /// + /// + /// + private void SaveMobyMessage(string OpName, int engineTypeID, string engineType, string engineID, string orderForm) + { + + if (MIS_BASE.hashtable_EngineGetOver_EngineTypeID == null) + { + MIS_BASE.InitHashtable_MesServerCode(); + } + if (MIS_BASE.hashtable_EngineGetOver_EngineTypeID.ContainsKey(OpName)) + { + MIS_BASE.hashtable_EngineGetOver_EngineTypeID[OpName] = engineTypeID; + } + if (MIS_BASE.hashtable_EngineGetOver_EngineType.ContainsKey(OpName)) + { + MIS_BASE.hashtable_EngineGetOver_EngineType[OpName] = engineType; + } + if (MIS_BASE.hashtable_EngineGetOver_EngineID.ContainsKey(OpName)) + { + MIS_BASE.hashtable_EngineGetOver_EngineID[OpName] = engineID; + } + if (MIS_BASE.hashtable_EngineGetOver_OrderForm.ContainsKey(OpName)) + { + MIS_BASE.hashtable_EngineGetOver_OrderForm[OpName] = orderForm; + } + } + + /// + /// 返修件需要工作 + /// + /// 工位号 + private void IsNeedRepaire_OK(string OpName) + { + + int isRepair; + int engineTypeID; + + string engineType = ""; + string engineID = ""; + string palletCode = ""; + string orderForm = ""; + string repairCode = ""; + //从监控系统中查询出本工位信息 + BaseDataSystemMES.OpName_MIS_Moby_Select(OpName, + out orderForm, out engineTypeID, out engineType, + out engineID, out palletCode, out isRepair, out repairCode); + + EngineTypeGetOver_PLC_Work(OpName, engineTypeID, engineType, engineID, Convert.ToInt32(palletCode),orderForm); + } + /// + /// 正常匹配分线和总线 + /// + /// + /// 总线工件号 + /// 总线工件机型代码 + /// 总线工件机型 + private void Match(string opName, string engineID, int engineTypeID, string engineType, int PartPallet_Code) + { + try + { + bool m_EngineGetOver_PLC_SubLine; + int engineTypeID_SubLine; + int partPallet_Code_SubLine; + int PalletInfo = 1;//总线托盘状态 + + string opName_SubLine = "";//分线工件信息 + string engineID_SubLine; + string engineType_SubLine; + string AlarmStr; + if (MIS_BASE.hashtable_OpNameRepair == null) + { + MIS_BASE.InitHashtable_MesServerCode(); + } + //第一步:获取分线中间交互工位号 + if (MIS_BASE.hashtable_OpNameRepair.ContainsKey(opName)) + { + opName_SubLine = MIS_BASE.hashtable_OpNameRepair[opName].ToString(); + } + if (opName_SubLine == "") + { + return; + } + + //第二步:获取分线传递机型信号 + MIS_BASE.Read_EngineGetOver_PLC(opName_SubLine, out m_EngineGetOver_PLC_SubLine); + if (!m_EngineGetOver_PLC_SubLine) return;//必须工件同时到位才能进行匹配 + + //第三步:判断合格标志 + MIS_BASE.Read_PalletInfo(opName_SubLine, out PalletInfo); + if (PalletInfo == 2) return; //若不合格则返回不进行匹配 + string OrderForm; + //第四步:获取分线的信息,匹配验证 + MIS_BASE.GetEngineTypeFromPLC(opName_SubLine, out engineTypeID_SubLine, out engineType_SubLine, out engineID_SubLine, out partPallet_Code_SubLine,out OrderForm); + //判断分线数据是否合格 + //if (!BaseDataSystemMES.QulityDataVerify(opName, engineID_SubLine, out AlarmStr) && !BaseDataSystemMES.QualityVerifyStatus_Hash_Read(opName)) + //{ + // SendInfomation("LineoutAlert", AlarmStr, opName); + // return; + //} + + if (engineTypeID_SubLine == engineTypeID) + { + BaseDataSystemMES.SubLineLoadPartCountMatch_Select(opName, out SubLineLoadPartCountMatch); + SubLineLoadPartCountMatch = SubLineLoadPartCountMatch + 1; + BaseDataSystemMES.SubLineLoadPartCountMatch_Update(opName, SubLineLoadPartCountMatch); + + + BaseDataSystemMES.MailLineAndSubLineData_Insert(engineID, engineTypeID, engineType, engineID_SubLine);//分线上总线数据转移 + MIS_BASE.Write_Match(opName, true);//匹配结果 + MIS_BASE.Write_MatchingCompleted(opName, true);//匹配完成 + if(SubLineLoadPartCountMatch== SubLineLoadPartCount) + { + MIS_BASE.Write_FixAllow(opName, true); + SubLineLoadPartCountMatch = 0; + BaseDataSystemMES.SubLineLoadPartCountMatch_Update(opName, SubLineLoadPartCountMatch); + + } + + SendMessageFun.SendInfomation("MatchSuccess", "1", opName); + sendmessage(opName, 1, "Match");//匹配结果 + } + else + { + MIS_BASE.Write_Match(opName, false);//匹配结果 + MIS_BASE.Write_MatchingCompleted(opName, true);//匹配完成//68:1、取消返修;2、匹配成功 自己监控发送 MES|MatchingCompleted + + //发送匹配完成和匹配结果信息 + SendMessageFun.AsyncSendMessage_Notice(opName,"匹配失败,工件型号不匹配!"); + SendMessageFun.SendInfomation("MatchSuccess", "0", opName); + sendmessage(opName, 0, "Match");//匹配结果 + } + + } + catch (Exception err) + { + ////ApplicationLog.WriteLog("Match:" + err.ToString()); + + } + } + + + + /// + /// 强制匹配分线和总线 + /// + /// + private void ForceMatch(string opName) + { + try + { + bool m_EngineGetOver_PLC_SubLine; + bool m_EngineGetOver_PLC; + + int engineTypeID_SubLine; + int engineTypeID; + int partPallet_Code_SubLine; + int partPallet_Code; + + string opName_SubLine = "";//分线工件信息 + string engineID_SubLine; + string engineType_SubLine; + string engineID; + string engineType; + if (MIS_BASE.hashtable_OpNameRepair == null) + { + MIS_BASE.InitHashtable_MesServerCode(); + } + //获取分线中间交互工位号 + if (MIS_BASE.hashtable_OpNameRepair.ContainsKey(opName)) + { + opName_SubLine = MIS_BASE.hashtable_OpNameRepair[opName].ToString(); + } + if (opName_SubLine == "") + { + return; + } + + MIS_BASE.Read_EngineGetOver_PLC(opName_SubLine, out m_EngineGetOver_PLC_SubLine);//1:读取分线工件到位的传递机型信号。 + + if (!m_EngineGetOver_PLC_SubLine) return;//必须工件同时到位才能进行匹配 + + MIS_BASE.Read_EngineGetOver_PLC(opName, out m_EngineGetOver_PLC);//2:读取总线工件到位的传递机型信号。 + + if (!m_EngineGetOver_PLC) return;//必须工件同时到位才能进行匹配 + string OrderForm; + MIS_BASE.GetEngineTypeFromPLC(opName_SubLine, out engineTypeID_SubLine, out engineType_SubLine, out engineID_SubLine, out partPallet_Code_SubLine,out OrderForm);//获取分线的信息 + MIS_BASE.GetEngineTypeFromPLC(opName, out engineTypeID, out engineType, out engineID, out partPallet_Code, out OrderForm); + + BaseDataSystemMES.MailLineAndSubLineData_Insert(engineID, engineTypeID, engineType, engineID_SubLine);//分线上总线数据转移 + + MIS_BASE.Write_Match(opName, true);//匹配结果 + MIS_BASE.Write_MatchingCompleted(opName, true);//匹配完成 + + SendMessageFun.SendInfomation("MatchSuccess", "1", opName);//界面显示匹配成功 + + MIS_BASE.Write_FixAllow(opName, true);//允许PLC工作 + + //发送匹配完成和匹配结果信息 + sendmessage(opName, 1, "MatchingComplete");//匹配完成 + sendmessage(opName, 1, "Match");//匹配结果 + } + catch + { + + } + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1058/Methods/SubmitToMisweb.cs b/MisDataFunction/MesServer.Function/Function1058/Methods/SubmitToMisweb.cs new file mode 100644 index 0000000..8d84430 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1058/Methods/SubmitToMisweb.cs @@ -0,0 +1,145 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using bizFacade; +//using SystemFramework; + +namespace MesServerFunctions +{ + + /// + /// 此类用于向WEB发送各种类型消息 + /// + partial class FunctionMES + { + + + // /// + // /// 批量发送WEB消息(Value为BOOL值) + // /// + // /// 消息编号组合 + // /// 消息值组合 + // /// 工位号 + // void Sendmessage(string MessageNumm,string Value, string OpName) + //{ + // for (int i=0;i + // /// 选择发送给WEB的消息 + // /// + // /// 消息类型 + // /// 消息工位 + //void Sendmessage(char Num,string Value, string OpName) + //{ + // string SendMessage; + // switch (Num) + // { + // case '1': + // //1(直接在界面通过选择机型确认工序内容) + // SendMessage = "MES|ProcessList|" + OpName + "|" + Value; + // AsyncSendMessage(SendMessage); + // break; + + // case '2': + // //2显示物料 + // SendMessage = "MES|MaterialList|" + OpName + "|" + Value; + // AsyncSendMessage(SendMessage); + // break; + + // case '3': + + // //3显示操作指导图片 + // SendMessage = "MES|PicShow|" + OpName + "|" + Value; + // AsyncSendMessage(SendMessage); + // break; + // case '4': + // //3显示操作指导图片 + // SendMessage = "MES|OrderFormList|" + OpName + "|" + Value; + // AsyncSendMessage(SendMessage); + // break; + + // case '5': + // SendMessage = "MES|ShowMoby|" + OpName + "|" + Value; + // AsyncSendMessage(SendMessage); + // break; + // case '6': + // SendMessage = "MES|MaterialCheckPosition|" + OpName + "|" +Value; + // AsyncSendMessage(SendMessage); + // break; + // case '7': + // SendMessage = "MES|WorkStart|" + OpName + "|" + Value; + // AsyncSendMessage(SendMessage); + // break; + // case '8': + // SendMessage = "MES|OrderFormList|" + OpName + "|" + Value; + // AsyncSendMessage(SendMessage); + // break; + // case '9': + // SendMessage = "MES|ConfirmOkGo|" + OpName + "|" + Value; + // AsyncSendMessage(SendMessage); + // break; + // case 'a': + // SendMessage = "MES|FixAllow|" + OpName + "|" + Value; + // AsyncSendMessage(SendMessage); + // break; + // case 'b': + // SendMessage = "MES|ShaftPosition|" + OpName + "|" + Value; + // AsyncSendMessage(SendMessage); + // break; + // case 'c': + // SendMessage = "MES|ShowQuality|" + OpName + "|" + Value; + // AsyncSendMessage(SendMessage); + // break; + // } + //} + + /// + /// 向WEB发送信息(value为字符串) + /// + /// 消息种类 + /// 消息内容 + /// 工位号 + //void SendInfomation(string Command, string Value, string OpName) + //{ + + // string SendMessage = "MES|" + Command + "|" + OpName + "|" + Value; + // AsyncSendMessage(SendMessage); + //} + + + ///// + ///// 发送在线产量、在线节拍 + ///// + ///// + ///// + //private void SendActuallyCount(string OpName, int tagValue) + //{ + // //当工件离开时,更新在线产量、在线节拍 + // if (tagValue == 0) + // { + // try + // { + // int opNameCount = 0;//在线产量 + // int opNameCountTime = 0;//在线节拍 + + // BaseDataSystemMES.OpNameCount_New(OpName, out opNameCount, out opNameCountTime); //基本数据_工作日历_班次产量查询_New + + // SendInfomation("ActuallyCount", opNameCount.ToString() + "&" + opNameCountTime.ToString(), OpName); + + // } + // catch (Exception err) + // { + // ////ApplicationLog.WriteLog(err, "Function01:SendActuallyCount"); + // } + // } + //} + + + } +} diff --git a/MisDataFunction/MesServer.Function/Function1058/Methods/UDP.Send.cs b/MisDataFunction/MesServer.Function/Function1058/Methods/UDP.Send.cs new file mode 100644 index 0000000..26acece --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1058/Methods/UDP.Send.cs @@ -0,0 +1,62 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using MesServerWork; +//using BasicData; +using System.Collections; +using bizFacade; +//using SystemFramework; +using System.Data; +using System.Threading; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + ///// + ///// 发送信息到MES通讯服务器或者其他的 + ///// + ///// + //private void AsyncSendMessage(string Message) + //{ + // MIS_BASE.asyncSendMessage(Message); + //} + + /// + /// 发送提示消息 + /// + /// + //private void AsyncSendMessage_Notice(string opname, string notice) + //{ + // //通知Web界面 + // BaseDataSystemMES.Web_Notice_Insert(opname, notice); + // string SendMessage = "MES|Notice|" + opname + "|" + "1"; + // MIS_BASE.asyncSendMessage(SendMessage); + //} + + /// + /// 发送信息到打印机 + /// + /// + private void asyncSendMessageToMark(string Message) + { + string messageSend = (string)Message; + //UDPClientSend.Send_ALL(ApplicationConfig.MES_MarkPortNum, messageSend); + } + + /// + /// 发送信息到LED + /// + /// + private void asyncSendMessageLED(string OpName) + { + + //发送到大屏幕显示 41104 + string strMessage = "MIS|" + OpName + "|" + "0" + "|" + "1"; + //UDPClientSend.Send_ALL(ApplicationConfig.Port_ShowLED_ProductCount, strMessage); + + } + + } +} diff --git a/MisDataFunction/MesServer.Function/Function1058/Methods/vssver2.scc b/MisDataFunction/MesServer.Function/Function1058/Methods/vssver2.scc new file mode 100644 index 0000000..7b1a830 Binary files /dev/null and b/MisDataFunction/MesServer.Function/Function1058/Methods/vssver2.scc differ diff --git a/MisDataFunction/MesServer.Function/Function1058/OpcServer/Barcode.cs b/MisDataFunction/MesServer.Function/Function1058/OpcServer/Barcode.cs new file mode 100644 index 0000000..f70a8bc --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1058/OpcServer/Barcode.cs @@ -0,0 +1,220 @@ +using System; +using System.Threading; +using System.Xml.Linq; +using bizFacade; + +//using SystemFramework; +using MesServerWork; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + object lockBarcode = new object(); + + ///第一步,判断条码类型,根据条码类型,执行对应的存储过程 + ///第二步,条码类型(将扫描的条码保存到对应的表中) + ///第三步,扫描完成之后给出允许工作信号 + /// 处理页面扫描条码 + /// + /// + /// + public void Barcode(object e) + { + lock(lockBarcode) + { + try + { + + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + string barcode = Convert.ToString(msgEvent.TagValue); + + int EngineTypeID;//机型代码 + string EngineType;//机型 + string EngineID;//工件编号 + + string OrderForm; + int Recipe1; + int Recipe2; + + bool IsNotRepeatedNumber = false; + //1:获得申请上线信息后,扫描条码才处理业务 + bool ispartload; + //(115) + int PTO; + //(118)0=不检测;1=24V,2=12V。检测线上线工位扫描总成条码,根据BOM,查出 + int NgearSwitch; + //(119)0=不检测;1=24V,2=12V。检测线上线工位扫描总成条码,根据BOM,查出 + int RgearSwitch; + //(120)0=不检测;1=检测。检测线上线工位扫描总成条码,根据BOM,查出 + int SpeedSensor; + //(121)例如:5S 400。检测线上线工位扫描总成条码,根据BOM,查出 + string PartTypeMid; + //(122) 0=不检测;1=24V,2=12V。检测线上线工位扫描总成条码,根据BOM,查出 + int Tcu_V; + //判断工件是否到位 + MIS_BASE.Read_WorkStart(OpName, out ispartload); + if (!ispartload) + { + SendMessageFun.AsyncSendMessage_Notice(OpName, "请检查设备是否到位(DBX500.1=1)"); + return; + } + //判断设备是否申请上线 + MIS_BASE.Read_UpdatePalletOK(OpName, out ispartload); + if (!ispartload) + { + SendMessageFun.AsyncSendMessage_Notice(OpName, "请检查设备是否申请上线(DBX500.3=1)"); + return; + } + // 判读条码是变速器序列号条码号还是物料号 小机型*日月年* 流水号(给起始号 + 数量) + // 选小机型 从北汽福田BOM中选 得先维护BOM + // 变速器序列号 '1333 050 062*16012023*30000001' + + //扫描完变速器序列号条码号 true + bool isGetOver_MES = false; + //判断上线工位,MES 是否将工件流水号、机型等信息已经写入到PLC了 + //MIS_BASE.Read_EngineTypeGetOver_MES(OpName, out isGetOver_MES); + MIS_BASE.Read_EngineGetOver_PLC(OpName, out isGetOver_MES); + //如果工件流水号、机型等信息没有写入PLC,扫描的条码按工件流水号进行验证 + //否则按装配物料进行验证 + if (!isGetOver_MES) + { + + if (barcode.Split(';').Length > 2 || barcode.Split('*').Length > 2) + { + + string partSn = barcode; + EngineID = barcode; + + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.EngineID_MES, EngineID); + SendMessage.ShowMoby(OpName); + + //2: 判断是否重号 + //IsRepeatedNumber true 不重号;false 重号; + IsNotRepeatedNumber = BaseDataSystemMES.EngineTypeID_IsNotRepeatedNumber(partSn); + if (IsNotRepeatedNumber) + { + // 从数据库获得机型、机型代码等信息 + BaseDataSystemMES.GetEngineTypeUpLoadOpName(partSn, OpName, out EngineTypeID, out EngineType, out OrderForm, out Recipe1, out Recipe2); + // 从数据库获得PTO等信息 + BaseDataSystemMES.UpLoadPTO(partSn, out PTO, out NgearSwitch, out RgearSwitch, out SpeedSensor, out PartTypeMid, out Tcu_V); + //PTO + MIS_BASE.WritePLC(115, OpName, PTO); + //空挡开关检测 + MIS_BASE.WritePLC(95, OpName, NgearSwitch); + //倒挡开关检测 + MIS_BASE.WritePLC(96, OpName, RgearSwitch); + //里程表检测 + MIS_BASE.WritePLC(97, OpName, SpeedSensor); + //大机型扩展 + MIS_BASE.WritePLC(98, OpName, PartTypeMid); + //TCU + MIS_BASE.WritePLC(122, OpName, Tcu_V); + // 先查询配方号 根据工位号 去moby表查配方号 + // 根据配方号 去配方表查配方数据 写入配方数据 + string tagStartAdr;//= "DB411.10"; + BaseDataSystemMES.PLCRcipeCurrent(OpName, out byte[] bytes, out tagStartAdr); + DtWebApi.ReadWritePLC.Write_TagValueByTagTypeID("94", OpName, System.Text.Encoding.ASCII.GetString(bytes)); + // 将产品信息写入PLC + MIS_BASE.Write_EngineTypeID_MES(OpName, EngineTypeID); + MIS_BASE.Write_EngineType_MES(OpName, EngineType); + MIS_BASE.Write_EngineID_MES(OpName, EngineID); + MIS_BASE.Write_OrderForm_MES(OpName, OrderForm); + + // 写入到数据库的[北汽福田工位状态监控MOBY]表中 + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.EngineID_MES, EngineID); + SendMessage.ShowMoby(OpName); + + SendMessageFun.AsyncSendMessage_Notice(OpName, "总成码扫码完成,请扫描后壳码!"); + + + MIS_BASE.Write_EngineTypeGetOver_MES(OpName, true); + + //Thread.Sleep(1000); + //// 临时增加 清除MES的传递机型 + //MIS_BASE.Write_EngineTypeGetOver_MES(OpName, false); + + } + else + { + SendMessageFun.AsyncSendMessage_Notice(OpName, "变速器序列号 重号,请确认!"); + } + } + else + { + SendMessageFun.AsyncSendMessage_Notice(OpName, "变速器序列号格式不正确,请确认!"); + + } + } + else//验证物料 + { + //物料号 + { + //读取PLC的传递机型信号 + bool tagValue; + MIS_BASE.Read_EngineGetOver_PLC(OpName, out tagValue); + if (tagValue) + { + //验证物料 + BaseDataSystemMES.PartMaterial_DM_Update(OpName, barcode, out bool IsSuccess); + if (!IsSuccess)//???? + { + SendMessageFun.AsyncSendMessage_Notice(OpName, "条码无效,请确认"); + return; + } + else + { + SendMessageFun.SendInfomation("MaterialList", "1", OpName);//通知界面更新零件信息 + } + //判断物料是否验证完成 + BaseDataSystemMES.MesServer_Judge_IsCanWork(OpName, out int IsAllowWork); + + + if (IsSuccess) + { + if (IsAllowWork == 1) + { + //移到允许保存信号中 + //BaseDataSystemMES.Material_Insert(OpName, 1); + + ////更新订单完工数量及物料 + SendMessageFun.SendMessage("245", "111", OpName); + + // 写入到数据库的[北汽福田工位状态监控MOBY]表中 + SendMessage.ShowMoby(OpName); + + SendMessageFun.AsyncSendMessage_Notice(OpName, "扫码完成,请开始工作!"); + + //物料验证完成,通知PLC允许工作,允许工作在保存完成时清空 + MIS_BASE.Write_FixAllow(OpName, true); + } + else + { + SendMessageFun.AsyncSendMessage_Notice(OpName, "请扫描物料!"); + } + } + else + { + SendMessageFun.AsyncSendMessage_Notice(OpName, "PLC未传递机型"); + } + } + else + { + SendMessage.AsyncSendMessage_Notice(OpName, "产品上线后,PLC获得变速器序列号后,再验证物料!"); + } + + } + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function08:Barcode"); + } + } + + } + + + } +} diff --git a/MisDataFunction/MesServer.Function/Function1058/OpcServer/ConfirmOkGo.cs b/MisDataFunction/MesServer.Function/Function1058/OpcServer/ConfirmOkGo.cs new file mode 100644 index 0000000..a978c1f --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1058/OpcServer/ConfirmOkGo.cs @@ -0,0 +1,35 @@ +using System; +//using SystemFramework; +using MesServerWork; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 合格放行 + /// + /// + /// + private void ConfirmOkGo(object e) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + + if (tagValue == 1) + { + MIS_BASE.Write_MaterialVerifyOver(OpName, true);//工作完成 + SendMessageFun.SendInfomation("OrderFormList","1", OpName); + + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function08:ConfirmOkGo"); + } + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1058/OpcServer/EngineGetOver.cs b/MisDataFunction/MesServer.Function/Function1058/OpcServer/EngineGetOver.cs new file mode 100644 index 0000000..db8fde9 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1058/OpcServer/EngineGetOver.cs @@ -0,0 +1,98 @@ +using System; +using System.Data; +using bizFacade; +using MesServerWork; +//using SystemFramework; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + object lockBarcodeEngineTypeGetOver = new object(); + + + /// + /// PLC传递机型处理 + /// + /// + /// + private void EngineTypeGetOver_PLC(object e) + { + lock(lockBarcodeEngineTypeGetOver) + { + + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + if (tagValue == 1) + { + bool MesRead = false; + + int EngineTypeID;//机型代码 + int PartPallet_Code;//托盘编号 + + string EngineType;//机型 + string EngineID;//工件编号 + + int EngineTypeID_MES;//机型代码 + string EngineType_MES;//机型 + string EngineID_MES;//工件编号 + + //上线工位清MES传递机型信号 + MIS_BASE.Write_EngineTypeGetOver_MES(OpName, false); + + MIS_BASE.Read_QualityData_Read_CF(OpName, out MesRead); + //第一步,判断允许保存和保存完成信号是否全部被清空,若未清空,则通知复位MES&PLC + if (MesRead) + { + //未能清空信号,请求复位 + SendMessageFun.SendInfomation("AskReset", "1", OpName); + return; + } + string OrderForm; + string OrderForm_MES; + MIS_BASE.GetEngineTypeFromPLC(OpName, out EngineTypeID, out EngineType, out EngineID, out PartPallet_Code, out OrderForm); + MIS_BASE.GetEngineTypeFromPLC_MES(OpName, out EngineTypeID_MES, out EngineType_MES, out EngineID_MES, out OrderForm_MES); + + //判断PLC机型与MES机型是否一致 + if (EngineTypeID_MES == EngineTypeID & EngineID_MES == EngineID & EngineType_MES == EngineType) + { + // 如果机型改变的话 提示机型发生变化 + DataTable dt = BaseDataSystemMES.EngineTypeChange(OpName, EngineType); + if (dt.Rows.Count > 0) + { + string mesValue = Newtonsoft.Json.JsonConvert.SerializeObject(dt);//(recData); + string message = "MES|MaterialList_Dif_Resources|" + OpName + "|" + mesValue; + SendMessage.AsyncSendMessage(message); + } + //写入到数据库的[北汽福田工位状态监控MOBY]表中 + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.EngineTypeID, EngineTypeID.ToString()); + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.EngineType, EngineType); + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.EngineID, EngineID); + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.OrderForm, OrderForm); + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.PartPallet_Code, PartPallet_Code.ToString()); + + EngineTypeGetOver_PLC_Work(OpName, EngineTypeID, EngineType, EngineID, PartPallet_Code, OrderForm); + return; + } + else + { + SendMessage.AsyncSendMessage_Notice(OpName, "码块RFID机型与MES机型不匹配!"); + } + + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function08:EngineTypeGetOver_PLC"); + } + } + + } + + + + } +} diff --git a/MisDataFunction/MesServer.Function/Function1058/OpcServer/FalseGO.cs b/MisDataFunction/MesServer.Function/Function1058/OpcServer/FalseGO.cs new file mode 100644 index 0000000..54c73c7 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1058/OpcServer/FalseGO.cs @@ -0,0 +1,37 @@ +using System; +using MesServerWork; +//using SystemFramework; + + +namespace MesServerFunctions +{ + partial class FunctionMES + { + + /// + /// 返修放行 + /// + /// + /// + private void FalseGO(object e) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + + if (tagValue == 1) + { + MIS_BASE.Write_MaterialVerifyOver(OpName, true);//工作完成 + SendMessageFun.SendInfomation("OrderFormList", "1", OpName); + + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function08:FalseGO"); + } + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1058/OpcServer/HeartBeat.cs b/MisDataFunction/MesServer.Function/Function1058/OpcServer/HeartBeat.cs new file mode 100644 index 0000000..93affd3 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1058/OpcServer/HeartBeat.cs @@ -0,0 +1,35 @@ +using bizFacade; +using MesServerWork; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// MES与PLC心跳监听 + /// + /// + /// + private void HeartBeat(object e) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + + //返写在MES心跳中 + MIS_BASE.WritePLC(15, OpName, tagValue); + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:FalseGO"); + } + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1058/OpcServer/MesRead.cs b/MisDataFunction/MesServer.Function/Function1058/OpcServer/MesRead.cs new file mode 100644 index 0000000..4705f0a --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1058/OpcServer/MesRead.cs @@ -0,0 +1,85 @@ +using System; +using bizFacade; +//using SystemFramework; +using MesServerWork; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + object lockMesRead = new object (); + /// + /// 保存完成(针对半自动和手动压装工位) + /// + /// + /// + private void MesRead(object e) + { + lock(lockMesRead) + { + try + { + int EngineTypeID; + string EngineType; + string EngineID; + int PartPallet_Code; + string OrderForm; + + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + + if (tagValue == 1) + { + MIS_BASE.GetEngineTypeFromPLC(OpName, out EngineTypeID, out EngineType, out EngineID, out PartPallet_Code, out OrderForm); + //保存数据到线首表 先保存到 北汽福田变速器序列号总线上线 用于之前判断是否重号 + if (Db.UpLoadOpNameInsert(EngineID, EngineTypeID, EngineType, OpName)) + { + //保存质量数据 + int qualityMask = MisDataSaveDateMesRead.Funtion.MesRead(OpName, tagValue.ToString(), msgEvent.TagID.ToString()); + //推送质量数据到MES的页面 + MIS_BASE.SendInfomation("ShowTimelyQuality", "1&" + qualityMask.ToString(), OpName); + + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.WorkStartOut, DateTime.Now.ToString()); + + //保存物料数据 + BaseDataSystemMES.Material_Insert(OpName, tagValue); + //测量数据发动机在线状态 + BaseDataSystemMES.WorkStartInsert(OpName, qualityMask); + + // MIS_BASE.Write_ConfirmOkGo(OpName, true); + + //MisDataSaveDate. + MIS_BASE.Write_MesReadOver(OpName, true); + MIS_BASE.Write_MaterialVerifyOver(OpName, true); + SendMessage.SendActuallyCount(OpName, tagValue);//统计在线产量,在线节拍 + } + else + { + SendMessage.AsyncSendMessage_Notice(OpName, "保存上线数据失败!"); + } + } + else + { + MIS_BASE.Write_MesReadOver(OpName, false); + MIS_BASE.Write_MaterialVerifyOver(OpName, false); + MIS_BASE.Write_ConfirmOkGo(OpName, false); + MIS_BASE.Write_FixAllow(OpName, false); + MIS_BASE.Write_ConfirmOkGo(OpName, false); + MIS_BASE.Write_ConfirmOkGo(OpName, false); + } + + } + + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function08:MesReadOver"); + } + + } + + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1058/OpcServer/MesReadOver.cs b/MisDataFunction/MesServer.Function/Function1058/OpcServer/MesReadOver.cs new file mode 100644 index 0000000..9b637f2 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1058/OpcServer/MesReadOver.cs @@ -0,0 +1,37 @@ +using System; +using bizFacade; +//using SystemFramework; +using MesServerWork; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 保存完成(针对半自动和手动压装工位) + /// + /// + /// + private void MesReadOver(object e) + { + try + { + //DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + //string OpName = Convert.ToString(msgEvent.OpName); + //int tagValue = Convert.ToInt32(msgEvent.TagValue); + + //if (tagValue == 1) + //{ + + // BaseDataSystemMES.Material_Insert(OpName, tagValue); + + // MIS_BASE.Write_ConfirmOkGo(OpName, true); + //} + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function08:MesReadOver"); + } + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1058/OpcServer/WebSubmit.cs b/MisDataFunction/MesServer.Function/Function1058/OpcServer/WebSubmit.cs new file mode 100644 index 0000000..4bfd077 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1058/OpcServer/WebSubmit.cs @@ -0,0 +1,342 @@ +using System; +using MesServerWork; +using bizFacade; +using System.Threading; +using MisDataSaveDate; +using System.Collections; +//using SystemFramework; + + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 处理WEB页面发送过来的请求(m_Command + "|" + m_Value;) + /// + /// + /// + private void WebSubmit(object e) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + string Content = Convert.ToString(msgEvent.TagValue); + + string opName_SubLine = ""; + string engineID = "";//工件信息 + string[] dataArray = Content.Split('|'); + + if (dataArray.Length != 2) + return; + + + string m_Command = dataArray[0].ToString();//消息类型 + string m_Value = dataArray[1].ToString();//消息参数 + string[] m_Value_array = m_Value.Split('&');//消息参数数量 + int m_Value_length = m_Value_array.Length; //消息参数长度 + + if (MIS_BASE.hashtable_EngineGetOver_EngineTypeID == null) + { + MIS_BASE.InitHashtable_MesServerCode(); + } + if (MIS_BASE.hashtable_EngineGetOver_EngineID.ContainsKey(OpName)) + { + engineID = MIS_BASE.hashtable_EngineGetOver_EngineID[OpName].ToString(); + } + if (MIS_BASE.hashtable_OpNameRepair == null) + { + MIS_BASE.InitHashtable_MesServerCode(); + } + DoWhatPlc.CustomeEvetnArgs _e = new DoWhatPlc.CustomeEvetnArgs(); + _e.OpName = OpName; + _e.TagValue = m_Value; + + //根据请求的命令处理逻辑 + switch (m_Command) + { + case "Barcode": + if (m_Value_length > 1) return; + fun_Barcode(_e); + break; + case "ConfirmOkGo"://合格放行 + //修改托盘状态 + + BaseDataSystemMES.BaseData_tagTable_Engine_IsNG_Delete(OpName, engineID); + MIS_BASE.Write_ConfirmOkGo(OpName, true); + MIS_BASE.Write_FalseGO(OpName, false); + Thread.Sleep(1000); + MIS_BASE.Write_ConfirmOkGo(OpName, false); + break; + case "FalseGO"://返修放行 + //修改托盘状态 + BaseDataSystemMES.BaseData_tagTable_Engine_IsNG_Delete(OpName, engineID); + MIS_BASE.Write_FalseGO(OpName, true); + MIS_BASE.Write_ConfirmOkGo(OpName, false); + Thread.Sleep(1000); + MIS_BASE.Write_FalseGO(OpName, false); + break; + case "NgGO"://不合格放行 + //修改托盘状态 + //保存不合格信息(必须保存不合格放行信息,由于B5A的Moby没有不合格标志位) + BaseDataSystemMES.BaseData_tagTable_Engine_IsNG_Insert(OpName, engineID, "", ""); + MIS_BASE.Write_FalseGO(OpName, true); + MIS_BASE.Write_ConfirmOkGo(OpName, false); + Thread.Sleep(1000); + MIS_BASE.Write_FalseGO(OpName, false); + break; + case "OnLineState"://在线0、离线1、屏蔽2 + try + { + if (m_Value_length > 1) return; + int a = Convert.ToInt32(m_Value); + if (a <= 2) + { + BaseDataSystemMES.IsOnLine_Update(OpName, m_Value.ToString()); + MIS_BASE.Write_OnLineState(OpName, Convert.ToInt32(m_Value)); + if (a == 2) SendMessage.AsyncSendMessage_Notice(OpName, "屏蔽MES!"); + if (a == 0) SendMessage.AsyncSendMessage_Notice(OpName, "启用MES!"); + } + } + catch + { + + } + break; + case "Reset"://复位,将MES所有的信息都复位了 + SetMoby(OpName);//将MES所有信号清空 + + break; + case "FixAllow"://重新拧紧 + break; + case "IsAutoGetEngineID"://自动手动申请编号(线首) + if (m_Value_length > 1) return; + MIS_BASE.Write_IsAutoGetEngineID(OpName, Convert.ToInt32(m_Value)); + break; + case "PartPalletGoOver"://空托盘放行 + MIS_BASE.Write_RepairUpline_MES(opName_SubLine, true); + //MIS_BASE.Write_PalletInfo(opName_SubLine, 4); + //MIS_BASE.Write_UpdatePalletOK(opName_SubLine, true); + MIS_BASE.Write_MaterialVerifyOver(opName_SubLine, true); + break; + case "SetMoby"://清空托盘(线首) + SetMoby(OpName);//将MES所有信号清空 + break; + case "RepairUplineMES"://返修上线 + MIS_BASE.Write_RepairUpline_MES(OpName, true); + break; + case "CancelRepair"://将返修件置为正常件 + + break; + case "PartPalletCode"://申请写入托盘号 + //MIS_BASE.Write_PartPalletCode_PLC(OpName, 1); + break; + case "WritePartPalletCode"://写入托盘号 + if (m_Value_length > 1) return; + MIS_BASE.Write_PalletCode(OpName, Convert.ToInt32(m_Value)); + break; + case "Normal"://启用正常拧紧工位 + MIS_BASE.Write_Normal(OpName, 1); + MIS_BASE.Write_UnNormal(OpName, 0); + break; + case "UnNormal"://启用备用拧紧工位 + MIS_BASE.Write_Normal(OpName, 0); + MIS_BASE.Write_UnNormal(OpName, 1); + break; + case "ResetDevice"://复位设备 + MIS_BASE.Write_ResetDevice(OpName, true); + System.Threading.Thread.Sleep(1000); + MIS_BASE.Write_ResetDevice(OpName, false); + break; + case "IsNeedRepaire"://返修上线(返修上线点) + if (Convert.ToInt32(m_Value) == 1) + { + //修改托盘状态 + MIS_BASE.Write_PalletInfo(OpName, 3); + //通知修改成功 + MIS_BASE.Write_UpdatePalletOK(OpName, true); + IsNeedRepaire_OK(OpName); + } + else if (Convert.ToInt32(m_Value) == 0) + { + //直接给出工作完成 + MIS_BASE.Write_MaterialVerifyOver(OpName, true); + } + break; + //强制匹配 + case "ForceMatch": + if (Convert.ToInt32(m_Value) == 1) + { + ForceMatch(OpName); + } + break; + case "PalletGO": + + if (Convert.ToInt32(m_Value) == 1) + { + //直接给出工作完成 + MIS_BASE.Write_MaterialVerifyOver(opName_SubLine, true); + } + break; + case "ContinueMatch": + BaseDataSystemMES.QualityVerifyStatus_Hash_Write(OpName, true); + fun_EngineTypeGetOverPLC(_e); + break; + //初始化网页信号 + case "IniSingalToWeb": + InitializeSingalToWeb(OpName); + break; + default: break; + } + } + catch(Exception err) + { + ////ApplicationLog.WriteLog(err, "Function08:WebSubmit"); + } + } + + private void SetMoby(string OpName) + { + try + { + //清空Moby时,需要将MES信号清空 + MIS_BASE.Write_ClearMesMoby(OpName); + + BaseDataSystemMES.MesServer_Process_EngineTypeOver(OpName); + + SendMessageFun.SendMessage("5123", "1111", OpName); + + MIS_BASE.Write_ResetDevice(OpName, true); + System.Threading.Thread.Sleep(1000); + MIS_BASE.Write_ResetDevice(OpName, false); + } + catch + { + + } + } + + + /// + /// 网页重现登录,恢复关闭前的页面状态 + /// + /// 工位号 + private void InitializeSingalToWeb(string Opname) + { + bool S_WorkOn;//申请上线 DBX0.1 + bool S_WorkStart;//工件到位 DBX0.1 + bool S_EngineGetOver;//传递机型 DBX0.4 + bool S_FixAllow;//允许工作 DBX3.1 + bool S_MaterialVerifyOver;//工作完成 DBX2.3 + string S_plcStatus;//DBX501.5 PLC直通,1 强制放行 0 正常循环 + + int IsCompleted = 0; + int S_Match = 0; + int PalletInfo_SubLine = 0;//显示分线托盘状态 + + MIS_BASE.Read_WorkStart(Opname, out S_WorkStart); + //5 显示订单、机型信息 线首工位用 + SendMessage.ShowMoby_FirstOpName(Opname); + //3显示操作指导图片 PicShow_String_FirstOpName + SendMessage.PicShow_FirstOpName(Opname); + //1(直接在界面通过选择机型确认工序内容) + SendMessage.ProcessList_FirstOpName(Opname); + //界面显示物料信息 + SendMessage.MaterialList_FirstOpName(Opname); + // 新增查询PLC直通状态 网页显示 + MIS_BASE.Read_TagTypeID(63, Opname, out S_plcStatus); + InitAlarm(Opname); + + if (S_plcStatus.ToLower() == "false") + { + SendMessageFun.SendInfomation("PlcStatus", "0", Opname); + } + else + { + SendMessageFun.SendInfomation("PlcStatus", "1", Opname); + } + + if (S_WorkStart == true) + { + SendMessageFun.SendInfomation("WorkStart", Convert.ToString(Convert.ToInt32(S_WorkStart)), Opname); + //sendmessage(Opname, Convert.ToInt32(S_WorkStart), "WorkStart_Subline"); + } + + //sendmessage(Opname, Convert.ToInt32(S_WorkStart), "EngineTypeGetOverMES_Subline"); + + MIS_BASE.Read_EngineGetOver_PLC(Opname, out S_EngineGetOver); + if (S_EngineGetOver == true) + { + SendMessageFun.SendInfomation("EngineTypeGetOverPLC", Convert.ToString(Convert.ToInt32(S_EngineGetOver)), Opname); + //sendmessage(Opname, Convert.ToInt32(S_EngineGetOver), "EngineTypeGetOverMES_Subline"); + } + + MIS_BASE.Read_FixAllow(Opname, out S_FixAllow); + + if (S_FixAllow == true) + { + SendMessageFun.SendInfomation("FixAllow", Convert.ToString(Convert.ToInt32(S_FixAllow)), Opname); + } + + MIS_BASE.Read_MaterialVerifyOver(Opname, out S_MaterialVerifyOver); + + if (S_MaterialVerifyOver == true) + { + SendMessageFun.SendInfomation("MaterialVerifyOver", Convert.ToString(Convert.ToInt32(S_MaterialVerifyOver)), Opname); + } + + //MIS_BASE.Read_MatchingCompleted(Opname, out IsCompleted); //DBX1.3 是否匹配 + //MIS_BASE.Read_Match(Opname, out S_Match); //DBX1.4 匹配结果 + + //if (IsCompleted == 1 && S_Match == 1)//发送匹配完成和匹配结果信息 + //{ + // SendMessageFun.SendInfomation("MatchingCompleted", "1", Opname); + // SendMessageFun.SendInfomation("Match", "1", Opname); + // SendMessageFun.SendInfomation("MatchSuccess", "1", Opname);//界面显示匹配成功 + //} + //else if (IsCompleted == 1 && S_Match == 0) + //{ + // SendMessageFun.SendInfomation("MatchSuccess", "0", Opname);//界面显示匹配失败 + //} + + //if (MIS_BASE.hashtable_OpNameRepair == null) + //{ + // MIS_BASE.InitHashtable_MesServerCode(); + //} + //string Opname_SubLine = ""; + //if (MIS_BASE.hashtable_OpNameRepair.ContainsKey(Opname)) + //{ + // Opname_SubLine = MIS_BASE.hashtable_OpNameRepair[Opname].ToString(); + //} + //if (Opname_SubLine == "") + //{ + // return; + //} + + //MIS_BASE.Read_PalletInfo(Opname, out PalletInfo_SubLine); + //sendmessage(Opname, PalletInfo_SubLine, "SubQualityMask"); + //SendMessageFun.SendInfomation("ShowMobySubLine", Opname_SubLine, Opname);//显示分线机型及流水号 + } + + //分线发送工件到位信号函数 + private void sendmessage(string OpName, int tagValue, string Command) + { + string SendMessage; + SendMessage = "MES|" + Command + "|" + OpName + "|" + tagValue; + SendMessageFun.AsyncSendMessage(SendMessage); + + } + private void InitAlarm(string Opname) + { + FuntionMesRead.Alarm_InitAlarm_Send(Opname, out Hashtable ht); + foreach (DictionaryEntry kv in ht) + { + var TagID = kv.Key.ToString(); + var TagValue = kv.Value.ToString(); + FuntionMesRead.Send_AlarmMsg(TagID, TagValue); + } + + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1058/OpcServer/WorkStart.cs b/MisDataFunction/MesServer.Function/Function1058/OpcServer/WorkStart.cs new file mode 100644 index 0000000..0582e8e --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1058/OpcServer/WorkStart.cs @@ -0,0 +1,55 @@ +using System; +using bizFacade; +using MesServerWork; +//using SystemFramework; + + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 工件到位与离开时,清空MES自身信号 + /// + /// + /// + private void WorkStart(object e) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + + //线首显示订单信息 + + if (tagValue == 1) + { + MIS_BASE.Write_TagTypeID(115, OpName, 0); + MIS_BASE.Write_TagTypeID(95, OpName, 0); + MIS_BASE.Write_TagTypeID(96, OpName, 0); + MIS_BASE.Write_TagTypeID(97, OpName, 0); + MIS_BASE.Write_TagTypeID(98, OpName, ""); + //清空MOBY的产品流水号 + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.WorkStartIn, DateTime.Now.ToString()); + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.WorkStart, tagValue.ToString()); + + } + else + { + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.WorkStartOut, DateTime.Now.ToString()); + MIS_BASE.Write_MesReadOver(OpName, false); + MIS_BASE.Write_ConfirmOkGo(OpName, false); + MIS_BASE.Write_FixAllow(OpName, false); + MIS_BASE.Write_ConfirmOkGo(OpName, false); + //工作完成 + MIS_BASE.Write_MaterialVerifyOver(OpName, false); + } + } + catch(Exception err) + { + ////ApplicationLog.WriteLog(err, "Function08:WorkStart"); + } + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1058/OpcServer/vssver2.scc b/MisDataFunction/MesServer.Function/Function1058/OpcServer/vssver2.scc new file mode 100644 index 0000000..e8dac03 Binary files /dev/null and b/MisDataFunction/MesServer.Function/Function1058/OpcServer/vssver2.scc differ diff --git a/MisDataFunction/MesServer.Function/Function1058/Properties/AssemblyInfo.cs b/MisDataFunction/MesServer.Function/Function1058/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..f3608c0 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1058/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// 有关程序集的常规信息通过以下 +// 特性集控制。更改这些特性值可修改 +// 与程序集关联的信息。 +[assembly: AssemblyTitle("Function08")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("苏州宏软信息技术有限公司")] +[assembly: AssemblyProduct("Function08")] +[assembly: AssemblyCopyright("Copyright © 苏州宏软信息技术有限公司 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// 将 ComVisible 设置为 false 使此程序集中的类型 +// 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型, +// 则将该类型上的 ComVisible 特性设置为 true。 +[assembly: ComVisible(false)] + +// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID +[assembly: Guid("47710f2c-e141-4252-8d13-701bf4c1c027")] + +// 程序集的版本信息由下面四个值组成: +// +// 主版本 +// 次版本 +// 内部版本号 +// 修订号 +// +// 可以指定所有这些值,也可以使用“内部版本号”和“修订号”的默认值, +// 方法是按如下所示使用“*”: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/MisDataFunction/MesServer.Function/Function1058/Properties/vssver2.scc b/MisDataFunction/MesServer.Function/Function1058/Properties/vssver2.scc new file mode 100644 index 0000000..87eebff Binary files /dev/null and b/MisDataFunction/MesServer.Function/Function1058/Properties/vssver2.scc differ diff --git a/MisDataFunction/MesServer.Function/Function1058/app.config b/MisDataFunction/MesServer.Function/Function1058/app.config new file mode 100644 index 0000000..b4c4daf --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1058/app.config @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + + + diff --git a/MisDataFunction/MesServer.Function/Function1058/mssccprj.scc b/MisDataFunction/MesServer.Function/Function1058/mssccprj.scc new file mode 100644 index 0000000..f184c61 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1058/mssccprj.scc @@ -0,0 +1,5 @@ +SCC = This is a Source Code Control file + +[Function08.csproj] +SCC_Aux_Path = "\\192.168.0.100\vss\MES4.0" +SCC_Project_Name = "$/MisData/MisData/MisData/MesServer.Function/Function08", KRHAAAAA diff --git a/MisDataFunction/MesServer.Function/Function1058/packages.config b/MisDataFunction/MesServer.Function/Function1058/packages.config new file mode 100644 index 0000000..b3e1761 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1058/packages.config @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/MisDataFunction/MesServer.Function/Function1058/vssver2.scc b/MisDataFunction/MesServer.Function/Function1058/vssver2.scc new file mode 100644 index 0000000..93af295 Binary files /dev/null and b/MisDataFunction/MesServer.Function/Function1058/vssver2.scc differ diff --git a/MisDataFunction/MesServer.Function/Function1059/DataAccess/DataAccess.cs b/MisDataFunction/MesServer.Function/Function1059/DataAccess/DataAccess.cs new file mode 100644 index 0000000..a7f91fa --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1059/DataAccess/DataAccess.cs @@ -0,0 +1,16 @@ + + +namespace MesServerFunctions +{ + partial class FunctionMES + { + //针对“MIS.BizFacade.Dll”中没有的存储过程,在此类中新建 + //新建原则:所有的函数用private,只允许在内部使用 + //针对单个工艺特殊,需要新建存储过程,但是存储过程不能被加入到“MIS.BizFacade.Dll”中 + + private void aa() + { + + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1059/DataAccess/vssver2.scc b/MisDataFunction/MesServer.Function/Function1059/DataAccess/vssver2.scc new file mode 100644 index 0000000..1083b3a Binary files /dev/null and b/MisDataFunction/MesServer.Function/Function1059/DataAccess/vssver2.scc differ diff --git a/MisDataFunction/MesServer.Function/Function1059/Db.cs b/MisDataFunction/MesServer.Function/Function1059/Db.cs new file mode 100644 index 0000000..64286ed --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1059/Db.cs @@ -0,0 +1,74 @@ +using System; +using System.Collections.Generic; +using System.Data.SqlClient; +using System.Data; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using DataLinkMesWork; + +namespace MesServerFunctions +{ + public class Db + { + /// + /// 北汽福田变速器序列号总线上线_获得机型信息 + /// + /// + /// + /// + /// + /// 0 不重号;1 重号;2:失败 + /// + public static bool GetEngineType(string partSn, out int EngineTypeID, out string EngineType, out string EngineID,out int IsRepeatedNumber) + { + DataTable dt = new DataTable(); + EngineTypeID = 0; + EngineType = ""; + EngineID = ""; + IsRepeatedNumber = 2; + string produceName = "北汽福田变速器序列号总线上线_获得机型信息"; + SqlParameter[] thisParms = new SqlParameter[1]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@变速器序列号", partSn); + + thisParms[2].Direction = ParameterDirection.Output; + if (DataAccess.ExecuteStoredProcedure(produceName, ref thisParms,out dt)) + { + if(dt.Rows.Count > 0) + { + IsRepeatedNumber = Convert.ToInt32( dt.Rows[0]["IsRepeatedNumber"]); + EngineTypeID = Convert.ToInt32(dt.Rows[0]["EngineTypeID"]); + EngineType = dt.Rows[0]["EngineType"].ToString(); + EngineID = partSn; + return true; + } + } + return false; + } + /// + /// 北汽福田变速器序列号总线上线_增加 + /// + /// + /// + /// + /// + /// + public static bool UpLoadOpNameInsert(string partSn, int EngineTypeID, string EngineType, string OpName) + { + + string produceName = "北汽福田变速器序列号总线上线_增加"; + SqlParameter[] thisParms = new SqlParameter[4]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@变速器序列号", partSn); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@基本型号代码", EngineTypeID); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@基本型号", EngineType); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@工位号", OpName); + return DataAccess.ExecuteStoredProcedure(produceName, ref thisParms); + } + + // ALTER PROCEDURE[dbo].[北汽福田变速器序列号总线上线_增加] + // @变速器序列号 nvarchar(50)='1333 050 062 0001*146012023*12345678',--'1333 050 062 0001' + //@基本型号代码 int=1, + //@基本型号 nvarchar(50)='1333 050 062 0001', + //@工位号 nvarchar(50) = 'J05PA010' + } +} diff --git a/MisDataFunction/MesServer.Function/Function1059/Function1059.csproj b/MisDataFunction/MesServer.Function/Function1059/Function1059.csproj new file mode 100644 index 0000000..e6c65d2 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1059/Function1059.csproj @@ -0,0 +1,113 @@ + + + + + Debug + AnyCPU + {3DCC04C0-32BF-4573-91F6-C4E342A0CF2A} + Library + Properties + Function1059 + Function1059 + v4.8 + 512 + true + + + + true + full + false + ..\..\..\dll_fun\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + False + ..\..\..\MisData_3.0_2022.08.23.1622.LLX\DLL\Newtonsoft.Json.dll + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + {f55da1a0-a982-4479-8c47-0d9a5aaf3e18} + 00MesWorkMqtt + + + {0d1af432-439a-4920-8692-43ae139f5530} + 01_01DoWhatPlc + + + {3e6d1dd5-01c9-435f-9941-61f906ce35bb} + 02_02WebApiCallPLC + + + {f434e066-4c59-47c8-aa82-6f48cc84501a} + 04-DataBaseAccess + + + {f0a0c525-03fd-428a-9b17-7f54aa0e4475} + 07BusinessFacade + + + {d98be764-adeb-488d-9714-61e308aa8201} + 08-WebFun_base + + + {90e76fb4-646d-45e2-95db-0b8ab4e465d6} + 09-MesDataFunction + + + {e4eb6420-906d-4672-947a-ca33ddcdadfc} + 12SendMessageToWeb + + + {55b510c1-59e9-4bfd-ae84-d76d46f6e365} + 02-13.3MIS_FuntionSaveData + + + + \ No newline at end of file diff --git a/MisDataFunction/MesServer.Function/Function1059/MesServerFunction/Function1059.cs b/MisDataFunction/MesServer.Function/Function1059/MesServerFunction/Function1059.cs new file mode 100644 index 0000000..67c16df --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1059/MesServerFunction/Function1059.cs @@ -0,0 +1,270 @@ + +using MesServerWork; +using System; +using System.Collections.Generic; +using System.Threading; + +namespace MesServerFunctions +{ + public partial class FunctionMES + { + object lockFunWork; + //public void FunWork(DoWhatPlc.CustomeEvetnArgs e) + public void FunWork(string recData) + { + + + lockFunWork = new object(); + lock (lockFunWork) + { + List dataArray = DoWhatPlc.MessageText.GetCmdStringList(recData); + //string[] dataArray = recData.Split('|'); + //if (dataArray.Count != 4) + //return; + //消息来源 + string m_Source = dataArray[0].ToString(); + //消息类型 Barcode + string m_Command = dataArray[1].ToString(); + //工位号 + string m_OpName = dataArray[2].ToString(); + //消息参数 + string m_Value = dataArray[3].ToString(); + + DoWhatPlc.CustomeEvetnArgs e =new DoWhatPlc.CustomeEvetnArgs();// = Newtonsoft.Json.JsonConvert.DeserializeObject(m_Value); + string tagValue; + + switch (m_Source) + { + case "BarCode": + e.OpName = m_OpName; + e.TagValue = m_Value; + fun_Barcode(e); + + break; + case "WEB": + e.OpName = m_OpName; + e.TagValue = m_Command + "|" + m_Value; + fun_WebSubmit(e); + break; + case "PLC": + e = Newtonsoft.Json.JsonConvert.DeserializeObject(m_Value); + switch (e.TagValue.ToString().ToLower()) + { + case "false": + tagValue = "0"; + break; + case "true": + tagValue = "1"; + break; + default: + tagValue = e.TagValue.ToString(); + break; + } + e.TagValue = tagValue; + switch (e.TagTypeCodeID.ToString()) + { + //PLC 工件到位 + case "2": + fun_WorkStart(e); + break; + //PLC 允许保存质量数据 + case "19": + fun_MesRead(e); + break; + //MES 保存数据完成 + case "20": + fun_MesReadOver(e); + break; + //PLC 传递机型 + case "43": + PartLoad(e); + break; + //PLC 传递机型 + case "44": + fun_EngineTypeGetOverPLC(e); + break; + //MES 合格放行 + case "51": + fun_ConfirmOkGo(e); + break; + //MES 不合格放行 + case "8": + fun_FalseGo(e); + break; + //MES保存实时质量数据 + case "65": + fun_MesSaveNowData(e); + break; + //MES 系统健康心跳 + case "14": + fun_HeartBeatMIS(e); + break; + case "63": + string S_plcStatus;//DBX501.5 PLC直通,1 强制放行 0 正常循环 + MIS_BASE.Read_TagTypeID(63, m_OpName, out S_plcStatus); + if (S_plcStatus.ToLower() != "true" || S_plcStatus.ToLower() == "1") + { + SendMessageFun.SendInfomation("PlcStatus", "0", m_OpName); + } + else + { + SendMessageFun.SendInfomation("PlcStatus", "1", m_OpName); + } + break; + } + break; + } + } + } + //public void FunWork(DoWhatPlc.CustomeEvetnArgs e) + //{ + // //lock1 = new object(); + // //lock (lock1) + // { + // switch (e.TagTypeCodeID.ToString()) + // { + // //PLC 工件到位 + // case "2": + // fun_WorkStart(e); + // break; + // //PLC 允许保存质量数据 + // case "19": + // fun_MesRead(e); + // break; + // //MES 保存数据完成 + // case "20": + // fun_MesReadOver(e); + // break; + // //PLC 传递机型 + // case "44": + // fun_EngineTypeGetOverPLC(e); + // break; + // //MES 合格放行 + // case "51": + // fun_ConfirmOkGo(e); + // break; + // //MES 不合格放行 + // case "8": + // fun_FalseGo(e); + // break; + // //MES 扫描条码 + // case "Barcode": + // fun_Barcode(e); + // break; + // //WEB 处理页面传递过来的数据 + // case "WebSubmit": + // fun_WebSubmit(e); + // break; + // } + // } + + //} + //1.工件到位后,PLC给MES传递机型(DBX0.4)(44), + //2.MES判断是否扫描完成 + //3.若扫描完成,则MES给出合格放行(DBX2.5)(51) + /// + /// 扫描条码 + /// + /// + /// + public void fun_Barcode(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(Barcode, e); + } + + /// + /// 系统健康心跳监测 + /// + /// + /// + public void fun_HeartBeatMIS(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(HeartBeat, e); + } + /// + /// 传递机型 + /// + /// + /// + public void fun_EngineTypeGetOverPLC(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(EngineTypeGetOver_PLC, e); + } + + /// + /// 合格放行 + /// + /// + /// + public void fun_ConfirmOkGo(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(ConfirmOkGo, e); + } + + /// + /// 不合格放行 + /// + /// + /// + public void fun_FalseGo(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(FalseGO, e); + } + + + /// + /// 保存完成 20 + /// + /// + /// + public void fun_MesReadOver(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(MesReadOver, e); + } + + /// + /// 保存完成 19 + /// + /// + /// + public void fun_MesRead(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(MesRead, e); + } + + /// + /// 工件到位离开(清空所有的MES信号) + /// + /// + /// + public void fun_WorkStart(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(WorkStart, e); + } + + /// + /// 处理WEB页面发送过来的请求(m_Command + "|" + m_Value;) + /// + /// + /// + public void fun_WebSubmit(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(WebSubmit, e); + } + + public int fun_SubLineLoadPartCountMatch() + { + return SubLineLoadPartCountMatch; + } + + /// + /// MES实时保存质量数据 + /// + /// + /// + public void fun_MesSaveNowData(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(MesSaveNowData, e); + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1059/MesServerFunction/vssver2.scc b/MisDataFunction/MesServer.Function/Function1059/MesServerFunction/vssver2.scc new file mode 100644 index 0000000..775bb6c Binary files /dev/null and b/MisDataFunction/MesServer.Function/Function1059/MesServerFunction/vssver2.scc differ diff --git a/MisDataFunction/MesServer.Function/Function1059/Methods/EngineGetOverBaseWork.cs b/MisDataFunction/MesServer.Function/Function1059/Methods/EngineGetOverBaseWork.cs new file mode 100644 index 0000000..895f4c1 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1059/Methods/EngineGetOverBaseWork.cs @@ -0,0 +1,279 @@ +using System; +using System.Data; +using bizFacade; +using MesServerWork; +//using SystemFramework; + + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 分线上总线的数量 + /// + public static int SubLineLoadPartCount = 2; + /// + /// 分线上总线已经匹配的数量 + /// + public static int SubLineLoadPartCountMatch = 0; + /// + /// 正常逻辑工作 + /// + /// + /// + /// + /// + /// + private void EngineTypeGetOver_PLC_Work(string OpName, int EngineTypeID, string EngineType, string EngineID, int PartPallet_Code,string OrderForm) + { + int IsAllowWork; + int RepairPartStatusPLC = 0; + int MES_QualityMask = 1; + //string OrderForm = "";//订单号 + //DataTable dt; + + if (EngineTypeID <= 0 || EngineID.Length == 0 || EngineType.Length == 0 || OrderForm.Length == 0) + { + SendMessageFun.AsyncSendMessage_Notice(OpName, "PLC传递机型为空"); + return; + } + //电子看板_装配零件_临时表_增加_北汽 + //第二步,将零件信息转移到零件_临时表中 + // BaseDataSystemMES.MesServer_Process_EngineTypeOverBQ(OpName); + + //通知web显示 + //SendMessageFun.SendMessage("123", "111", OpName); + + //第四步,获取是否允许工作 + BaseDataSystemMES.MesServer_Judge_IsCanWork(OpName, out IsAllowWork); + + // 暂时先定义为扫描完成才能进行压装工作,因为考虑到工作完成后,操作工未必会去扫描物料的情况 + + if (IsAllowWork == 1) + { + //通知PLC允许工作,允许工作在保存完成时清空 + MIS_BASE.Write_FixAllow(OpName, true); + } + else + { + SendMessageFun.AsyncSendMessage_Notice(OpName, "请扫描物料!"); + } + + + } + + + /// + /// 保存MOBY信息 + /// + /// + /// + /// + /// + private void SaveMobyMessage(string OpName, int engineTypeID, string engineType, string engineID, string orderForm) + { + + if (MIS_BASE.hashtable_EngineGetOver_EngineTypeID == null) + { + MIS_BASE.InitHashtable_MesServerCode(); + } + if (MIS_BASE.hashtable_EngineGetOver_EngineTypeID.ContainsKey(OpName)) + { + MIS_BASE.hashtable_EngineGetOver_EngineTypeID[OpName] = engineTypeID; + } + if (MIS_BASE.hashtable_EngineGetOver_EngineType.ContainsKey(OpName)) + { + MIS_BASE.hashtable_EngineGetOver_EngineType[OpName] = engineType; + } + if (MIS_BASE.hashtable_EngineGetOver_EngineID.ContainsKey(OpName)) + { + MIS_BASE.hashtable_EngineGetOver_EngineID[OpName] = engineID; + } + if (MIS_BASE.hashtable_EngineGetOver_OrderForm.ContainsKey(OpName)) + { + MIS_BASE.hashtable_EngineGetOver_OrderForm[OpName] = orderForm; + } + } + + /// + /// 返修件需要工作 + /// + /// 工位号 + private void IsNeedRepaire_OK(string OpName) + { + + int isRepair; + int engineTypeID; + + string engineType = ""; + string engineID = ""; + string palletCode = ""; + string orderForm = ""; + string repairCode = ""; + //从监控系统中查询出本工位信息 + BaseDataSystemMES.OpName_MIS_Moby_Select(OpName, + out orderForm, out engineTypeID, out engineType, + out engineID, out palletCode, out isRepair, out repairCode); + + EngineTypeGetOver_PLC_Work(OpName, engineTypeID, engineType, engineID, Convert.ToInt32(palletCode),orderForm); + } + /// + /// 正常匹配分线和总线 + /// + /// + /// 总线工件号 + /// 总线工件机型代码 + /// 总线工件机型 + private void Match(string opName, string engineID, int engineTypeID, string engineType, int PartPallet_Code) + { + try + { + bool m_EngineGetOver_PLC_SubLine; + int engineTypeID_SubLine; + int partPallet_Code_SubLine; + int PalletInfo = 1;//总线托盘状态 + + string opName_SubLine = "";//分线工件信息 + string engineID_SubLine; + string engineType_SubLine; + string AlarmStr; + if (MIS_BASE.hashtable_OpNameRepair == null) + { + MIS_BASE.InitHashtable_MesServerCode(); + } + //第一步:获取分线中间交互工位号 + if (MIS_BASE.hashtable_OpNameRepair.ContainsKey(opName)) + { + opName_SubLine = MIS_BASE.hashtable_OpNameRepair[opName].ToString(); + } + if (opName_SubLine == "") + { + return; + } + + //第二步:获取分线传递机型信号 + MIS_BASE.Read_EngineGetOver_PLC(opName_SubLine, out m_EngineGetOver_PLC_SubLine); + if (!m_EngineGetOver_PLC_SubLine) return;//必须工件同时到位才能进行匹配 + + //第三步:判断合格标志 + MIS_BASE.Read_PalletInfo(opName_SubLine, out PalletInfo); + if (PalletInfo == 2) return; //若不合格则返回不进行匹配 + string OrderForm; + //第四步:获取分线的信息,匹配验证 + MIS_BASE.GetEngineTypeFromPLC(opName_SubLine, out engineTypeID_SubLine, out engineType_SubLine, out engineID_SubLine, out partPallet_Code_SubLine,out OrderForm); + //判断分线数据是否合格 + //if (!BaseDataSystemMES.QulityDataVerify(opName, engineID_SubLine, out AlarmStr) && !BaseDataSystemMES.QualityVerifyStatus_Hash_Read(opName)) + //{ + // SendInfomation("LineoutAlert", AlarmStr, opName); + // return; + //} + + if (engineTypeID_SubLine == engineTypeID) + { + BaseDataSystemMES.SubLineLoadPartCountMatch_Select(opName, out SubLineLoadPartCountMatch); + SubLineLoadPartCountMatch = SubLineLoadPartCountMatch + 1; + BaseDataSystemMES.SubLineLoadPartCountMatch_Update(opName, SubLineLoadPartCountMatch); + + + BaseDataSystemMES.MailLineAndSubLineData_Insert(engineID, engineTypeID, engineType, engineID_SubLine);//分线上总线数据转移 + MIS_BASE.Write_Match(opName, true);//匹配结果 + MIS_BASE.Write_MatchingCompleted(opName, true);//匹配完成 + if(SubLineLoadPartCountMatch== SubLineLoadPartCount) + { + MIS_BASE.Write_FixAllow(opName, true); + SubLineLoadPartCountMatch = 0; + BaseDataSystemMES.SubLineLoadPartCountMatch_Update(opName, SubLineLoadPartCountMatch); + + } + + SendMessageFun.SendInfomation("MatchSuccess", "1", opName); + sendmessage(opName, 1, "Match");//匹配结果 + } + else + { + MIS_BASE.Write_Match(opName, false);//匹配结果 + MIS_BASE.Write_MatchingCompleted(opName, true);//匹配完成//68:1、取消返修;2、匹配成功 自己监控发送 MES|MatchingCompleted + + //发送匹配完成和匹配结果信息 + SendMessageFun.AsyncSendMessage_Notice(opName,"匹配失败,工件型号不匹配!"); + SendMessageFun.SendInfomation("MatchSuccess", "0", opName); + sendmessage(opName, 0, "Match");//匹配结果 + } + + } + catch (Exception err) + { + ////ApplicationLog.WriteLog("Match:" + err.ToString()); + + } + } + + + + /// + /// 强制匹配分线和总线 + /// + /// + private void ForceMatch(string opName) + { + try + { + bool m_EngineGetOver_PLC_SubLine; + bool m_EngineGetOver_PLC; + + int engineTypeID_SubLine; + int engineTypeID; + int partPallet_Code_SubLine; + int partPallet_Code; + + string opName_SubLine = "";//分线工件信息 + string engineID_SubLine; + string engineType_SubLine; + string engineID; + string engineType; + if (MIS_BASE.hashtable_OpNameRepair == null) + { + MIS_BASE.InitHashtable_MesServerCode(); + } + //获取分线中间交互工位号 + if (MIS_BASE.hashtable_OpNameRepair.ContainsKey(opName)) + { + opName_SubLine = MIS_BASE.hashtable_OpNameRepair[opName].ToString(); + } + if (opName_SubLine == "") + { + return; + } + + MIS_BASE.Read_EngineGetOver_PLC(opName_SubLine, out m_EngineGetOver_PLC_SubLine);//1:读取分线工件到位的传递机型信号。 + + if (!m_EngineGetOver_PLC_SubLine) return;//必须工件同时到位才能进行匹配 + + MIS_BASE.Read_EngineGetOver_PLC(opName, out m_EngineGetOver_PLC);//2:读取总线工件到位的传递机型信号。 + + if (!m_EngineGetOver_PLC) return;//必须工件同时到位才能进行匹配 + string OrderForm; + MIS_BASE.GetEngineTypeFromPLC(opName_SubLine, out engineTypeID_SubLine, out engineType_SubLine, out engineID_SubLine, out partPallet_Code_SubLine,out OrderForm);//获取分线的信息 + MIS_BASE.GetEngineTypeFromPLC(opName, out engineTypeID, out engineType, out engineID, out partPallet_Code, out OrderForm); + + BaseDataSystemMES.MailLineAndSubLineData_Insert(engineID, engineTypeID, engineType, engineID_SubLine);//分线上总线数据转移 + + MIS_BASE.Write_Match(opName, true);//匹配结果 + MIS_BASE.Write_MatchingCompleted(opName, true);//匹配完成 + + SendMessageFun.SendInfomation("MatchSuccess", "1", opName);//界面显示匹配成功 + + MIS_BASE.Write_FixAllow(opName, true);//允许PLC工作 + + //发送匹配完成和匹配结果信息 + sendmessage(opName, 1, "MatchingComplete");//匹配完成 + sendmessage(opName, 1, "Match");//匹配结果 + } + catch + { + + } + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1059/Methods/SubmitToMisweb.cs b/MisDataFunction/MesServer.Function/Function1059/Methods/SubmitToMisweb.cs new file mode 100644 index 0000000..8d84430 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1059/Methods/SubmitToMisweb.cs @@ -0,0 +1,145 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using bizFacade; +//using SystemFramework; + +namespace MesServerFunctions +{ + + /// + /// 此类用于向WEB发送各种类型消息 + /// + partial class FunctionMES + { + + + // /// + // /// 批量发送WEB消息(Value为BOOL值) + // /// + // /// 消息编号组合 + // /// 消息值组合 + // /// 工位号 + // void Sendmessage(string MessageNumm,string Value, string OpName) + //{ + // for (int i=0;i + // /// 选择发送给WEB的消息 + // /// + // /// 消息类型 + // /// 消息工位 + //void Sendmessage(char Num,string Value, string OpName) + //{ + // string SendMessage; + // switch (Num) + // { + // case '1': + // //1(直接在界面通过选择机型确认工序内容) + // SendMessage = "MES|ProcessList|" + OpName + "|" + Value; + // AsyncSendMessage(SendMessage); + // break; + + // case '2': + // //2显示物料 + // SendMessage = "MES|MaterialList|" + OpName + "|" + Value; + // AsyncSendMessage(SendMessage); + // break; + + // case '3': + + // //3显示操作指导图片 + // SendMessage = "MES|PicShow|" + OpName + "|" + Value; + // AsyncSendMessage(SendMessage); + // break; + // case '4': + // //3显示操作指导图片 + // SendMessage = "MES|OrderFormList|" + OpName + "|" + Value; + // AsyncSendMessage(SendMessage); + // break; + + // case '5': + // SendMessage = "MES|ShowMoby|" + OpName + "|" + Value; + // AsyncSendMessage(SendMessage); + // break; + // case '6': + // SendMessage = "MES|MaterialCheckPosition|" + OpName + "|" +Value; + // AsyncSendMessage(SendMessage); + // break; + // case '7': + // SendMessage = "MES|WorkStart|" + OpName + "|" + Value; + // AsyncSendMessage(SendMessage); + // break; + // case '8': + // SendMessage = "MES|OrderFormList|" + OpName + "|" + Value; + // AsyncSendMessage(SendMessage); + // break; + // case '9': + // SendMessage = "MES|ConfirmOkGo|" + OpName + "|" + Value; + // AsyncSendMessage(SendMessage); + // break; + // case 'a': + // SendMessage = "MES|FixAllow|" + OpName + "|" + Value; + // AsyncSendMessage(SendMessage); + // break; + // case 'b': + // SendMessage = "MES|ShaftPosition|" + OpName + "|" + Value; + // AsyncSendMessage(SendMessage); + // break; + // case 'c': + // SendMessage = "MES|ShowQuality|" + OpName + "|" + Value; + // AsyncSendMessage(SendMessage); + // break; + // } + //} + + /// + /// 向WEB发送信息(value为字符串) + /// + /// 消息种类 + /// 消息内容 + /// 工位号 + //void SendInfomation(string Command, string Value, string OpName) + //{ + + // string SendMessage = "MES|" + Command + "|" + OpName + "|" + Value; + // AsyncSendMessage(SendMessage); + //} + + + ///// + ///// 发送在线产量、在线节拍 + ///// + ///// + ///// + //private void SendActuallyCount(string OpName, int tagValue) + //{ + // //当工件离开时,更新在线产量、在线节拍 + // if (tagValue == 0) + // { + // try + // { + // int opNameCount = 0;//在线产量 + // int opNameCountTime = 0;//在线节拍 + + // BaseDataSystemMES.OpNameCount_New(OpName, out opNameCount, out opNameCountTime); //基本数据_工作日历_班次产量查询_New + + // SendInfomation("ActuallyCount", opNameCount.ToString() + "&" + opNameCountTime.ToString(), OpName); + + // } + // catch (Exception err) + // { + // ////ApplicationLog.WriteLog(err, "Function01:SendActuallyCount"); + // } + // } + //} + + + } +} diff --git a/MisDataFunction/MesServer.Function/Function1059/Methods/UDP.Send.cs b/MisDataFunction/MesServer.Function/Function1059/Methods/UDP.Send.cs new file mode 100644 index 0000000..26acece --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1059/Methods/UDP.Send.cs @@ -0,0 +1,62 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using MesServerWork; +//using BasicData; +using System.Collections; +using bizFacade; +//using SystemFramework; +using System.Data; +using System.Threading; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + ///// + ///// 发送信息到MES通讯服务器或者其他的 + ///// + ///// + //private void AsyncSendMessage(string Message) + //{ + // MIS_BASE.asyncSendMessage(Message); + //} + + /// + /// 发送提示消息 + /// + /// + //private void AsyncSendMessage_Notice(string opname, string notice) + //{ + // //通知Web界面 + // BaseDataSystemMES.Web_Notice_Insert(opname, notice); + // string SendMessage = "MES|Notice|" + opname + "|" + "1"; + // MIS_BASE.asyncSendMessage(SendMessage); + //} + + /// + /// 发送信息到打印机 + /// + /// + private void asyncSendMessageToMark(string Message) + { + string messageSend = (string)Message; + //UDPClientSend.Send_ALL(ApplicationConfig.MES_MarkPortNum, messageSend); + } + + /// + /// 发送信息到LED + /// + /// + private void asyncSendMessageLED(string OpName) + { + + //发送到大屏幕显示 41104 + string strMessage = "MIS|" + OpName + "|" + "0" + "|" + "1"; + //UDPClientSend.Send_ALL(ApplicationConfig.Port_ShowLED_ProductCount, strMessage); + + } + + } +} diff --git a/MisDataFunction/MesServer.Function/Function1059/Methods/vssver2.scc b/MisDataFunction/MesServer.Function/Function1059/Methods/vssver2.scc new file mode 100644 index 0000000..7b1a830 Binary files /dev/null and b/MisDataFunction/MesServer.Function/Function1059/Methods/vssver2.scc differ diff --git a/MisDataFunction/MesServer.Function/Function1059/OpcServer/Barcode.cs b/MisDataFunction/MesServer.Function/Function1059/OpcServer/Barcode.cs new file mode 100644 index 0000000..f99b4a1 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1059/OpcServer/Barcode.cs @@ -0,0 +1,239 @@ +using System; +using System.Threading; +using System.Xml.Linq; +using bizFacade; + +//using SystemFramework; +using MesServerWork; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + object lockBarcode = new object(); + + ///第一步,判断条码类型,根据条码类型,执行对应的存储过程 + ///第二步,条码类型(将扫描的条码保存到对应的表中) + ///第三步,扫描完成之后给出允许工作信号 + /// 处理页面扫描条码 + /// + /// + /// + public void Barcode(object e) + { + lock(lockBarcode) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + //+*************DbName***************** + string DbName = Convert.ToString(msgEvent.OpName); + string barcode = Convert.ToString(msgEvent.TagValue); + + int EngineTypeID;//机型代码 + string EngineType;//机型 + string EngineID;//工件编号 + + string OrderForm; + int Recipe1; + int Recipe2; + + bool IsNotRepeatedNumber = false; + //1:获得申请上线信息后,扫描条码才处理业务 + bool ispartload; + //(115) + int PTO; + //(118)0=不检测;1=24V,2=12V。检测线上线工位扫描总成条码,根据BOM,查出 + int NgearSwitch; + //(119)0=不检测;1=24V,2=12V。检测线上线工位扫描总成条码,根据BOM,查出 + int RgearSwitch; + //(120)0=不检测;1=检测。检测线上线工位扫描总成条码,根据BOM,查出 + int SpeedSensor; + //(121)例如:5S 400。检测线上线工位扫描总成条码,根据BOM,查出 + string PartTypeMid; + //(122) 0=不检测;1=24V,2=12V。检测线上线工位扫描总成条码,根据BOM,查出 + int Tcu_V; + //判断工件是否到位 + MIS_BASE.Read_WorkStart(OpName, out ispartload); + if (!ispartload) + { + SendMessageFun.AsyncSendMessage_Notice(OpName, "请检查设备是否到位(DBX500.1=1)"); + return; + } + //判断设备是否申请上线 + //MIS_BASE.Read_UpdatePalletOK(OpName, out ispartload); + //if (!ispartload) + //{ + // SendMessageFun.AsyncSendMessage_Notice(OpName, "请检查设备是否申请上线(DBX500.3=1)"); + // return; + //} + // 判读条码是变速器序列号条码号还是物料号 小机型*日月年* 流水号(给起始号 + 数量) + // 选小机型 从北汽福田BOM中选 得先维护BOM + // 变速器序列号 '1333 050 062*16012023*30000001' + + //扫描完变速器序列号条码号 true + bool isGetOver_MES = false; + //判断上线工位,MES 是否将工件流水号、机型等信息已经写入到PLC了 + MIS_BASE.Read_EngineTypeGetOver_MES(OpName, out isGetOver_MES); + + //如果工件流水号、机型等信息没有写入PLC,扫描的条码按工件流水号进行验证 + //否则按装配物料进行验证 + if (!isGetOver_MES) + { + + if (barcode.Split('*').Length > 2) + { + //2: 判断是否重号, 从数据库获得机型、机型代码等信息 + string partSn = barcode; + EngineID = barcode; + + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.EngineID_MES, EngineID); + + //Db.GetEngineType( partSn, out EngineTypeID, out EngineType, out EngineID, out IsRepeatedNumber); + //Db.GetEngineType( partSn, out EngineTypeID, out EngineType, out EngineID, out IsRepeatedNumber); + + //IsRepeatedNumber true 不重号;false 重号; + IsNotRepeatedNumber = BaseDataSystemMES.EngineTypeID_IsNotRepeatedNumber(partSn); + if (IsNotRepeatedNumber) + { + BaseDataSystemMES.GetEngineTypeUpLoadOpName(partSn, OpName, out EngineTypeID, out EngineType, out OrderForm, out Recipe1, out Recipe2); + + //MIS_BASE.Write_EngineID_MES(OpName, EngineID); + //MIS_BASE.Write_EngineTypeID_MES(OpName, EngineTypeID); + //MIS_BASE.Write_EngineType_MES(OpName, EngineType); + //MIS_BASE.Write_OrderForm_MES(OpName, OrderForm); + + + BaseDataSystemMES.UpLoadPTO(partSn, out PTO, out NgearSwitch, out RgearSwitch, out SpeedSensor, out PartTypeMid, out Tcu_V); + //PTO + MIS_BASE.WritePLC(115, OpName, PTO); + //空挡开关检测 + MIS_BASE.WritePLC(95, OpName, NgearSwitch); + //倒挡开关检测 + MIS_BASE.WritePLC(96, OpName, RgearSwitch); + //里程表检测 + MIS_BASE.WritePLC(97, OpName, SpeedSensor); + //大机型扩展 + MIS_BASE.WritePLC(98, OpName, PartTypeMid); + //TCU + MIS_BASE.WritePLC(122, OpName, PartTypeMid); + string tagStartAdr;//= "DB411.10"; + + // 先查询配方号 根据工位号 去moby表查配方号 + // 根据配方号 去配方表查配方数据 + // 写入配方数据 + BaseDataSystemMES.PLCRcipeCurrent(OpName, out byte[] bytes, out tagStartAdr); + DtWebApi.ReadWritePLC.Write_TagValueByTagTypeID("94", OpName, System.Text.Encoding.ASCII.GetString(bytes)); + ////将产品信息写入PLC + MIS_BASE.Write_EngineTypeID_MES(OpName, EngineTypeID); + MIS_BASE.Write_EngineType_MES(OpName, EngineType); + MIS_BASE.Write_EngineID_MES(OpName, EngineID); + MIS_BASE.Write_OrderForm_MES(OpName, OrderForm); + + //写入到数据库的[北汽福田工位状态监控MOBY]表中 + //BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.EngineTypeID_MES, EngineTypeID.ToString()); + //BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.EngineType_MES, EngineType); + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.EngineID_MES, EngineID); + //BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.OrderForm_MES, OrderForm); + + + // 工位号],[订单号],[产品型号代码],[变速器序列号],[发动机型号],[机型基本代码],[变速器总成号] ,[托盘号] + // [产品型号代码_MES],[变速器序列号_MES],[发动机型号_MES] + // [机床上电],[循环开始],[机床故障],[上料无件],[下料堵塞],[工件到位] + // [传递机型],[申请上件],[允许保存],[保存完成],[合格标志],[前序合格] + // [工号],[班次],[是否返修件],[合格放行],[不合格放行],[扫描条码] + + //BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, "产品型号代码_MES", EngineTypeID.ToString()); + //BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, "发动机型号_MES", EngineType); + + MIS_BASE.Write_EngineTypeGetOver_MES(OpName, true); + + //Thread.Sleep(5000); + //MIS_BASE.Write_EngineTypeGetOver_MES(OpName, false); + + //等待PLC将数据写入RFID;写入PLC的DB块,通知MES验证RFID机型数据是否正确传递 + + //通知web显示 + SendMessage.ShowMoby(OpName); + //SendMessageFun.SendMessage("1235", "1111", OpName); + + SendMessageFun.AsyncSendMessage_Notice(OpName, "扫码完成!"); + } + else + { + SendMessageFun.AsyncSendMessage_Notice(OpName, "变速器序列号 重号,请确认!"); + } + } + else + { + SendMessageFun.AsyncSendMessage_Notice(OpName, "变速器序列号格式不正确,请确认!"); + + } + } + else//验证物料 + { + //物料号 + { + //读取PLC的传递机型信号 + bool tagValue; + MIS_BASE.Read_EngineGetOver_PLC(OpName, out tagValue); + if (tagValue) + { + //验证物料 + BaseDataSystemMES.PartMaterial_DM_Update(OpName, barcode, out bool IsSuccess); + if (!IsSuccess)//???? + { + SendMessageFun.AsyncSendMessage_Notice(OpName, "条码无效,请确认"); + return; + } + else + { + SendMessageFun.SendInfomation("MaterialList", "1", OpName);//通知界面更新零件信息 + } + //判断物料是否验证完成 + BaseDataSystemMES.MesServer_Judge_IsCanWork(OpName, out int IsAllowWork); + + + if (IsSuccess) + { + if (IsAllowWork == 1) + { + //移到允许保存信号中 + //BaseDataSystemMES.Material_Insert(OpName, 1); + + ////更新订单完工数量及物料 + SendMessageFun.SendMessage("24", "11", OpName); + + //物料验证完成,通知PLC允许工作,允许工作在保存完成时清空 + MIS_BASE.Write_FixAllow(OpName, true); + } + else + { + SendMessageFun.AsyncSendMessage_Notice(OpName, "请扫描物料!"); + } + } + else + { + SendMessageFun.AsyncSendMessage_Notice(OpName, "PLC未传递机型"); + } + } + else + { + SendMessage.AsyncSendMessage_Notice(OpName, "产品上线后,PLC获得变速器序列号后,再验证物料!"); + } + + } + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function08:Barcode"); + } + } + + } + + + } +} diff --git a/MisDataFunction/MesServer.Function/Function1059/OpcServer/ConfirmOkGo.cs b/MisDataFunction/MesServer.Function/Function1059/OpcServer/ConfirmOkGo.cs new file mode 100644 index 0000000..a978c1f --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1059/OpcServer/ConfirmOkGo.cs @@ -0,0 +1,35 @@ +using System; +//using SystemFramework; +using MesServerWork; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 合格放行 + /// + /// + /// + private void ConfirmOkGo(object e) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + + if (tagValue == 1) + { + MIS_BASE.Write_MaterialVerifyOver(OpName, true);//工作完成 + SendMessageFun.SendInfomation("OrderFormList","1", OpName); + + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function08:ConfirmOkGo"); + } + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1059/OpcServer/EngineGetOver.cs b/MisDataFunction/MesServer.Function/Function1059/OpcServer/EngineGetOver.cs new file mode 100644 index 0000000..5cf02f9 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1059/OpcServer/EngineGetOver.cs @@ -0,0 +1,108 @@ +using System; +using System.Data; +using bizFacade; +using MesServerWork; +//using SystemFramework; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + object lockBarcodeEngineTypeGetOver = new object(); + + + /// + /// PLC传递机型处理 + /// + /// + /// + private void EngineTypeGetOver_PLC(object e) + { + lock(lockBarcodeEngineTypeGetOver) + { + + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + //判断PLC机型与MES机型是否一致 + if (tagValue == 1) + { + bool MesRead = false; + + int EngineTypeID;//机型代码 + int PartPallet_Code;//托盘编号 + + string EngineType;//机型 + string EngineID;//工件编号 + + int EngineTypeID_MES;//机型代码 + string EngineType_MES;//机型 + string EngineID_MES;//工件编号 + + //上线工位清MES传递机型信号 + MIS_BASE.Write_EngineTypeGetOver_MES(OpName, false); + + MIS_BASE.Read_QualityData_Read_CF(OpName, out MesRead); + //第一步,判断允许保存和保存完成信号是否全部被清空,若未清空,则通知复位MES&PLC + if (MesRead) + { + //未能清空信号,请求复位 + SendMessageFun.SendInfomation("AskReset", "1", OpName); + return; + } + string OrderForm; + string OrderForm_MES; + MIS_BASE.GetEngineTypeFromPLC(OpName, out EngineTypeID, out EngineType, out EngineID, out PartPallet_Code, out OrderForm); + MIS_BASE.GetEngineTypeFromPLC_MES(OpName, out EngineTypeID_MES, out EngineType_MES, out EngineID_MES, out OrderForm_MES); + + // 测试的时候用的 plc读取订单号有问题 + // OrderForm = BaseDataSystemMES.GetOrderDataBySn(EngineID); + + if (EngineTypeID_MES == EngineTypeID & EngineID_MES == EngineID & EngineType_MES == EngineType & OrderForm_MES == OrderForm) + { + // + DataTable dt = BaseDataSystemMES.EngineTypeChange(OpName, EngineType); + // 提示机型发生变化 + if (dt.Rows.Count > 0) + { + string mesValue = Newtonsoft.Json.JsonConvert.SerializeObject(dt);//(recData); + string message = "MES|MaterialList_Dif_Resources|" + OpName + "|" + mesValue; + SendMessage.AsyncSendMessage(message); + } + + + //写入到数据库的[北汽福田工位状态监控MOBY]表中 + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.EngineTypeID, EngineTypeID.ToString()); + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.EngineType, EngineType); + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.EngineID, EngineID); + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.OrderForm, OrderForm); + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.PartPallet_Code, PartPallet_Code.ToString()); + + //显示当前订单信息 + SendMessage.ShowMoby(OpName); + + + EngineTypeGetOver_PLC_Work(OpName, EngineTypeID, EngineType, EngineID, PartPallet_Code, OrderForm); + return; + } + else + { + SendMessage.AsyncSendMessage_Notice(OpName, "码块RFID机型与MES机型不匹配!"); + } + + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function08:EngineTypeGetOver_PLC"); + } + } + + } + + + + } +} diff --git a/MisDataFunction/MesServer.Function/Function1059/OpcServer/FalseGO.cs b/MisDataFunction/MesServer.Function/Function1059/OpcServer/FalseGO.cs new file mode 100644 index 0000000..54c73c7 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1059/OpcServer/FalseGO.cs @@ -0,0 +1,37 @@ +using System; +using MesServerWork; +//using SystemFramework; + + +namespace MesServerFunctions +{ + partial class FunctionMES + { + + /// + /// 返修放行 + /// + /// + /// + private void FalseGO(object e) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + + if (tagValue == 1) + { + MIS_BASE.Write_MaterialVerifyOver(OpName, true);//工作完成 + SendMessageFun.SendInfomation("OrderFormList", "1", OpName); + + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function08:FalseGO"); + } + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1059/OpcServer/HeartBeat.cs b/MisDataFunction/MesServer.Function/Function1059/OpcServer/HeartBeat.cs new file mode 100644 index 0000000..93affd3 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1059/OpcServer/HeartBeat.cs @@ -0,0 +1,35 @@ +using bizFacade; +using MesServerWork; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// MES与PLC心跳监听 + /// + /// + /// + private void HeartBeat(object e) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + + //返写在MES心跳中 + MIS_BASE.WritePLC(15, OpName, tagValue); + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:FalseGO"); + } + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1059/OpcServer/MesRead.cs b/MisDataFunction/MesServer.Function/Function1059/OpcServer/MesRead.cs new file mode 100644 index 0000000..9bc056d --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1059/OpcServer/MesRead.cs @@ -0,0 +1,77 @@ +using System; +using bizFacade; +//using SystemFramework; +using MesServerWork; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + object lockMesRead = new object (); + /// + /// 保存完成(针对半自动和手动压装工位) + /// + /// + /// + private void MesRead(object e) + { + lock(lockMesRead) + { + try + { + int EngineTypeID; + string EngineType; + string EngineID; + int PartPallet_Code; + string OrderForm; + + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + + if (tagValue == 1) + { + MIS_BASE.GetEngineTypeFromPLC(OpName, out EngineTypeID, out EngineType, out EngineID, out PartPallet_Code, out OrderForm); + //保存数据到线首表 先保存到 北汽福田变速器序列号总线上线 用于之前判断是否重号 + if (Db.UpLoadOpNameInsert(EngineID, EngineTypeID, EngineType, OpName)) + { + // 保存质量数据 + int qualityMask = MisDataSaveDateMesRead.Funtion.MesRead(OpName, tagValue.ToString(), msgEvent.TagID.ToString()); + // 推送质量数据到MES的页面 + MIS_BASE.SendInfomation("ShowTimelyQuality", "1&" + qualityMask.ToString(), OpName); + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.WorkStartOut, DateTime.Now.ToString()); + // 保存物料数据 + BaseDataSystemMES.Material_Insert(OpName, tagValue); + // 测量数据发动机在线状态 + BaseDataSystemMES.WorkStartInsert(OpName, qualityMask); + SendMessage.SendActuallyCount(OpName, tagValue);//统计在线产量,在线节拍 + + //通知设备,MES的质量数据(和物料数据)保存完成 + MIS_BASE.Write_MesReadOver(OpName, true); + // MES工作完成 + MIS_BASE.Write_MaterialVerifyOver(OpName, true); + } + else + { + SendMessage.AsyncSendMessage_Notice(OpName, "保存上线数据失败!"); + } + } + else + { + MIS_BASE.Write_MesReadOver(OpName, false); + } + + } + + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function08:MesReadOver"); + } + + } + + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1059/OpcServer/MesReadOver.cs b/MisDataFunction/MesServer.Function/Function1059/OpcServer/MesReadOver.cs new file mode 100644 index 0000000..9b637f2 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1059/OpcServer/MesReadOver.cs @@ -0,0 +1,37 @@ +using System; +using bizFacade; +//using SystemFramework; +using MesServerWork; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 保存完成(针对半自动和手动压装工位) + /// + /// + /// + private void MesReadOver(object e) + { + try + { + //DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + //string OpName = Convert.ToString(msgEvent.OpName); + //int tagValue = Convert.ToInt32(msgEvent.TagValue); + + //if (tagValue == 1) + //{ + + // BaseDataSystemMES.Material_Insert(OpName, tagValue); + + // MIS_BASE.Write_ConfirmOkGo(OpName, true); + //} + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function08:MesReadOver"); + } + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1059/OpcServer/MesSaveNowData.cs b/MisDataFunction/MesServer.Function/Function1059/OpcServer/MesSaveNowData.cs new file mode 100644 index 0000000..be4c8ce --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1059/OpcServer/MesSaveNowData.cs @@ -0,0 +1,35 @@ +using bizFacade; +using MesServerWork; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// MES保存实时质量数据 + /// + /// + /// + private void MesSaveNowData(object e) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + + // 保存质量数据 + MisDataSaveDateMesRead.Funtion.MesRead(OpName, tagValue.ToString(), msgEvent.TagID.ToString(),true); + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:FalseGO"); + } + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1059/OpcServer/PartLoad.cs b/MisDataFunction/MesServer.Function/Function1059/OpcServer/PartLoad.cs new file mode 100644 index 0000000..e221f64 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1059/OpcServer/PartLoad.cs @@ -0,0 +1,39 @@ +using System; +using bizFacade; +//using SystemFramework; +using MesServerWork; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 申请上线(针对上线工位) + /// + /// + /// + private void PartLoad(object e) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + + if (tagValue == 1) + { + SendMessageFun.AsyncSendMessage_Notice(OpName, "请扫描总成码"); + } + else + { + //上线工位清MES传递机型信号 + MIS_BASE.Write_EngineTypeGetOver_MES(OpName, false); + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function08:MesReadOver"); + } + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1059/OpcServer/WebSubmit.cs b/MisDataFunction/MesServer.Function/Function1059/OpcServer/WebSubmit.cs new file mode 100644 index 0000000..0272c32 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1059/OpcServer/WebSubmit.cs @@ -0,0 +1,343 @@ +using System; +using MesServerWork; +using bizFacade; +using System.Threading; +using MisDataSaveDate; +using System.Collections; +//using SystemFramework; + + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 处理WEB页面发送过来的请求(m_Command + "|" + m_Value;) + /// + /// + /// + private void WebSubmit(object e) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + string Content = Convert.ToString(msgEvent.TagValue); + + string opName_SubLine = ""; + string engineID = "";//工件信息 + string[] dataArray = Content.Split('|'); + + if (dataArray.Length != 2) + return; + + + string m_Command = dataArray[0].ToString();//消息类型 + string m_Value = dataArray[1].ToString();//消息参数 + string[] m_Value_array = m_Value.Split('&');//消息参数数量 + int m_Value_length = m_Value_array.Length; //消息参数长度 + + if (MIS_BASE.hashtable_EngineGetOver_EngineTypeID == null) + { + MIS_BASE.InitHashtable_MesServerCode(); + } + if (MIS_BASE.hashtable_EngineGetOver_EngineID.ContainsKey(OpName)) + { + engineID = MIS_BASE.hashtable_EngineGetOver_EngineID[OpName].ToString(); + } + if (MIS_BASE.hashtable_OpNameRepair == null) + { + MIS_BASE.InitHashtable_MesServerCode(); + } + DoWhatPlc.CustomeEvetnArgs _e = new DoWhatPlc.CustomeEvetnArgs(); + _e.OpName = OpName; + _e.TagValue = m_Value; + + //根据请求的命令处理逻辑 + switch (m_Command) + { + case "Barcode": + if (m_Value_length > 1) return; + fun_Barcode(_e); + break; + case "ConfirmOkGo"://合格放行 + //修改托盘状态 + + BaseDataSystemMES.BaseData_tagTable_Engine_IsNG_Delete(OpName, engineID); + MIS_BASE.Write_ConfirmOkGo(OpName, true); + MIS_BASE.Write_FalseGO(OpName, false); + Thread.Sleep(1000); + MIS_BASE.Write_ConfirmOkGo(OpName, false); + break; + case "FalseGO"://返修放行 + //修改托盘状态 + BaseDataSystemMES.BaseData_tagTable_Engine_IsNG_Delete(OpName, engineID); + MIS_BASE.Write_FalseGO(OpName, true); + MIS_BASE.Write_ConfirmOkGo(OpName, false); + Thread.Sleep(1000); + MIS_BASE.Write_FalseGO(OpName, false); + break; + case "NgGO"://不合格放行 + //修改托盘状态 + //保存不合格信息(必须保存不合格放行信息,由于B5A的Moby没有不合格标志位) + BaseDataSystemMES.BaseData_tagTable_Engine_IsNG_Insert(OpName, engineID, "", ""); + MIS_BASE.Write_FalseGO(OpName, true); + MIS_BASE.Write_ConfirmOkGo(OpName, false); + Thread.Sleep(1000); + MIS_BASE.Write_FalseGO(OpName, false); + break; + case "OnLineState"://在线0、离线1、屏蔽2 + try + { + if (m_Value_length > 1) return; + int a = Convert.ToInt32(m_Value); + if (a <= 2) + { + BaseDataSystemMES.IsOnLine_Update(OpName, m_Value.ToString()); + MIS_BASE.Write_OnLineState(OpName, Convert.ToInt32(m_Value)); + + if (a == 2) SendMessage.AsyncSendMessage_Notice(OpName, "屏蔽MES!"); + if (a == 0) SendMessage.AsyncSendMessage_Notice(OpName, "启用MES!"); + } + } + catch + { + + } + break; + case "Reset"://复位,将MES所有的信息都复位了 + SetMoby(OpName);//将MES所有信号清空 + + break; + case "FixAllow"://重新拧紧 + break; + case "IsAutoGetEngineID"://自动手动申请编号(线首) + if (m_Value_length > 1) return; + MIS_BASE.Write_IsAutoGetEngineID(OpName, Convert.ToInt32(m_Value)); + break; + case "PartPalletGoOver"://空托盘放行 + MIS_BASE.Write_RepairUpline_MES(opName_SubLine, true); + //MIS_BASE.Write_PalletInfo(opName_SubLine, 4); + //MIS_BASE.Write_UpdatePalletOK(opName_SubLine, true); + MIS_BASE.Write_MaterialVerifyOver(opName_SubLine, true); + break; + case "SetMoby"://清空托盘(线首) + SetMoby(OpName);//将MES所有信号清空 + break; + case "RepairUplineMES"://返修上线 + MIS_BASE.Write_RepairUpline_MES(OpName, true); + break; + case "CancelRepair"://将返修件置为正常件 + + break; + case "PartPalletCode"://申请写入托盘号 + //MIS_BASE.Write_PartPalletCode_PLC(OpName, 1); + break; + case "WritePartPalletCode"://写入托盘号 + if (m_Value_length > 1) return; + MIS_BASE.Write_PalletCode(OpName, Convert.ToInt32(m_Value)); + break; + case "Normal"://启用正常拧紧工位 + MIS_BASE.Write_Normal(OpName, 1); + MIS_BASE.Write_UnNormal(OpName, 0); + break; + case "UnNormal"://启用备用拧紧工位 + MIS_BASE.Write_Normal(OpName, 0); + MIS_BASE.Write_UnNormal(OpName, 1); + break; + case "ResetDevice"://复位设备 + MIS_BASE.Write_ResetDevice(OpName, true); + System.Threading.Thread.Sleep(1000); + MIS_BASE.Write_ResetDevice(OpName, false); + break; + case "IsNeedRepaire"://返修上线(返修上线点) + if (Convert.ToInt32(m_Value) == 1) + { + //修改托盘状态 + MIS_BASE.Write_PalletInfo(OpName, 3); + //通知修改成功 + MIS_BASE.Write_UpdatePalletOK(OpName, true); + IsNeedRepaire_OK(OpName); + } + else if (Convert.ToInt32(m_Value) == 0) + { + //直接给出工作完成 + MIS_BASE.Write_MaterialVerifyOver(OpName, true); + } + break; + //强制匹配 + case "ForceMatch": + if (Convert.ToInt32(m_Value) == 1) + { + ForceMatch(OpName); + } + break; + case "PalletGO": + + if (Convert.ToInt32(m_Value) == 1) + { + //直接给出工作完成 + MIS_BASE.Write_MaterialVerifyOver(opName_SubLine, true); + } + break; + case "ContinueMatch": + BaseDataSystemMES.QualityVerifyStatus_Hash_Write(OpName, true); + fun_EngineTypeGetOverPLC(_e); + break; + //初始化网页信号 + case "IniSingalToWeb": + InitializeSingalToWeb(OpName); + break; + default: break; + } + } + catch(Exception err) + { + ////ApplicationLog.WriteLog(err, "Function08:WebSubmit"); + } + } + + private void SetMoby(string OpName) + { + try + { + //清空Moby时,需要将MES信号清空 + MIS_BASE.Write_ClearMesMoby(OpName); + + BaseDataSystemMES.MesServer_Process_EngineTypeOver(OpName); + + SendMessageFun.SendMessage("5123", "1111", OpName); + + MIS_BASE.Write_ResetDevice(OpName, true); + System.Threading.Thread.Sleep(1000); + MIS_BASE.Write_ResetDevice(OpName, false); + } + catch + { + + } + } + + + /// + /// 网页重现登录,恢复关闭前的页面状态 + /// + /// 工位号 + private void InitializeSingalToWeb(string Opname) + { + bool S_WorkStart;//工件到位 DBX0.1 + bool S_EngineGetOver;//传递机型 DBX0.4 + bool S_FixAllow;//允许工作 DBX3.1 + bool S_MaterialVerifyOver;//工作完成 DBX2.3 + string S_plcStatus;//DBX501.5 PLC直通,1 强制放行 0 正常循环 + + int IsCompleted = 0; + int S_Match = 0; + int PalletInfo_SubLine = 0;//显示分线托盘状态 + + MIS_BASE.Read_WorkStart(Opname, out S_WorkStart); + + //5 显示订单、机型信息 线首工位用 + SendMessage.ShowMoby_FirstOpName(Opname); + //3显示操作指导图片 PicShow_String_FirstOpName + SendMessage.PicShow_FirstOpName(Opname); + //1(直接在界面通过选择机型确认工序内容) + SendMessage.ProcessList_FirstOpName(Opname); + //界面显示物料信息 + SendMessage.MaterialList_FirstOpName(Opname); + // 新增查询PLC直通状态 网页显示 + MIS_BASE.Read_TagTypeID(63, Opname, out S_plcStatus); + InitAlarm(Opname); + + if (S_plcStatus.ToLower() == "false") + { + SendMessageFun.SendInfomation("PlcStatus", "0", Opname); + } + else + { + SendMessageFun.SendInfomation("PlcStatus", "1", Opname); + } + + if (S_WorkStart == true) + { + SendMessageFun.SendInfomation("WorkStart", Convert.ToString(Convert.ToInt32(S_WorkStart)), Opname); + //sendmessage(Opname, Convert.ToInt32(S_WorkStart), "WorkStart_Subline"); + } + + //sendmessage(Opname, Convert.ToInt32(S_WorkStart), "EngineTypeGetOverMES_Subline"); + + MIS_BASE.Read_EngineGetOver_PLC(Opname, out S_EngineGetOver); + if (S_EngineGetOver == true) + { + SendMessageFun.SendInfomation("EngineTypeGetOverPLC", Convert.ToString(Convert.ToInt32(S_EngineGetOver)), Opname); + //sendmessage(Opname, Convert.ToInt32(S_EngineGetOver), "EngineTypeGetOverMES_Subline"); + } + + MIS_BASE.Read_FixAllow(Opname, out S_FixAllow); + + if (S_FixAllow == true) + { + SendMessageFun.SendInfomation("FixAllow", Convert.ToString(Convert.ToInt32(S_FixAllow)), Opname); + } + + MIS_BASE.Read_MaterialVerifyOver(Opname, out S_MaterialVerifyOver); + + if (S_MaterialVerifyOver == true) + { + SendMessageFun.SendInfomation("MaterialVerifyOver", Convert.ToString(Convert.ToInt32(S_MaterialVerifyOver)), Opname); + } + + //MIS_BASE.Read_MatchingCompleted(Opname, out IsCompleted); //DBX1.3 是否匹配 + //MIS_BASE.Read_Match(Opname, out S_Match); //DBX1.4 匹配结果 + + //if (IsCompleted == 1 && S_Match == 1)//发送匹配完成和匹配结果信息 + //{ + // SendMessageFun.SendInfomation("MatchingCompleted", "1", Opname); + // SendMessageFun.SendInfomation("Match", "1", Opname); + // SendMessageFun.SendInfomation("MatchSuccess", "1", Opname);//界面显示匹配成功 + //} + //else if (IsCompleted == 1 && S_Match == 0) + //{ + // SendMessageFun.SendInfomation("MatchSuccess", "0", Opname);//界面显示匹配失败 + //} + + //if (MIS_BASE.hashtable_OpNameRepair == null) + //{ + // MIS_BASE.InitHashtable_MesServerCode(); + //} + //string Opname_SubLine = ""; + //if (MIS_BASE.hashtable_OpNameRepair.ContainsKey(Opname)) + //{ + // Opname_SubLine = MIS_BASE.hashtable_OpNameRepair[Opname].ToString(); + //} + //if (Opname_SubLine == "") + //{ + // return; + //} + + //MIS_BASE.Read_PalletInfo(Opname, out PalletInfo_SubLine); + //sendmessage(Opname, PalletInfo_SubLine, "SubQualityMask"); + //SendMessageFun.SendInfomation("ShowMobySubLine", Opname_SubLine, Opname);//显示分线机型及流水号 + } + + //分线发送工件到位信号函数 + private void sendmessage(string OpName, int tagValue, string Command) + { + string SendMessage; + SendMessage = "MES|" + Command + "|" + OpName + "|" + tagValue; + SendMessageFun.AsyncSendMessage(SendMessage); + + } + private void InitAlarm(string Opname) + { + FuntionMesRead.Alarm_InitAlarm_Send(Opname, out Hashtable ht); + foreach (DictionaryEntry kv in ht) + { + var TagID = kv.Key.ToString(); + var TagValue = kv.Value.ToString(); + FuntionMesRead.Send_AlarmMsg(TagID, TagValue); + } + + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1059/OpcServer/WorkStart.cs b/MisDataFunction/MesServer.Function/Function1059/OpcServer/WorkStart.cs new file mode 100644 index 0000000..a16c909 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1059/OpcServer/WorkStart.cs @@ -0,0 +1,75 @@ +using System; +using bizFacade; +using MesServerWork; +//using SystemFramework; + + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 工件到位与离开时,清空MES自身信号 + /// + /// + /// + private void WorkStart(object e) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + + //线首显示订单信息 + + if (tagValue == 1) + { + MIS_BASE.Write_TagTypeID(115, OpName, 0); + MIS_BASE.Write_TagTypeID(95, OpName, 0); + MIS_BASE.Write_TagTypeID(96, OpName, 0); + MIS_BASE.Write_TagTypeID(97, OpName, 0); + MIS_BASE.Write_TagTypeID(98, OpName, ""); + //清空MOBY的产品流水号 + + // 北汽福田工位状态监控MOBY_增加 + // 工位号],[订单号],[产品型号代码],[变速器序列号],[发动机型号],[机型基本代码],[变速器总成号] ,[托盘号] + // [产品型号代码_MES],[变速器序列号_MES],[发动机型号_MES] + // [机床上电],[循环开始],[机床故障],[上料无件],[下料堵塞],[工件到位] + // [传递机型],[申请上件],[允许保存],[保存完成],[合格标志],[前序合格] + // [工号],[班次],[是否返修件],[合格放行],[不合格放行],[扫描条码] + //[到达时间],[离开时间],[持续时间] + + //初始化物料临时表 + //第二步,将零件信息转移到零件_临时表中(本地BOM与订单BOM的选择显示关系) + BaseDataSystemMES.MesServer_Process_EngineTypeOver_BQ_FirstOP(OpName); + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.WorkStartIn, DateTime.Now.ToString()); + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.WorkStart, tagValue.ToString()); + + //5 显示订单、机型信息 线首工位用 + SendMessage.ShowMoby_FirstOpName(OpName); + //3显示操作指导图片 PicShow_String_FirstOpName + SendMessage.PicShow_FirstOpName(OpName); + //1(直接在界面通过选择机型确认工序内容) + SendMessage.ProcessList_FirstOpName(OpName); + //界面显示物料信息 + SendMessage.MaterialList_FirstOpName(OpName); + } + else + { + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.WorkStartOut, DateTime.Now.ToString()); + MIS_BASE.Write_MesReadOver(OpName, false); + MIS_BASE.Write_ConfirmOkGo(OpName, false); + MIS_BASE.Write_FixAllow(OpName, false); + MIS_BASE.Write_EngineTypeGetOver_MES(OpName, false); + //工作完成 + MIS_BASE.Write_MaterialVerifyOver(OpName, false); + } + } + catch(Exception err) + { + ////ApplicationLog.WriteLog(err, "Function08:WorkStart"); + } + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1059/OpcServer/vssver2.scc b/MisDataFunction/MesServer.Function/Function1059/OpcServer/vssver2.scc new file mode 100644 index 0000000..e8dac03 Binary files /dev/null and b/MisDataFunction/MesServer.Function/Function1059/OpcServer/vssver2.scc differ diff --git a/MisDataFunction/MesServer.Function/Function1059/Properties/AssemblyInfo.cs b/MisDataFunction/MesServer.Function/Function1059/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..5afe3c2 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1059/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// 有关程序集的一般信息由以下 +// 控制。更改这些特性值可修改 +// 与程序集关联的信息。 +[assembly: AssemblyTitle("Function1059")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("Function1059")] +[assembly: AssemblyCopyright("Copyright © 2023")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// 将 ComVisible 设置为 false 会使此程序集中的类型 +//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型 +//请将此类型的 ComVisible 特性设置为 true。 +[assembly: ComVisible(false)] + +// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID +[assembly: Guid("3dcc04c0-32bf-4573-91f6-c4e342a0cf2a")] + +// 程序集的版本信息由下列四个值组成: +// +// 主版本 +// 次版本 +// 生成号 +// 修订号 +// +//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值 +//通过使用 "*",如下所示: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/MisDataFunction/MesServer.Function/Function1059/app.config b/MisDataFunction/MesServer.Function/Function1059/app.config new file mode 100644 index 0000000..b4c4daf --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1059/app.config @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + + + diff --git a/MisDataFunction/MesServer.Function/Function1059/mssccprj.scc b/MisDataFunction/MesServer.Function/Function1059/mssccprj.scc new file mode 100644 index 0000000..f184c61 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1059/mssccprj.scc @@ -0,0 +1,5 @@ +SCC = This is a Source Code Control file + +[Function08.csproj] +SCC_Aux_Path = "\\192.168.0.100\vss\MES4.0" +SCC_Project_Name = "$/MisData/MisData/MisData/MesServer.Function/Function08", KRHAAAAA diff --git a/MisDataFunction/MesServer.Function/Function1059/packages.config b/MisDataFunction/MesServer.Function/Function1059/packages.config new file mode 100644 index 0000000..b3e1761 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1059/packages.config @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/MisDataFunction/MesServer.Function/Function1060/DataAccess/DataAccess.cs b/MisDataFunction/MesServer.Function/Function1060/DataAccess/DataAccess.cs new file mode 100644 index 0000000..cd36930 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1060/DataAccess/DataAccess.cs @@ -0,0 +1,15 @@ + +namespace MesServerFunctions +{ + partial class Function1053 + { + //针对“MIS.BizFacade.Dll”中没有的存储过程,在此类中新建 + //新建原则:所有的函数用private,只允许在内部使用 + //针对单个工艺特殊,需要新建存储过程,但是存储过程不能被加入到“MIS.BizFacade.Dll”中 + + private void aa() + { + + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1060/DataAccess/vssver2.scc b/MisDataFunction/MesServer.Function/Function1060/DataAccess/vssver2.scc new file mode 100644 index 0000000..d045c26 Binary files /dev/null and b/MisDataFunction/MesServer.Function/Function1060/DataAccess/vssver2.scc differ diff --git a/MisDataFunction/MesServer.Function/Function1060/Db.cs b/MisDataFunction/MesServer.Function/Function1060/Db.cs new file mode 100644 index 0000000..64286ed --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1060/Db.cs @@ -0,0 +1,74 @@ +using System; +using System.Collections.Generic; +using System.Data.SqlClient; +using System.Data; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using DataLinkMesWork; + +namespace MesServerFunctions +{ + public class Db + { + /// + /// 北汽福田变速器序列号总线上线_获得机型信息 + /// + /// + /// + /// + /// + /// 0 不重号;1 重号;2:失败 + /// + public static bool GetEngineType(string partSn, out int EngineTypeID, out string EngineType, out string EngineID,out int IsRepeatedNumber) + { + DataTable dt = new DataTable(); + EngineTypeID = 0; + EngineType = ""; + EngineID = ""; + IsRepeatedNumber = 2; + string produceName = "北汽福田变速器序列号总线上线_获得机型信息"; + SqlParameter[] thisParms = new SqlParameter[1]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@变速器序列号", partSn); + + thisParms[2].Direction = ParameterDirection.Output; + if (DataAccess.ExecuteStoredProcedure(produceName, ref thisParms,out dt)) + { + if(dt.Rows.Count > 0) + { + IsRepeatedNumber = Convert.ToInt32( dt.Rows[0]["IsRepeatedNumber"]); + EngineTypeID = Convert.ToInt32(dt.Rows[0]["EngineTypeID"]); + EngineType = dt.Rows[0]["EngineType"].ToString(); + EngineID = partSn; + return true; + } + } + return false; + } + /// + /// 北汽福田变速器序列号总线上线_增加 + /// + /// + /// + /// + /// + /// + public static bool UpLoadOpNameInsert(string partSn, int EngineTypeID, string EngineType, string OpName) + { + + string produceName = "北汽福田变速器序列号总线上线_增加"; + SqlParameter[] thisParms = new SqlParameter[4]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@变速器序列号", partSn); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@基本型号代码", EngineTypeID); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@基本型号", EngineType); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@工位号", OpName); + return DataAccess.ExecuteStoredProcedure(produceName, ref thisParms); + } + + // ALTER PROCEDURE[dbo].[北汽福田变速器序列号总线上线_增加] + // @变速器序列号 nvarchar(50)='1333 050 062 0001*146012023*12345678',--'1333 050 062 0001' + //@基本型号代码 int=1, + //@基本型号 nvarchar(50)='1333 050 062 0001', + //@工位号 nvarchar(50) = 'J05PA010' + } +} diff --git a/MisDataFunction/MesServer.Function/Function1060/Function1060.csproj b/MisDataFunction/MesServer.Function/Function1060/Function1060.csproj new file mode 100644 index 0000000..2815a07 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1060/Function1060.csproj @@ -0,0 +1,109 @@ + + + + + Debug + AnyCPU + {58215063-87F5-4708-8DDA-031524C70B54} + Library + Properties + Function1060 + Function1060 + v4.8 + 512 + true + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + ..\..\..\MisDataFunDll\MisDataFunDll\bin\Debug\00.1Newtonsoft.Json.dll + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + {f55da1a0-a982-4479-8c47-0d9a5aaf3e18} + 00MesWorkMqtt + + + {0d1af432-439a-4920-8692-43ae139f5530} + 01_01DoWhatPlc + + + {3e6d1dd5-01c9-435f-9941-61f906ce35bb} + 02_02WebApiCallPLC + + + {f434e066-4c59-47c8-aa82-6f48cc84501a} + 04-DataBaseAccess + + + {f0a0c525-03fd-428a-9b17-7f54aa0e4475} + 07BusinessFacade + + + {d98be764-adeb-488d-9714-61e308aa8201} + 08-WebFun_base + + + {90e76fb4-646d-45e2-95db-0b8ab4e465d6} + 09-MesDataFunction + + + {e4eb6420-906d-4672-947a-ca33ddcdadfc} + 12SendMessageToWeb + + + {55b510c1-59e9-4bfd-ae84-d76d46f6e365} + 02-13.3MIS_FuntionSaveData + + + + \ No newline at end of file diff --git a/MisDataFunction/MesServer.Function/Function1060/MesServerFunction/Fun_1060.cs b/MisDataFunction/MesServer.Function/Function1060/MesServerFunction/Fun_1060.cs new file mode 100644 index 0000000..48817f0 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1060/MesServerFunction/Fun_1060.cs @@ -0,0 +1,217 @@ +using MesServerWork; +using System.Collections.Generic; +using System.Threading; + +namespace MesServerFunctions +{ + public partial class FunctionMES + { + object lockFunWork; + //public void FunWork(DoWhatPlc.CustomeEvetnArgs e) + public void FunWork(string recData) + { + + + lockFunWork = new object(); + lock (lockFunWork) + { + List dataArray = DoWhatPlc.MessageText.GetCmdStringList(recData); + //string[] dataArray = recData.Split('|'); + //if (dataArray.Count != 4) + //return; + //消息来源 + string m_Source = dataArray[0].ToString(); + //消息类型 Barcode + string m_Command = dataArray[1].ToString(); + //工位号 + string m_OpName = dataArray[2].ToString(); + //消息参数 + string m_Value = dataArray[3].ToString(); + + DoWhatPlc.CustomeEvetnArgs e = new DoWhatPlc.CustomeEvetnArgs();// = Newtonsoft.Json.JsonConvert.DeserializeObject(m_Value); + string tagValue; + + switch (m_Source) + { + case "BarCode": + e.OpName = m_OpName; + e.TagValue = m_Value; + fun_Barcode(e); + break; + case "WEB": + e.OpName = m_OpName; + e.TagValue = m_Command + "|" + m_Value; + fun_WebSubmit(e); + break; + case "PLC": + e = Newtonsoft.Json.JsonConvert.DeserializeObject(m_Value); + switch (e.TagValue.ToString().ToLower()) + { + case "false": + tagValue = "0"; + break; + case "true": + tagValue = "1"; + break; + default: + tagValue = e.TagValue.ToString(); + break; + } + e.TagValue = tagValue; + switch (e.TagTypeCodeID.ToString()) + { + //PLC 工件到位 + case "2": + fun_WorkStart(e); + break; + //PLC 允许保存质量数据 + case "19": + fun_MesRead(e); + break; + //MES 保存数据完成 + case "20": + fun_MesReadOver(e); + break; + //PLC 传递机型 + case "44": + fun_EngineTypeGetOverPLC(e); + break; + //MES 合格放行 + case "51": + fun_ConfirmOkGo(e); + break; + //MES 不合格放行 + case "8": + fun_FalseGo(e); + break; + //MES保存实时质量数据 + case "65": + fun_MesSaveNowData(e); + break; + //MES 系统健康心跳 + case "14": + fun_HeartBeatMIS(e); + break; + case "63": + string S_plcStatus;//DBX501.5 PLC直通,1 强制放行 0 正常循环 + MIS_BASE.Read_TagTypeID(63, m_OpName, out S_plcStatus); + if (S_plcStatus.ToLower() != "true" || S_plcStatus.ToLower() == "1") + { + SendMessageFun.SendInfomation("PlcStatus", "0", m_OpName); + } + else + { + SendMessageFun.SendInfomation("PlcStatus", "1", m_OpName); + } + break; + } + break; + } + } + } + //1.工件到位后,PLC给MES传递机型(DBX0.4)(44), + //MES判断条码是否全部扫描完成 + //PLC给出允许保存(DBX100.2)(19),MES见到(DBX100.2)(19)为1后给出保存完成(DBX102.2)(20), + //PLC见到保存完成(DBX102.2)(20)为1后,清空允许保存(DBX100.2)(19), + //MES见到允许保存(DBX100.2)(19)为0后,清空保存完成(DBX102.2)(20) + //MES判断总合格标志(INT104)(21)为1后,给出合格放行(DBX2.5)(51) + /// + /// 扫描条码 + /// + /// + /// + public void fun_Barcode(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(Barcode, e); + } + + /// + /// 传递机型 + /// + /// + /// + public void fun_EngineTypeGetOverPLC(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(EngineTypeGetOver_PLC, e); + } + + /// + /// 合格放行 + /// + /// + /// + public void fun_ConfirmOkGo(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(ConfirmOkGo, e); + } + /// + /// 系统健康心跳监测 + /// + /// + /// + public void fun_HeartBeatMIS(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(HeartBeat, e); + } + /// + /// 不合格放行 + /// + /// + /// + public void fun_FalseGo(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(FalseGO, e); + } + + /// + /// 允许保存 + /// + /// + /// + public void fun_MesRead(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(MesRead, e); + } + + /// + /// 保存完成 + /// + /// + /// + public void fun_MesReadOver(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(MesReadOver, e); + } + + /// + /// 工件到位离开(清空所有的MES信号) + /// + /// + /// + public void fun_WorkStart(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(WorkStart, e); + } + + /// + /// 处理WEB页面发送过来的请求(m_Command + "|" + m_Value;) + /// + /// + /// + public void fun_WebSubmit(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(WebSubmit, e); + } + + /// + /// MES实时保存质量数据 + /// + /// + /// + public void fun_MesSaveNowData(DoWhatPlc.CustomeEvetnArgs e) + { + ThreadPool.QueueUserWorkItem(MesSaveNowData, e); + } + + } +} diff --git a/MisDataFunction/MesServer.Function/Function1060/MesServerFunction/vssver2.scc b/MisDataFunction/MesServer.Function/Function1060/MesServerFunction/vssver2.scc new file mode 100644 index 0000000..a246f67 Binary files /dev/null and b/MisDataFunction/MesServer.Function/Function1060/MesServerFunction/vssver2.scc differ diff --git a/MisDataFunction/MesServer.Function/Function1060/Methods/EngineGetOverBaseWork.cs b/MisDataFunction/MesServer.Function/Function1060/Methods/EngineGetOverBaseWork.cs new file mode 100644 index 0000000..a9dd932 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1060/Methods/EngineGetOverBaseWork.cs @@ -0,0 +1,96 @@ +using System; +using System.Data; +using bizFacade; +using MesServerWork; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 正常逻辑工作(传递机型) + /// + /// + /// + /// + /// + /// + private void EngineTypeGetOver_PLC_Work(string OpName, int EngineTypeID, string EngineType, string EngineID, int PartPallet_Code,string OrderForm) + { + int IsAllowWork; + int RepairPartStatusPLC = 0; + int MES_QualityMask = 1; + //string OrderForm = "";//订单号 + //DataTable dt; + + if (EngineTypeID <= 0 || EngineID.Length == 0 || EngineType.Length == 0 || OrderForm.Length == 0) + { + SendMessageFun.AsyncSendMessage_Notice(OpName, "PLC传递机型为空"); + return; + } + //电子看板_装配零件_临时表_增加_北汽 + //第二步,将零件信息转移到零件_临时表中 + BaseDataSystemMES.MesServer_Process_EngineTypeOverBQ(OpName); + + //通知web显示 + SendMessageFun.SendMessage("1235", "1111", OpName); + MIS_BASE.Read_PalletInfo(OpName, out MES_QualityMask);//合格标志 + MIS_BASE.Read_RepairStatus_PLC(OpName, out RepairPartStatusPLC);//返修标志 + SendMessageFun.SendInfomation("QualityMask", Convert.ToString(MES_QualityMask), OpName);//显示合格标志 + SendMessageFun.SendInfomation("RepairPartStatusPLC", Convert.ToString(RepairPartStatusPLC), OpName);//显示返修标志 + + if (MES_QualityMask == 2) + { + //// 工作完成 + //MIS_BASE.Write_MaterialVerifyOver(OpName, true); + //SendMessageFun.SendInfomation("NgGO", "1", OpName);//显示不合格标志 + //return; + } + + + //第三步,用于工件离开后完工数量统计及工件编号追溯 + //BaseDataSystemMES.MaterialPush_EngineIDStatus_Insert(OpName);//更新订单产量 + + //第四步,获取是否允许工作 + BaseDataSystemMES.MesServer_Judge_IsCanWork(OpName, out IsAllowWork); + + //暂时先定义为扫描完成才能进行压装工作,因为考虑到工作完成后,操作工未必会去扫描物料的情况 + if (IsAllowWork == 1) + { + //通知PLC允许工作,允许工作在保存完成时清空 + MIS_BASE.Write_FixAllow(OpName, true); + } + else + { + SendMessageFun.AsyncSendMessage_Notice(OpName, "请扫描物料!"); + } + + } + + + /// + /// 返修件需要工作 + /// + /// 工位号 + private void IsNeedRepaire_OK(string OpName) + { + string orderForm = ""; + int engineTypeID; + string engineType = ""; + string engineID = ""; + string palletCode = ""; + int isRepair; + string repairCode = ""; + //从监控系统中查询出本工位信息 + BaseDataSystemMES.OpName_MIS_Moby_Select(OpName, + out orderForm, out engineTypeID, out engineType, + out engineID, out palletCode, out isRepair, out repairCode); + + EngineTypeGetOver_PLC_Work(OpName, engineTypeID, engineType, engineID, Convert.ToInt32(palletCode),orderForm); + } + + + + + } +} diff --git a/MisDataFunction/MesServer.Function/Function1060/Methods/SubmitToMisweb.cs b/MisDataFunction/MesServer.Function/Function1060/Methods/SubmitToMisweb.cs new file mode 100644 index 0000000..52ce16f --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1060/Methods/SubmitToMisweb.cs @@ -0,0 +1,127 @@ +using System; +using bizFacade; +//using SystemFramework; + +namespace MesServerFunctions +{ + + /// + /// 此类用于向WEB发送各种类型消息 + /// + partial class FunctionMES + { + + /// + /// 批量发送WEB消息(Value为BOOL值) + /// + /// 消息编号组合 + /// 消息值组合 + /// 工位号 + void Sendmessage(string MessageNumm,string Value, string OpName) + { + for (int i=0;i + /// 选择发送给WEB的消息 + /// + /// 消息类型 + /// 消息工位 + string Sendmessage(char Num,string Value, string OpName) + { + string SendMessage; + string result = ""; + switch (Num) + { + case '1': + //1(直接在界面通过选择机型确认工序内容) + SendMessage = "MES|ProcessList|" + OpName + "|" + Value; + result = AsyncSendMessage(SendMessage); + break; + case '2': + //2显示物料 + SendMessage = "MES|MaterialList|" + OpName + "|" + Value; + result = AsyncSendMessage(SendMessage); + break; + case '3': + //3显示操作指导图片 + SendMessage = "MES|PicShow|" + OpName + "|" + Value; + result = AsyncSendMessage(SendMessage); + break; + case '4': + //4订单完工模块刷新完成数量 + SendMessage = "MES|OrderFormList|" + OpName + "|" + Value; + AsyncSendMessage(SendMessage); + break; + case '5': + SendMessage = "MES|ShowMoby|" + OpName + "|" + Value; + result = AsyncSendMessage(SendMessage); + break; + case '6': + SendMessage = "MES|MaterialCheckPosition|" + OpName + "|" +Value; + result = AsyncSendMessage(SendMessage); + break; + case '7': + SendMessage = "MES|WorkStart|" + OpName + "|" + Value; + result = AsyncSendMessage(SendMessage); + break; + case '8'://清除MES生成编号 + + break; + case '9': + SendMessage = "MES|ConfirmOkGo|" + OpName + "|" + Value; + result = AsyncSendMessage(SendMessage); + break; + case 'a': + SendMessage = "MES|FixAllow|" + OpName + "|" + Value; + result = AsyncSendMessage(SendMessage); + break; + } + return result; + } + /// + /// 向WEB发送信息(value为字符串) + /// + /// 消息种类 + /// 消息内容 + /// 工位号 + string SendInfomation(string Command, string Value, string OpName) + { + string SendMessage = "MES|" + Command + "|" + OpName + "|" + Value; + return AsyncSendMessage(SendMessage); + } + + + /// + /// 发送在线产量、在线节拍 + /// + /// + /// + private void SendActuallyCount(string OpName, int tagValue) + { + //当工件离开时,更新在线产量、在线节拍 + if (tagValue == 0) + { + try + { + int opNameCount = 0;//在线产量 + int opNameCountTime = 0;//在线节拍 + //基本数据_工作日历_班次产量查询_New + BaseDataSystemMES.OpNameCount_New(OpName, out opNameCount, out opNameCountTime); + string SendMessage; + SendMessage = "MES|ActuallyCount|" + OpName + "|" + opNameCount.ToString() + "&" + opNameCountTime.ToString(); + AsyncSendMessage(SendMessage); + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:SendActuallyCount"); + } + } + } + + + } +} diff --git a/MisDataFunction/MesServer.Function/Function1060/Methods/UDP.Send.cs b/MisDataFunction/MesServer.Function/Function1060/Methods/UDP.Send.cs new file mode 100644 index 0000000..aed7cc3 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1060/Methods/UDP.Send.cs @@ -0,0 +1,53 @@ +using bizFacade; +//using SystemFramework; +using MesServerWork; +using DataLinkMesWork; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 发送信息到MES通讯服务器或者其他的 + /// + /// + private string AsyncSendMessage(string Message) + { + return MIS_BASE.asyncSendMessage(Message); + } + + /// + /// 发送提示消息 + /// + /// + private void AsyncSendMessage_Notice(string opname, string notice) + { + //通知Web界面 + BaseDataSystemMES.Web_Notice_Insert(opname, notice); + string SendMessage = "MES|Notice|" + opname + "|" + "1"; + MIS_BASE.asyncSendMessage(SendMessage); + } + + /// + /// 发送信息到打印机 + /// + /// + private void asyncSendMessageToMark(string Message) + { + string messageSend = (string)Message; + //UDPClientSend.Send_ALL(ApplicationConfig.MES_MarkPortNum, messageSend); + } + + /// + /// 发送信息到LED + /// + /// + private void asyncSendMessageLED(string OpName) + { + //发送到大屏幕显示 41104 + string strMessage = "MIS|" + OpName + "|" + "0" + "|" + "1"; + //UDPClientSend.Send_ALL(ApplicationConfig.Port_ShowLED_ProductCount, strMessage); + + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1060/Methods/vssver2.scc b/MisDataFunction/MesServer.Function/Function1060/Methods/vssver2.scc new file mode 100644 index 0000000..7782f6f Binary files /dev/null and b/MisDataFunction/MesServer.Function/Function1060/Methods/vssver2.scc differ diff --git a/MisDataFunction/MesServer.Function/Function1060/OpcServer/Barcode.cs b/MisDataFunction/MesServer.Function/Function1060/OpcServer/Barcode.cs new file mode 100644 index 0000000..5d80b2f --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1060/OpcServer/Barcode.cs @@ -0,0 +1,97 @@ +using System; +//using System.Windows.Forms; +using bizFacade; +//using SystemFramework; +using MesServerWork; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + ///1.扫描配送单号,用于接收物料,扫描单号的时候,将接收的物料信息显示在“物料拉动”Tab区域 + ///2.扫描料箱标签/看板卡,用于追溯物料批次信息 + ///3.扫描零件条码,根据零件图号进行防错 + ///第一步,判断条码类型,根据条码类型,执行对应的存储过程 + ///第二步,条码类型(将扫描的条码保存到对应的表中) + ///第三步,扫描完成之后给出允许工作信号 + /// 处理页面扫描条码 + /// + /// + /// + public void Barcode(object e) + { + + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + string barcode = Convert.ToString(msgEvent.TagValue); + string AlarmStr = ""; + + int IsAllowWork; + bool IsSuccess = false; + bool EngineGetOver_PLC_NextWorkStep; + //传递机型是否到位 + MIS_BASE.Read_EngineGetOver_PLC(OpName, out EngineGetOver_PLC_NextWorkStep); + if (!EngineGetOver_PLC_NextWorkStep) + { + SendMessageFun.AsyncSendMessage_Notice(OpName, "PLC未传递机型"); + return; + } + //物料验证 + BaseDataSystemMES.PartMaterial_DM_Update(OpName, barcode, out IsSuccess); + if (!IsSuccess) + { + SendMessageFun.AsyncSendMessage_Notice(OpName, "条码无效,请确认"); + return; + } + else + { + SendMessageFun.SendInfomation("MaterialList", "1", OpName);//通知界面更新零件信息 + } + + + + + //获取是否允许工作 + BaseDataSystemMES.MesServer_Judge_IsCanWork(OpName, out IsAllowWork); + + //此处逻辑有问题 需要考虑到批次扫描 提示PLC未传递机型的情况 + if (IsAllowWork == 1) + { + //BaseDataSystemMES.Material_Insert(OpName, 1); + + //更新订单完工数量及物料 + SendMessageFun.SendMessage("24", "11", OpName); + + //工作完成 + //MIS_BASE.Write_MaterialVerifyOver(OpName, true); + //if (!BaseDataSystemMES.QualityVerifyStatusOutline(OpName, out AlarmStr)) + //{ + // SendInfomation("LineoutAlert", AlarmStr, OpName); + // return; + //} + //通知PLC允许工作,允许工作在保存完成时清空 + MIS_BASE.Write_FixAllow(OpName, true); + } + else + { + SendMessageFun.AsyncSendMessage_Notice(OpName, "请扫描物料!"); + } + + + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:Barcode"); + } + + } + + } + + + } +} diff --git a/MisDataFunction/MesServer.Function/Function1060/OpcServer/ConfirmOkGo.cs b/MisDataFunction/MesServer.Function/Function1060/OpcServer/ConfirmOkGo.cs new file mode 100644 index 0000000..ac8affd --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1060/OpcServer/ConfirmOkGo.cs @@ -0,0 +1,41 @@ +using System; +using bizFacade; +//using SystemFramework; +using MesServerWork; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 合格放行 + /// + /// + /// + private void ConfirmOkGo(object e) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + + if (tagValue == 1) + { + + //BaseDataSystemMES.Material_Insert(OpName, 1); + + ////更新订单完工数量及物料 + //Sendmessage("24", "11", OpName); + + ////工作完成 + //MIS_BASE.Write_MaterialVerifyOver(OpName, true); + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:ConfirmOkGo"); + } + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1060/OpcServer/EngineGetOver.cs b/MisDataFunction/MesServer.Function/Function1060/OpcServer/EngineGetOver.cs new file mode 100644 index 0000000..db74c48 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1060/OpcServer/EngineGetOver.cs @@ -0,0 +1,90 @@ +using System; +using System.Data; +//using System.Windows.Forms; +using System.Xml.Linq; +using bizFacade; +//using SystemFramework; +using MesServerWork; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// PLC传递机型处理 + /// + /// + /// + private void EngineTypeGetOver_PLC(object e) + { + + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + + if (tagValue == 1) + { + int EngineTypeID;//机型代码 + int PartPallet_Code;//托盘编号 + + string EngineType;//机型 + string EngineID;//工件编号 + string OrderForm; + string OrderForm_MES; + + int EngineTypeID_MES;//机型代码 + string EngineType_MES;//机型 + string EngineID_MES;//工件编号 + + MIS_BASE.GetEngineTypeFromPLC(OpName, out EngineTypeID, out EngineType, out EngineID, out PartPallet_Code, out OrderForm); + MIS_BASE.GetEngineTypeFromPLC_MES(OpName, out EngineTypeID_MES, out EngineType_MES, out EngineID_MES, out OrderForm_MES); + + // 测试的时候用的 plc读取订单号有问题 + // OrderForm = BaseDataSystemMES.GetOrderDataBySn(EngineID); + + if (EngineTypeID_MES == EngineTypeID & EngineID_MES == EngineID & EngineType_MES == EngineType) + { + DataTable dt; + dt = BaseDataSystemMES.EngineTypeChange(OpName, EngineType); + //提示机型发生变化 + if (dt.Rows.Count > 0) + { + string mesValue = Newtonsoft.Json.JsonConvert.SerializeObject(dt);//(recData); + string message = "MES|MaterialList_Dif_Resources|" + OpName + "|" + mesValue; + SendMessage.AsyncSendMessage(message); + } + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.EngineTypeID, EngineTypeID.ToString()); + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.EngineType, EngineType); + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.EngineID, EngineID); + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.OrderForm, OrderForm); + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.PartPallet_Code, PartPallet_Code.ToString()); + + //显示当前订单信息 + SendMessage.ShowMoby(OpName); + + EngineTypeGetOver_PLC_Work(OpName, EngineTypeID, EngineType, EngineID, PartPallet_Code, OrderForm); + } + else + { + SendMessage.AsyncSendMessage_Notice(OpName, "PLC机型与MES机型不匹配!"); + } + + + + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:EngineTypeGetOver_PLC"); + } + } + + + } + + + } +} diff --git a/MisDataFunction/MesServer.Function/Function1060/OpcServer/FalseGO.cs b/MisDataFunction/MesServer.Function/Function1060/OpcServer/FalseGO.cs new file mode 100644 index 0000000..e6d4179 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1060/OpcServer/FalseGO.cs @@ -0,0 +1,41 @@ +using System; +using bizFacade; +//using SystemFramework; +using MesServerWork; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 不合格放行 + /// + /// + /// + private void FalseGO(object e) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + + if (tagValue == 1) + { + //总合格标志2(不合格) + + //BaseDataSystemMES.Material_Insert_NG(OpName, 2); + + //Sendmessage("24", "11", OpName); + + ////工作完成 + //MIS_BASE.Write_MaterialVerifyOver(OpName, true); + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:FalseGO"); + } + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1060/OpcServer/HeartBeat.cs b/MisDataFunction/MesServer.Function/Function1060/OpcServer/HeartBeat.cs new file mode 100644 index 0000000..93affd3 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1060/OpcServer/HeartBeat.cs @@ -0,0 +1,35 @@ +using bizFacade; +using MesServerWork; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// MES与PLC心跳监听 + /// + /// + /// + private void HeartBeat(object e) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + + //返写在MES心跳中 + MIS_BASE.WritePLC(15, OpName, tagValue); + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:FalseGO"); + } + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1060/OpcServer/MesRead.cs b/MisDataFunction/MesServer.Function/Function1060/OpcServer/MesRead.cs new file mode 100644 index 0000000..2c468df --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1060/OpcServer/MesRead.cs @@ -0,0 +1,72 @@ +using bizFacade; +using MesServerWork; +using System; +//using SystemFramework; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 允许保存(针对半自动和手动压装工位) + /// + /// + /// + private void MesRead(object e) + { + { + try + { + int EngineTypeID; + string EngineType; + string EngineID; + int PartPallet_Code; + string OrderForm; + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + if (tagValue == 1) + { + MIS_BASE.GetEngineTypeFromPLC(OpName, out EngineTypeID, out EngineType, out EngineID, out PartPallet_Code, out OrderForm); + + //保存数据到线首表 先保存到 北汽福田变速器序列号总线上线 用于之前判断是否重号 + if (Db.UpLoadOpNameInsert(EngineID, EngineTypeID, EngineType, OpName)) + { + //保存质量数据 + int qualityMask = MisDataSaveDateMesRead.Funtion.MesRead(OpName, tagValue.ToString(), msgEvent.TagID.ToString()); + //保存物料数据 + BaseDataSystemMES.Material_Insert(OpName, qualityMask); + //测量数据发动机在线状态 + BaseDataSystemMES.WorkStartInsert(OpName, qualityMask); + //推送质量数据到MES的页面 + SendMessageFun.SendInfomation("ShowTimelyQuality", "1&" + qualityMask.ToString(), OpName); + //统计在线产量,在线节拍 + SendMessage.SendActuallyCount(OpName, tagValue); + + //通知设备,MES的质量数据(和物料数据)保存完成 + MIS_BASE.Write_MesReadOver(OpName, true); + //MES工作完成 + MIS_BASE.Write_MaterialVerifyOver(OpName, true); + } + else + { + SendMessage.AsyncSendMessage_Notice(OpName, "保存上线数据失败!"); + } + } + else + { + MIS_BASE.Write_MesReadOver(OpName, false); + } + } + + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function08:MesReadOver"); + } + } + + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1060/OpcServer/MesReadOver.cs b/MisDataFunction/MesServer.Function/Function1060/OpcServer/MesReadOver.cs new file mode 100644 index 0000000..f96a7d3 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1060/OpcServer/MesReadOver.cs @@ -0,0 +1,55 @@ +using System; +//using SystemFramework; +using MesServerWork; +using bizFacade; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 保存完成(针对半自动和手动压装工位) + /// + /// + /// + private void MesReadOver(object e) + { + //try + //{ + // DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + // string OpName = Convert.ToString(msgEvent.OpName); + // var tagValue = msgEvent.TagValue.ToString (); + + // if (tagValue == "1" | tagValue.ToLower () == "true") + // { + // int qualityMask; + // MIS_BASE.Read_QualityMask(OpName, out qualityMask); + + // SendInfomation("ShowTimelyQuality", "1&" + qualityMask.ToString(), OpName);//发给Web页面显示质量数据 + + // if (qualityMask == 1)//全部OK,给出合格放行 + // { + // //如果存在线外扫描工位,根据扫描条码绑定线外数据 需要时解除禁用 + // //BaseDataSystemMES.TransLaunchDataByMainMaterial(OpName, EngineType, EngineID, EngineTypeID); + + // //如果存在线外排队工位,根据排队编号绑定线外数据 需要时解除禁用 + // ////BaseDataSystemMES.MailLineAndSubLineData_InsertByEngineID_Subline(OpName,EngineID, EngineTypeID, EngineType); + + // MIS_BASE.Write_ConfirmOkGo(OpName, true); + // //MIS_BASE.Write_FalseGO(OpName, false); + // } + // else + // { + // //MIS_BASE.Write_ConfirmOkGo(OpName, false); + // MIS_BASE.Write_FalseGO(OpName, true); + // } + + // } + //} + //catch (Exception err) + //{ + // ////ApplicationLog.WriteLog(err, "Function02:MesReadOver"); + //} + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1060/OpcServer/MesSaveNowData.cs b/MisDataFunction/MesServer.Function/Function1060/OpcServer/MesSaveNowData.cs new file mode 100644 index 0000000..11c9129 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1060/OpcServer/MesSaveNowData.cs @@ -0,0 +1,35 @@ +using bizFacade; +using MesServerWork; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// MES保存实时质量数据 + /// + /// + /// + private void MesSaveNowData(object e) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + + // 保存质量数据 + MisDataSaveDateMesRead.Funtion.MesRead(OpName, tagValue.ToString(), msgEvent.TagID.ToString()); + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:FalseGO"); + } + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1060/OpcServer/PartLoad.cs b/MisDataFunction/MesServer.Function/Function1060/OpcServer/PartLoad.cs new file mode 100644 index 0000000..75debe9 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1060/OpcServer/PartLoad.cs @@ -0,0 +1,23 @@ +using bizFacade; +using MesServerWork; +using System; +using System.Collections.Generic; +using System.Data; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 申请上线 43 + /// + /// + /// + private void PartLoad(object e) + { + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1060/OpcServer/WebSubmit.cs b/MisDataFunction/MesServer.Function/Function1060/OpcServer/WebSubmit.cs new file mode 100644 index 0000000..87548a3 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1060/OpcServer/WebSubmit.cs @@ -0,0 +1,334 @@ +using System; +using MesServerWork; +using bizFacade; +using System.Threading; +using MisDataSaveDate; +using System.Collections; +//using SystemFramework; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 处理WEB页面发送过来的请求(m_Command + "|" + m_Value;) + /// + /// + /// + private void WebSubmit(object e) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName=Convert.ToString(msgEvent.OpName); + string Content = Convert.ToString(msgEvent.TagValue); + + string[] dataArray = Content.Split('|'); + if (dataArray.Length != 2) + return; + //消息类型 + string m_Command = dataArray[0].ToString(); + //消息参数 + string m_Value = dataArray[1].ToString(); + //消息参数数量 + string[] m_Value_array = m_Value.Split('&'); + //消息参数长度 + int m_Value_length = m_Value_array.Length; + + //工件信息 + string engineID = ""; + if (MIS_BASE.hashtable_EngineGetOver_EngineTypeID == null) + { + MIS_BASE.InitHashtable_MesServerCode(); + } + if (MIS_BASE.hashtable_EngineGetOver_EngineID.ContainsKey(OpName)) + { + engineID = MIS_BASE.hashtable_EngineGetOver_EngineID[OpName].ToString(); + } + + DoWhatPlc.CustomeEvetnArgs _e = new DoWhatPlc.CustomeEvetnArgs(); + _e.OpName = OpName; + _e.TagValue = m_Value; + + //根据请求的命令处理逻辑 + switch (m_Command) + { + case "Barcode": + if (m_Value_length > 1) return; + fun_Barcode(_e); + break; + case "ConfirmOkGo"://合格放行 + //删除不合格放行记录 + //修改托盘状态 + //Update_PalletStatus(OpName, 1, false); + BaseDataSystemMES.BaseData_tagTable_Engine_IsNG_Delete(OpName, engineID); + MIS_BASE.Write_ConfirmOkGo(OpName, true); + MIS_BASE.Write_FalseGO(OpName, false); + Thread.Sleep(1000); + MIS_BASE.Write_ConfirmOkGo(OpName, false); + break; + case "FalseGO"://返修放行 + //修改托盘状态 + //Update_PalletStatus(OpName, 3, false); + BaseDataSystemMES.BaseData_tagTable_Engine_IsNG_Delete(OpName, engineID); + MIS_BASE.Write_FalseGO(OpName, true); + MIS_BASE.Write_ConfirmOkGo(OpName, false); + Thread.Sleep(1000); + MIS_BASE.Write_FalseGO(OpName, false); + break; + case "NgGO"://不合格放行 + //修改托盘状态 + //Update_PalletStatus(OpName, 2, false); + //保存不合格信息(必须保存不合格放行信息,由于B5A的Moby没有不合格标志位) + BaseDataSystemMES.BaseData_tagTable_Engine_IsNG_Insert(OpName, engineID, "", ""); + MIS_BASE.Write_FalseGO(OpName, true); + MIS_BASE.Write_ConfirmOkGo(OpName, false); + Thread.Sleep(1000); + MIS_BASE.Write_FalseGO(OpName, false); + break; + case "OnLineState"://在线0、离线1、屏蔽2 + try + { + if (m_Value_length > 1) return; + int a = Convert.ToInt32(m_Value); + if (a <= 2) + { + BaseDataSystemMES.IsOnLine_Update(OpName, m_Value.ToString()); + MIS_BASE.Write_OnLineState(OpName, Convert.ToInt32(m_Value)); + if (a == 2) SendMessage.AsyncSendMessage_Notice(OpName, "屏蔽MES!"); + if (a == 0) SendMessage.AsyncSendMessage_Notice(OpName, "启用MES!"); + } + } + catch + { + + } + break; + case "Reset"://复位,将MES所有的信息都复位了 + SetMoby(OpName);//将MES所有信号清空 + break; + case "FixAllow"://重新拧紧 + MIS_BASE.Write_FixAllow(OpName, false); + MIS_BASE.Write_FixAllow(OpName, true); + break; + case "IsAutoGetEngineID"://自动手动申请编号(线首) + if (m_Value_length > 1) return; + MIS_BASE.Write_IsAutoGetEngineID(OpName, Convert.ToInt32(m_Value)); + break; + case "PartPalletGoOver"://空托盘放行 + int Is_PartPalletGoOver; + MIS_BASE.Read_PartPalletGoOver(OpName, out Is_PartPalletGoOver); + if (Is_PartPalletGoOver == 1) + { + MIS_BASE.Write_PartPalletGoOver(OpName, 1); + } + else + { + MIS_BASE.Write_PartPalletGoOver(OpName,0); + } + break; + case "SetMoby"://清空托盘(线首) + SetMoby(OpName);//将MES所有信号清空 + //MIS_BASE.Write_PartPalletCode_PLC(OpName, 1); + break; + case "RepairUplineMES"://返修上线 + MIS_BASE.Write_RepairUpline_MES(OpName, true); + break; + case "CancelRepair"://将返修件置为正常件 + + break; + case "PartPalletCode"://申请写入托盘号 + //MIS_BASE.Write_PartPalletCode_PLC(OpName, 1); + break; + case "WritePartPalletCode"://写入托盘号 + if (m_Value_length > 1) return; + MIS_BASE.Write_PalletCode(OpName, Convert.ToInt32(m_Value)); + break; + case "Normal"://启用正常拧紧工位 + MIS_BASE.Write_Normal(OpName, 1); + MIS_BASE.Write_UnNormal(OpName, 0); + break; + case "UnNormal"://启用备用拧紧工位 + MIS_BASE.Write_Normal(OpName, 0); + MIS_BASE.Write_UnNormal(OpName, 1); + break; + case "ResetDevice"://复位设备 + MIS_BASE.Write_ResetDevice(OpName, true); + System.Threading.Thread.Sleep(1000); + MIS_BASE.Write_ResetDevice(OpName, false); + break; + case "IsNeedRepaire"://返修上线(返修上线点) + if (Convert.ToInt32(m_Value) == 1) + { + //修改托盘状态 + MIS_BASE.Write_PalletInfo(OpName, 3); + //通知修改成功 + MIS_BASE.Write_UpdatePalletOK(OpName, true); + IsNeedRepaire_OK(OpName); + + } + else if (Convert.ToInt32(m_Value) == 0) + { + //通知修改成功 + MIS_BASE.Write_UpdatePalletOK(OpName, true); + //直接给出工作完成 + MIS_BASE.Write_MaterialVerifyOver(OpName, true); + } + else + { } + + break; + case "ContinueMatch": + BaseDataSystemMES.QualityVerifyStatus_Hash_Write(OpName, true); + break; + //初始化网页信号 + case "IniSingalToWeb": + InitializeSingalToWeb(OpName); + break; + case "Reset_Engine"://返修上线(返修上线点) + SetMoby(OpName);//将MES所有信号清空 + //fun_EngineTypeGetOverPLC(OpName, 0); + //fun_EngineTypeGetOverPLC(OpName, 1); + break; + + + default: break; + } + } + catch(Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:WebSubmit"); + } + } + private void SetMoby(string OpName) + { + try + { + //清空Moby时,需要将MES信号清空 + MIS_BASE.Write_ClearMesMoby(OpName); + + BaseDataSystemMES.MesServer_Process_EngineTypeOver(OpName); + + Sendmessage("5123", "1111", OpName); + + MIS_BASE.Write_ResetDevice(OpName, true); + System.Threading.Thread.Sleep(1000); + MIS_BASE.Write_ResetDevice(OpName, false); + } + catch + { + + } + } + /// 网页重现登录,恢复关闭前的页面状态 + /// + /// 工位号 + private void InitializeSingalToWeb(string Opname) + { + bool S_WorkStart;//工件到位 DBX0.1 + bool S_EngineGetOver;//传递机型 DBX0.4 + bool S_FixAllow;//允许工作 DBX3.1 + bool S_MaterialVerifyOver;//工作完成 DBX2.3 + string S_plcStatus;//DBX501.5 PLC直通,1 强制放行 0 正常循环 + + int IsCompleted = 0; + int S_Match = 0; + int PalletInfo_SubLine = 0;//显示分线托盘状态 + + MIS_BASE.Read_WorkStart(Opname, out S_WorkStart); + + //5 显示订单、机型信息 线首工位用 + SendMessage.ShowMoby_FirstOpName(Opname); + //3显示操作指导图片 PicShow_String_FirstOpName + SendMessage.PicShow_FirstOpName(Opname); + //1(直接在界面通过选择机型确认工序内容) + SendMessage.ProcessList_FirstOpName(Opname); + //界面显示物料信息 + SendMessage.MaterialList_FirstOpName(Opname); + // 新增查询PLC直通状态 网页显示 + MIS_BASE.Read_TagTypeID(63, Opname, out S_plcStatus); + InitAlarm(Opname); + + if (S_plcStatus.ToLower() == "false") + { + SendMessageFun.SendInfomation("PlcStatus", "0", Opname); + } + else + { + SendMessageFun.SendInfomation("PlcStatus", "1", Opname); + } + + if (S_WorkStart == true) + { + SendMessageFun.SendInfomation("WorkStart", Convert.ToString(Convert.ToInt32(S_WorkStart)), Opname); + //sendmessage(Opname, Convert.ToInt32(S_WorkStart), "WorkStart_Subline"); + } + + //sendmessage(Opname, Convert.ToInt32(S_WorkStart), "EngineTypeGetOverMES_Subline"); + + MIS_BASE.Read_EngineGetOver_PLC(Opname, out S_EngineGetOver); + if (S_EngineGetOver == true) + { + SendMessageFun.SendInfomation("EngineTypeGetOverPLC", Convert.ToString(Convert.ToInt32(S_EngineGetOver)), Opname); + //sendmessage(Opname, Convert.ToInt32(S_EngineGetOver), "EngineTypeGetOverMES_Subline"); + } + + MIS_BASE.Read_FixAllow(Opname, out S_FixAllow); + + if (S_FixAllow == true) + { + SendMessageFun.SendInfomation("FixAllow", Convert.ToString(Convert.ToInt32(S_FixAllow)), Opname); + } + + MIS_BASE.Read_MaterialVerifyOver(Opname, out S_MaterialVerifyOver); + + if (S_MaterialVerifyOver == true) + { + SendMessageFun.SendInfomation("MaterialVerifyOver", Convert.ToString(Convert.ToInt32(S_MaterialVerifyOver)), Opname); + } + + //MIS_BASE.Read_MatchingCompleted(Opname, out IsCompleted); //DBX1.3 是否匹配 + //MIS_BASE.Read_Match(Opname, out S_Match); //DBX1.4 匹配结果 + + //if (IsCompleted == 1 && S_Match == 1)//发送匹配完成和匹配结果信息 + //{ + // SendMessageFun.SendInfomation("MatchingCompleted", "1", Opname); + // SendMessageFun.SendInfomation("Match", "1", Opname); + // SendMessageFun.SendInfomation("MatchSuccess", "1", Opname);//界面显示匹配成功 + //} + //else if (IsCompleted == 1 && S_Match == 0) + //{ + // SendMessageFun.SendInfomation("MatchSuccess", "0", Opname);//界面显示匹配失败 + //} + + //if (MIS_BASE.hashtable_OpNameRepair == null) + //{ + // MIS_BASE.InitHashtable_MesServerCode(); + //} + //string Opname_SubLine = ""; + //if (MIS_BASE.hashtable_OpNameRepair.ContainsKey(Opname)) + //{ + // Opname_SubLine = MIS_BASE.hashtable_OpNameRepair[Opname].ToString(); + //} + //if (Opname_SubLine == "") + //{ + // return; + //} + + //MIS_BASE.Read_PalletInfo(Opname, out PalletInfo_SubLine); + //sendmessage(Opname, PalletInfo_SubLine, "SubQualityMask"); + //SendMessageFun.SendInfomation("ShowMobySubLine", Opname_SubLine, Opname);//显示分线机型及流水号 + } + private void InitAlarm(string Opname) + { + FuntionMesRead.Alarm_InitAlarm_Send(Opname, out Hashtable ht); + foreach (DictionaryEntry kv in ht) + { + var TagID = kv.Key.ToString(); + var TagValue = kv.Value.ToString(); + FuntionMesRead.Send_AlarmMsg(TagID, TagValue); + } + + } + } +} diff --git a/MisDataFunction/MesServer.Function/Function1060/OpcServer/WorkStart.cs b/MisDataFunction/MesServer.Function/Function1060/OpcServer/WorkStart.cs new file mode 100644 index 0000000..904295e --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1060/OpcServer/WorkStart.cs @@ -0,0 +1,91 @@ +using bizFacade; +using MesServerWork; +using System; +using System.Data; +using System.Threading; +//using SystemFramework; + +namespace MesServerFunctions +{ + partial class FunctionMES + { + /// + /// 工件到位与离开时,清空MES自身信号 + /// + /// + /// + private void WorkStart(object e) + { + try + { + int EngineTypeID;//机型代码 + string EngineType;//机型 + string EngineID;//工件编号 + + string OrderForm; + + int PLCRcipe; + + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + + int tagValue = Convert.ToInt32(msgEvent.TagValue); + if (tagValue > 0) + { + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.WorkStartIn, DateTime.Now.ToString()); + //北汽福田工位状态监控MOBY_查询_订单下达用 + DataTable dt; + dt = BaseDataSystemMES.DownOrderToOpNameMobyList(OpName); + if (dt != null) + { + //开始上线前清空交互区数据 + MIS_BASE.WritePLC(73, OpName, ""); + MIS_BASE.WritePLC(74, OpName, ""); + MIS_BASE.WritePLC(75, OpName, ""); + int workType = 0; + if (dt.Rows.Count > 0) + { + // 正常逻辑 获得机型信息、配方号、 + EngineTypeID = Convert.ToInt32(dt.Rows[0][MobyTagType.EngineTypeID_MES]); + EngineType = dt.Rows[0][MobyTagType.EngineType_MES].ToString(); + OrderForm = dt.Rows[0][MobyTagType.OrderForm_MES].ToString(); + PLCRcipe = Convert.ToInt32(dt.Rows[0][MobyTagType.PLCRcipe]); + EngineID = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss").Replace("-", "").Replace(" ", "").Replace(":", ""); + EngineID = EngineID + "_" + EngineType; //拼接工件编号 按照唯一码加时间来拼接 + // 将产品信息写入PLC + MIS_BASE.Write_EngineTypeID_MES(OpName, EngineTypeID); + MIS_BASE.Write_EngineType_MES(OpName, EngineType); + MIS_BASE.Write_EngineID_MES(OpName, EngineID); + MIS_BASE.Write_OrderForm_MES(OpName, OrderForm); + + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.EngineID_MES, EngineID); + // 获得配方数据 + BaseDataSystemMES.PLCRcipeByOpName(OpName, out byte[] bytes, out string tagStartAdr, PLCRcipe); + // 写入配方数据 + DtWebApi.ReadWritePLC.Write_TagValueByTagTypeID("94", OpName, System.Text.Encoding.ASCII.GetString(bytes)); + // MES传递机型 + MIS_BASE.Write_EngineTypeGetOver_MES(OpName, true); + } + } + } + else + { + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, MobyTagType.WorkStartOut, DateTime.Now.ToString()); + + MIS_BASE.Write_MesReadOver(OpName, false); + MIS_BASE.Write_ConfirmOkGo(OpName, false); + MIS_BASE.Write_FixAllow(OpName, false); + MIS_BASE.Write_ConfirmOkGo(OpName, false); + MIS_BASE.Write_EngineTypeGetOver_MES(OpName, false); + //工作完成 + MIS_BASE.Write_MaterialVerifyOver(OpName, false); + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function02:FalseGO"); + } + } + + } +} diff --git a/MisDataFunction/MesServer.Function/Function1060/OpcServer/vssver2.scc b/MisDataFunction/MesServer.Function/Function1060/OpcServer/vssver2.scc new file mode 100644 index 0000000..b884d13 Binary files /dev/null and b/MisDataFunction/MesServer.Function/Function1060/OpcServer/vssver2.scc differ diff --git a/MisDataFunction/MesServer.Function/Function1060/Properties/AssemblyInfo.cs b/MisDataFunction/MesServer.Function/Function1060/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..36f4b02 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1060/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// 有关程序集的一般信息由以下 +// 控制。更改这些特性值可修改 +// 与程序集关联的信息。 +[assembly: AssemblyTitle("Function1060")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("Function1060")] +[assembly: AssemblyCopyright("Copyright © 2023")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// 将 ComVisible 设置为 false 会使此程序集中的类型 +//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型 +//请将此类型的 ComVisible 特性设置为 true。 +[assembly: ComVisible(false)] + +// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID +[assembly: Guid("58215063-87f5-4708-8dda-031524c70b54")] + +// 程序集的版本信息由下列四个值组成: +// +// 主版本 +// 次版本 +// 生成号 +// 修订号 +// +//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值 +//通过使用 "*",如下所示: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/MisDataFunction/MesServer.Function/Function1060/app.config b/MisDataFunction/MesServer.Function/Function1060/app.config new file mode 100644 index 0000000..b4c4daf --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1060/app.config @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + + + diff --git a/MisDataFunction/MesServer.Function/Function1060/packages.config b/MisDataFunction/MesServer.Function/Function1060/packages.config new file mode 100644 index 0000000..b3e1761 --- /dev/null +++ b/MisDataFunction/MesServer.Function/Function1060/packages.config @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/MisDataFunction/MisDataFunction.sln b/MisDataFunction/MisDataFunction.sln new file mode 100644 index 0000000..bab0559 --- /dev/null +++ b/MisDataFunction/MisDataFunction.sln @@ -0,0 +1,127 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.32602.291 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Function22", "MesServer.Function\Function22\Function22.csproj", "{B8922826-D7D3-4D7B-8ADA-D7378016631C}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Function01", "MesServer.Function\Function01\Function01.csproj", "{709E27BC-5141-4B90-9900-09A78CB08FB5}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Function02", "MesServer.Function\Function02\Function02.csproj", "{CA8A12C5-7BF0-4489-93FA-180B1C492BBA}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Function03", "MesServer.Function\Function03\Function03.csproj", "{9EC40AD1-F398-4959-8674-BFFBD45549D0}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Function04", "MesServer.Function\Function04\Function04.csproj", "{A778B93C-FF1A-453A-9051-18FA3A002AF2}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Function05", "MesServer.Function\Function05\Function05.csproj", "{583369BD-AF70-4ADC-95EE-16658BCAF722}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Function06", "MesServer.Function\Function06\Function06.csproj", "{EB17DF24-B22A-4654-8103-0AC6A9079175}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Function07", "MesServer.Function\Function07\Function07.csproj", "{2843ED13-A354-453A-BA14-AE124BBD0944}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Function10", "MesServer.Function\Function10\Function10.csproj", "{E5C5CFB9-DDF8-42CC-B188-6D3C02398FDD}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Function11", "MesServer.Function\Function11\Function11.csproj", "{803AB2F6-D4D1-4E3C-8D12-54E89D443DAA}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Function15", "MesServer.Function\Function15\Function15.csproj", "{A0850468-74F6-43C3-9871-538CB40E31EE}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Function17", "MesServer.Function\Function17\Function17.csproj", "{AFAF85C0-B2DD-4740-8744-2E08D3F59396}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Function23", "MesServer.Function\Function23\Function23.csproj", "{B8C8DA70-2EF2-40CC-880D-2389B87D92CB}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Function29", "MesServer.Function\Function29\Function29.csproj", "{B8D5D60E-193D-43FF-8EB6-EA310E5A81E3}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Function08", "MesServer.Function\Function08\Function08.csproj", "{5DCBBFDD-F8A2-4EDD-A5F1-A49579D0F3F5}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Function09", "MesServer.Function\Function09\Function09.csproj", "{8C73F329-66CE-47D2-8639-21B1D95EA27A}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Function30", "MesServer.Function\Function30\Function30.csproj", "{EF2CC629-DD9E-4BA2-9098-41F46508EA4F}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Function28", "MesServer.Function\Function28\Function28.csproj", "{926C639C-653C-4B9F-907E-1617B96A7EF0}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {B8922826-D7D3-4D7B-8ADA-D7378016631C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B8922826-D7D3-4D7B-8ADA-D7378016631C}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B8922826-D7D3-4D7B-8ADA-D7378016631C}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B8922826-D7D3-4D7B-8ADA-D7378016631C}.Release|Any CPU.Build.0 = Release|Any CPU + {709E27BC-5141-4B90-9900-09A78CB08FB5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {709E27BC-5141-4B90-9900-09A78CB08FB5}.Debug|Any CPU.Build.0 = Debug|Any CPU + {709E27BC-5141-4B90-9900-09A78CB08FB5}.Release|Any CPU.ActiveCfg = Release|Any CPU + {709E27BC-5141-4B90-9900-09A78CB08FB5}.Release|Any CPU.Build.0 = Release|Any CPU + {CA8A12C5-7BF0-4489-93FA-180B1C492BBA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {CA8A12C5-7BF0-4489-93FA-180B1C492BBA}.Debug|Any CPU.Build.0 = Debug|Any CPU + {CA8A12C5-7BF0-4489-93FA-180B1C492BBA}.Release|Any CPU.ActiveCfg = Release|Any CPU + {CA8A12C5-7BF0-4489-93FA-180B1C492BBA}.Release|Any CPU.Build.0 = Release|Any CPU + {9EC40AD1-F398-4959-8674-BFFBD45549D0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {9EC40AD1-F398-4959-8674-BFFBD45549D0}.Debug|Any CPU.Build.0 = Debug|Any CPU + {9EC40AD1-F398-4959-8674-BFFBD45549D0}.Release|Any CPU.ActiveCfg = Release|Any CPU + {9EC40AD1-F398-4959-8674-BFFBD45549D0}.Release|Any CPU.Build.0 = Release|Any CPU + {A778B93C-FF1A-453A-9051-18FA3A002AF2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A778B93C-FF1A-453A-9051-18FA3A002AF2}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A778B93C-FF1A-453A-9051-18FA3A002AF2}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A778B93C-FF1A-453A-9051-18FA3A002AF2}.Release|Any CPU.Build.0 = Release|Any CPU + {583369BD-AF70-4ADC-95EE-16658BCAF722}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {583369BD-AF70-4ADC-95EE-16658BCAF722}.Debug|Any CPU.Build.0 = Debug|Any CPU + {583369BD-AF70-4ADC-95EE-16658BCAF722}.Release|Any CPU.ActiveCfg = Release|Any CPU + {583369BD-AF70-4ADC-95EE-16658BCAF722}.Release|Any CPU.Build.0 = Release|Any CPU + {EB17DF24-B22A-4654-8103-0AC6A9079175}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {EB17DF24-B22A-4654-8103-0AC6A9079175}.Debug|Any CPU.Build.0 = Debug|Any CPU + {EB17DF24-B22A-4654-8103-0AC6A9079175}.Release|Any CPU.ActiveCfg = Release|Any CPU + {EB17DF24-B22A-4654-8103-0AC6A9079175}.Release|Any CPU.Build.0 = Release|Any CPU + {2843ED13-A354-453A-BA14-AE124BBD0944}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {2843ED13-A354-453A-BA14-AE124BBD0944}.Debug|Any CPU.Build.0 = Debug|Any CPU + {2843ED13-A354-453A-BA14-AE124BBD0944}.Release|Any CPU.ActiveCfg = Release|Any CPU + {2843ED13-A354-453A-BA14-AE124BBD0944}.Release|Any CPU.Build.0 = Release|Any CPU + {E5C5CFB9-DDF8-42CC-B188-6D3C02398FDD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E5C5CFB9-DDF8-42CC-B188-6D3C02398FDD}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E5C5CFB9-DDF8-42CC-B188-6D3C02398FDD}.Release|Any CPU.ActiveCfg = Release|Any CPU + {E5C5CFB9-DDF8-42CC-B188-6D3C02398FDD}.Release|Any CPU.Build.0 = Release|Any CPU + {803AB2F6-D4D1-4E3C-8D12-54E89D443DAA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {803AB2F6-D4D1-4E3C-8D12-54E89D443DAA}.Debug|Any CPU.Build.0 = Debug|Any CPU + {803AB2F6-D4D1-4E3C-8D12-54E89D443DAA}.Release|Any CPU.ActiveCfg = Release|Any CPU + {803AB2F6-D4D1-4E3C-8D12-54E89D443DAA}.Release|Any CPU.Build.0 = Release|Any CPU + {A0850468-74F6-43C3-9871-538CB40E31EE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A0850468-74F6-43C3-9871-538CB40E31EE}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A0850468-74F6-43C3-9871-538CB40E31EE}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A0850468-74F6-43C3-9871-538CB40E31EE}.Release|Any CPU.Build.0 = Release|Any CPU + {AFAF85C0-B2DD-4740-8744-2E08D3F59396}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {AFAF85C0-B2DD-4740-8744-2E08D3F59396}.Debug|Any CPU.Build.0 = Debug|Any CPU + {AFAF85C0-B2DD-4740-8744-2E08D3F59396}.Release|Any CPU.ActiveCfg = Release|Any CPU + {AFAF85C0-B2DD-4740-8744-2E08D3F59396}.Release|Any CPU.Build.0 = Release|Any CPU + {B8C8DA70-2EF2-40CC-880D-2389B87D92CB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B8C8DA70-2EF2-40CC-880D-2389B87D92CB}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B8C8DA70-2EF2-40CC-880D-2389B87D92CB}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B8C8DA70-2EF2-40CC-880D-2389B87D92CB}.Release|Any CPU.Build.0 = Release|Any CPU + {B8D5D60E-193D-43FF-8EB6-EA310E5A81E3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B8D5D60E-193D-43FF-8EB6-EA310E5A81E3}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B8D5D60E-193D-43FF-8EB6-EA310E5A81E3}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B8D5D60E-193D-43FF-8EB6-EA310E5A81E3}.Release|Any CPU.Build.0 = Release|Any CPU + {5DCBBFDD-F8A2-4EDD-A5F1-A49579D0F3F5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {5DCBBFDD-F8A2-4EDD-A5F1-A49579D0F3F5}.Debug|Any CPU.Build.0 = Debug|Any CPU + {5DCBBFDD-F8A2-4EDD-A5F1-A49579D0F3F5}.Release|Any CPU.ActiveCfg = Release|Any CPU + {5DCBBFDD-F8A2-4EDD-A5F1-A49579D0F3F5}.Release|Any CPU.Build.0 = Release|Any CPU + {8C73F329-66CE-47D2-8639-21B1D95EA27A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {8C73F329-66CE-47D2-8639-21B1D95EA27A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {8C73F329-66CE-47D2-8639-21B1D95EA27A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {8C73F329-66CE-47D2-8639-21B1D95EA27A}.Release|Any CPU.Build.0 = Release|Any CPU + {EF2CC629-DD9E-4BA2-9098-41F46508EA4F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {EF2CC629-DD9E-4BA2-9098-41F46508EA4F}.Debug|Any CPU.Build.0 = Debug|Any CPU + {EF2CC629-DD9E-4BA2-9098-41F46508EA4F}.Release|Any CPU.ActiveCfg = Release|Any CPU + {EF2CC629-DD9E-4BA2-9098-41F46508EA4F}.Release|Any CPU.Build.0 = Release|Any CPU + {926C639C-653C-4B9F-907E-1617B96A7EF0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {926C639C-653C-4B9F-907E-1617B96A7EF0}.Debug|Any CPU.Build.0 = Debug|Any CPU + {926C639C-653C-4B9F-907E-1617B96A7EF0}.Release|Any CPU.ActiveCfg = Release|Any CPU + {926C639C-653C-4B9F-907E-1617B96A7EF0}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {AC76E79B-C576-4AF6-889E-57D1B50CC4F4} + EndGlobalSection +EndGlobal diff --git a/MisDataPlcTagID/MisDataPlcTagID.sln b/MisDataPlcTagID/MisDataPlcTagID.sln new file mode 100644 index 0000000..94232d2 --- /dev/null +++ b/MisDataPlcTagID/MisDataPlcTagID.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.32929.386 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MisDataPlcTagID", "MisDataPlcTagID\MisDataPlcTagID.csproj", "{0F887AB8-1BC5-4EF0-9240-E7AFD91A9911}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {0F887AB8-1BC5-4EF0-9240-E7AFD91A9911}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {0F887AB8-1BC5-4EF0-9240-E7AFD91A9911}.Debug|Any CPU.Build.0 = Debug|Any CPU + {0F887AB8-1BC5-4EF0-9240-E7AFD91A9911}.Release|Any CPU.ActiveCfg = Release|Any CPU + {0F887AB8-1BC5-4EF0-9240-E7AFD91A9911}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {B0928489-1030-4953-9B89-CE088204B0F0} + EndGlobalSection +EndGlobal diff --git a/MisDataPlcTagID/MisDataPlcTagID/20-12MisDataPlcTagID.csproj b/MisDataPlcTagID/MisDataPlcTagID/20-12MisDataPlcTagID.csproj new file mode 100644 index 0000000..dd695fc --- /dev/null +++ b/MisDataPlcTagID/MisDataPlcTagID/20-12MisDataPlcTagID.csproj @@ -0,0 +1,148 @@ + + + + + Debug + AnyCPU + {0F887AB8-1BC5-4EF0-9240-E7AFD91A9911} + Library + Properties + MisDataPlcTagID + MisDataPlcTagID + v4.6.1 + 512 + true + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + ..\..\..\Common\dll\MQTTnet.dll + + + ..\..\..\Common\dll\MQTTnet.Extensions.ManagedClient.dll + + + + + + + + + + + + + + + + + Component + + + Form + + + Form + + + Form + + + MisDataWebFun.cs + + + Form + + + MisDataWebFunSim.cs + + + + Form + + + Form + + + Form + + + WriteQualityValueForm.cs + + + Form + + + WriteQualityValueFormSim.cs + + + + + MisDataWebFun.cs + + + MisDataWebFunSim.cs + + + WriteQualityValueForm.cs + + + WriteQualityValueFormSim.cs + + + + + {1a10fdb2-1a6a-44a8-ab4d-33387563247e} + 00-0Json8.3.1 + + + {f55da1a0-a982-4479-8c47-0d9a5aaf3e18} + 00MesWorkMqtt + + + {0d1af432-439a-4920-8692-43ae139f5530} + 01_01DoWhatPlc + + + {3e6d1dd5-01c9-435f-9941-61f906ce35bb} + 02_02WebApiCallPLC + + + {f0a0c525-03fd-428a-9b17-7f54aa0e4475} + 07BusinessFacade + + + {d98be764-adeb-488d-9714-61e308aa8201} + 08-WebFun_base + + + {90e76fb4-646d-45e2-95db-0b8ab4e465d6} + 09-MesDataFunction + + + {7a8cc5ec-9795-4fcd-a85f-bb01da377225} + 20-04Foundation + + + {b258f56f-59e9-4c6f-bcc0-04a151d51251} + 20-06BasicOperation + + + + \ No newline at end of file diff --git a/MisDataPlcTagID/MisDataPlcTagID/Class1.cs b/MisDataPlcTagID/MisDataPlcTagID/Class1.cs new file mode 100644 index 0000000..754fbd7 --- /dev/null +++ b/MisDataPlcTagID/MisDataPlcTagID/Class1.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MisDataPlcTagID +{ + public class Class1 + { + } +} diff --git a/MisDataPlcTagID/MisDataPlcTagID/ListViewNF .cs b/MisDataPlcTagID/MisDataPlcTagID/ListViewNF .cs new file mode 100644 index 0000000..b69daa3 --- /dev/null +++ b/MisDataPlcTagID/MisDataPlcTagID/ListViewNF .cs @@ -0,0 +1,28 @@ + + +using System; +using System.Collections.Generic; +using System.Text; +using System.Windows.Forms; +namespace ListViewDouble +{ + class ListViewNF : System.Windows.Forms.ListView + { + public ListViewNF() + { + // 开启双缓冲 + this.SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint, true); + // Enable the OnNotifyMessage event so we get a chance to filter out + // Windows messages before they get to the form's WndProc + this.SetStyle(ControlStyles.EnableNotifyMessage, true); + } + protected override void OnNotifyMessage(Message m) + { + //Filter out the WM_ERASEBKGND message + if (m.Msg != 0x14) + { + base.OnNotifyMessage(m); + } + } + } +} diff --git a/MisDataPlcTagID/MisDataPlcTagID/ManualSimulateSignal.cs b/MisDataPlcTagID/MisDataPlcTagID/ManualSimulateSignal.cs new file mode 100644 index 0000000..ed95faf --- /dev/null +++ b/MisDataPlcTagID/MisDataPlcTagID/ManualSimulateSignal.cs @@ -0,0 +1,522 @@ +//using BasicData; + +using DoWhatPlc; +using MesServerWork; +using MisDataFunction; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading; +using System.Windows.Forms; +//using SystemFramework; + +namespace MisDataSaveDate +{ + public partial class MisData:Form + { + public void InitFormBtnColor() + { + try + { + if (!Cbx_StatusDisplay.Checked) return; + string OpName = WorkStationNum_Now; + foreach (Control GroupBox in this.groupBox_SignialSimulator.Controls) + { + foreach (Control Btn in GroupBox.Controls) + { + if (Btn.Name.Length < 8) continue; + if (Btn.Name.Substring(0, 8) == "Btn_PLC_" || Btn.Name.Substring(0, 8) == "Btn_MES_") + { + ControlData Ctrl1 = new ControlData(Btn, OpName); + Thread t=new Thread(new ParameterizedThreadStart(InitFormBtn_Thread)); + t.Start(Ctrl1); + } + } + } + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, err.Message); + + } + + + } + + static object test; + static void InitFormBtn_Thread(Object obj) + { + try + { + ControlData Btn = (ControlData)obj; + + test = DtWebApi.ReadWritePLC.ReadPLC(Btn.TagType.ToString(), Btn.opName); + + bool Result = Convert.ToBoolean(test); + if (Btn.btn.InvokeRequired) + { + Action actionDelegate = (x) => { Btn.btn.BackColor = x; }; + if (Result) + { + Btn.btn.BeginInvoke(actionDelegate, System.Drawing.Color.Green); + } + else + { + Btn.btn.BeginInvoke(actionDelegate, System.Drawing.Color.SlateGray); + } + } + else + { + if (Result) + { + Btn.btn.BackColor = System.Drawing.Color.Green; + } + else + { + Btn.btn.BackColor = System.Drawing.Color.SlateGray; + } + } + } + catch (Exception err) + { + ControlData Btn = (ControlData)obj; + //ApplicationLog.WriteLog(err, err.Message+"采集数据值:"+ ";按钮名称:"+test+ Btn.btn .Name +"工位号"+ WorkStationNum_Now); + } + } + + + + + + + /// + /// 通过点击界面按钮写入Bool信号 + /// + /// + /// + private void WriteBoolSignalByFormBtn(Object Sender) + { + try + { + string BtnName = ((System.Windows.Forms.Control)Sender).Name; + string[] Array_BtnNameSplit = BtnName.Split('_'); + int tagType = Convert.ToInt32(Array_BtnNameSplit[2]); + string OpName = WorkStationNum_Now; + + QualityDataQueryStruct QualityQueryStruct = new QualityDataQueryStruct(OpName, tagType); + Thread t = new Thread(new ParameterizedThreadStart(WriteBoolSignal_Thread)); + t.Start(QualityQueryStruct); + + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, err.Message); + + } + } + + void WriteBoolSignal_Thread(object obj) + { + try + { + QualityDataQueryStruct QDQ = (QualityDataQueryStruct)obj; + if (IsDemoMesServer==1) + { + string tagValueStr = ""; + MIS_BASE.Read_TagTypeID(QDQ.tagType, QDQ.OpName, out tagValueStr); + + if (tagValueStr=="1") + { + tagValueStr = "True"; + } + else if (tagValueStr == "0") + { + tagValueStr = "False"; + } + + bool ReadResult = Convert.ToBoolean(tagValueStr); + if (ReadResult) + { + MIS_BASE.Write_TagTypeID(QDQ.tagType, QDQ.OpName, false); + } + else + { + MIS_BASE.Write_TagTypeID(QDQ.tagType, QDQ.OpName, true); + } + } + else + { + bool ReadResult = Convert.ToBoolean(DtWebApi.ReadWritePLC.ReadPLC(QDQ.tagType.ToString(), QDQ.OpName)); + if (ReadResult) + { + DtWebApi.ReadWritePLC.WritePLC(QDQ.tagType.ToString(), QDQ.OpName, false); + } + else + { + DtWebApi.ReadWritePLC.WritePLC(QDQ.tagType.ToString(), QDQ.OpName, true); + } + } + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, err.Message); + + } + + } + + + + /// + /// 写入机型 + /// + /// + private void WriteNormalDataBygroupBox_SignialSimulatorWriteBtn(object Sender) + { + try + { + string BtnName = ((System.Windows.Forms.Control)Sender).Name; + string OpName = WorkStationNum_Now; + if (BtnName == "Btn_Write_PLC") + { + foreach (Control Tbx in this.groupBox_PLC.Controls) + { + if (Tbx.Name.Length < 12) continue; + if (Tbx.Name.Substring(0, 8) != "Tbx_PLC_") continue; + + string[] TbxName_Split = Tbx.Name.Split('_'); + int TagType = Convert.ToInt32(TbxName_Split[2]); + + HashtableList htList = DtWebApi.OpcDemo.GetHashtableList(); + int tagDataType = Convert.ToInt32(htList.hashtable_TagTypeDataType[TagType.ToString()]); + + string tagValue = Tbx.Text.Trim(); + short tagValue_int; + string tagValue_str; + byte tagValue_byte; + bool tagValue_bool; + + switch (tagDataType) + { + case 2: + if (!Regex.IsMatch(tagValue, @"^[-]?\d*$")) + { + MessageBox.Show("文本框\"" + Tbx.Name + "\"输入不是整数!"); + return; + } + if (tagValue == "") return; + tagValue_int = Convert.ToInt16(tagValue); + WriteAnyData_Thread(TagType, OpName, tagValue_int); + break; + case 8: + tagValue_str = tagValue.ToString(); + WriteAnyData_Thread(TagType, OpName, tagValue_str); + break; + case 17: + if (!Regex.IsMatch(tagValue, @"^[-]?\d*$")) + { + MessageBox.Show("文本框\"" + Tbx.Name + "\"输入不是整数!"); + return; + } + if (Convert.ToInt32(tagValue) > 255) + { + MessageBox.Show("文本框\"" + Tbx.Name + "\"输入数据不在范围内"); + return; + } + if (tagValue == "") return; + tagValue_byte = Convert.ToByte(tagValue); + WriteAnyData_Thread(TagType, OpName, tagValue_byte); + break; + case 11: + tagValue_bool = Convert.ToBoolean(Convert.ToInt32(tagValue)); + WriteAnyData_Thread(TagType, OpName, tagValue_bool); + break; + default: + tagValue_str = tagValue.ToString(); + WriteAnyData_Thread(TagType, OpName, tagValue_str); + break; + } + } + } + else if (BtnName == "Btn_Write_MES") + { + foreach (Control Tbx in this.groupBox_MES.Controls) + { + if (Tbx.Name.Length < 12) continue; + if (Tbx.Name.Substring(0, 8) != "Tbx_MES_") continue; + + string[] TbxName_Split = Tbx.Name.Split('_'); + int TagType = Convert.ToInt32(TbxName_Split[2]); + HashtableList htList = DtWebApi.OpcDemo.GetHashtableList(); + int tagDataType = Convert.ToInt32(htList.hashtable_TagTypeDataType[TagType.ToString()]); + //int tagDataType = Convert.ToInt32(MesDataFunction.OpcOperation.hashtable_TagTypeDataType[TagType.ToString()]); + + string tagValue = Tbx.Text.Trim(); + short tagValue_int; + string tagValue_str; + byte tagValue_byte; + bool tagValue_bool; + + switch (tagDataType) + { + case 2: + if (!Regex.IsMatch(tagValue, @"^[-]?\d*$")) + { + MessageBox.Show("文本框\"" + Tbx.Name + "\"输入不是整数!"); + return; + } + tagValue_int = Convert.ToInt16(tagValue); + WriteAnyData_Thread(TagType, OpName, tagValue_int); + break; + case 8: + tagValue_str = tagValue.ToString(); + WriteAnyData_Thread(TagType, OpName, tagValue_str); + break; + case 17: + if (!Regex.IsMatch(tagValue, @"^[-]?\d*$")) + { + MessageBox.Show("文本框\"" + Tbx.Name + "\"输入不是整数!"); + return; + } + if (Convert.ToInt32(tagValue) > 255) + { + MessageBox.Show("文本框\"" + Tbx.Name + "\"输入数据不在范围内"); + return; + } + tagValue_byte = Convert.ToByte(tagValue); + WriteAnyData_Thread(TagType, OpName, tagValue_byte); + break; + case 11: + tagValue_bool = Convert.ToBoolean(Convert.ToInt32(tagValue)); + WriteAnyData_Thread(TagType, OpName, tagValue_bool); + break; + default: + tagValue_str = tagValue.ToString(); + WriteAnyData_Thread(TagType, OpName, tagValue_str); + break; + } + } + } + + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, err.Message); + } + } + + + void WriteAnyData_Thread(int tagType, string opName, object tagValue) + { + try + { + QualityDataQueryStruct QualityStruct = new QualityDataQueryStruct(opName, tagType, tagValue); + + Thread t = new Thread(new ParameterizedThreadStart(WriteNormalDataBygroupBox_SignialSimulatorWriteBtn_Thread)); + t.Start(QualityStruct); + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, err.Message); + } + } + + void WriteNormalDataBygroupBox_SignialSimulatorWriteBtn_Thread(object obj) + { + try + { + QualityDataQueryStruct QualityStruct = (QualityDataQueryStruct)obj; + + MIS_BASE.WritePLC(QualityStruct.tagType, QualityStruct. OpName, QualityStruct.tagValue); + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, err.Message); + } + } + + + + /// + /// 根据工位号查询质量数据,返回质量数据列表 + /// + /// + /// + QualityDataType[] ReadPLC_ValueListForQualityDataTypeArray(string opName) + { + try + { + int i1 = 0; + Hashtable valueList; + valueList = Function.ReadPLC_Sync_DataList_MesRead(opName); + if (valueList != null) + { + QualityDataType[] QualityValue = new QualityDataType[valueList.Count]; + foreach (DictionaryEntry de in valueList) + { + try + { + QualityValue[i1] = (QualityDataType)de.Value; + i1++; + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, err.Message); + } + } + //ThisWorkStationData = QualityValue; + return QualityValue; + } + return null; + } + catch (Exception err) + { + + //ApplicationLog.WriteLog(err, err.Message); + return null; + } + + + } + + + //public QualityDataType[] ThisWorkStationData + //{ get; set; } + + //object QueryThisWorkStationDataByTagTypeFromThisWorkStationDataProperty(int TagType) + //{ + //try + //{ + // foreach (QualityDataType Data in ThisWorkStationData) + // { + // if (Data.tagValueType == TagType) + // { + // return Data.tagValue; + + // } + + // } + // return null; + //} + //catch (Exception err) + //{ + // ApplicationLog.WriteLog(err, err.Message); + // return null; + //} + + //} + + void RefreshBtnColor(object obj) + { + try + { + ControlChangeByTagType ControlValue = (ControlChangeByTagType)obj; + + if (!Cbx_StatusDisplay.Checked) return; + string OpName = WorkStationNum_Now; + + foreach (Control GroupBox in this.groupBox_SignialSimulator.Controls) + { + foreach (Control Btn in GroupBox.Controls) + { + if (Btn.Name.Length < 8) continue; + if (Btn.Name.Substring(0, 8) == "Btn_PLC_" || Btn.Name.Substring(0, 8) == "Btn_MES_") + { + string BtnName = Btn.Name; + string[] BtnName_SplitArray = BtnName.Split('_'); + if (Btn.InvokeRequired) + { + Action ActionDelegate = (x) => { Btn.BackColor = x; }; + if (Convert.ToInt32(BtnName_SplitArray[2]) == ControlValue.TagType) + { + if (ControlValue.Value == "1") + { + Btn.BeginInvoke(ActionDelegate, System.Drawing.Color.Green); + + } + else + { + Btn.BeginInvoke(ActionDelegate, System.Drawing.Color.LightGray); + } + } + + + } + else + { + if (Convert.ToInt32(BtnName_SplitArray[2]) == ControlValue.TagType) + { + if (ControlValue.Value == "1") + { + Btn.BackColor = System.Drawing.Color.Green; + } + else + { + + Btn.BackColor = System.Drawing.Color.LightGray; + } + } + } + } + + } + } + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, err.Message); + + } + + } + void RefreshBtnColor_Thread(int TagType, string Value) + { + ControlChangeByTagType ControlValue = new ControlChangeByTagType(TagType, Value); + Thread t = new Thread(new ParameterizedThreadStart(RefreshBtnColor)); + t.Start(ControlValue); + } + + + /// + /// 按钮颜色还原 + /// + void RefreshBtnColorWriteNull() + { + try + { + string OpName = WorkStationNum_Now; + + foreach (Control GroupBox in this.groupBox_SignialSimulator.Controls) + { + foreach (Control Btn in GroupBox.Controls) + { + if (Btn.Name.Length < 8) continue; + if (Btn.Name.Substring(0, 8) == "Btn_PLC_" || Btn.Name.Substring(0, 8) == "Btn_MES_") + { + if (Btn.InvokeRequired) + { + Action ActionDelegate = (x) => { Btn.BackColor = x; }; + Btn.BeginInvoke(ActionDelegate, System.Drawing.Color.LightGray); + } + else + { + Btn.BackColor = System.Drawing.Color.LightGray; + } + + } + } + } + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, err.Message); + + } + + } + + } +} diff --git a/MisDataPlcTagID/MisDataPlcTagID/ManualSimulateSignalSim.cs b/MisDataPlcTagID/MisDataPlcTagID/ManualSimulateSignalSim.cs new file mode 100644 index 0000000..b8a2dcc --- /dev/null +++ b/MisDataPlcTagID/MisDataPlcTagID/ManualSimulateSignalSim.cs @@ -0,0 +1,522 @@ +//using BasicData; + +using DoWhatPlc; +using MesServerWork; +using MisDataFunction; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading; +using System.Windows.Forms; +//using SystemFramework; + +namespace MisDataSaveDateSim +{ + public partial class MisData:Form + { + public void InitFormBtnColor() + { + try + { + if (!Cbx_StatusDisplay.Checked) return; + string OpName = WorkStationNum_Now; + foreach (Control GroupBox in this.groupBox_SignialSimulatorOld.Controls) + { + foreach (Control Btn in GroupBox.Controls) + { + if (Btn.Name.Length < 8) continue; + if (Btn.Name.Substring(0, 8) == "Btn_PLC_" || Btn.Name.Substring(0, 8) == "Btn_MES_") + { + ControlData Ctrl1 = new ControlData(Btn, OpName); + Thread t=new Thread(new ParameterizedThreadStart(InitFormBtn_Thread)); + t.Start(Ctrl1); + } + } + } + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, err.Message); + + } + + + } + + static object test; + static void InitFormBtn_Thread(Object obj) + { + try + { + ControlData Btn = (ControlData)obj; + + test = DtWebApi.ReadWritePLC.ReadPLC(Btn.TagType.ToString(), Btn.opName); + + bool Result = Convert.ToBoolean(test); + if (Btn.btn.InvokeRequired) + { + Action actionDelegate = (x) => { Btn.btn.BackColor = x; }; + if (Result) + { + Btn.btn.BeginInvoke(actionDelegate, System.Drawing.Color.Green); + } + else + { + Btn.btn.BeginInvoke(actionDelegate, System.Drawing.Color.SlateGray); + } + } + else + { + if (Result) + { + Btn.btn.BackColor = System.Drawing.Color.Green; + } + else + { + Btn.btn.BackColor = System.Drawing.Color.SlateGray; + } + } + } + catch (Exception err) + { + ControlData Btn = (ControlData)obj; + //ApplicationLog.WriteLog(err, err.Message+"采集数据值:"+ ";按钮名称:"+test+ Btn.btn .Name +"工位号"+ WorkStationNum_Now); + } + } + + + + + + + /// + /// 通过点击界面按钮写入Bool信号 + /// + /// + /// + private void WriteBoolSignalByFormBtn(Object Sender) + { + try + { + string BtnName = ((System.Windows.Forms.Control)Sender).Name; + string[] Array_BtnNameSplit = BtnName.Split('_'); + int tagType = Convert.ToInt32(Array_BtnNameSplit[2]); + string OpName = WorkStationNum_Now; + + QualityDataQueryStruct QualityQueryStruct = new QualityDataQueryStruct(OpName, tagType); + Thread t = new Thread(new ParameterizedThreadStart(WriteBoolSignal_Thread)); + t.Start(QualityQueryStruct); + + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, err.Message); + + } + } + + void WriteBoolSignal_Thread(object obj) + { + try + { + QualityDataQueryStruct QDQ = (QualityDataQueryStruct)obj; + if (IsDemoMesServer==1) + { + string tagValueStr = ""; + MIS_BASE.Read_TagTypeID(QDQ.tagType, QDQ.OpName, out tagValueStr); + + if (tagValueStr=="1") + { + tagValueStr = "True"; + } + else if (tagValueStr == "0") + { + tagValueStr = "False"; + } + + bool ReadResult = Convert.ToBoolean(tagValueStr); + if (ReadResult) + { + MIS_BASE.Write_TagTypeID(QDQ.tagType, QDQ.OpName, false); + } + else + { + MIS_BASE.Write_TagTypeID(QDQ.tagType, QDQ.OpName, true); + } + } + else + { + bool ReadResult = Convert.ToBoolean(DtWebApi.ReadWritePLC.ReadPLC(QDQ.tagType.ToString(), QDQ.OpName)); + if (ReadResult) + { + DtWebApi.ReadWritePLC.WritePLC(QDQ.tagType.ToString(), QDQ.OpName, false); + } + else + { + DtWebApi.ReadWritePLC.WritePLC(QDQ.tagType.ToString(), QDQ.OpName, true); + } + } + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, err.Message); + + } + + } + + + + /// + /// 写入机型 + /// + /// + private void WriteNormalDataBygroupBox_SignialSimulatorWriteBtn(object Sender) + { + try + { + string BtnName = ((System.Windows.Forms.Control)Sender).Name; + string OpName = WorkStationNum_Now; + if (BtnName == "Btn_Write_PLC") + { + foreach (Control Tbx in this.groupBox_PLC.Controls) + { + if (Tbx.Name.Length < 12) continue; + if (Tbx.Name.Substring(0, 8) != "Tbx_PLC_") continue; + + string[] TbxName_Split = Tbx.Name.Split('_'); + int TagType = Convert.ToInt32(TbxName_Split[2]); + + HashtableList htList = DtWebApi.OpcDemo.GetHashtableList(); + int tagDataType = Convert.ToInt32(htList.hashtable_TagTypeDataType[TagType.ToString()]); + + string tagValue = Tbx.Text.Trim(); + short tagValue_int; + string tagValue_str; + byte tagValue_byte; + bool tagValue_bool; + + switch (tagDataType) + { + case 2: + if (!Regex.IsMatch(tagValue, @"^[-]?\d*$")) + { + MessageBox.Show("文本框\"" + Tbx.Name + "\"输入不是整数!"); + return; + } + if (tagValue == "") return; + tagValue_int = Convert.ToInt16(tagValue); + WriteAnyData_Thread(TagType, OpName, tagValue_int); + break; + case 8: + tagValue_str = tagValue.ToString(); + WriteAnyData_Thread(TagType, OpName, tagValue_str); + break; + case 17: + if (!Regex.IsMatch(tagValue, @"^[-]?\d*$")) + { + MessageBox.Show("文本框\"" + Tbx.Name + "\"输入不是整数!"); + return; + } + if (Convert.ToInt32(tagValue) > 255) + { + MessageBox.Show("文本框\"" + Tbx.Name + "\"输入数据不在范围内"); + return; + } + if (tagValue == "") return; + tagValue_byte = Convert.ToByte(tagValue); + WriteAnyData_Thread(TagType, OpName, tagValue_byte); + break; + case 11: + tagValue_bool = Convert.ToBoolean(Convert.ToInt32(tagValue)); + WriteAnyData_Thread(TagType, OpName, tagValue_bool); + break; + default: + tagValue_str = tagValue.ToString(); + WriteAnyData_Thread(TagType, OpName, tagValue_str); + break; + } + } + } + else if (BtnName == "Btn_Write_MES") + { + foreach (Control Tbx in this.groupBox_MES.Controls) + { + if (Tbx.Name.Length < 12) continue; + if (Tbx.Name.Substring(0, 8) != "Tbx_MES_") continue; + + string[] TbxName_Split = Tbx.Name.Split('_'); + int TagType = Convert.ToInt32(TbxName_Split[2]); + HashtableList htList = DtWebApi.OpcDemo.GetHashtableList(); + int tagDataType = Convert.ToInt32(htList.hashtable_TagTypeDataType[TagType.ToString()]); + //int tagDataType = Convert.ToInt32(MesDataFunction.OpcOperation.hashtable_TagTypeDataType[TagType.ToString()]); + + string tagValue = Tbx.Text.Trim(); + short tagValue_int; + string tagValue_str; + byte tagValue_byte; + bool tagValue_bool; + + switch (tagDataType) + { + case 2: + if (!Regex.IsMatch(tagValue, @"^[-]?\d*$")) + { + MessageBox.Show("文本框\"" + Tbx.Name + "\"输入不是整数!"); + return; + } + tagValue_int = Convert.ToInt16(tagValue); + WriteAnyData_Thread(TagType, OpName, tagValue_int); + break; + case 8: + tagValue_str = tagValue.ToString(); + WriteAnyData_Thread(TagType, OpName, tagValue_str); + break; + case 17: + if (!Regex.IsMatch(tagValue, @"^[-]?\d*$")) + { + MessageBox.Show("文本框\"" + Tbx.Name + "\"输入不是整数!"); + return; + } + if (Convert.ToInt32(tagValue) > 255) + { + MessageBox.Show("文本框\"" + Tbx.Name + "\"输入数据不在范围内"); + return; + } + tagValue_byte = Convert.ToByte(tagValue); + WriteAnyData_Thread(TagType, OpName, tagValue_byte); + break; + case 11: + tagValue_bool = Convert.ToBoolean(Convert.ToInt32(tagValue)); + WriteAnyData_Thread(TagType, OpName, tagValue_bool); + break; + default: + tagValue_str = tagValue.ToString(); + WriteAnyData_Thread(TagType, OpName, tagValue_str); + break; + } + } + } + + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, err.Message); + } + } + + + void WriteAnyData_Thread(int tagType, string opName, object tagValue) + { + try + { + QualityDataQueryStruct QualityStruct = new QualityDataQueryStruct(opName, tagType, tagValue); + + Thread t = new Thread(new ParameterizedThreadStart(WriteNormalDataBygroupBox_SignialSimulatorWriteBtn_Thread)); + t.Start(QualityStruct); + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, err.Message); + } + } + + void WriteNormalDataBygroupBox_SignialSimulatorWriteBtn_Thread(object obj) + { + try + { + QualityDataQueryStruct QualityStruct = (QualityDataQueryStruct)obj; + + MIS_BASE.WritePLC(QualityStruct.tagType, QualityStruct. OpName, QualityStruct.tagValue); + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, err.Message); + } + } + + + + /// + /// 根据工位号查询质量数据,返回质量数据列表 + /// + /// + /// + QualityDataType[] ReadPLC_ValueListForQualityDataTypeArray(string opName) + { + try + { + int i1 = 0; + Hashtable valueList; + valueList = Function.ReadPLC_Sync_DataList_MesRead(opName); + if (valueList != null) + { + QualityDataType[] QualityValue = new QualityDataType[valueList.Count]; + foreach (DictionaryEntry de in valueList) + { + try + { + QualityValue[i1] = (QualityDataType)de.Value; + i1++; + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, err.Message); + } + } + //ThisWorkStationData = QualityValue; + return QualityValue; + } + return null; + } + catch (Exception err) + { + + //ApplicationLog.WriteLog(err, err.Message); + return null; + } + + + } + + + //public QualityDataType[] ThisWorkStationData + //{ get; set; } + + //object QueryThisWorkStationDataByTagTypeFromThisWorkStationDataProperty(int TagType) + //{ + //try + //{ + // foreach (QualityDataType Data in ThisWorkStationData) + // { + // if (Data.tagValueType == TagType) + // { + // return Data.tagValue; + + // } + + // } + // return null; + //} + //catch (Exception err) + //{ + // ApplicationLog.WriteLog(err, err.Message); + // return null; + //} + + //} + + void RefreshBtnColor(object obj) + { + try + { + ControlChangeByTagType ControlValue = (ControlChangeByTagType)obj; + + if (!Cbx_StatusDisplay.Checked) return; + string OpName = WorkStationNum_Now; + + foreach (Control GroupBox in this.groupBox_SignialSimulatorOld.Controls) + { + foreach (Control Btn in GroupBox.Controls) + { + if (Btn.Name.Length < 8) continue; + if (Btn.Name.Substring(0, 8) == "Btn_PLC_" || Btn.Name.Substring(0, 8) == "Btn_MES_") + { + string BtnName = Btn.Name; + string[] BtnName_SplitArray = BtnName.Split('_'); + if (Btn.InvokeRequired) + { + Action ActionDelegate = (x) => { Btn.BackColor = x; }; + if (Convert.ToInt32(BtnName_SplitArray[2]) == ControlValue.TagType) + { + if (ControlValue.Value == "1") + { + Btn.BeginInvoke(ActionDelegate, System.Drawing.Color.Green); + + } + else + { + Btn.BeginInvoke(ActionDelegate, System.Drawing.Color.LightGray); + } + } + + + } + else + { + if (Convert.ToInt32(BtnName_SplitArray[2]) == ControlValue.TagType) + { + if (ControlValue.Value == "1") + { + Btn.BackColor = System.Drawing.Color.Green; + } + else + { + + Btn.BackColor = System.Drawing.Color.LightGray; + } + } + } + } + + } + } + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, err.Message); + + } + + } + void RefreshBtnColor_Thread(int TagType, string Value) + { + ControlChangeByTagType ControlValue = new ControlChangeByTagType(TagType, Value); + Thread t = new Thread(new ParameterizedThreadStart(RefreshBtnColor)); + t.Start(ControlValue); + } + + + /// + /// 按钮颜色还原 + /// + void RefreshBtnColorWriteNull() + { + try + { + string OpName = WorkStationNum_Now; + + foreach (Control GroupBox in this.groupBox_SignialSimulatorOld.Controls) + { + foreach (Control Btn in GroupBox.Controls) + { + if (Btn.Name.Length < 8) continue; + if (Btn.Name.Substring(0, 8) == "Btn_PLC_" || Btn.Name.Substring(0, 8) == "Btn_MES_") + { + if (Btn.InvokeRequired) + { + Action ActionDelegate = (x) => { Btn.BackColor = x; }; + Btn.BeginInvoke(ActionDelegate, System.Drawing.Color.LightGray); + } + else + { + Btn.BackColor = System.Drawing.Color.LightGray; + } + + } + } + } + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, err.Message); + + } + + } + + } +} diff --git a/MisDataPlcTagID/MisDataPlcTagID/MisDataWebFun.Designer.cs b/MisDataPlcTagID/MisDataPlcTagID/MisDataWebFun.Designer.cs new file mode 100644 index 0000000..a7649e9 --- /dev/null +++ b/MisDataPlcTagID/MisDataPlcTagID/MisDataWebFun.Designer.cs @@ -0,0 +1,1923 @@ +namespace MisDataSaveDate +{ + partial class MisData + { + /// + /// 必需的设计器变量。 + /// + 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.components = new System.ComponentModel.Container(); + System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MisData)); + this.comboBox_OpName = new System.Windows.Forms.ComboBox(); + this.label_OpNameList = new System.Windows.Forms.Label(); + this.textBox_tagValue_Read = new System.Windows.Forms.TextBox(); + this.textBox_tagValue = new System.Windows.Forms.TextBox(); + this.textBox_Cmd = new System.Windows.Forms.TextBox(); + this.button_Read = new System.Windows.Forms.Button(); + this.button_Write = new System.Windows.Forms.Button(); + this.listBox1 = new System.Windows.Forms.ListBox(); + this.checkBox_WorkStart = new System.Windows.Forms.CheckBox(); + this.numericUpDown1 = new System.Windows.Forms.NumericUpDown(); + this.button_ReadData = new System.Windows.Forms.Button(); + this.groupBox_SignialSimulator = new System.Windows.Forms.GroupBox(); + this.groupBox_WorkStationStatus = new System.Windows.Forms.GroupBox(); + this.Cbx_StatusDisplay = new System.Windows.Forms.CheckBox(); + this.Tbx_Status_11_EngineType = new System.Windows.Forms.TextBox(); + this.Tbx_Status_9_EngineTypeID = new System.Windows.Forms.TextBox(); + this.label2 = new System.Windows.Forms.Label(); + this.Tbx_Status_10_EngineID = new System.Windows.Forms.TextBox(); + this.label20 = new System.Windows.Forms.Label(); + this.Tbx_Status_80_Pallet = new System.Windows.Forms.TextBox(); + this.label21 = new System.Windows.Forms.Label(); + this.label22 = new System.Windows.Forms.Label(); + this.groupBox_PLC = new System.Windows.Forms.GroupBox(); + this.checkBox_PLCData_Display = new System.Windows.Forms.CheckBox(); + this.Btn_Read_PLC = new System.Windows.Forms.Button(); + this.Tbx_PLC_23_RepairMark = new System.Windows.Forms.TextBox(); + this.Tbx_PLC_22_PalletStatus = new System.Windows.Forms.TextBox(); + this.Tbx_PLC_21_ResultMark = new System.Windows.Forms.TextBox(); + this.Tbx_PLC_80_PalletNum = new System.Windows.Forms.TextBox(); + this.Tbx_PLC_10_EngineID = new System.Windows.Forms.TextBox(); + this.Tbx_PLC_18_Actual = new System.Windows.Forms.TextBox(); + this.Tbx_PLC_9_EngineTypeID = new System.Windows.Forms.TextBox(); + this.Tbx_PLC_17_TargetTime = new System.Windows.Forms.TextBox(); + this.Tbx_PLC_11_Enginetype = new System.Windows.Forms.TextBox(); + this.label3 = new System.Windows.Forms.Label(); + this.label4 = 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.label18 = new System.Windows.Forms.Label(); + this.label17 = new System.Windows.Forms.Label(); + this.label9 = new System.Windows.Forms.Label(); + this.groupBox3 = new System.Windows.Forms.GroupBox(); + this.Btn_PLC_1003_ShortFall = new System.Windows.Forms.Button(); + this.Btn_PLC_19_MesRead = new System.Windows.Forms.Button(); + this.Btn_PLC_1002_MachaineBreak = new System.Windows.Forms.Button(); + this.Btn_PLC_59_FixOK = new System.Windows.Forms.Button(); + this.Btn_PLC_1001_CycleStart = new System.Windows.Forms.Button(); + this.Btn_PLC_1000_MachinePowerOn = new System.Windows.Forms.Button(); + this.Btn_PLC_44_EngineTypeGetOver = new System.Windows.Forms.Button(); + this.Btn_PLC_13_PalletIn = new System.Windows.Forms.Button(); + this.Btn_PLC_50_ApplyOffline = new System.Windows.Forms.Button(); + this.Btn_PLC_43_PartLoad = new System.Windows.Forms.Button(); + this.Btn_Write_PLC = new System.Windows.Forms.Button(); + this.Btn_PLC_16_AllowReadCycleTime = new System.Windows.Forms.Button(); + this.Btn_PLC_1004_Jam = new System.Windows.Forms.Button(); + this.Btn_PLC_14_HeartBeat = new System.Windows.Forms.Button(); + this.Btn_PLC_2_WorkStart = new System.Windows.Forms.Button(); + this.groupBox_MES = new System.Windows.Forms.GroupBox(); + this.checkBox_MESData_Display = new System.Windows.Forms.CheckBox(); + this.Btn_Read_MES = new System.Windows.Forms.Button(); + this.Tbx_MES_88_SocketNum = new System.Windows.Forms.TextBox(); + this.Tbx_MES_77_FixOrder = new System.Windows.Forms.TextBox(); + this.Tbx_MES_74_EngineID = new System.Windows.Forms.TextBox(); + this.Tbx_MES_79_OnlineStatus = new System.Windows.Forms.TextBox(); + this.Tbx_MES_4_WorkStationRepairStr = new System.Windows.Forms.TextBox(); + this.Tbx_MES_93_RepairMark = new System.Windows.Forms.TextBox(); + this.label19 = new System.Windows.Forms.Label(); + this.Tbx_MES_73_EngineTypeID = new System.Windows.Forms.TextBox(); + this.Tbx_MES_75_Enginetype = new System.Windows.Forms.TextBox(); + this.label10 = new System.Windows.Forms.Label(); + this.label11 = new System.Windows.Forms.Label(); + this.label12 = new System.Windows.Forms.Label(); + this.label13 = new System.Windows.Forms.Label(); + this.label14 = new System.Windows.Forms.Label(); + this.label15 = new System.Windows.Forms.Label(); + this.label16 = new System.Windows.Forms.Label(); + this.groupBox5 = new System.Windows.Forms.GroupBox(); + this.Btn_MES_69_MachResult = new System.Windows.Forms.Button(); + this.Btn_MES_8_FalseGo = new System.Windows.Forms.Button(); + this.Btn_MES_67_FixOver = new System.Windows.Forms.Button(); + this.Btn_MES_7_WorkComplete = new System.Windows.Forms.Button(); + this.Btn_MES_53_OffLineOK = new System.Windows.Forms.Button(); + this.Btn_MES_66_AllowWork = new System.Windows.Forms.Button(); + this.Btn_MES_5_EngineTypeGetOver = new System.Windows.Forms.Button(); + this.Btn_MES_72_MobyClear = new System.Windows.Forms.Button(); + this.Btn_MES_54_ReadCycleTimeOK = new System.Windows.Forms.Button(); + this.Btn_MES_68_MachComplete = new System.Windows.Forms.Button(); + this.Btn_MES_52_ResetEquipment = new System.Windows.Forms.Button(); + this.Btn_MES_6_PalletGo = new System.Windows.Forms.Button(); + this.Btn_Write_MES = new System.Windows.Forms.Button(); + this.Btn_MES_20_MesReadOver = new System.Windows.Forms.Button(); + this.Btn_MES_71_IsAuto = new System.Windows.Forms.Button(); + this.Btn_MES_51_ConfirmOkGo = new System.Windows.Forms.Button(); + this.Btn_MES_15_HeartBeat = new System.Windows.Forms.Button(); + this.groupBox_WorkStationQuality = new System.Windows.Forms.GroupBox(); + this.groupBox2 = new System.Windows.Forms.GroupBox(); + this.textBox_Copy_Item = new System.Windows.Forms.TextBox(); + this.textBox_Copy_TagID = new System.Windows.Forms.TextBox(); + this.textBox_Base_Item = new System.Windows.Forms.TextBox(); + this.textBox_Base_TagID = new System.Windows.Forms.TextBox(); + this.radioButton_Copy = new System.Windows.Forms.RadioButton(); + this.radioButton_Base = new System.Windows.Forms.RadioButton(); + this.groupBox1 = new System.Windows.Forms.GroupBox(); + this.radioButton_MQTT = new System.Windows.Forms.RadioButton(); + this.radioButton_PlcSignl_Copy = new System.Windows.Forms.RadioButton(); + this.radioButton_PartCodeSanner = new System.Windows.Forms.RadioButton(); + this.radioButton_PlcSignl = new System.Windows.Forms.RadioButton(); + this.cb_QdData = new System.Windows.Forms.CheckBox(); + this.cb_MonitorData = new System.Windows.Forms.CheckBox(); + this.listView_ShowQualityData = new ListViewDouble.ListViewNF(); + this.columnHeader4 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); + this.columnHeader2 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); + this.columnHeader3 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); + this.columnHeader1 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); + this.columnHeader5 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); + this.contextMenuStrip_MIS = new System.Windows.Forms.ContextMenuStrip(this.components); + this.toolStripMenuItem_Show = new System.Windows.Forms.ToolStripMenuItem(); + this.toolStripMenuItem_Hide = new System.Windows.Forms.ToolStripMenuItem(); + this.toolStripMenuItem_Exit = new System.Windows.Forms.ToolStripMenuItem(); + this.menuStrip_Main = new System.Windows.Forms.MenuStrip(); + this.ToolStripMenuItem_Start = new System.Windows.Forms.ToolStripMenuItem(); + this.ToolStripMenuItem_PrintScreen = new System.Windows.Forms.ToolStripMenuItem(); + this.ToolStripMenuItem_SaveLog = new System.Windows.Forms.ToolStripMenuItem(); + this.ToolStripMenuItem_LockForm = new System.Windows.Forms.ToolStripMenuItem(); + this.ToolStripMenuItem_Quit = new System.Windows.Forms.ToolStripMenuItem(); + this.ToolStripMenuItem_Visual = new System.Windows.Forms.ToolStripMenuItem(); + this.ToolStripMenuItem_VWSStatus = new System.Windows.Forms.ToolStripMenuItem(); + this.EToolStripMenuItem_EquipAlarm = new System.Windows.Forms.ToolStripMenuItem(); + this.ToolStripMenuItem_Assembly = new System.Windows.Forms.ToolStripMenuItem(); + this.TSM_DebugPage = new System.Windows.Forms.ToolStripMenuItem(); + this.ToolStripMenuItem_Help = new System.Windows.Forms.ToolStripMenuItem(); + this.ToolStripMenuItem_HHelp = new System.Windows.Forms.ToolStripMenuItem(); + this.toolStripMenuItem_HVersion = new System.Windows.Forms.ToolStripMenuItem(); + this.MToolStripMenuItem_AboutMacroinf = new System.Windows.Forms.ToolStripMenuItem(); + this.groupBox_Depart = new System.Windows.Forms.GroupBox(); + this.statusStrip1 = new System.Windows.Forms.StatusStrip(); + this.toolStripStatusLabel_RunningStatu = new System.Windows.Forms.ToolStripStatusLabel(); + this.toolStripStatusLabel_RunningStatus = new System.Windows.Forms.ToolStripStatusLabel(); + this.toolStripStatusLabel2 = new System.Windows.Forms.ToolStripStatusLabel(); + this.toolStripStatusLabel_StartTime = new System.Windows.Forms.ToolStripStatusLabel(); + this.toolStripStatusLabel3 = new System.Windows.Forms.ToolStripStatusLabel(); + this.toolStripStatusLabel_RunTime = new System.Windows.Forms.ToolStripStatusLabel(); + this.toolStripStatusLabel1 = new System.Windows.Forms.ToolStripStatusLabel(); + this.toolStripStatusLabel_WorkStationNum = new System.Windows.Forms.ToolStripStatusLabel(); + this.toolStripStatusLabel6 = new System.Windows.Forms.ToolStripStatusLabel(); + this.toolStripStatusLabel_OnlineNum = new System.Windows.Forms.ToolStripStatusLabel(); + this.toolStripStatusLabel8 = new System.Windows.Forms.ToolStripStatusLabel(); + this.toolStripStatusLabel_DownLine = new System.Windows.Forms.ToolStripStatusLabel(); + this.toolStripStatusLabel4 = new System.Windows.Forms.ToolStripStatusLabel(); + this.toolStripStatusLabel_Version = new System.Windows.Forms.ToolStripStatusLabel(); + this.groupBox_Alarm = new System.Windows.Forms.GroupBox(); + this.timer_ReadTagValues = new System.Windows.Forms.Timer(this.components); + ((System.ComponentModel.ISupportInitialize)(this.numericUpDown1)).BeginInit(); + this.groupBox_SignialSimulator.SuspendLayout(); + this.groupBox_WorkStationStatus.SuspendLayout(); + this.groupBox_PLC.SuspendLayout(); + this.groupBox_MES.SuspendLayout(); + this.groupBox_WorkStationQuality.SuspendLayout(); + this.groupBox2.SuspendLayout(); + this.groupBox1.SuspendLayout(); + this.contextMenuStrip_MIS.SuspendLayout(); + this.menuStrip_Main.SuspendLayout(); + this.statusStrip1.SuspendLayout(); + this.SuspendLayout(); + // + // comboBox_OpName + // + this.comboBox_OpName.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; + this.comboBox_OpName.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.comboBox_OpName.FormattingEnabled = true; + this.comboBox_OpName.Location = new System.Drawing.Point(72, 15); + this.comboBox_OpName.Name = "comboBox_OpName"; + this.comboBox_OpName.Size = new System.Drawing.Size(76, 20); + this.comboBox_OpName.TabIndex = 1425; + this.comboBox_OpName.SelectedIndexChanged += new System.EventHandler(this.comboBox_OpName_SelectedIndexChanged); + // + // label_OpNameList + // + this.label_OpNameList.AutoSize = true; + this.label_OpNameList.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.label_OpNameList.Location = new System.Drawing.Point(6, 19); + this.label_OpNameList.Name = "label_OpNameList"; + this.label_OpNameList.Size = new System.Drawing.Size(65, 12); + this.label_OpNameList.TabIndex = 1424; + this.label_OpNameList.Text = "工位编号:"; + this.label_OpNameList.DoubleClick += new System.EventHandler(this.label_OpNameList_DoubleClick); + // + // textBox_tagValue_Read + // + this.textBox_tagValue_Read.Location = new System.Drawing.Point(84, 91); + this.textBox_tagValue_Read.Margin = new System.Windows.Forms.Padding(2); + this.textBox_tagValue_Read.Name = "textBox_tagValue_Read"; + this.textBox_tagValue_Read.ReadOnly = true; + this.textBox_tagValue_Read.Size = new System.Drawing.Size(119, 21); + this.textBox_tagValue_Read.TabIndex = 1464; + // + // textBox_tagValue + // + this.textBox_tagValue.Location = new System.Drawing.Point(84, 124); + this.textBox_tagValue.Margin = new System.Windows.Forms.Padding(2); + this.textBox_tagValue.Name = "textBox_tagValue"; + this.textBox_tagValue.Size = new System.Drawing.Size(119, 21); + this.textBox_tagValue.TabIndex = 1458; + // + // textBox_Cmd + // + this.textBox_Cmd.Location = new System.Drawing.Point(123, 151); + this.textBox_Cmd.Margin = new System.Windows.Forms.Padding(2); + this.textBox_Cmd.Name = "textBox_Cmd"; + this.textBox_Cmd.Size = new System.Drawing.Size(80, 21); + this.textBox_Cmd.TabIndex = 1460; + // + // button_Read + // + this.button_Read.Location = new System.Drawing.Point(17, 89); + this.button_Read.Margin = new System.Windows.Forms.Padding(2); + this.button_Read.Name = "button_Read"; + this.button_Read.Size = new System.Drawing.Size(56, 25); + this.button_Read.TabIndex = 1454; + this.button_Read.Text = "读取"; + this.button_Read.UseVisualStyleBackColor = true; + this.button_Read.Click += new System.EventHandler(this.button_Read_Click); + // + // button_Write + // + this.button_Write.Location = new System.Drawing.Point(17, 122); + this.button_Write.Margin = new System.Windows.Forms.Padding(2); + this.button_Write.Name = "button_Write"; + this.button_Write.Size = new System.Drawing.Size(56, 25); + this.button_Write.TabIndex = 1455; + this.button_Write.Text = "写入"; + this.button_Write.UseVisualStyleBackColor = true; + this.button_Write.Click += new System.EventHandler(this.button_Write_Click); + // + // listBox1 + // + this.listBox1.FormattingEnabled = true; + this.listBox1.ItemHeight = 12; + this.listBox1.Location = new System.Drawing.Point(210, 86); + this.listBox1.Margin = new System.Windows.Forms.Padding(2); + this.listBox1.Name = "listBox1"; + this.listBox1.Size = new System.Drawing.Size(225, 88); + this.listBox1.TabIndex = 1453; + this.listBox1.SelectedValueChanged += new System.EventHandler(this.listBox1_SelectedValueChanged); + // + // checkBox_WorkStart + // + this.checkBox_WorkStart.AutoSize = true; + this.checkBox_WorkStart.Location = new System.Drawing.Point(18, 156); + this.checkBox_WorkStart.Margin = new System.Windows.Forms.Padding(2); + this.checkBox_WorkStart.Name = "checkBox_WorkStart"; + this.checkBox_WorkStart.Size = new System.Drawing.Size(48, 16); + this.checkBox_WorkStart.TabIndex = 1466; + this.checkBox_WorkStart.Text = "模拟"; + this.checkBox_WorkStart.UseVisualStyleBackColor = true; + this.checkBox_WorkStart.CheckedChanged += new System.EventHandler(this.checkBox_WorkStart_CheckedChanged); + // + // numericUpDown1 + // + this.numericUpDown1.Location = new System.Drawing.Point(84, 151); + this.numericUpDown1.Margin = new System.Windows.Forms.Padding(2); + this.numericUpDown1.Name = "numericUpDown1"; + this.numericUpDown1.Size = new System.Drawing.Size(35, 21); + this.numericUpDown1.TabIndex = 1467; + this.numericUpDown1.Value = new decimal(new int[] { + 5, + 0, + 0, + 0}); + this.numericUpDown1.ValueChanged += new System.EventHandler(this.numericUpDown1_ValueChanged); + // + // button_ReadData + // + this.button_ReadData.Location = new System.Drawing.Point(114, 20); + this.button_ReadData.Name = "button_ReadData"; + this.button_ReadData.Size = new System.Drawing.Size(62, 23); + this.button_ReadData.TabIndex = 1470; + this.button_ReadData.Text = "读取数据"; + this.button_ReadData.UseVisualStyleBackColor = true; + this.button_ReadData.Click += new System.EventHandler(this.button_ReadData_Click); + // + // groupBox_SignialSimulator + // + this.groupBox_SignialSimulator.Controls.Add(this.groupBox_WorkStationStatus); + this.groupBox_SignialSimulator.Controls.Add(this.groupBox_PLC); + this.groupBox_SignialSimulator.Controls.Add(this.textBox_Cmd); + this.groupBox_SignialSimulator.Controls.Add(this.button_Write); + this.groupBox_SignialSimulator.Controls.Add(this.groupBox_MES); + this.groupBox_SignialSimulator.Controls.Add(this.button_Read); + this.groupBox_SignialSimulator.Controls.Add(this.numericUpDown1); + this.groupBox_SignialSimulator.Controls.Add(this.listBox1); + this.groupBox_SignialSimulator.Controls.Add(this.checkBox_WorkStart); + this.groupBox_SignialSimulator.Controls.Add(this.textBox_tagValue_Read); + this.groupBox_SignialSimulator.Controls.Add(this.textBox_tagValue); + this.groupBox_SignialSimulator.Location = new System.Drawing.Point(549, 29); + this.groupBox_SignialSimulator.Name = "groupBox_SignialSimulator"; + this.groupBox_SignialSimulator.Size = new System.Drawing.Size(447, 642); + this.groupBox_SignialSimulator.TabIndex = 1471; + this.groupBox_SignialSimulator.TabStop = false; + this.groupBox_SignialSimulator.Text = "信号模拟"; + // + // groupBox_WorkStationStatus + // + this.groupBox_WorkStationStatus.Controls.Add(this.Cbx_StatusDisplay); + this.groupBox_WorkStationStatus.Controls.Add(this.label_OpNameList); + this.groupBox_WorkStationStatus.Controls.Add(this.Tbx_Status_11_EngineType); + this.groupBox_WorkStationStatus.Controls.Add(this.Tbx_Status_9_EngineTypeID); + this.groupBox_WorkStationStatus.Controls.Add(this.comboBox_OpName); + this.groupBox_WorkStationStatus.Controls.Add(this.label2); + this.groupBox_WorkStationStatus.Controls.Add(this.Tbx_Status_10_EngineID); + this.groupBox_WorkStationStatus.Controls.Add(this.label20); + this.groupBox_WorkStationStatus.Controls.Add(this.Tbx_Status_80_Pallet); + this.groupBox_WorkStationStatus.Controls.Add(this.label21); + this.groupBox_WorkStationStatus.Controls.Add(this.label22); + this.groupBox_WorkStationStatus.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.groupBox_WorkStationStatus.Location = new System.Drawing.Point(12, 14); + this.groupBox_WorkStationStatus.Name = "groupBox_WorkStationStatus"; + this.groupBox_WorkStationStatus.Size = new System.Drawing.Size(423, 69); + this.groupBox_WorkStationStatus.TabIndex = 1468; + this.groupBox_WorkStationStatus.TabStop = false; + this.groupBox_WorkStationStatus.Text = "WorkStationStatus"; + // + // Cbx_StatusDisplay + // + this.Cbx_StatusDisplay.AutoSize = true; + this.Cbx_StatusDisplay.Enabled = false; + this.Cbx_StatusDisplay.Location = new System.Drawing.Point(355, 17); + this.Cbx_StatusDisplay.Name = "Cbx_StatusDisplay"; + this.Cbx_StatusDisplay.Size = new System.Drawing.Size(48, 16); + this.Cbx_StatusDisplay.TabIndex = 1426; + this.Cbx_StatusDisplay.Text = "同步"; + this.Cbx_StatusDisplay.UseVisualStyleBackColor = true; + // + // Tbx_Status_11_EngineType + // + this.Tbx_Status_11_EngineType.Location = new System.Drawing.Point(309, 41); + this.Tbx_Status_11_EngineType.Name = "Tbx_Status_11_EngineType"; + this.Tbx_Status_11_EngineType.ReadOnly = true; + this.Tbx_Status_11_EngineType.Size = new System.Drawing.Size(94, 21); + this.Tbx_Status_11_EngineType.TabIndex = 3; + this.Tbx_Status_11_EngineType.Text = "加载中..."; + // + // Tbx_Status_9_EngineTypeID + // + this.Tbx_Status_9_EngineTypeID.Location = new System.Drawing.Point(210, 15); + this.Tbx_Status_9_EngineTypeID.Name = "Tbx_Status_9_EngineTypeID"; + this.Tbx_Status_9_EngineTypeID.ReadOnly = true; + this.Tbx_Status_9_EngineTypeID.Size = new System.Drawing.Size(29, 21); + this.Tbx_Status_9_EngineTypeID.TabIndex = 3; + this.Tbx_Status_9_EngineTypeID.Text = "..."; + // + // label2 + // + this.label2.AutoSize = true; + this.label2.Location = new System.Drawing.Point(6, 45); + this.label2.Name = "label2"; + this.label2.Size = new System.Drawing.Size(65, 12); + this.label2.TabIndex = 2; + this.label2.Text = "产品编号:"; + // + // Tbx_Status_10_EngineID + // + this.Tbx_Status_10_EngineID.Location = new System.Drawing.Point(72, 41); + this.Tbx_Status_10_EngineID.Name = "Tbx_Status_10_EngineID"; + this.Tbx_Status_10_EngineID.ReadOnly = true; + this.Tbx_Status_10_EngineID.Size = new System.Drawing.Size(167, 21); + this.Tbx_Status_10_EngineID.TabIndex = 3; + this.Tbx_Status_10_EngineID.Text = "加载中..."; + // + // label20 + // + this.label20.AutoSize = true; + this.label20.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.label20.Location = new System.Drawing.Point(245, 45); + this.label20.Name = "label20"; + this.label20.Size = new System.Drawing.Size(65, 12); + this.label20.TabIndex = 2; + this.label20.Text = "产品型号:"; + // + // Tbx_Status_80_Pallet + // + this.Tbx_Status_80_Pallet.Location = new System.Drawing.Point(309, 15); + this.Tbx_Status_80_Pallet.Name = "Tbx_Status_80_Pallet"; + this.Tbx_Status_80_Pallet.ReadOnly = true; + this.Tbx_Status_80_Pallet.Size = new System.Drawing.Size(31, 21); + this.Tbx_Status_80_Pallet.TabIndex = 5; + this.Tbx_Status_80_Pallet.Text = "..."; + // + // label21 + // + this.label21.AutoSize = true; + this.label21.Location = new System.Drawing.Point(150, 19); + this.label21.Name = "label21"; + this.label21.Size = new System.Drawing.Size(65, 12); + this.label21.TabIndex = 2; + this.label21.Text = "机型代码:"; + // + // label22 + // + this.label22.AutoSize = true; + this.label22.Location = new System.Drawing.Point(245, 19); + this.label22.Name = "label22"; + this.label22.Size = new System.Drawing.Size(65, 12); + this.label22.TabIndex = 2; + this.label22.Text = "托盘编号:"; + // + // groupBox_PLC + // + this.groupBox_PLC.Controls.Add(this.checkBox_PLCData_Display); + this.groupBox_PLC.Controls.Add(this.Btn_Read_PLC); + this.groupBox_PLC.Controls.Add(this.Tbx_PLC_23_RepairMark); + this.groupBox_PLC.Controls.Add(this.Tbx_PLC_22_PalletStatus); + this.groupBox_PLC.Controls.Add(this.Tbx_PLC_21_ResultMark); + this.groupBox_PLC.Controls.Add(this.Tbx_PLC_80_PalletNum); + this.groupBox_PLC.Controls.Add(this.Tbx_PLC_10_EngineID); + this.groupBox_PLC.Controls.Add(this.Tbx_PLC_18_Actual); + this.groupBox_PLC.Controls.Add(this.Tbx_PLC_9_EngineTypeID); + this.groupBox_PLC.Controls.Add(this.Tbx_PLC_17_TargetTime); + this.groupBox_PLC.Controls.Add(this.Tbx_PLC_11_Enginetype); + this.groupBox_PLC.Controls.Add(this.label3); + this.groupBox_PLC.Controls.Add(this.label4); + this.groupBox_PLC.Controls.Add(this.label5); + this.groupBox_PLC.Controls.Add(this.label6); + this.groupBox_PLC.Controls.Add(this.label7); + this.groupBox_PLC.Controls.Add(this.label8); + this.groupBox_PLC.Controls.Add(this.label18); + this.groupBox_PLC.Controls.Add(this.label17); + this.groupBox_PLC.Controls.Add(this.label9); + this.groupBox_PLC.Controls.Add(this.groupBox3); + this.groupBox_PLC.Controls.Add(this.Btn_PLC_1003_ShortFall); + this.groupBox_PLC.Controls.Add(this.Btn_PLC_19_MesRead); + this.groupBox_PLC.Controls.Add(this.Btn_PLC_1002_MachaineBreak); + this.groupBox_PLC.Controls.Add(this.Btn_PLC_59_FixOK); + this.groupBox_PLC.Controls.Add(this.Btn_PLC_1001_CycleStart); + this.groupBox_PLC.Controls.Add(this.Btn_PLC_1000_MachinePowerOn); + this.groupBox_PLC.Controls.Add(this.Btn_PLC_44_EngineTypeGetOver); + this.groupBox_PLC.Controls.Add(this.Btn_PLC_13_PalletIn); + this.groupBox_PLC.Controls.Add(this.Btn_PLC_50_ApplyOffline); + this.groupBox_PLC.Controls.Add(this.Btn_PLC_43_PartLoad); + this.groupBox_PLC.Controls.Add(this.Btn_Write_PLC); + this.groupBox_PLC.Controls.Add(this.Btn_PLC_16_AllowReadCycleTime); + this.groupBox_PLC.Controls.Add(this.Btn_PLC_1004_Jam); + this.groupBox_PLC.Controls.Add(this.Btn_PLC_14_HeartBeat); + this.groupBox_PLC.Controls.Add(this.Btn_PLC_2_WorkStart); + this.groupBox_PLC.Location = new System.Drawing.Point(12, 174); + this.groupBox_PLC.Name = "groupBox_PLC"; + this.groupBox_PLC.Size = new System.Drawing.Size(423, 212); + this.groupBox_PLC.TabIndex = 0; + this.groupBox_PLC.TabStop = false; + this.groupBox_PLC.Text = "PLC"; + // + // checkBox_PLCData_Display + // + this.checkBox_PLCData_Display.AutoSize = true; + this.checkBox_PLCData_Display.Checked = true; + this.checkBox_PLCData_Display.CheckState = System.Windows.Forms.CheckState.Checked; + this.checkBox_PLCData_Display.Location = new System.Drawing.Point(192, 188); + this.checkBox_PLCData_Display.Name = "checkBox_PLCData_Display"; + this.checkBox_PLCData_Display.Size = new System.Drawing.Size(48, 16); + this.checkBox_PLCData_Display.TabIndex = 7; + this.checkBox_PLCData_Display.Text = "同步"; + this.checkBox_PLCData_Display.UseVisualStyleBackColor = true; + // + // Btn_Read_PLC + // + this.Btn_Read_PLC.Location = new System.Drawing.Point(249, 185); + this.Btn_Read_PLC.Name = "Btn_Read_PLC"; + this.Btn_Read_PLC.Size = new System.Drawing.Size(75, 23); + this.Btn_Read_PLC.TabIndex = 6; + this.Btn_Read_PLC.Text = "读取 PLC"; + this.Btn_Read_PLC.UseVisualStyleBackColor = true; + this.Btn_Read_PLC.Click += new System.EventHandler(this.Btn_Read_PLC_Click); + // + // Tbx_PLC_23_RepairMark + // + this.Tbx_PLC_23_RepairMark.Location = new System.Drawing.Point(373, 160); + this.Tbx_PLC_23_RepairMark.Name = "Tbx_PLC_23_RepairMark"; + this.Tbx_PLC_23_RepairMark.Size = new System.Drawing.Size(33, 21); + this.Tbx_PLC_23_RepairMark.TabIndex = 5; + this.Tbx_PLC_23_RepairMark.Text = "0"; + // + // Tbx_PLC_22_PalletStatus + // + this.Tbx_PLC_22_PalletStatus.Location = new System.Drawing.Point(373, 133); + this.Tbx_PLC_22_PalletStatus.Name = "Tbx_PLC_22_PalletStatus"; + this.Tbx_PLC_22_PalletStatus.Size = new System.Drawing.Size(33, 21); + this.Tbx_PLC_22_PalletStatus.TabIndex = 5; + this.Tbx_PLC_22_PalletStatus.Text = "1"; + // + // Tbx_PLC_21_ResultMark + // + this.Tbx_PLC_21_ResultMark.Location = new System.Drawing.Point(259, 161); + this.Tbx_PLC_21_ResultMark.Name = "Tbx_PLC_21_ResultMark"; + this.Tbx_PLC_21_ResultMark.Size = new System.Drawing.Size(37, 21); + this.Tbx_PLC_21_ResultMark.TabIndex = 5; + this.Tbx_PLC_21_ResultMark.Text = "1"; + // + // Tbx_PLC_80_PalletNum + // + this.Tbx_PLC_80_PalletNum.Location = new System.Drawing.Point(259, 134); + this.Tbx_PLC_80_PalletNum.Name = "Tbx_PLC_80_PalletNum"; + this.Tbx_PLC_80_PalletNum.Size = new System.Drawing.Size(37, 21); + this.Tbx_PLC_80_PalletNum.TabIndex = 5; + this.Tbx_PLC_80_PalletNum.Text = "2"; + // + // Tbx_PLC_10_EngineID + // + this.Tbx_PLC_10_EngineID.Location = new System.Drawing.Point(259, 108); + this.Tbx_PLC_10_EngineID.Name = "Tbx_PLC_10_EngineID"; + this.Tbx_PLC_10_EngineID.Size = new System.Drawing.Size(146, 21); + this.Tbx_PLC_10_EngineID.TabIndex = 3; + this.Tbx_PLC_10_EngineID.Text = "H12C3-00001001"; + // + // Tbx_PLC_18_Actual + // + this.Tbx_PLC_18_Actual.Location = new System.Drawing.Point(101, 186); + this.Tbx_PLC_18_Actual.Name = "Tbx_PLC_18_Actual"; + this.Tbx_PLC_18_Actual.Size = new System.Drawing.Size(61, 21); + this.Tbx_PLC_18_Actual.TabIndex = 3; + this.Tbx_PLC_18_Actual.Text = "50"; + // + // Tbx_PLC_9_EngineTypeID + // + this.Tbx_PLC_9_EngineTypeID.Location = new System.Drawing.Point(77, 133); + this.Tbx_PLC_9_EngineTypeID.Name = "Tbx_PLC_9_EngineTypeID"; + this.Tbx_PLC_9_EngineTypeID.Size = new System.Drawing.Size(85, 21); + this.Tbx_PLC_9_EngineTypeID.TabIndex = 3; + this.Tbx_PLC_9_EngineTypeID.Text = "1"; + // + // Tbx_PLC_17_TargetTime + // + this.Tbx_PLC_17_TargetTime.Location = new System.Drawing.Point(101, 160); + this.Tbx_PLC_17_TargetTime.Name = "Tbx_PLC_17_TargetTime"; + this.Tbx_PLC_17_TargetTime.Size = new System.Drawing.Size(61, 21); + this.Tbx_PLC_17_TargetTime.TabIndex = 3; + this.Tbx_PLC_17_TargetTime.Text = "50"; + // + // Tbx_PLC_11_Enginetype + // + this.Tbx_PLC_11_Enginetype.Location = new System.Drawing.Point(77, 108); + this.Tbx_PLC_11_Enginetype.Name = "Tbx_PLC_11_Enginetype"; + this.Tbx_PLC_11_Enginetype.Size = new System.Drawing.Size(85, 21); + this.Tbx_PLC_11_Enginetype.TabIndex = 3; + this.Tbx_PLC_11_Enginetype.Text = "H12C3-00001"; + // + // label3 + // + this.label3.AutoSize = true; + this.label3.Location = new System.Drawing.Point(192, 112); + this.label3.Name = "label3"; + this.label3.Size = new System.Drawing.Size(65, 12); + this.label3.TabIndex = 2; + this.label3.Text = "产品编号:"; + // + // label4 + // + this.label4.AutoSize = true; + this.label4.Location = new System.Drawing.Point(306, 138); + this.label4.Name = "label4"; + this.label4.Size = new System.Drawing.Size(65, 12); + this.label4.TabIndex = 2; + this.label4.Text = "托盘状态:"; + // + // label5 + // + this.label5.AutoSize = true; + this.label5.Location = new System.Drawing.Point(192, 138); + this.label5.Name = "label5"; + this.label5.Size = new System.Drawing.Size(65, 12); + this.label5.TabIndex = 2; + this.label5.Text = "托盘编号:"; + // + // label6 + // + this.label6.AutoSize = true; + this.label6.Location = new System.Drawing.Point(306, 164); + this.label6.Name = "label6"; + this.label6.Size = new System.Drawing.Size(65, 12); + this.label6.TabIndex = 2; + this.label6.Text = "返修标志:"; + // + // label7 + // + this.label7.AutoSize = true; + this.label7.Location = new System.Drawing.Point(192, 164); + this.label7.Name = "label7"; + this.label7.Size = new System.Drawing.Size(65, 12); + this.label7.TabIndex = 2; + this.label7.Text = "合格标志:"; + // + // label8 + // + this.label8.AutoSize = true; + this.label8.Location = new System.Drawing.Point(6, 138); + this.label8.Name = "label8"; + this.label8.Size = new System.Drawing.Size(65, 12); + this.label8.TabIndex = 2; + this.label8.Text = "机型代码:"; + // + // label18 + // + this.label18.AutoSize = true; + this.label18.Location = new System.Drawing.Point(6, 190); + this.label18.Name = "label18"; + this.label18.Size = new System.Drawing.Size(89, 12); + this.label18.TabIndex = 2; + this.label18.Text = "实际运行时间:"; + // + // label17 + // + this.label17.AutoSize = true; + this.label17.Location = new System.Drawing.Point(6, 164); + this.label17.Name = "label17"; + this.label17.Size = new System.Drawing.Size(89, 12); + this.label17.TabIndex = 2; + this.label17.Text = "目标运行时间:"; + // + // label9 + // + this.label9.AutoSize = true; + this.label9.Location = new System.Drawing.Point(6, 112); + this.label9.Name = "label9"; + this.label9.Size = new System.Drawing.Size(65, 12); + this.label9.TabIndex = 2; + this.label9.Text = "产品型号:"; + // + // groupBox3 + // + this.groupBox3.Location = new System.Drawing.Point(3, 100); + this.groupBox3.Name = "groupBox3"; + this.groupBox3.Size = new System.Drawing.Size(415, 1); + this.groupBox3.TabIndex = 1; + this.groupBox3.TabStop = false; + // + // Btn_PLC_1003_ShortFall + // + this.Btn_PLC_1003_ShortFall.Location = new System.Drawing.Point(87, 73); + this.Btn_PLC_1003_ShortFall.Name = "Btn_PLC_1003_ShortFall"; + this.Btn_PLC_1003_ShortFall.Size = new System.Drawing.Size(75, 23); + this.Btn_PLC_1003_ShortFall.TabIndex = 0; + this.Btn_PLC_1003_ShortFall.Text = "上料无件"; + this.Btn_PLC_1003_ShortFall.UseVisualStyleBackColor = true; + this.Btn_PLC_1003_ShortFall.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_PLC_19_MesRead + // + this.Btn_PLC_19_MesRead.Location = new System.Drawing.Point(330, 15); + this.Btn_PLC_19_MesRead.Name = "Btn_PLC_19_MesRead"; + this.Btn_PLC_19_MesRead.Size = new System.Drawing.Size(75, 23); + this.Btn_PLC_19_MesRead.TabIndex = 0; + this.Btn_PLC_19_MesRead.Text = "允许保存"; + this.Btn_PLC_19_MesRead.UseVisualStyleBackColor = true; + this.Btn_PLC_19_MesRead.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_PLC_1002_MachaineBreak + // + this.Btn_PLC_1002_MachaineBreak.Location = new System.Drawing.Point(330, 44); + this.Btn_PLC_1002_MachaineBreak.Name = "Btn_PLC_1002_MachaineBreak"; + this.Btn_PLC_1002_MachaineBreak.Size = new System.Drawing.Size(75, 23); + this.Btn_PLC_1002_MachaineBreak.TabIndex = 0; + this.Btn_PLC_1002_MachaineBreak.Text = "机床故障"; + this.Btn_PLC_1002_MachaineBreak.UseVisualStyleBackColor = true; + this.Btn_PLC_1002_MachaineBreak.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_PLC_59_FixOK + // + this.Btn_PLC_59_FixOK.Location = new System.Drawing.Point(249, 15); + this.Btn_PLC_59_FixOK.Name = "Btn_PLC_59_FixOK"; + this.Btn_PLC_59_FixOK.Size = new System.Drawing.Size(75, 23); + this.Btn_PLC_59_FixOK.TabIndex = 0; + this.Btn_PLC_59_FixOK.Text = "拧紧完成"; + this.Btn_PLC_59_FixOK.UseVisualStyleBackColor = true; + this.Btn_PLC_59_FixOK.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_PLC_1001_CycleStart + // + this.Btn_PLC_1001_CycleStart.Location = new System.Drawing.Point(168, 45); + this.Btn_PLC_1001_CycleStart.Name = "Btn_PLC_1001_CycleStart"; + this.Btn_PLC_1001_CycleStart.Size = new System.Drawing.Size(75, 23); + this.Btn_PLC_1001_CycleStart.TabIndex = 0; + this.Btn_PLC_1001_CycleStart.Text = "循环开始"; + this.Btn_PLC_1001_CycleStart.UseVisualStyleBackColor = true; + this.Btn_PLC_1001_CycleStart.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_PLC_1000_MachinePowerOn + // + this.Btn_PLC_1000_MachinePowerOn.Location = new System.Drawing.Point(249, 45); + this.Btn_PLC_1000_MachinePowerOn.Name = "Btn_PLC_1000_MachinePowerOn"; + this.Btn_PLC_1000_MachinePowerOn.Size = new System.Drawing.Size(75, 23); + this.Btn_PLC_1000_MachinePowerOn.TabIndex = 0; + this.Btn_PLC_1000_MachinePowerOn.Text = "机床上电"; + this.Btn_PLC_1000_MachinePowerOn.UseVisualStyleBackColor = true; + this.Btn_PLC_1000_MachinePowerOn.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_PLC_44_EngineTypeGetOver + // + this.Btn_PLC_44_EngineTypeGetOver.Location = new System.Drawing.Point(168, 15); + this.Btn_PLC_44_EngineTypeGetOver.Name = "Btn_PLC_44_EngineTypeGetOver"; + this.Btn_PLC_44_EngineTypeGetOver.Size = new System.Drawing.Size(75, 23); + this.Btn_PLC_44_EngineTypeGetOver.TabIndex = 0; + this.Btn_PLC_44_EngineTypeGetOver.Text = "传递机型"; + this.Btn_PLC_44_EngineTypeGetOver.UseVisualStyleBackColor = true; + this.Btn_PLC_44_EngineTypeGetOver.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_PLC_13_PalletIn + // + this.Btn_PLC_13_PalletIn.Location = new System.Drawing.Point(6, 73); + this.Btn_PLC_13_PalletIn.Name = "Btn_PLC_13_PalletIn"; + this.Btn_PLC_13_PalletIn.Size = new System.Drawing.Size(75, 23); + this.Btn_PLC_13_PalletIn.TabIndex = 0; + this.Btn_PLC_13_PalletIn.Text = "托盘到位"; + this.Btn_PLC_13_PalletIn.UseVisualStyleBackColor = true; + this.Btn_PLC_13_PalletIn.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_PLC_50_ApplyOffline + // + this.Btn_PLC_50_ApplyOffline.Location = new System.Drawing.Point(87, 44); + this.Btn_PLC_50_ApplyOffline.Name = "Btn_PLC_50_ApplyOffline"; + this.Btn_PLC_50_ApplyOffline.Size = new System.Drawing.Size(75, 23); + this.Btn_PLC_50_ApplyOffline.TabIndex = 0; + this.Btn_PLC_50_ApplyOffline.Text = "申请下线"; + this.Btn_PLC_50_ApplyOffline.UseVisualStyleBackColor = true; + this.Btn_PLC_50_ApplyOffline.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_PLC_43_PartLoad + // + this.Btn_PLC_43_PartLoad.Location = new System.Drawing.Point(87, 15); + this.Btn_PLC_43_PartLoad.Name = "Btn_PLC_43_PartLoad"; + this.Btn_PLC_43_PartLoad.Size = new System.Drawing.Size(75, 23); + this.Btn_PLC_43_PartLoad.TabIndex = 0; + this.Btn_PLC_43_PartLoad.Text = "申请上线"; + this.Btn_PLC_43_PartLoad.UseVisualStyleBackColor = true; + this.Btn_PLC_43_PartLoad.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_Write_PLC + // + this.Btn_Write_PLC.Location = new System.Drawing.Point(331, 185); + this.Btn_Write_PLC.Name = "Btn_Write_PLC"; + this.Btn_Write_PLC.Size = new System.Drawing.Size(75, 23); + this.Btn_Write_PLC.TabIndex = 0; + this.Btn_Write_PLC.Text = "写入 PLC"; + this.Btn_Write_PLC.UseVisualStyleBackColor = true; + this.Btn_Write_PLC.Click += new System.EventHandler(this.Btn_Write_PLC_Click); + // + // Btn_PLC_16_AllowReadCycleTime + // + this.Btn_PLC_16_AllowReadCycleTime.Location = new System.Drawing.Point(249, 74); + this.Btn_PLC_16_AllowReadCycleTime.Name = "Btn_PLC_16_AllowReadCycleTime"; + this.Btn_PLC_16_AllowReadCycleTime.Size = new System.Drawing.Size(75, 23); + this.Btn_PLC_16_AllowReadCycleTime.TabIndex = 0; + this.Btn_PLC_16_AllowReadCycleTime.Text = "允许读节拍"; + this.Btn_PLC_16_AllowReadCycleTime.UseVisualStyleBackColor = true; + this.Btn_PLC_16_AllowReadCycleTime.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_PLC_1004_Jam + // + this.Btn_PLC_1004_Jam.Location = new System.Drawing.Point(168, 73); + this.Btn_PLC_1004_Jam.Name = "Btn_PLC_1004_Jam"; + this.Btn_PLC_1004_Jam.Size = new System.Drawing.Size(75, 23); + this.Btn_PLC_1004_Jam.TabIndex = 0; + this.Btn_PLC_1004_Jam.Text = "下料堵塞"; + this.Btn_PLC_1004_Jam.UseVisualStyleBackColor = true; + this.Btn_PLC_1004_Jam.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_PLC_14_HeartBeat + // + this.Btn_PLC_14_HeartBeat.Location = new System.Drawing.Point(6, 44); + this.Btn_PLC_14_HeartBeat.Name = "Btn_PLC_14_HeartBeat"; + this.Btn_PLC_14_HeartBeat.Size = new System.Drawing.Size(75, 23); + this.Btn_PLC_14_HeartBeat.TabIndex = 0; + this.Btn_PLC_14_HeartBeat.Text = "心跳信号"; + this.Btn_PLC_14_HeartBeat.UseVisualStyleBackColor = true; + this.Btn_PLC_14_HeartBeat.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_PLC_2_WorkStart + // + this.Btn_PLC_2_WorkStart.Location = new System.Drawing.Point(6, 15); + this.Btn_PLC_2_WorkStart.Name = "Btn_PLC_2_WorkStart"; + this.Btn_PLC_2_WorkStart.Size = new System.Drawing.Size(75, 23); + this.Btn_PLC_2_WorkStart.TabIndex = 0; + this.Btn_PLC_2_WorkStart.Text = "工件到位"; + this.Btn_PLC_2_WorkStart.UseVisualStyleBackColor = true; + this.Btn_PLC_2_WorkStart.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // groupBox_MES + // + this.groupBox_MES.Controls.Add(this.checkBox_MESData_Display); + this.groupBox_MES.Controls.Add(this.Btn_Read_MES); + this.groupBox_MES.Controls.Add(this.Tbx_MES_88_SocketNum); + this.groupBox_MES.Controls.Add(this.Tbx_MES_77_FixOrder); + this.groupBox_MES.Controls.Add(this.Tbx_MES_74_EngineID); + this.groupBox_MES.Controls.Add(this.Tbx_MES_79_OnlineStatus); + this.groupBox_MES.Controls.Add(this.Tbx_MES_4_WorkStationRepairStr); + this.groupBox_MES.Controls.Add(this.Tbx_MES_93_RepairMark); + this.groupBox_MES.Controls.Add(this.label19); + this.groupBox_MES.Controls.Add(this.Tbx_MES_73_EngineTypeID); + this.groupBox_MES.Controls.Add(this.Tbx_MES_75_Enginetype); + this.groupBox_MES.Controls.Add(this.label10); + this.groupBox_MES.Controls.Add(this.label11); + this.groupBox_MES.Controls.Add(this.label12); + this.groupBox_MES.Controls.Add(this.label13); + this.groupBox_MES.Controls.Add(this.label14); + this.groupBox_MES.Controls.Add(this.label15); + this.groupBox_MES.Controls.Add(this.label16); + this.groupBox_MES.Controls.Add(this.groupBox5); + this.groupBox_MES.Controls.Add(this.Btn_MES_69_MachResult); + this.groupBox_MES.Controls.Add(this.Btn_MES_8_FalseGo); + this.groupBox_MES.Controls.Add(this.Btn_MES_67_FixOver); + this.groupBox_MES.Controls.Add(this.Btn_MES_7_WorkComplete); + this.groupBox_MES.Controls.Add(this.Btn_MES_53_OffLineOK); + this.groupBox_MES.Controls.Add(this.Btn_MES_66_AllowWork); + this.groupBox_MES.Controls.Add(this.Btn_MES_5_EngineTypeGetOver); + this.groupBox_MES.Controls.Add(this.Btn_MES_72_MobyClear); + this.groupBox_MES.Controls.Add(this.Btn_MES_54_ReadCycleTimeOK); + this.groupBox_MES.Controls.Add(this.Btn_MES_68_MachComplete); + this.groupBox_MES.Controls.Add(this.Btn_MES_52_ResetEquipment); + this.groupBox_MES.Controls.Add(this.Btn_MES_6_PalletGo); + this.groupBox_MES.Controls.Add(this.Btn_Write_MES); + this.groupBox_MES.Controls.Add(this.Btn_MES_20_MesReadOver); + this.groupBox_MES.Controls.Add(this.Btn_MES_71_IsAuto); + this.groupBox_MES.Controls.Add(this.Btn_MES_51_ConfirmOkGo); + this.groupBox_MES.Controls.Add(this.Btn_MES_15_HeartBeat); + this.groupBox_MES.Location = new System.Drawing.Point(12, 388); + this.groupBox_MES.Name = "groupBox_MES"; + this.groupBox_MES.Size = new System.Drawing.Size(423, 245); + this.groupBox_MES.TabIndex = 0; + this.groupBox_MES.TabStop = false; + this.groupBox_MES.Text = "MES"; + // + // checkBox_MESData_Display + // + this.checkBox_MESData_Display.AutoSize = true; + this.checkBox_MESData_Display.Checked = true; + this.checkBox_MESData_Display.CheckState = System.Windows.Forms.CheckState.Checked; + this.checkBox_MESData_Display.Location = new System.Drawing.Point(192, 217); + this.checkBox_MESData_Display.Name = "checkBox_MESData_Display"; + this.checkBox_MESData_Display.Size = new System.Drawing.Size(48, 16); + this.checkBox_MESData_Display.TabIndex = 7; + this.checkBox_MESData_Display.Text = "同步"; + this.checkBox_MESData_Display.UseVisualStyleBackColor = true; + // + // Btn_Read_MES + // + this.Btn_Read_MES.Location = new System.Drawing.Point(249, 214); + this.Btn_Read_MES.Name = "Btn_Read_MES"; + this.Btn_Read_MES.Size = new System.Drawing.Size(75, 23); + this.Btn_Read_MES.TabIndex = 6; + this.Btn_Read_MES.Text = "读取 MES"; + this.Btn_Read_MES.UseVisualStyleBackColor = true; + this.Btn_Read_MES.Click += new System.EventHandler(this.Btn_Read_MES_Click); + // + // Tbx_MES_88_SocketNum + // + this.Tbx_MES_88_SocketNum.Location = new System.Drawing.Point(373, 189); + this.Tbx_MES_88_SocketNum.Name = "Tbx_MES_88_SocketNum"; + this.Tbx_MES_88_SocketNum.Size = new System.Drawing.Size(33, 21); + this.Tbx_MES_88_SocketNum.TabIndex = 3; + this.Tbx_MES_88_SocketNum.Text = "1"; + // + // Tbx_MES_77_FixOrder + // + this.Tbx_MES_77_FixOrder.Location = new System.Drawing.Point(259, 189); + this.Tbx_MES_77_FixOrder.Name = "Tbx_MES_77_FixOrder"; + this.Tbx_MES_77_FixOrder.Size = new System.Drawing.Size(29, 21); + this.Tbx_MES_77_FixOrder.TabIndex = 3; + this.Tbx_MES_77_FixOrder.Text = "1"; + // + // Tbx_MES_74_EngineID + // + this.Tbx_MES_74_EngineID.Location = new System.Drawing.Point(259, 163); + this.Tbx_MES_74_EngineID.Name = "Tbx_MES_74_EngineID"; + this.Tbx_MES_74_EngineID.Size = new System.Drawing.Size(147, 21); + this.Tbx_MES_74_EngineID.TabIndex = 3; + this.Tbx_MES_74_EngineID.Text = "H12C3-00001001"; + // + // Tbx_MES_79_OnlineStatus + // + this.Tbx_MES_79_OnlineStatus.Location = new System.Drawing.Point(373, 136); + this.Tbx_MES_79_OnlineStatus.Name = "Tbx_MES_79_OnlineStatus"; + this.Tbx_MES_79_OnlineStatus.Size = new System.Drawing.Size(33, 21); + this.Tbx_MES_79_OnlineStatus.TabIndex = 3; + this.Tbx_MES_79_OnlineStatus.Text = "1"; + // + // Tbx_MES_4_WorkStationRepairStr + // + this.Tbx_MES_4_WorkStationRepairStr.Location = new System.Drawing.Point(77, 137); + this.Tbx_MES_4_WorkStationRepairStr.Name = "Tbx_MES_4_WorkStationRepairStr"; + this.Tbx_MES_4_WorkStationRepairStr.Size = new System.Drawing.Size(223, 21); + this.Tbx_MES_4_WorkStationRepairStr.TabIndex = 3; + this.Tbx_MES_4_WorkStationRepairStr.Text = "1111111111111111111"; + // + // Tbx_MES_93_RepairMark + // + this.Tbx_MES_93_RepairMark.Location = new System.Drawing.Point(77, 215); + this.Tbx_MES_93_RepairMark.Name = "Tbx_MES_93_RepairMark"; + this.Tbx_MES_93_RepairMark.Size = new System.Drawing.Size(85, 21); + this.Tbx_MES_93_RepairMark.TabIndex = 3; + this.Tbx_MES_93_RepairMark.Text = "0"; + // + // label19 + // + this.label19.AutoSize = true; + this.label19.Location = new System.Drawing.Point(6, 141); + this.label19.Name = "label19"; + this.label19.Size = new System.Drawing.Size(65, 12); + this.label19.TabIndex = 2; + this.label19.Text = "返修工位:"; + // + // Tbx_MES_73_EngineTypeID + // + this.Tbx_MES_73_EngineTypeID.Location = new System.Drawing.Point(77, 189); + this.Tbx_MES_73_EngineTypeID.Name = "Tbx_MES_73_EngineTypeID"; + this.Tbx_MES_73_EngineTypeID.Size = new System.Drawing.Size(85, 21); + this.Tbx_MES_73_EngineTypeID.TabIndex = 3; + this.Tbx_MES_73_EngineTypeID.Text = "1"; + // + // Tbx_MES_75_Enginetype + // + this.Tbx_MES_75_Enginetype.Location = new System.Drawing.Point(77, 163); + this.Tbx_MES_75_Enginetype.Name = "Tbx_MES_75_Enginetype"; + this.Tbx_MES_75_Enginetype.Size = new System.Drawing.Size(85, 21); + this.Tbx_MES_75_Enginetype.TabIndex = 3; + this.Tbx_MES_75_Enginetype.Text = "H12C3-00001"; + // + // label10 + // + this.label10.AutoSize = true; + this.label10.Location = new System.Drawing.Point(192, 167); + this.label10.Name = "label10"; + this.label10.Size = new System.Drawing.Size(65, 12); + this.label10.TabIndex = 2; + this.label10.Text = "产品编号:"; + // + // label11 + // + this.label11.AutoSize = true; + this.label11.Location = new System.Drawing.Point(306, 193); + this.label11.Name = "label11"; + this.label11.Size = new System.Drawing.Size(65, 12); + this.label11.TabIndex = 2; + this.label11.Text = "套筒编号:"; + // + // label12 + // + this.label12.AutoSize = true; + this.label12.Location = new System.Drawing.Point(192, 193); + this.label12.Name = "label12"; + this.label12.Size = new System.Drawing.Size(65, 12); + this.label12.TabIndex = 2; + this.label12.Text = "拧紧序号:"; + // + // label13 + // + this.label13.AutoSize = true; + this.label13.Location = new System.Drawing.Point(306, 140); + this.label13.Name = "label13"; + this.label13.Size = new System.Drawing.Size(65, 12); + this.label13.TabIndex = 2; + this.label13.Text = "工位状态:"; + // + // label14 + // + this.label14.AutoSize = true; + this.label14.Location = new System.Drawing.Point(6, 219); + this.label14.Name = "label14"; + this.label14.Size = new System.Drawing.Size(65, 12); + this.label14.TabIndex = 2; + this.label14.Text = "返修标志:"; + // + // label15 + // + this.label15.AutoSize = true; + this.label15.Location = new System.Drawing.Point(6, 193); + this.label15.Name = "label15"; + this.label15.Size = new System.Drawing.Size(65, 12); + this.label15.TabIndex = 2; + this.label15.Text = "机型代码:"; + // + // label16 + // + this.label16.AutoSize = true; + this.label16.Location = new System.Drawing.Point(6, 167); + this.label16.Name = "label16"; + this.label16.Size = new System.Drawing.Size(65, 12); + this.label16.TabIndex = 2; + this.label16.Text = "产品型号:"; + // + // groupBox5 + // + this.groupBox5.Location = new System.Drawing.Point(3, 128); + this.groupBox5.Name = "groupBox5"; + this.groupBox5.Size = new System.Drawing.Size(415, 1); + this.groupBox5.TabIndex = 1; + this.groupBox5.TabStop = false; + // + // Btn_MES_69_MachResult + // + this.Btn_MES_69_MachResult.Location = new System.Drawing.Point(87, 73); + this.Btn_MES_69_MachResult.Name = "Btn_MES_69_MachResult"; + this.Btn_MES_69_MachResult.Size = new System.Drawing.Size(75, 23); + this.Btn_MES_69_MachResult.TabIndex = 0; + this.Btn_MES_69_MachResult.Text = "匹配结果"; + this.Btn_MES_69_MachResult.UseVisualStyleBackColor = true; + this.Btn_MES_69_MachResult.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_MES_8_FalseGo + // + this.Btn_MES_8_FalseGo.Location = new System.Drawing.Point(168, 44); + this.Btn_MES_8_FalseGo.Name = "Btn_MES_8_FalseGo"; + this.Btn_MES_8_FalseGo.Size = new System.Drawing.Size(75, 23); + this.Btn_MES_8_FalseGo.TabIndex = 0; + this.Btn_MES_8_FalseGo.Text = "不合格放行"; + this.Btn_MES_8_FalseGo.UseVisualStyleBackColor = true; + this.Btn_MES_8_FalseGo.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_MES_67_FixOver + // + this.Btn_MES_67_FixOver.Location = new System.Drawing.Point(168, 15); + this.Btn_MES_67_FixOver.Name = "Btn_MES_67_FixOver"; + this.Btn_MES_67_FixOver.Size = new System.Drawing.Size(75, 23); + this.Btn_MES_67_FixOver.TabIndex = 0; + this.Btn_MES_67_FixOver.Text = "完成确认"; + this.Btn_MES_67_FixOver.UseVisualStyleBackColor = true; + this.Btn_MES_67_FixOver.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_MES_7_WorkComplete + // + this.Btn_MES_7_WorkComplete.Location = new System.Drawing.Point(330, 15); + this.Btn_MES_7_WorkComplete.Name = "Btn_MES_7_WorkComplete"; + this.Btn_MES_7_WorkComplete.Size = new System.Drawing.Size(75, 23); + this.Btn_MES_7_WorkComplete.TabIndex = 0; + this.Btn_MES_7_WorkComplete.Text = "工作完成"; + this.Btn_MES_7_WorkComplete.UseVisualStyleBackColor = true; + this.Btn_MES_7_WorkComplete.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_MES_53_OffLineOK + // + this.Btn_MES_53_OffLineOK.Location = new System.Drawing.Point(249, 44); + this.Btn_MES_53_OffLineOK.Name = "Btn_MES_53_OffLineOK"; + this.Btn_MES_53_OffLineOK.Size = new System.Drawing.Size(75, 23); + this.Btn_MES_53_OffLineOK.TabIndex = 0; + this.Btn_MES_53_OffLineOK.Text = "下线完成"; + this.Btn_MES_53_OffLineOK.UseVisualStyleBackColor = true; + this.Btn_MES_53_OffLineOK.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_MES_66_AllowWork + // + this.Btn_MES_66_AllowWork.Location = new System.Drawing.Point(87, 15); + this.Btn_MES_66_AllowWork.Name = "Btn_MES_66_AllowWork"; + this.Btn_MES_66_AllowWork.Size = new System.Drawing.Size(75, 23); + this.Btn_MES_66_AllowWork.TabIndex = 0; + this.Btn_MES_66_AllowWork.Text = "允许工作"; + this.Btn_MES_66_AllowWork.UseVisualStyleBackColor = true; + this.Btn_MES_66_AllowWork.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_MES_5_EngineTypeGetOver + // + this.Btn_MES_5_EngineTypeGetOver.Location = new System.Drawing.Point(6, 15); + this.Btn_MES_5_EngineTypeGetOver.Name = "Btn_MES_5_EngineTypeGetOver"; + this.Btn_MES_5_EngineTypeGetOver.Size = new System.Drawing.Size(75, 23); + this.Btn_MES_5_EngineTypeGetOver.TabIndex = 0; + this.Btn_MES_5_EngineTypeGetOver.Text = "传递机型"; + this.Btn_MES_5_EngineTypeGetOver.UseVisualStyleBackColor = true; + this.Btn_MES_5_EngineTypeGetOver.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_MES_72_MobyClear + // + this.Btn_MES_72_MobyClear.Location = new System.Drawing.Point(249, 73); + this.Btn_MES_72_MobyClear.Name = "Btn_MES_72_MobyClear"; + this.Btn_MES_72_MobyClear.Size = new System.Drawing.Size(75, 23); + this.Btn_MES_72_MobyClear.TabIndex = 0; + this.Btn_MES_72_MobyClear.Text = "清空Moby"; + this.Btn_MES_72_MobyClear.UseVisualStyleBackColor = true; + this.Btn_MES_72_MobyClear.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_MES_54_ReadCycleTimeOK + // + this.Btn_MES_54_ReadCycleTimeOK.Location = new System.Drawing.Point(330, 73); + this.Btn_MES_54_ReadCycleTimeOK.Name = "Btn_MES_54_ReadCycleTimeOK"; + this.Btn_MES_54_ReadCycleTimeOK.Size = new System.Drawing.Size(75, 23); + this.Btn_MES_54_ReadCycleTimeOK.TabIndex = 0; + this.Btn_MES_54_ReadCycleTimeOK.Text = "读节拍完成"; + this.Btn_MES_54_ReadCycleTimeOK.UseVisualStyleBackColor = true; + this.Btn_MES_54_ReadCycleTimeOK.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_MES_68_MachComplete + // + this.Btn_MES_68_MachComplete.Location = new System.Drawing.Point(6, 73); + this.Btn_MES_68_MachComplete.Name = "Btn_MES_68_MachComplete"; + this.Btn_MES_68_MachComplete.Size = new System.Drawing.Size(75, 23); + this.Btn_MES_68_MachComplete.TabIndex = 0; + this.Btn_MES_68_MachComplete.Text = "匹配完成"; + this.Btn_MES_68_MachComplete.UseVisualStyleBackColor = true; + this.Btn_MES_68_MachComplete.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_MES_52_ResetEquipment + // + this.Btn_MES_52_ResetEquipment.Location = new System.Drawing.Point(6, 102); + this.Btn_MES_52_ResetEquipment.Name = "Btn_MES_52_ResetEquipment"; + this.Btn_MES_52_ResetEquipment.Size = new System.Drawing.Size(75, 23); + this.Btn_MES_52_ResetEquipment.TabIndex = 0; + this.Btn_MES_52_ResetEquipment.Text = "复位设备"; + this.Btn_MES_52_ResetEquipment.UseVisualStyleBackColor = true; + this.Btn_MES_52_ResetEquipment.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_MES_6_PalletGo + // + this.Btn_MES_6_PalletGo.Location = new System.Drawing.Point(330, 44); + this.Btn_MES_6_PalletGo.Name = "Btn_MES_6_PalletGo"; + this.Btn_MES_6_PalletGo.Size = new System.Drawing.Size(75, 23); + this.Btn_MES_6_PalletGo.TabIndex = 0; + this.Btn_MES_6_PalletGo.Text = "空托盘放行"; + this.Btn_MES_6_PalletGo.UseVisualStyleBackColor = true; + this.Btn_MES_6_PalletGo.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_Write_MES + // + this.Btn_Write_MES.Location = new System.Drawing.Point(331, 214); + this.Btn_Write_MES.Name = "Btn_Write_MES"; + this.Btn_Write_MES.Size = new System.Drawing.Size(75, 23); + this.Btn_Write_MES.TabIndex = 0; + this.Btn_Write_MES.Text = "写入 MES"; + this.Btn_Write_MES.UseVisualStyleBackColor = true; + this.Btn_Write_MES.Click += new System.EventHandler(this.Btn_Write_MES_Click); + // + // Btn_MES_20_MesReadOver + // + this.Btn_MES_20_MesReadOver.Location = new System.Drawing.Point(249, 15); + this.Btn_MES_20_MesReadOver.Name = "Btn_MES_20_MesReadOver"; + this.Btn_MES_20_MesReadOver.Size = new System.Drawing.Size(75, 23); + this.Btn_MES_20_MesReadOver.TabIndex = 0; + this.Btn_MES_20_MesReadOver.Text = "保存完成"; + this.Btn_MES_20_MesReadOver.UseVisualStyleBackColor = true; + this.Btn_MES_20_MesReadOver.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_MES_71_IsAuto + // + this.Btn_MES_71_IsAuto.Location = new System.Drawing.Point(168, 73); + this.Btn_MES_71_IsAuto.Name = "Btn_MES_71_IsAuto"; + this.Btn_MES_71_IsAuto.Size = new System.Drawing.Size(75, 23); + this.Btn_MES_71_IsAuto.TabIndex = 0; + this.Btn_MES_71_IsAuto.Text = "自动手动"; + this.Btn_MES_71_IsAuto.UseVisualStyleBackColor = true; + this.Btn_MES_71_IsAuto.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_MES_51_ConfirmOkGo + // + this.Btn_MES_51_ConfirmOkGo.Location = new System.Drawing.Point(87, 44); + this.Btn_MES_51_ConfirmOkGo.Name = "Btn_MES_51_ConfirmOkGo"; + this.Btn_MES_51_ConfirmOkGo.Size = new System.Drawing.Size(75, 23); + this.Btn_MES_51_ConfirmOkGo.TabIndex = 0; + this.Btn_MES_51_ConfirmOkGo.Text = "合格放行"; + this.Btn_MES_51_ConfirmOkGo.UseVisualStyleBackColor = true; + this.Btn_MES_51_ConfirmOkGo.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_MES_15_HeartBeat + // + this.Btn_MES_15_HeartBeat.Location = new System.Drawing.Point(6, 44); + this.Btn_MES_15_HeartBeat.Name = "Btn_MES_15_HeartBeat"; + this.Btn_MES_15_HeartBeat.Size = new System.Drawing.Size(75, 23); + this.Btn_MES_15_HeartBeat.TabIndex = 0; + this.Btn_MES_15_HeartBeat.Text = "心跳信号"; + this.Btn_MES_15_HeartBeat.UseVisualStyleBackColor = true; + this.Btn_MES_15_HeartBeat.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // groupBox_WorkStationQuality + // + this.groupBox_WorkStationQuality.Controls.Add(this.groupBox2); + this.groupBox_WorkStationQuality.Controls.Add(this.groupBox1); + this.groupBox_WorkStationQuality.Controls.Add(this.cb_QdData); + this.groupBox_WorkStationQuality.Controls.Add(this.cb_MonitorData); + this.groupBox_WorkStationQuality.Controls.Add(this.listView_ShowQualityData); + this.groupBox_WorkStationQuality.Controls.Add(this.button_ReadData); + this.groupBox_WorkStationQuality.Location = new System.Drawing.Point(8, 29); + this.groupBox_WorkStationQuality.Name = "groupBox_WorkStationQuality"; + this.groupBox_WorkStationQuality.Size = new System.Drawing.Size(535, 593); + this.groupBox_WorkStationQuality.TabIndex = 1472; + this.groupBox_WorkStationQuality.TabStop = false; + this.groupBox_WorkStationQuality.Text = "质量数据"; + // + // groupBox2 + // + this.groupBox2.Controls.Add(this.textBox_Copy_Item); + this.groupBox2.Controls.Add(this.textBox_Copy_TagID); + this.groupBox2.Controls.Add(this.textBox_Base_Item); + this.groupBox2.Controls.Add(this.textBox_Base_TagID); + this.groupBox2.Controls.Add(this.radioButton_Copy); + this.groupBox2.Controls.Add(this.radioButton_Base); + this.groupBox2.Location = new System.Drawing.Point(10, 60); + this.groupBox2.Name = "groupBox2"; + this.groupBox2.Size = new System.Drawing.Size(498, 78); + this.groupBox2.TabIndex = 1474; + this.groupBox2.TabStop = false; + this.groupBox2.Text = "当前选择的信号"; + // + // textBox_Copy_Item + // + this.textBox_Copy_Item.Location = new System.Drawing.Point(283, 47); + this.textBox_Copy_Item.Name = "textBox_Copy_Item"; + this.textBox_Copy_Item.ReadOnly = true; + this.textBox_Copy_Item.Size = new System.Drawing.Size(186, 21); + this.textBox_Copy_Item.TabIndex = 1; + // + // textBox_Copy_TagID + // + this.textBox_Copy_TagID.Location = new System.Drawing.Point(79, 47); + this.textBox_Copy_TagID.Name = "textBox_Copy_TagID"; + this.textBox_Copy_TagID.ReadOnly = true; + this.textBox_Copy_TagID.Size = new System.Drawing.Size(186, 21); + this.textBox_Copy_TagID.TabIndex = 1; + // + // textBox_Base_Item + // + this.textBox_Base_Item.Location = new System.Drawing.Point(283, 20); + this.textBox_Base_Item.Name = "textBox_Base_Item"; + this.textBox_Base_Item.ReadOnly = true; + this.textBox_Base_Item.Size = new System.Drawing.Size(186, 21); + this.textBox_Base_Item.TabIndex = 1; + // + // textBox_Base_TagID + // + this.textBox_Base_TagID.Location = new System.Drawing.Point(79, 20); + this.textBox_Base_TagID.Name = "textBox_Base_TagID"; + this.textBox_Base_TagID.ReadOnly = true; + this.textBox_Base_TagID.Size = new System.Drawing.Size(186, 21); + this.textBox_Base_TagID.TabIndex = 1; + // + // radioButton_Copy + // + this.radioButton_Copy.AutoSize = true; + this.radioButton_Copy.Enabled = false; + this.radioButton_Copy.Location = new System.Drawing.Point(7, 50); + this.radioButton_Copy.Name = "radioButton_Copy"; + this.radioButton_Copy.Size = new System.Drawing.Size(71, 16); + this.radioButton_Copy.TabIndex = 0; + this.radioButton_Copy.Text = "拷贝信号"; + this.radioButton_Copy.UseVisualStyleBackColor = true; + // + // radioButton_Base + // + this.radioButton_Base.AutoSize = true; + this.radioButton_Base.Checked = true; + this.radioButton_Base.Enabled = false; + this.radioButton_Base.Location = new System.Drawing.Point(7, 20); + this.radioButton_Base.Name = "radioButton_Base"; + this.radioButton_Base.Size = new System.Drawing.Size(71, 16); + this.radioButton_Base.TabIndex = 0; + this.radioButton_Base.TabStop = true; + this.radioButton_Base.Text = "基本信号"; + this.radioButton_Base.UseVisualStyleBackColor = true; + // + // groupBox1 + // + this.groupBox1.Controls.Add(this.radioButton_MQTT); + this.groupBox1.Controls.Add(this.radioButton_PlcSignl_Copy); + this.groupBox1.Controls.Add(this.radioButton_PartCodeSanner); + this.groupBox1.Controls.Add(this.radioButton_PlcSignl); + this.groupBox1.Location = new System.Drawing.Point(182, 8); + this.groupBox1.Name = "groupBox1"; + this.groupBox1.Size = new System.Drawing.Size(326, 46); + this.groupBox1.TabIndex = 1473; + this.groupBox1.TabStop = false; + this.groupBox1.Enter += new System.EventHandler(this.groupBox1_Enter); + // + // radioButton_MQTT + // + this.radioButton_MQTT.AutoSize = true; + this.radioButton_MQTT.Location = new System.Drawing.Point(222, 18); + this.radioButton_MQTT.Name = "radioButton_MQTT"; + this.radioButton_MQTT.Size = new System.Drawing.Size(47, 16); + this.radioButton_MQTT.TabIndex = 1; + this.radioButton_MQTT.TabStop = true; + this.radioButton_MQTT.Text = "MQTT"; + this.radioButton_MQTT.UseVisualStyleBackColor = true; + this.radioButton_MQTT.Click += new System.EventHandler(this.radioButton_MQTT_Click); + // + // radioButton_PlcSignl_Copy + // + this.radioButton_PlcSignl_Copy.AutoSize = true; + this.radioButton_PlcSignl_Copy.Location = new System.Drawing.Point(145, 18); + this.radioButton_PlcSignl_Copy.Name = "radioButton_PlcSignl_Copy"; + this.radioButton_PlcSignl_Copy.Size = new System.Drawing.Size(71, 16); + this.radioButton_PlcSignl_Copy.TabIndex = 1; + this.radioButton_PlcSignl_Copy.TabStop = true; + this.radioButton_PlcSignl_Copy.Text = "拷贝信号"; + this.radioButton_PlcSignl_Copy.UseVisualStyleBackColor = true; + this.radioButton_PlcSignl_Copy.Click += new System.EventHandler(this.radioButton_PlcSignl_Copy_Click); + // + // radioButton_PartCodeSanner + // + this.radioButton_PartCodeSanner.AutoSize = true; + this.radioButton_PartCodeSanner.Location = new System.Drawing.Point(68, 18); + this.radioButton_PartCodeSanner.Name = "radioButton_PartCodeSanner"; + this.radioButton_PartCodeSanner.Size = new System.Drawing.Size(71, 16); + this.radioButton_PartCodeSanner.TabIndex = 0; + this.radioButton_PartCodeSanner.Text = "物料扫描"; + this.radioButton_PartCodeSanner.UseVisualStyleBackColor = true; + this.radioButton_PartCodeSanner.Click += new System.EventHandler(this.radioButton_PartCodeSanner_Click); + // + // radioButton_PlcSignl + // + this.radioButton_PlcSignl.AutoSize = true; + this.radioButton_PlcSignl.Checked = true; + this.radioButton_PlcSignl.Location = new System.Drawing.Point(6, 19); + this.radioButton_PlcSignl.Name = "radioButton_PlcSignl"; + this.radioButton_PlcSignl.Size = new System.Drawing.Size(65, 16); + this.radioButton_PlcSignl.TabIndex = 0; + this.radioButton_PlcSignl.TabStop = true; + this.radioButton_PlcSignl.Text = "PLC信号"; + this.radioButton_PlcSignl.UseVisualStyleBackColor = true; + this.radioButton_PlcSignl.Click += new System.EventHandler(this.radioButton_PlcSignl_Click); + // + // cb_QdData + // + this.cb_QdData.AutoSize = true; + this.cb_QdData.Enabled = false; + this.cb_QdData.Location = new System.Drawing.Point(10, 40); + this.cb_QdData.Name = "cb_QdData"; + this.cb_QdData.Size = new System.Drawing.Size(72, 16); + this.cb_QdData.TabIndex = 1472; + this.cb_QdData.Text = "质量数据"; + this.cb_QdData.UseVisualStyleBackColor = true; + // + // cb_MonitorData + // + this.cb_MonitorData.AutoSize = true; + this.cb_MonitorData.Location = new System.Drawing.Point(10, 20); + this.cb_MonitorData.Name = "cb_MonitorData"; + this.cb_MonitorData.Size = new System.Drawing.Size(72, 16); + this.cb_MonitorData.TabIndex = 1472; + this.cb_MonitorData.Text = "监控数据"; + this.cb_MonitorData.UseVisualStyleBackColor = true; + this.cb_MonitorData.Click += new System.EventHandler(this.cb_MonitorData_Click); + // + // listView_ShowQualityData + // + this.listView_ShowQualityData.AllowColumnReorder = true; + this.listView_ShowQualityData.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { + this.columnHeader4, + this.columnHeader2, + this.columnHeader3, + this.columnHeader1, + this.columnHeader5}); + this.listView_ShowQualityData.FullRowSelect = true; + this.listView_ShowQualityData.GridLines = true; + this.listView_ShowQualityData.HideSelection = false; + this.listView_ShowQualityData.Location = new System.Drawing.Point(6, 151); + this.listView_ShowQualityData.Margin = new System.Windows.Forms.Padding(2); + this.listView_ShowQualityData.MultiSelect = false; + this.listView_ShowQualityData.Name = "listView_ShowQualityData"; + this.listView_ShowQualityData.ShowItemToolTips = true; + this.listView_ShowQualityData.Size = new System.Drawing.Size(502, 437); + this.listView_ShowQualityData.TabIndex = 1469; + this.listView_ShowQualityData.UseCompatibleStateImageBehavior = false; + this.listView_ShowQualityData.View = System.Windows.Forms.View.Details; + this.listView_ShowQualityData.SelectedIndexChanged += new System.EventHandler(this.listView_ShowQualityData_SelectedIndexChanged); + this.listView_ShowQualityData.Click += new System.EventHandler(this.listView_ShowQualityData_Click); + this.listView_ShowQualityData.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(this.listView_ShowQualityData_MouseDoubleClick); + // + // columnHeader4 + // + this.columnHeader4.DisplayIndex = 3; + this.columnHeader4.Text = "工位号"; + this.columnHeader4.Width = 70; + // + // columnHeader2 + // + this.columnHeader2.Text = "测量项目"; + this.columnHeader2.Width = 150; + // + // columnHeader3 + // + this.columnHeader3.Text = "值"; + this.columnHeader3.Width = 180; + // + // columnHeader1 + // + this.columnHeader1.DisplayIndex = 0; + this.columnHeader1.Text = "TagID"; + this.columnHeader1.Width = 70; + // + // columnHeader5 + // + this.columnHeader5.Text = "TagTypeCodeID"; + // + // contextMenuStrip_MIS + // + this.contextMenuStrip_MIS.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { + this.toolStripMenuItem_Show, + this.toolStripMenuItem_Hide, + this.toolStripMenuItem_Exit}); + this.contextMenuStrip_MIS.Name = "contextMenuStrip_MIS"; + this.contextMenuStrip_MIS.Size = new System.Drawing.Size(101, 70); + // + // toolStripMenuItem_Show + // + this.toolStripMenuItem_Show.Name = "toolStripMenuItem_Show"; + this.toolStripMenuItem_Show.Size = new System.Drawing.Size(100, 22); + this.toolStripMenuItem_Show.Text = "显示"; + this.toolStripMenuItem_Show.Click += new System.EventHandler(this.toolStripMenuItem_Show_Click); + // + // toolStripMenuItem_Hide + // + this.toolStripMenuItem_Hide.Name = "toolStripMenuItem_Hide"; + this.toolStripMenuItem_Hide.Size = new System.Drawing.Size(100, 22); + this.toolStripMenuItem_Hide.Text = "隐藏"; + this.toolStripMenuItem_Hide.Click += new System.EventHandler(this.toolStripMenuItem_Hide_Click); + // + // toolStripMenuItem_Exit + // + this.toolStripMenuItem_Exit.Name = "toolStripMenuItem_Exit"; + this.toolStripMenuItem_Exit.Size = new System.Drawing.Size(100, 22); + this.toolStripMenuItem_Exit.Text = "退出"; + this.toolStripMenuItem_Exit.Click += new System.EventHandler(this.toolStripMenuItem_Exit_Click); + // + // menuStrip_Main + // + this.menuStrip_Main.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { + this.ToolStripMenuItem_Start, + this.ToolStripMenuItem_Visual, + this.ToolStripMenuItem_Help}); + this.menuStrip_Main.Location = new System.Drawing.Point(0, 0); + this.menuStrip_Main.Name = "menuStrip_Main"; + this.menuStrip_Main.Size = new System.Drawing.Size(1008, 25); + this.menuStrip_Main.TabIndex = 1474; + this.menuStrip_Main.Text = "开始"; + // + // ToolStripMenuItem_Start + // + this.ToolStripMenuItem_Start.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { + this.ToolStripMenuItem_PrintScreen, + this.ToolStripMenuItem_SaveLog, + this.ToolStripMenuItem_LockForm, + this.ToolStripMenuItem_Quit}); + this.ToolStripMenuItem_Start.Name = "ToolStripMenuItem_Start"; + this.ToolStripMenuItem_Start.Size = new System.Drawing.Size(59, 21); + this.ToolStripMenuItem_Start.Text = "开始(&S)"; + // + // ToolStripMenuItem_PrintScreen + // + this.ToolStripMenuItem_PrintScreen.Name = "ToolStripMenuItem_PrintScreen"; + this.ToolStripMenuItem_PrintScreen.Size = new System.Drawing.Size(157, 22); + this.ToolStripMenuItem_PrintScreen.Text = "屏幕快照(&C)"; + this.ToolStripMenuItem_PrintScreen.Click += new System.EventHandler(this.ToolStripMenuItem_PrintScreen_Click); + // + // ToolStripMenuItem_SaveLog + // + this.ToolStripMenuItem_SaveLog.Name = "ToolStripMenuItem_SaveLog"; + this.ToolStripMenuItem_SaveLog.Size = new System.Drawing.Size(157, 22); + this.ToolStripMenuItem_SaveLog.Text = "保存PLC消息(&I)"; + this.ToolStripMenuItem_SaveLog.Click += new System.EventHandler(this.ToolStripMenuItem_SaveLog_Click); + // + // ToolStripMenuItem_LockForm + // + this.ToolStripMenuItem_LockForm.Name = "ToolStripMenuItem_LockForm"; + this.ToolStripMenuItem_LockForm.Size = new System.Drawing.Size(157, 22); + this.ToolStripMenuItem_LockForm.Text = "锁定(&L)"; + this.ToolStripMenuItem_LockForm.Click += new System.EventHandler(this.ToolStripMenuItem_LockForm_Click); + // + // ToolStripMenuItem_Quit + // + this.ToolStripMenuItem_Quit.Name = "ToolStripMenuItem_Quit"; + this.ToolStripMenuItem_Quit.Size = new System.Drawing.Size(157, 22); + this.ToolStripMenuItem_Quit.Text = "退出(&X)"; + this.ToolStripMenuItem_Quit.Click += new System.EventHandler(this.ToolStripMenuItem_Quit_Click); + // + // ToolStripMenuItem_Visual + // + this.ToolStripMenuItem_Visual.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { + this.ToolStripMenuItem_VWSStatus, + this.EToolStripMenuItem_EquipAlarm, + this.ToolStripMenuItem_Assembly, + this.TSM_DebugPage}); + this.ToolStripMenuItem_Visual.Name = "ToolStripMenuItem_Visual"; + this.ToolStripMenuItem_Visual.Size = new System.Drawing.Size(60, 21); + this.ToolStripMenuItem_Visual.Text = "窗口(&V)"; + // + // ToolStripMenuItem_VWSStatus + // + this.ToolStripMenuItem_VWSStatus.Name = "ToolStripMenuItem_VWSStatus"; + this.ToolStripMenuItem_VWSStatus.Size = new System.Drawing.Size(152, 22); + this.ToolStripMenuItem_VWSStatus.Text = "工位状态(&T)"; + this.ToolStripMenuItem_VWSStatus.Click += new System.EventHandler(this.ToolStripMenuItem_VWSStatus_Click); + // + // EToolStripMenuItem_EquipAlarm + // + this.EToolStripMenuItem_EquipAlarm.Checked = true; + this.EToolStripMenuItem_EquipAlarm.CheckState = System.Windows.Forms.CheckState.Checked; + this.EToolStripMenuItem_EquipAlarm.Name = "EToolStripMenuItem_EquipAlarm"; + this.EToolStripMenuItem_EquipAlarm.Size = new System.Drawing.Size(152, 22); + this.EToolStripMenuItem_EquipAlarm.Text = "设备报警(&E)"; + this.EToolStripMenuItem_EquipAlarm.Click += new System.EventHandler(this.EToolStripMenuItem_EquipAlarm_Click); + // + // ToolStripMenuItem_Assembly + // + this.ToolStripMenuItem_Assembly.Name = "ToolStripMenuItem_Assembly"; + this.ToolStripMenuItem_Assembly.Size = new System.Drawing.Size(152, 22); + this.ToolStripMenuItem_Assembly.Text = "程序集管理(&A)"; + this.ToolStripMenuItem_Assembly.Click += new System.EventHandler(this.ToolStripMenuItem_Assembly_Click); + // + // TSM_DebugPage + // + this.TSM_DebugPage.Name = "TSM_DebugPage"; + this.TSM_DebugPage.Size = new System.Drawing.Size(152, 22); + this.TSM_DebugPage.Text = "调试界面"; + this.TSM_DebugPage.Click += new System.EventHandler(this.TSM_DebugPage_Click); + // + // ToolStripMenuItem_Help + // + this.ToolStripMenuItem_Help.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { + this.ToolStripMenuItem_HHelp, + this.toolStripMenuItem_HVersion, + this.MToolStripMenuItem_AboutMacroinf}); + this.ToolStripMenuItem_Help.Name = "ToolStripMenuItem_Help"; + this.ToolStripMenuItem_Help.Size = new System.Drawing.Size(61, 21); + this.ToolStripMenuItem_Help.Text = "帮助(&H)"; + // + // ToolStripMenuItem_HHelp + // + this.ToolStripMenuItem_HHelp.Name = "ToolStripMenuItem_HHelp"; + this.ToolStripMenuItem_HHelp.Size = new System.Drawing.Size(144, 22); + this.ToolStripMenuItem_HHelp.Text = "MIS手册(&G)"; + this.ToolStripMenuItem_HHelp.Click += new System.EventHandler(this.ToolStripMenuItem_HHelp_Click); + // + // toolStripMenuItem_HVersion + // + this.toolStripMenuItem_HVersion.Name = "toolStripMenuItem_HVersion"; + this.toolStripMenuItem_HVersion.Size = new System.Drawing.Size(144, 22); + this.toolStripMenuItem_HVersion.Text = "版本信息(&O)"; + this.toolStripMenuItem_HVersion.Click += new System.EventHandler(this.toolStripMenuItem_HVersion_Click); + // + // MToolStripMenuItem_AboutMacroinf + // + this.MToolStripMenuItem_AboutMacroinf.Name = "MToolStripMenuItem_AboutMacroinf"; + this.MToolStripMenuItem_AboutMacroinf.Size = new System.Drawing.Size(144, 22); + this.MToolStripMenuItem_AboutMacroinf.Text = "关于迈思(&M)"; + this.MToolStripMenuItem_AboutMacroinf.Click += new System.EventHandler(this.MToolStripMenuItem_AboutMacroinf_Click); + // + // groupBox_Depart + // + this.groupBox_Depart.Location = new System.Drawing.Point(0, 25); + this.groupBox_Depart.Name = "groupBox_Depart"; + this.groupBox_Depart.Size = new System.Drawing.Size(1014, 1); + this.groupBox_Depart.TabIndex = 1475; + this.groupBox_Depart.TabStop = false; + this.groupBox_Depart.Text = "groupBox1"; + // + // statusStrip1 + // + this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { + this.toolStripStatusLabel_RunningStatu, + this.toolStripStatusLabel_RunningStatus, + this.toolStripStatusLabel2, + this.toolStripStatusLabel_StartTime, + this.toolStripStatusLabel3, + this.toolStripStatusLabel_RunTime, + this.toolStripStatusLabel1, + this.toolStripStatusLabel_WorkStationNum, + this.toolStripStatusLabel6, + this.toolStripStatusLabel_OnlineNum, + this.toolStripStatusLabel8, + this.toolStripStatusLabel_DownLine, + this.toolStripStatusLabel4, + this.toolStripStatusLabel_Version}); + this.statusStrip1.Location = new System.Drawing.Point(0, 673); + this.statusStrip1.Name = "statusStrip1"; + this.statusStrip1.Size = new System.Drawing.Size(1008, 26); + this.statusStrip1.TabIndex = 1478; + this.statusStrip1.Text = "statusStrip1"; + // + // toolStripStatusLabel_RunningStatu + // + this.toolStripStatusLabel_RunningStatu.Name = "toolStripStatusLabel_RunningStatu"; + this.toolStripStatusLabel_RunningStatu.Size = new System.Drawing.Size(68, 21); + this.toolStripStatusLabel_RunningStatu.Text = "运行状态:"; + // + // toolStripStatusLabel_RunningStatus + // + this.toolStripStatusLabel_RunningStatus.ActiveLinkColor = System.Drawing.Color.Red; + this.toolStripStatusLabel_RunningStatus.AutoSize = false; + this.toolStripStatusLabel_RunningStatus.BackColor = System.Drawing.Color.Yellow; + this.toolStripStatusLabel_RunningStatus.Name = "toolStripStatusLabel_RunningStatus"; + this.toolStripStatusLabel_RunningStatus.Size = new System.Drawing.Size(62, 21); + this.toolStripStatusLabel_RunningStatus.Text = "变量模拟"; + // + // toolStripStatusLabel2 + // + this.toolStripStatusLabel2.BorderSides = System.Windows.Forms.ToolStripStatusLabelBorderSides.Left; + this.toolStripStatusLabel2.Name = "toolStripStatusLabel2"; + this.toolStripStatusLabel2.Size = new System.Drawing.Size(72, 21); + this.toolStripStatusLabel2.Text = "启动时间:"; + // + // toolStripStatusLabel_StartTime + // + this.toolStripStatusLabel_StartTime.AutoSize = false; + this.toolStripStatusLabel_StartTime.BorderSides = System.Windows.Forms.ToolStripStatusLabelBorderSides.Right; + this.toolStripStatusLabel_StartTime.Name = "toolStripStatusLabel_StartTime"; + this.toolStripStatusLabel_StartTime.Size = new System.Drawing.Size(130, 21); + this.toolStripStatusLabel_StartTime.Text = "2018/08/08 08:08:08"; + // + // toolStripStatusLabel3 + // + this.toolStripStatusLabel3.Name = "toolStripStatusLabel3"; + this.toolStripStatusLabel3.Size = new System.Drawing.Size(68, 21); + this.toolStripStatusLabel3.Text = "运行时长:"; + // + // toolStripStatusLabel_RunTime + // + this.toolStripStatusLabel_RunTime.AutoSize = false; + this.toolStripStatusLabel_RunTime.BorderSides = System.Windows.Forms.ToolStripStatusLabelBorderSides.Right; + this.toolStripStatusLabel_RunTime.Name = "toolStripStatusLabel_RunTime"; + this.toolStripStatusLabel_RunTime.Size = new System.Drawing.Size(145, 21); + this.toolStripStatusLabel_RunTime.Text = "0天0小时0分0秒"; + // + // toolStripStatusLabel1 + // + this.toolStripStatusLabel1.Name = "toolStripStatusLabel1"; + this.toolStripStatusLabel1.Size = new System.Drawing.Size(68, 21); + this.toolStripStatusLabel1.Text = "工位数量:"; + // + // toolStripStatusLabel_WorkStationNum + // + this.toolStripStatusLabel_WorkStationNum.AutoSize = false; + this.toolStripStatusLabel_WorkStationNum.BorderSides = System.Windows.Forms.ToolStripStatusLabelBorderSides.Right; + this.toolStripStatusLabel_WorkStationNum.Name = "toolStripStatusLabel_WorkStationNum"; + this.toolStripStatusLabel_WorkStationNum.Size = new System.Drawing.Size(35, 21); + this.toolStripStatusLabel_WorkStationNum.Text = "100"; + // + // toolStripStatusLabel6 + // + this.toolStripStatusLabel6.Name = "toolStripStatusLabel6"; + this.toolStripStatusLabel6.Size = new System.Drawing.Size(68, 21); + this.toolStripStatusLabel6.Text = "在线数量:"; + // + // toolStripStatusLabel_OnlineNum + // + this.toolStripStatusLabel_OnlineNum.AutoSize = false; + this.toolStripStatusLabel_OnlineNum.BorderSides = System.Windows.Forms.ToolStripStatusLabelBorderSides.Right; + this.toolStripStatusLabel_OnlineNum.Name = "toolStripStatusLabel_OnlineNum"; + this.toolStripStatusLabel_OnlineNum.Size = new System.Drawing.Size(35, 21); + this.toolStripStatusLabel_OnlineNum.Text = "0"; + // + // toolStripStatusLabel8 + // + this.toolStripStatusLabel8.Name = "toolStripStatusLabel8"; + this.toolStripStatusLabel8.Size = new System.Drawing.Size(68, 21); + this.toolStripStatusLabel8.Text = "离线数量:"; + // + // toolStripStatusLabel_DownLine + // + this.toolStripStatusLabel_DownLine.AutoSize = false; + this.toolStripStatusLabel_DownLine.BorderSides = System.Windows.Forms.ToolStripStatusLabelBorderSides.Right; + this.toolStripStatusLabel_DownLine.Name = "toolStripStatusLabel_DownLine"; + this.toolStripStatusLabel_DownLine.Size = new System.Drawing.Size(35, 21); + this.toolStripStatusLabel_DownLine.Text = "0"; + // + // toolStripStatusLabel4 + // + this.toolStripStatusLabel4.Name = "toolStripStatusLabel4"; + this.toolStripStatusLabel4.Size = new System.Drawing.Size(44, 21); + this.toolStripStatusLabel4.Text = "版本:"; + // + // toolStripStatusLabel_Version + // + this.toolStripStatusLabel_Version.Name = "toolStripStatusLabel_Version"; + this.toolStripStatusLabel_Version.Size = new System.Drawing.Size(42, 21); + this.toolStripStatusLabel_Version.Text = "8.6.12"; + // + // groupBox_Alarm + // + this.groupBox_Alarm.Location = new System.Drawing.Point(0, 0); + this.groupBox_Alarm.Name = "groupBox_Alarm"; + this.groupBox_Alarm.Size = new System.Drawing.Size(200, 100); + this.groupBox_Alarm.TabIndex = 1; + this.groupBox_Alarm.TabStop = false; + // + // timer_ReadTagValues + // + this.timer_ReadTagValues.Interval = 1000; + this.timer_ReadTagValues.Tick += new System.EventHandler(this.timer_ReadTagValues_Tick); + // + // MisData + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(1008, 699); + this.Controls.Add(this.statusStrip1); + this.Controls.Add(this.groupBox_Depart); + this.Controls.Add(this.menuStrip_Main); + this.Controls.Add(this.groupBox_WorkStationQuality); + this.Controls.Add(this.groupBox_SignialSimulator); + this.Controls.Add(this.groupBox_Alarm); + this.DoubleBuffered = true; + this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; + this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); + this.MainMenuStrip = this.menuStrip_Main; + this.Margin = new System.Windows.Forms.Padding(2); + this.MaximumSize = new System.Drawing.Size(1024, 738); + this.MinimumSize = new System.Drawing.Size(1024, 705); + this.Name = "MisData"; + this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; + this.Text = "Demo Mes Work System 仿真虚拟调试信号面板 2022.10.15.001"; + this.TopMost = true; + this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.MisData_FormClosing); + this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.MisData_FormClosed); + this.Load += new System.EventHandler(this.MisData_Load); + ((System.ComponentModel.ISupportInitialize)(this.numericUpDown1)).EndInit(); + this.groupBox_SignialSimulator.ResumeLayout(false); + this.groupBox_SignialSimulator.PerformLayout(); + this.groupBox_WorkStationStatus.ResumeLayout(false); + this.groupBox_WorkStationStatus.PerformLayout(); + this.groupBox_PLC.ResumeLayout(false); + this.groupBox_PLC.PerformLayout(); + this.groupBox_MES.ResumeLayout(false); + this.groupBox_MES.PerformLayout(); + this.groupBox_WorkStationQuality.ResumeLayout(false); + this.groupBox_WorkStationQuality.PerformLayout(); + this.groupBox2.ResumeLayout(false); + this.groupBox2.PerformLayout(); + this.groupBox1.ResumeLayout(false); + this.groupBox1.PerformLayout(); + this.contextMenuStrip_MIS.ResumeLayout(false); + this.menuStrip_Main.ResumeLayout(false); + this.menuStrip_Main.PerformLayout(); + this.statusStrip1.ResumeLayout(false); + this.statusStrip1.PerformLayout(); + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + private System.Windows.Forms.ComboBox comboBox_OpName; + private System.Windows.Forms.Label label_OpNameList; + private System.Windows.Forms.TextBox textBox_tagValue_Read; + private System.Windows.Forms.TextBox textBox_tagValue; + private System.Windows.Forms.TextBox textBox_Cmd; + private System.Windows.Forms.Button button_Read; + private System.Windows.Forms.Button button_Write; + private System.Windows.Forms.ListBox listBox1; + private System.Windows.Forms.CheckBox checkBox_WorkStart; + private System.Windows.Forms.NumericUpDown numericUpDown1; + private ListViewDouble.ListViewNF listView_ShowQualityData; + private System.Windows.Forms.ColumnHeader columnHeader1; + private System.Windows.Forms.ColumnHeader columnHeader2; + private System.Windows.Forms.ColumnHeader columnHeader3; + private System.Windows.Forms.ColumnHeader columnHeader4; + private System.Windows.Forms.Button button_ReadData; + private System.Windows.Forms.GroupBox groupBox_SignialSimulator; + private System.Windows.Forms.GroupBox groupBox_MES; + private System.Windows.Forms.TextBox Tbx_MES_74_EngineID; + private System.Windows.Forms.TextBox Tbx_MES_75_Enginetype; + private System.Windows.Forms.Label label10; + private System.Windows.Forms.Label label11; + private System.Windows.Forms.Label label12; + private System.Windows.Forms.Label label13; + private System.Windows.Forms.Label label14; + private System.Windows.Forms.Label label15; + private System.Windows.Forms.Label label16; + private System.Windows.Forms.GroupBox groupBox5; + private System.Windows.Forms.Button Btn_MES_69_MachResult; + private System.Windows.Forms.Button Btn_MES_8_FalseGo; + private System.Windows.Forms.Button Btn_MES_67_FixOver; + private System.Windows.Forms.Button Btn_MES_7_WorkComplete; + private System.Windows.Forms.Button Btn_MES_53_OffLineOK; + private System.Windows.Forms.Button Btn_MES_66_AllowWork; + private System.Windows.Forms.Button Btn_MES_5_EngineTypeGetOver; + private System.Windows.Forms.Button Btn_MES_68_MachComplete; + private System.Windows.Forms.Button Btn_MES_52_ResetEquipment; + private System.Windows.Forms.Button Btn_MES_6_PalletGo; + private System.Windows.Forms.Button Btn_Write_MES; + private System.Windows.Forms.Button Btn_MES_71_IsAuto; + private System.Windows.Forms.Button Btn_MES_51_ConfirmOkGo; + private System.Windows.Forms.Button Btn_MES_15_HeartBeat; + private System.Windows.Forms.GroupBox groupBox_PLC; + private System.Windows.Forms.TextBox Tbx_PLC_10_EngineID; + private System.Windows.Forms.TextBox Tbx_PLC_11_Enginetype; + private System.Windows.Forms.Label label3; + private System.Windows.Forms.Label label4; + 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.Label label9; + private System.Windows.Forms.GroupBox groupBox3; + private System.Windows.Forms.Button Btn_PLC_1003_ShortFall; + private System.Windows.Forms.Button Btn_PLC_19_MesRead; + private System.Windows.Forms.Button Btn_PLC_1002_MachaineBreak; + private System.Windows.Forms.Button Btn_PLC_59_FixOK; + private System.Windows.Forms.Button Btn_PLC_1001_CycleStart; + private System.Windows.Forms.Button Btn_PLC_1000_MachinePowerOn; + private System.Windows.Forms.Button Btn_PLC_44_EngineTypeGetOver; + private System.Windows.Forms.Button Btn_PLC_13_PalletIn; + private System.Windows.Forms.Button Btn_PLC_50_ApplyOffline; + private System.Windows.Forms.Button Btn_PLC_43_PartLoad; + private System.Windows.Forms.Button Btn_Write_PLC; + private System.Windows.Forms.Button Btn_PLC_1004_Jam; + private System.Windows.Forms.Button Btn_PLC_14_HeartBeat; + private System.Windows.Forms.Button Btn_PLC_2_WorkStart; + private System.Windows.Forms.Button Btn_MES_20_MesReadOver; + private System.Windows.Forms.Button Btn_MES_72_MobyClear; + private System.Windows.Forms.TextBox Tbx_PLC_18_Actual; + private System.Windows.Forms.TextBox Tbx_PLC_17_TargetTime; + private System.Windows.Forms.Label label18; + private System.Windows.Forms.Label label17; + private System.Windows.Forms.Button Btn_PLC_16_AllowReadCycleTime; + private System.Windows.Forms.Button Btn_MES_54_ReadCycleTimeOK; + private System.Windows.Forms.TextBox Tbx_MES_73_EngineTypeID; + private System.Windows.Forms.TextBox Tbx_MES_79_OnlineStatus; + private System.Windows.Forms.TextBox Tbx_MES_93_RepairMark; + private System.Windows.Forms.TextBox Tbx_MES_88_SocketNum; + private System.Windows.Forms.TextBox Tbx_MES_77_FixOrder; + private System.Windows.Forms.TextBox Tbx_MES_4_WorkStationRepairStr; + private System.Windows.Forms.Label label19; + private System.Windows.Forms.TextBox Tbx_PLC_9_EngineTypeID; + private System.Windows.Forms.TextBox Tbx_PLC_23_RepairMark; + private System.Windows.Forms.TextBox Tbx_PLC_22_PalletStatus; + private System.Windows.Forms.TextBox Tbx_PLC_21_ResultMark; + private System.Windows.Forms.TextBox Tbx_PLC_80_PalletNum; + private System.Windows.Forms.GroupBox groupBox_WorkStationStatus; + private System.Windows.Forms.TextBox Tbx_Status_11_EngineType; + private System.Windows.Forms.TextBox Tbx_Status_9_EngineTypeID; + private System.Windows.Forms.Label label2; + private System.Windows.Forms.Label label20; + private System.Windows.Forms.TextBox Tbx_Status_10_EngineID; + private System.Windows.Forms.TextBox Tbx_Status_80_Pallet; + private System.Windows.Forms.Label label21; + private System.Windows.Forms.Label label22; + private System.Windows.Forms.GroupBox groupBox_WorkStationQuality; + private System.Windows.Forms.CheckBox Cbx_StatusDisplay; + private System.Windows.Forms.Button Btn_Read_PLC; + private System.Windows.Forms.Button Btn_Read_MES; + private System.Windows.Forms.ContextMenuStrip contextMenuStrip_MIS; + private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem_Show; + private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem_Hide; + private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem_Exit; + private System.Windows.Forms.MenuStrip menuStrip_Main; + private System.Windows.Forms.ToolStripMenuItem ToolStripMenuItem_Start; + private System.Windows.Forms.ToolStripMenuItem ToolStripMenuItem_SaveLog; + private System.Windows.Forms.ToolStripMenuItem ToolStripMenuItem_LockForm; + private System.Windows.Forms.ToolStripMenuItem ToolStripMenuItem_Quit; + private System.Windows.Forms.ToolStripMenuItem ToolStripMenuItem_Visual; + private System.Windows.Forms.ToolStripMenuItem ToolStripMenuItem_VWSStatus; + private System.Windows.Forms.ToolStripMenuItem ToolStripMenuItem_Help; + private System.Windows.Forms.ToolStripMenuItem ToolStripMenuItem_HHelp; + private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem_HVersion; + private System.Windows.Forms.ToolStripMenuItem ToolStripMenuItem_PrintScreen; + private System.Windows.Forms.GroupBox groupBox_Depart; + private System.Windows.Forms.ToolStripMenuItem MToolStripMenuItem_AboutMacroinf; + private System.Windows.Forms.CheckBox checkBox_PLCData_Display; + private System.Windows.Forms.CheckBox checkBox_MESData_Display; + private System.Windows.Forms.ToolStripMenuItem EToolStripMenuItem_EquipAlarm; + private System.Windows.Forms.StatusStrip statusStrip1; + private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel_RunningStatu; + private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel_RunningStatus; + private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel2; + private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel_StartTime; + private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel3; + private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel_RunTime; + private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel1; + private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel_WorkStationNum; + private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel6; + private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel_OnlineNum; + private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel8; + private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel_DownLine; + private System.Windows.Forms.GroupBox groupBox_Alarm; + private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel4; + private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel_Version; + private System.Windows.Forms.ToolStripMenuItem ToolStripMenuItem_Assembly; + private System.Windows.Forms.ToolStripMenuItem TSM_DebugPage; + private System.Windows.Forms.CheckBox cb_QdData; + private System.Windows.Forms.CheckBox cb_MonitorData; + private System.Windows.Forms.GroupBox groupBox1; + private System.Windows.Forms.RadioButton radioButton_PartCodeSanner; + private System.Windows.Forms.RadioButton radioButton_PlcSignl; + private System.Windows.Forms.GroupBox groupBox2; + private System.Windows.Forms.RadioButton radioButton_Copy; + private System.Windows.Forms.RadioButton radioButton_Base; + private System.Windows.Forms.TextBox textBox_Copy_Item; + private System.Windows.Forms.TextBox textBox_Copy_TagID; + private System.Windows.Forms.TextBox textBox_Base_Item; + private System.Windows.Forms.TextBox textBox_Base_TagID; + private System.Windows.Forms.RadioButton radioButton_PlcSignl_Copy; + private System.Windows.Forms.Timer timer_ReadTagValues; + private System.Windows.Forms.ColumnHeader columnHeader5; + private System.Windows.Forms.RadioButton radioButton_MQTT; + } +} + diff --git a/MisDataPlcTagID/MisDataPlcTagID/MisDataWebFun.cs b/MisDataPlcTagID/MisDataPlcTagID/MisDataWebFun.cs new file mode 100644 index 0000000..26cac08 --- /dev/null +++ b/MisDataPlcTagID/MisDataPlcTagID/MisDataWebFun.cs @@ -0,0 +1,1043 @@ +//using BasicData; +using bizFacade; +//using OpcData; +using System; +using System.Collections; +using System.Data; +using System.Threading; +using System.Windows.Forms; +//using SystemFramework; + +using System.Drawing; +//using MesServerWork; +using System.Configuration; +//using MisDataFunction; +using System.Collections.Generic; +using MQTTnet.Client.Connecting; +using MQTTnet.Client.Disconnecting; +using MQTTnet.Client.Receiving; +using System.Linq; +using DoWhatPlc; +/// +/// +/// +namespace MisDataSaveDate +{ + + /// + /// + /// + /// + /// + public delegate void RefreshForm(object obj1, EventArgs obj2); + /// + /// + /// + public partial class MisData:Form + { + /// + /// + /// + public static string BasicDataTableFile = ConfigurationManager.AppSettings["BasicDataTableFile"]; + /// + /// + /// + public static int IsDemoMesServer = Convert.ToInt32(ConfigurationManager.AppSettings["IsDemoMesServer"]); + /// + /// + /// + public static string MqttUrl = ConfigurationManager.AppSettings["MqttUrl"]; + public static string MqttUrlPLC = ConfigurationManager.AppSettings["MqttUrlPLC"]; + /// + /// + /// + public static string MqttTargetTopic = ConfigurationManager.AppSettings["MqttTargetTopic"]; + public static string MqttTargetTopicPLC = ConfigurationManager.AppSettings["MqttTargetTopicPLC"]; + /// + /// + /// + public static int IsWriteMonitorLog = Convert.ToInt32(ConfigurationManager.AppSettings["IsWriteMonitorLog"]); + /// + /// + /// + public static string ConnectionString_MES = ConfigurationManager.AppSettings["ConnectionString_MES"]; + /// + /// + /// + public static int WebApiPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["WebApiPort"]); + /// + /// + /// + public static RefreshForm MainFormRefresh, TestPlcStatusDel; + /// + /// 允许使用附加功能的变量,只有在系统开始加载Tag时,才允许读取PLC数据 + /// + public static bool AllowLoad; + /// + /// + /// + public MisData() + { + InitializeComponent(); + + + CheckForIllegalCrossThreadCalls = false; + + + } + + + + + + private void InitcomboBox_OpNameWebApi() + { + List opNameList; + try + { + //全部工位号 + comboBox_OpName.DataSource = opNameList = DtWebApi.OpcDemo.Get_opNameList(); + + + //FunctionForm_HashiTable.OpName_Hash_Write("OpNameList", opNameList); + toolStripStatusLabel_WorkStationNum.Text = opNameList.Count.ToString(); + toolStripStatusLabel_DownLine.Text = toolStripStatusLabel_WorkStationNum.Text; + if (comboBox_OpName.Items.Count > 0) + { + WorkStationNum_Now = comboBox_OpName.SelectedValue.ToString(); + } + } + catch { } + + + } + + private void listBox1_SelectedValueChanged(object sender, EventArgs e) + { + //try + //{ + // string cmd; + // string opName; + // string tagValue; + // string[] strList; + // if (listBox1.Text != null) + // { + // strList = listBox1.Text.Split('|'); + // if (strList.Length >= 4) + // { + // cmd = strList[1]; + // opName = strList[2]; + // tagValue = strList[3]; + // textBox_Cmd.Text = cmd; + // textBox_tagValue.Text = tagValue; + // } + // } + //} + //catch (Exception err) + //{ + // ApplicationLog.WriteLog(err, err.Message); + + //} + + } + + private void button_Write_Click(object sender, EventArgs e) + { + try + { + short tagValue_int; + string tagValue_str; + byte tagValue_byte; + bool tagValue_bool; + int tagType; + int tagDataType; + string cmd = textBox_Cmd.Text; + string opName = WorkStationNum_Now; + string tagValue = textBox_tagValue.Text; + HashtableList htList = DtWebApi.OpcDemo.GetHashtableList(); + + tagType = Convert.ToInt32(htList.hashtable_TagType[cmd]); + + tagDataType = Convert.ToInt32(htList.hashtable_TagTypeDataType[tagType.ToString()]); + switch (tagDataType) + { + case 2: + tagValue_int = Convert.ToInt16(tagValue); + WriteAnyData_Thread(tagType, opName, tagValue_int); + break; + case 8: + tagValue_str = tagValue.ToString(); + WriteAnyData_Thread(tagType, opName, tagValue_str); + break; + case 17: + tagValue_byte = Convert.ToByte(tagValue); + WriteAnyData_Thread(tagType, opName, tagValue_byte); + break; + case 11: + tagValue_bool = Convert.ToBoolean(Convert.ToInt32(tagValue)); + WriteAnyData_Thread(tagType, opName, tagValue_bool); + break; + } + + } + catch (Exception err) + { + MessageBox.Show("输入命令异常,请重新输入!"); + //ApplicationLog.WriteLog(err, err.Message); + + } + } + + private void button_Read_Click(object sender, EventArgs e) + { + try + { + int tagType; + string cmd = textBox_Cmd.Text; + string opName = WorkStationNum_Now; + string tagValue = textBox_tagValue.Text; + + HashtableList htList = DtWebApi.OpcDemo.GetHashtableList(); + + tagType = Convert.ToInt32(htList.hashtable_TagType[cmd]); + + QualityDataQueryStruct QualityStruct = new QualityDataQueryStruct(opName, tagType, textBox_tagValue_Read); + Thread t = new Thread(new ParameterizedThreadStart(ReadPLC_ByTagType_Thread)); + t.Start(QualityStruct); + } + catch (Exception err) + { + // ApplicationLog.WriteLog(err, err.Message); + + } + } + + void ReadPLC_ByTagType_Thread(object obj) + { + //try + //{ + // QualityDataQueryStruct QualityStruct = (QualityDataQueryStruct)obj; + // TextBox tbx = (TextBox)QualityStruct.Ctrl; + + // tbx.Text = ReadPLC(QualityStruct.tagType, QualityStruct.OpName).ToString(); + //} + //catch (Exception err) + //{ + // ApplicationLog.WriteLog(err, err.Message); + //} + } + + + bool isWorkStart; + private void timer_WorkStart_Tick(object sender, EventArgs e) + { + //if (isWorkStart) + // isWorkStart = false; + //else + // isWorkStart = true; + //if (isWorkStart) + //{ + // textBox_tagValue.Text = "1"; + // button_Write_Click(null, null); + //} + //else + //{ + // textBox_tagValue.Text = "0"; + // button_Write_Click(null, null); + //} + } + + private void checkBox_WorkStart_CheckedChanged(object sender, EventArgs e) + { + //if (textBox_Cmd.Text == "" && checkBox_WorkStart.Checked) + //{ + // MessageBox.Show("请选择命令"); + // checkBox_WorkStart.Checked = false; + // return; + //} + //if (checkBox_WorkStart.Checked) + //{ + // timer_WorkStart.Enabled = true; + // listBox1.Enabled = false; + // textBox_Cmd.ReadOnly = true; + //} + //else + //{ + // timer_WorkStart.Enabled = false; + // listBox1.Enabled = true; + // textBox_Cmd.ReadOnly = false; + //} + + } + + private void numericUpDown1_ValueChanged(object sender, EventArgs e) + { + //timer_WorkStart.Interval = Convert.ToInt32(numericUpDown1.Value) * 1000; + } + + static Thread ReadQuality_t = null; + private void ReadQualityData(string opName) + { + try + { + if (ReadQualityRunning) return; + ReadQualityRunning = true; + QualityDataQueryStruct QltyQueryStr = new QualityDataQueryStruct(opName, listView_ShowQualityData); + + ReadQuality_t = new Thread(new ParameterizedThreadStart(ReadQualityData_Thread)); + ReadQuality_t.Start(QltyQueryStr); + + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, err.Message); + + } + } + private void ReadQualityDataUpdate(string opName) + { + try + { + if (ReadQualityRunning) return; + ReadQualityRunning = true; + QualityDataQueryStruct QltyQueryStr = new QualityDataQueryStruct(opName, listView_ShowQualityData); + + ReadQuality_t = new Thread(new ParameterizedThreadStart(ReadQualityData_Thread_Update)); + ReadQuality_t.Start(QltyQueryStr); + + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, err.Message); + + } + } + public QualityDataType[] ThisWorkStationData + { get; set; } + static bool ReadQualityRunning = false; + void ReadQualityData_Thread(object obj) + { + int fTime = 0; + try + { + + QualityDataQueryStruct QualityStruct = (QualityDataQueryStruct)obj; + + ListView listViewTemp = (ListView)QualityStruct.Ctrl; + ListViewItem listViewItem = null; + string[] listViewItemString = new string[5]; + if (listViewTemp.InvokeRequired) + { + Action ActionDelegate = () => { listViewTemp.Items.Clear(); }; + listViewTemp.Invoke(ActionDelegate); + } + else + { + listViewTemp.Items.Clear(); + } + + System.Collections.Concurrent.ConcurrentDictionary cd = new System.Collections.Concurrent.ConcurrentDictionary(); + List cdTagIDTagFormat = null; + if (cb_MonitorData.Checked) + { + + cdTagIDTagFormat = DtWebApi.OpcDemo.ReadPLC_GroupMonitor(QualityStruct.OpName); + //cd = MesWork.PlcLinkForm.ReadPLC_GroupMonitor(QualityStruct.OpName); + } + if (cb_QdData.Checked) + { + cdTagIDTagFormat = DtWebApi.OpcDemo.ReadPLC_GroupData_Qd(QualityStruct.OpName); + //cd = MesWork.PlcLinkForm.ReadPLC_GroupData_Qd(QualityStruct.OpName); + } + if (cb_MonitorData.Checked == false & cb_QdData.Checked == false) + { + cdTagIDTagFormat = DtWebApi.OpcDemo.ReadPLC_GroupData(QualityStruct.OpName); + //cd = MesWork.PlcLinkForm.ReadPLC_GroupData(QualityStruct.OpName); + } + if (cb_MonitorData.Checked == true & cb_QdData.Checked == true) + { + cdTagIDTagFormat = DtWebApi.OpcDemo.ReadPLC_GroupData(QualityStruct.OpName); + //cd = MesWork.PlcLinkForm.ReadPLC_GroupData(QualityStruct.OpName); + } + if (cdTagIDTagFormat == null) return; + foreach (var item in cdTagIDTagFormat) + { + if (!cd.ContainsKey(item.TagID)) + { + cd.TryAdd(item.TagID, item.TF); + } + } + //排序 + var result2 = from pair in cd orderby pair.Key select pair; + ThisWorkStationData = new QualityDataType[cd.Count]; + var sortResult2 = from pair in cd orderby pair.Key descending select pair; + //cd.o.OrderBy(p => p.Value.Speed); + //foreach (KeyValuePair _cd in cd) + foreach (KeyValuePair _cd in result2) + { + var tagID = _cd.Key; + var TF = (DoWhatPlc.TagFormat)_cd.Value; + + listViewItemString[0] = TF.OpName; + listViewItemString[3] = TF.TagID; + listViewItemString[1] = TF.ItemName; + listViewItemString[2] = TF.TagValue.ToString(); + listViewItemString[4] = TF.TagTypeCodeID.ToString(); + + listViewItem = new ListViewItem(listViewItemString); + //if (TF.IsMonitor == 1) + //{ + // // listViewItem.BackColor = Color.LimeGreen; + //} + //if (listViewTemp.InvokeRequired) + //{ + // Action ActionDelegate = (x) => { listViewTemp.Items.Add(x); }; + // listViewTemp.BeginInvoke(ActionDelegate, listViewItem); + //} + //else + { + listViewTemp.Items.Add(listViewItem); + } + + QualityDataType t00 = new QualityDataType(); + t00.opName = TF.OpName; + t00.tagID = TF.TagID; + t00.tagTypeID = TF.TagTypeID; + t00.tagValue = TF.TagValue; + ThisWorkStationData[fTime] = t00; + //ThisWorkStationData[fTime].opName = TF.OpName; + //ThisWorkStationData[fTime].tagID = TF.TagID; + //ThisWorkStationData[fTime].tagTypeID = TF.TagTypeID; + //ThisWorkStationData[fTime].tagValue = TF.TagValue; + + + fTime++; + + } + InitFormBtnColorUpdate(); + ReadQualityRunning = false; + } + catch (Exception err) + { + ReadQualityRunning = false; + // ApplicationLog.WriteLog(err, err.Message); + + } + + + + } + + void ReadQualityData_Thread_Update(object obj) + { + try + { + + QualityDataQueryStruct QualityStruct = (QualityDataQueryStruct)obj; + + ListView listViewTemp = (ListView)QualityStruct.Ctrl; + ListViewItem listViewItem = null; + string[] listViewItemString = new string[4]; + + + System.Collections.Concurrent.ConcurrentDictionary cd = new System.Collections.Concurrent.ConcurrentDictionary(); + List cdTagIDTagFormat = null; + //if (cb_MonitorData.Checked) + //{ + + // cdTagIDTagFormat = DtWebApi.OpcDemo.ReadPLC_GroupMonitor(QualityStruct.OpName); + // //cd = MesWork.PlcLinkForm.ReadPLC_GroupMonitor(QualityStruct.OpName); + //} + //if (cb_QdData.Checked) + //{ + // cdTagIDTagFormat = DtWebApi.OpcDemo.ReadPLC_GroupData_Qd(QualityStruct.OpName); + // //cd = MesWork.PlcLinkForm.ReadPLC_GroupData_Qd(QualityStruct.OpName); + //} + //if (cb_MonitorData.Checked == false & cb_QdData.Checked == false) + //{ + // cdTagIDTagFormat = DtWebApi.OpcDemo.ReadPLC_GroupData(QualityStruct.OpName); + // //cd = MesWork.PlcLinkForm.ReadPLC_GroupData(QualityStruct.OpName); + //} + //if (cb_MonitorData.Checked == true & cb_QdData.Checked == true) + //{ + // cdTagIDTagFormat = DtWebApi.OpcDemo.ReadPLC_GroupData(QualityStruct.OpName); + // //cd = MesWork.PlcLinkForm.ReadPLC_GroupData(QualityStruct.OpName); + //} + cdTagIDTagFormat = DtWebApi.OpcDemo.ReadPLC_GroupData(QualityStruct.OpName); + + if (cdTagIDTagFormat == null) return; + foreach (var item in cdTagIDTagFormat) + { + if (!cd.ContainsKey(item.TagID)) + { + cd.TryAdd(item.TagID, item.TF); + } + } + //listView_ShowQualityData + string tagID; + for(int i=0;i< listView_ShowQualityData.Items.Count;i++) + { + tagID = listView_ShowQualityData.Items[i].SubItems[3].Text; + var TF = (DoWhatPlc.TagFormat)cd[tagID]; + listView_ShowQualityData.Items[i].SubItems[2].Text = TF.TagValue.ToString(); + } + + listView_ShowQualityData.Invalidate(); + ReadQualityRunning = false; + InitFormBtnColorUpdate(); + } + catch (Exception err) + { + ReadQualityRunning = false; + // ApplicationLog.WriteLog(err, err.Message); + + } + } + + + public void InitFormBtnColorUpdate() + { + try + { + //if (!Cbx_StatusDisplay.Checked) return; + string OpName = WorkStationNum_Now; + foreach (Control GroupBox in this.groupBox_SignialSimulator.Controls) + { + foreach (Control Btn in GroupBox.Controls) + { + if (Btn.Name.Length < 8) continue; + if (Btn.Name.Substring(0, 8) == "Btn_PLC_" || Btn.Name.Substring(0, 8) == "Btn_MES_") + { + ControlData Ctrl1 = new ControlData(Btn, OpName); + Thread t = new Thread(new ParameterizedThreadStart(InitFormBtn_Thread_Update)); + t.Start(Ctrl1); + } + } + } + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, err.Message); + + } + + + } + + void InitFormBtn_Thread_Update(Object obj) + { + try + { + ControlData Btn = (ControlData)obj; + + //test = ReadPLC(Btn.TagType, Btn.opName); + + //bool Result = Convert.ToBoolean(test); + ListViewItem li = listView_ShowQualityData.Items.Cast().First(x => x.SubItems[4].Text == Btn.TagType.ToString() && x.SubItems[0].Text == Btn.opName); + var result = li.SubItems[2].Text; + bool Result = false; + switch (result.ToLower()) + { + case "true": + case "1": + Result = true; + break; + } + if (Btn.btn.InvokeRequired) + { + Action actionDelegate = (x) => { Btn.btn.BackColor = x; }; + if (Result) + { + Btn.btn.BeginInvoke(actionDelegate, System.Drawing.Color.Green); + } + else + { + Btn.btn.BeginInvoke(actionDelegate, System.Drawing.Color.SlateGray); + } + } + else + { + if (Result) + { + Btn.btn.BackColor = System.Drawing.Color.Green; + } + else + { + Btn.btn.BackColor = System.Drawing.Color.SlateGray; + } + } + } + catch (Exception err) + { + ControlData Btn = (ControlData)obj; + //ApplicationLog.WriteLog(err, err.Message + "采集数据值:" + ";按钮名称:" + test + Btn.btn.Name + "工位号" + WorkStationNum_Now); + } + } + + + private void button_ReadData_Click(object sender, EventArgs e) + { + WorkStationNum_Now = comboBox_OpName.SelectedValue.ToString(); + ReadQualityData(WorkStationNum_Now); + + } + + + private void comboBox_OpName_SelectedIndexChanged(object sender, EventArgs e) + { + WorkStationNum_Now = comboBox_OpName.SelectedValue.ToString(); + ReadQualityData(WorkStationNum_Now); + ListBox1_Item_Init(); + } + void ListBox1_Item_Init() + { + listBox1.Items.Clear(); + List strings = new List(); + //listBox1.Items.Clear(); + DataTable dt = BaseDataSystemMES.dt_TagTypeDataType(); + + foreach (DataRow row in dt.Rows) + { + listBox1.Items.Add("MES|" + row["TagName"].ToString() + "|" + WorkStationNum_Now + "|1"); + + //strings.Add("MES|" + row["TagName"].ToString() + "|" + opName + "|1"); + } + } + + private void listView_ShowQualityData_MouseDoubleClick(object sender, MouseEventArgs e) + { + try + { + var items = listView_ShowQualityData.SelectedItems; + QualityDataType SelectData = new QualityDataType(); + ListView.SelectedIndexCollection index = new ListView.SelectedIndexCollection(listView_ShowQualityData); + SelectData = ThisWorkStationData[index[0]]; + WriteQualityValueForm WriteForm = new WriteQualityValueForm(SelectData, this); + WriteForm.ShowDialog(); + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, err.Message); + + } + } + + private void groupBox_SignialSimulatorBtn_Click(object sender, EventArgs e) + { + WriteBoolSignalByFormBtn(sender); + } + + private void Btn_Write_PLC_Click(object sender, EventArgs e) + { + WriteNormalDataBygroupBox_SignialSimulatorWriteBtn(sender); + } + + private void Btn_Write_MES_Click(object sender, EventArgs e) + { + WriteNormalDataBygroupBox_SignialSimulatorWriteBtn(sender); + } + + + + + private void Btn_Read_PLC_Click(object sender, EventArgs e) + { + ReadPLC_ProductInfo(); + + } + + private void Btn_Read_MES_Click(object sender, EventArgs e) + { + ReadMES_ProductInfo(); + } + + private void MisData_FormClosed(object sender, FormClosedEventArgs e) + { + //notifyIcon_MIS.Visible = false; + //this.Dispose(); + //Application.Exit(); + //System.Environment.Exit(0); + } + + private void toolStripMenuItem_Show_Click(object sender, EventArgs e) + { + //this.Show(); + //this.WindowState = FormWindowState.Normal; + //this.Activate(); + } + + private void toolStripMenuItem_Hide_Click(object sender, EventArgs e) + { + //this.Hide(); + //if (PlcChange != null) + //{ + + // Sencondform.Invoke(SecondFormClose); + // ToolStripMenuItem_VWSStatus.Checked = false; + + //} + + } + + private void toolStripMenuItem_Exit_Click(object sender, EventArgs e) + { + //this.Close(); + } + + + + public static string WorkStationNum_Now; + private void MisData_FormClosing(object sender, FormClosingEventArgs e) + { + //notifyIcon_MIS.Visible = false; + //if (MessageBox.Show("你确定要退出程序吗?", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.OK) + //{ + // notifyIcon_MIS.Visible = false; + // e.Cancel = false; + + // //判断SecondForm是否关闭 + // if (PlcChange != null) + // { + // Sencondform.BeginInvoke(SecondFormClose); + // } + + // StopServer(); + // MesWork.Mqtt.StopAsync(); + + //} + //else + //{ + // notifyIcon_MIS.Visible = true; + // e.Cancel = true; + + //} + } + + + private void ToolStripMenuItem_PrintScreen_Click(object sender, EventArgs e) + { + + //PrintMainForm_Thread(); + + } + + private void ToolStripMenuItem_Quit_Click(object sender, EventArgs e) + { + //this.Close(); + } + + private void ToolStripMenuItem_SaveLog_Click(object sender, EventArgs e) + { + //SavePLCMessage SavePlcMSG = new SavePLCMessage(); + //SavePlcMSG.SavePlcMessage_Thread(richTextBox_MessagePLC.Text); + } + + + private void ToolStripMenuItem_LockForm_Click(object sender, EventArgs e) + { + //MainFormLock = new MainAct(LockMainForm); + //MainFormUnlock = new MainAct(UnLockForm); + //MainLockConfirm LockConfirm = new MainLockConfirm(this, Sencondform); + //LockConfirm.ShowDialog(); + + + + } + + private void ToolStripMenuItem_VWSStatus_Click(object sender, EventArgs e) + { + //if (PlcChange == null) + //{ + // OpenSecondForm_Thread(); + + //} + //else + //{ + // Sencondform.BeginInvoke(SecondFormClose); + // ToolStripMenuItem_VWSStatus.Checked = false; + //} + + } + + + + + private void MToolStripMenuItem_AboutMacroinf_Click(object sender, EventArgs e) + { + //System.Diagnostics.Process.Start("https://www.meswork.com"); + } + + private void toolStripMenuItem_HVersion_Click(object sender, EventArgs e) + { + //VersionsInformation VersionForm = new VersionsInformation(); + //VersionForm.ShowDialog(); + } + + + private void MisData_Load(object sender, EventArgs e) + { + + InitcomboBox_OpNameWebApi(); + + + + //MesWork.Mqtt.StartAsync(MqttUrl); + //MesWork.Mqtt.mqttClient.ConnectedHandler = new MqttClientConnectedHandlerDelegate(OnSubscriberConnected); + //MesWork.Mqtt.mqttClient.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(OnSubscriberDisconnected); + //MesWork.Mqtt.mqttClient.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(OnSubscriberMessageReceived); + } + + + + + + bool EToolStripMenuItem_EquipAlarm_Visiable = false; + + + + private void ToolStripMenuItem_HHelp_Click(object sender, EventArgs e) + { + //string file = Environment.CurrentDirectory + "\\MisData操作手册.pdf"; + //string str = file.Replace("\\bin\\Debug", "\\PDF\\MisData说明文档.pdf"); + //System.Diagnostics.Process.Start(file); + } + + /// + /// 程序集界面 + /// + /// + /// + private void ToolStripMenuItem_Assembly_Click(object sender, EventArgs e) + { + //AssemblyManagement AssemblyView = new AssemblyManagement(); + //AssemblyView.ShowDialog(); + } + //MesWork.OpcForm opcForm = null; + private void TSM_DebugPage_Click(object sender, EventArgs e) + { + //if (opcForm != null) + //{ + // opcForm.Close(); + // opcForm.Dispose(); + // opcForm = null; + //} + + //opcForm = new MesWork.OpcForm(IsDemoMesServer); + //opcForm.Show(); + + + } + + private void button1_Click(object sender, EventArgs e) + { + //WritePLC("71015001", 1); + //WritePLC("71015002", 1.1); + //WritePLC("71015003", 2.2); + + //WritePLC("71015004", 0); + //WritePLC("71015005", 3.3); + //WritePLC("71015006", 4.4); + + } + + private void label_OpNameList_DoubleClick(object sender, EventArgs e) + { + InitcomboBox_OpNameWebApi(); + } + + private void listView_ShowQualityData_Click(object sender, EventArgs e) + { + //if (GlobalEventInterface.E_DeviceSignalSimGantt_TransmitTagToDeviceSignalSim != null) + //{ + // GlobalEventInterface.E_DeviceSignalSimGantt_TransmitTagToDeviceSignalSim(currTagID, currTagName); + //} + } + + private void listView_ShowQualityData_SelectedIndexChanged(object sender, EventArgs e) + { + if(listView_ShowQualityData.SelectedItems.Count>0) + { + string opName = listView_ShowQualityData.SelectedItems[0].SubItems[0].Text; + string itemName = listView_ShowQualityData.SelectedItems[0].SubItems[1].Text; + string tagName = opName + "-"+ itemName; + string tagID = listView_ShowQualityData.SelectedItems[0].SubItems[3].Text; + int tagFrom = 2; + string tagIDCopy = ""; + if (radioButton_PlcSignl.Checked) + { + textBox_Base_TagID.Text = tagID; + textBox_Base_Item.Text = itemName; + //if (GlobalEventInterface.E_MisDataPlcTagIDSignal_TransmitTagToDeviceSignalSim != null) + //{ + // GlobalEventInterface.E_MisDataPlcTagIDSignal_TransmitTagToDeviceSignalSim(tagID, tagName, tagFrom, opName, tagIDCopy); + //} + } + else if(radioButton_PlcSignl_Copy.Checked) + { + tagFrom = 4; + if (radioButton_Base.Checked) + { + textBox_Base_TagID.Text = tagID; + textBox_Base_Item.Text = itemName; + } + else if(radioButton_Copy.Checked) + { + textBox_Copy_TagID.Text = tagID; + textBox_Copy_Item.Text = itemName; + } + tagID = textBox_Base_TagID.Text; + tagName = opName + "-" + textBox_Base_Item.Text+"[拷贝信号:"+ textBox_Copy_Item.Text+"]"; + tagIDCopy = textBox_Copy_TagID.Text; + //if (GlobalEventInterface.E_MisDataPlcTagIDSignal_TransmitTagToDeviceSignalSim != null) + //{ + // GlobalEventInterface.E_MisDataPlcTagIDSignal_TransmitTagToDeviceSignalSim(tagID, tagName, tagFrom, opName, tagIDCopy); + //} + } + } + } + + private void radioButton_PartCodeSanner_Click(object sender, EventArgs e) + { + radioButton_Base.Checked = true; + radioButton_Base.Enabled = false; + radioButton_Copy.Enabled = false; + if (radioButton_PartCodeSanner.Checked) + { + var tagID = Guid.NewGuid().ToString(); + string opName = comboBox_OpName.Text; + string tagName = opName + "-" + "扫描条码"; + int tagFrom = 3; + string tagIDCopy = ""; + //GlobalEventInterface.E_MisDataPlcTagIDSignal_TransmitTagToDeviceSignalSim(tagID, tagName, tagFrom, opName,tagIDCopy); + } + } + + private void radioButton_PlcSignl_CheckedChanged(object sender, EventArgs e) + { + radioButton_Base.Checked = true; + radioButton_Base.Enabled = false; + radioButton_Copy.Enabled = false; + } + + + + private void radioButton_PlcSignl_Click(object sender, EventArgs e) + { + radioButton_Base.Checked = true; + radioButton_Base.Enabled = false; + radioButton_Copy.Enabled = false; + } + private void radioButton_MQTT_Click(object sender, EventArgs e) + { + + if (radioButton_MQTT.Checked) + { + var tagID = Guid.NewGuid().ToString(); + string opName = comboBox_OpName.Text; + string tagName = opName + "-" + "MQTT"; + int tagFrom = 5; + string tagIDCopy = ""; + //GlobalEventInterface.E_MisDataPlcTagIDSignal_TransmitTagToDeviceSignalSim(tagID, tagName, tagFrom, opName, tagIDCopy); + } + } + private void radioButton_PlcSignl_Copy_Click(object sender, EventArgs e) + { + radioButton_Base.Enabled = true; + radioButton_Copy.Enabled = true; + if (listView_ShowQualityData.SelectedItems.Count < 1) return; + string opName = listView_ShowQualityData.SelectedItems[0].SubItems[0].Text; + string tagName; + string tagID ; + int tagFrom ; + string tagIDCopy ; + + if (radioButton_PlcSignl_Copy.Checked) + { + tagFrom = 4; + tagID = textBox_Base_TagID.Text; + tagName = opName + "-" + textBox_Base_Item.Text; + tagIDCopy = textBox_Copy_TagID.Text; + //if (GlobalEventInterface.E_MisDataPlcTagIDSignal_TransmitTagToDeviceSignalSim != null) + //{ + // GlobalEventInterface.E_MisDataPlcTagIDSignal_TransmitTagToDeviceSignalSim(tagID, tagName, tagFrom, opName, tagIDCopy); + //} + } + } + + private void cb_MonitorData_Click(object sender, EventArgs e) + { + if(cb_MonitorData.Checked) + { + timer_ReadTagValues.Enabled = true; + } + else + { + timer_ReadTagValues.Enabled = false; + } + } + + private void timer_ReadTagValues_Tick(object sender, EventArgs e) + { + ThreadPool.QueueUserWorkItem(UpdateForm,null); + } + + private void UpdateForm(object e) + { + if (listView_ShowQualityData.Items.Count > 0) + { + ReadQualityDataUpdate(WorkStationNum_Now); + + } + else + { + ReadQualityData(WorkStationNum_Now); + } + InitFormBtnColorUpdate(); + } + + private void groupBox1_Enter(object sender, EventArgs e) + { + + } + + + + + + private void EToolStripMenuItem_EquipAlarm_Click(object sender, EventArgs e) + { + //try + //{ + // if (!EToolStripMenuItem_EquipAlarm.Checked) + // { + + // groupBox_WorkStationQuality.Width = 307; + // groupBox_WorkStationQuality.Height = 313; + // listView_ShowQualityData.Width = 294; + // listView_ShowQualityData.Height = 234; + // button_ReadData_Click(null, null); + // groupBox_Alarm.Visible = true; + // EToolStripMenuItem_EquipAlarm.Checked = true; + // EToolStripMenuItem_EquipAlarm_Visiable = true; + // } + // else + // { + // groupBox_Alarm.Visible = false; + + // groupBox_WorkStationQuality.Width = 307; + // groupBox_WorkStationQuality.Height = 642; + // listView_ShowQualityData.Width = 294; + // listView_ShowQualityData.Height = 572; + // button_ReadData_Click(null, null); + // EToolStripMenuItem_EquipAlarm.Checked = false; + // } + //} + //catch (Exception err) + //{ + // ApplicationLog.WriteLog(err, err.Message); + + //} + } + + } +} diff --git a/MisDataPlcTagID/MisDataPlcTagID/MisDataWebFun.resx b/MisDataPlcTagID/MisDataPlcTagID/MisDataWebFun.resx new file mode 100644 index 0000000..a430b9c --- /dev/null +++ b/MisDataPlcTagID/MisDataPlcTagID/MisDataWebFun.resx @@ -0,0 +1,212 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 423, 5 + + + 608, 4 + + + 749, 3 + + + 870, 3 + + + 37 + + + + + AAABAAEAICAAAAEAIACoEAAAFgAAACgAAAAgAAAAQAAAAAEAIAAAAAAAABAAABMLAAATCwAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMgChADIAoQIyAKEgMgChczIA + occyAKHqMgChmTIAoTwyAKEJMgChAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMgChADIAoQQyAKEvMgChdzIA + odYyAKH7MgCh/zIAof8yAKH/MgCh6jIAoacyAKFJMgChEjIAoQAyAKEAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAyAKEAMgChADIAoQoyAKE+MgChkTIA + oeoyAKH+MgCh+TIAoe0yAKH+MgCh/zIAofwyAKH3MgCh/jIAofgyAKHBMgChZDIAoR4yAKEBMgChAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAyAKEAMgChATIAoRUyAKFcMgChujIA + ofEyAKH/MgCh9DIAobcyAKFPMgChfjIAof8yAKH/MgCh5TIAoVUyAKGLMgCh4jIAofwyAKH9MgCh2TIA + oYcyAKEoMgChBTIAoQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAyAKEAMgChAjIAoSYyAKF2MgCh0DIA + ofcyAKH+MgCh8zIAof8yAKGjMgChDTIAoQAyAKFpMgCh/zIAof8yAKHhMgChHjIAoQIyAKEiMgChbjIA + ocoyAKH3MgCh/jIAoeUyAKGfMgChQTIAoQsyAKEAAAAAAAAAAAAAAAAAMgChCDIAoUEyAKGXMgCh4jIA + of4yAKH/MgChzzIAoW0yAKFoMgCh+zIAoZcyAKEAMgChADIAoWkyAKH/MgCh/zIAoeEyAKEeMgChADIA + oQAyAKEBMgChETIAoVAyAKGiMgCh8DIAof8yAKH0MgChuTIAoW0yAKEVMgChADIAoQAyAKG2MgCh7TIA + of8yAKHvMgCh7jIAofgyAKFLMgChADIAoTcyAKH1MgChlzIAoQAyAKEAMgChaTIAof8yAKH/MgCh4TIA + oR4yAKEAAAAAAAAAAAAAAAAAMgChADIAoQcyAKE4MgChijIAod8yAKH9MgCh+zIAoc4yAKFdMgChADIA + of8yAKHlMgChlDIAoToyAKGgMgCh7jIAoSwyAKEAMgChFzIAodgyAKGZMgChADIAoQAyAKFpMgCh/zIA + of8yAKHxMgChfDIAoSkyAKEBMgChAAAAAAAAAAAAAAAAADIAoQAyAKECMgChITIAoW8yAKG/MgCh/zIA + oZYyAKEAMgCh/zIAoZoyAKEBMgChADIAoZkyAKHSMgChEjIAoQAyAKEGMgChujIAoZoyAKEAMgChADIA + oWkyAKH/MgCh/zIAof0yAKH+MgCh4TIAoZIyAKFEMgChDjIAoQAyAKEAAAAAAAAAAAAAAAAAMgChADIA + oUIyAKH7MgChlzIAoQAyAKH/MgChlzIAoQAyAKEAMgChmjIAobMyAKEEMgChADIAoQAyAKGcMgChmzIA + oQAyAKEAMgChaTIAof8yAKH/MgCh4zIAoZYyAKHRMgCh+zIAofQyAKHDMgChZDIAoSIyAKEBMgChAAAA + AAAyAKEAMgChPzIAofsyAKGXMgChADIAof8yAKGXMgChADIAoQAyAKGaMgChiDIAoQAAAAAAMgChADIA + oYgyAKGaMgChADIAoQAyAKFpMgCh/zIAof8yAKHhMgChIDIAoRIyAKFeMgChqzIAoe0yAKH+MgCh3jIA + oYYyAKEqMgChADIAoQAyAKE/MgCh+zIAoZcyAKEAMgCh/zIAoZcyAKEAMgChADIAoZgyAKFtMgChAAAA + AAAyAKEAMgChXDIAoZQyAKEAMgChADIAoWkyAKH/MgCh/zIAoeEyAKEeMgChADIAoQAyAKEGMgChMDIA + oX8yAKHTMgCh+jIAoWkyAKEAMgChADIAoT8yAKH7MgChlzIAoQAyAKH/MgChlzIAoQAyAKEAMgChlTIA + oWMyAKEAAAAAADIAoQAyAKE2MgChhTIAoQAyAKEAMgChaTIAof8yAKH/MgCh4TIAoR4yAKEAAAAAAAAA + AAAyAKEAMgChATIAoRUyAKFYMgChQDIAoQAyAKEAMgChPzIAofsyAKGXMgChADIAof8yAKGXMgChADIA + oQAyAKGLMgChQTIAoQAyAKEFMgChADIAoSMyAKF4MgChADIAoQAyAKFpMgCh/zIAof8yAKHhMgChHjIA + oQAAAAAAAAAAAAAAAAAAAAAAMgChADIAoQAyAKEBMgChADIAoQAyAKE/MgCh+zIAoZcyAKEAMgCh/zIA + oZcyAKEAMgChADIAoXcyAKEkMgChBzIAoUIyAKEBMgChFjIAoWUyAKEBMgChADIAoWkyAKH/MgCh/zIA + oeEyAKEeMgChADIAoQAyAKE5MgChSTIAoQ8yAKEBMgChAAAAAAAAAAAAMgChADIAoT8yAKH7MgChlzIA + oQAyAKH/MgChlzIAoQAyAKECMgChWzIAoQ8yAKEVMgChhTIAoQoyAKEHMgChMzIAoQEyAKEAMgChaTIA + of8yAKH/MgCh4TIAoR4yAKEAMgChADIAoWkyAKH1MgChyzIAoX8yAKE4MgChBTIAoQAyAKEAMgChPzIA + ofsyAKGXMgChADIAof8yAKGXMgChADIAoQMyAKFZMgChCzIAoS4yAKHDMgChGjIAoQAAAAAAAAAAADIA + oQAyAKFpMgCh/zIAof8yAKHhMgChHjIAoQAyAKEAMgChLDIAoaEyAKHkMgCh/DIAoe8yAKGrMgChUzIA + oREyAKFBMgCh+zIAoZcyAKEAMgCh/zIAoZcyAKEAMgChBzIAoVAyAKEEMgChQTIAodoyAKEjMgChAAAA + AAAAAAAAMgChADIAoWkyAKH/MgCh/zIAoeEyAKEeMgChAAAAAAAyAKEAMgChBjIAoSAyAKFyMgChwjIA + ofMyAKH4MgCh0zIAobMyAKH9MgChljIAoQAyAKH/MgChlzIAoQAyAKEBMgChBDIAoQAyAKFKMgCh7jIA + oT0yAKEAAAAAADIAoQAyAKEAMgChbDIAof8yAKH/MgCh4TIAoR8yAKEAAAAAAAAAAAAAAAAAMgChADIA + oQEyAKELMgChRzIAoZYyAKHeMgCh/TIAof8yAKGWMgChADIAof8yAKGXMgChAAAAAAAAAAAAMgChADIA + oW0yAKH/MgChZDIAoQAyAKEEMgChHDIAoWAyAKHPMgCh/zIAof8yAKH3MgChkTIAoS8yAKELMgChADIA + oQAAAAAAAAAAAAAAAAAyAKEAMgChATIAoSAyAKF2MgCh/zIAoZYyAKEAMgCh/zIAoZcyAKEAAAAAADIA + oQAyAKEAMgChljIAof8yAKGeMgChOTIAoZEyAKHcMgCh+TIAof8yAKH/MgCh/zIAof8yAKH+MgCh6jIA + obgyAKFXMgChITIAoQEyAKEAAAAAAAAAAAAAAAAAMgChADIAoT8yAKH7MgChlzIAoQAyAKH/MgChlzIA + oQAAAAAAMgChADIAoQwyAKG9MgCh/zIAofMyAKHyMgCh/jIAof8yAKH/MgCh/zIAofoyAKH3MgCh/jIA + of8yAKH/MgCh/zIAofsyAKHbMgChmzIAoUwyAKENMgChATIAoQAyAKEAMgChPzIAofsyAKGXMgChADIA + of8yAKGXMgChATIAoRkyAKFbMgChsTIAofAyAKH/MgCh/zIAof8yAKH/MgCh/DIAoeYyAKGxMgChVTIA + oUIyAKGFMgCh1TIAofUyAKH/MgCh/zIAof8yAKH/MgCh9DIAocUyAKGDMgChMDIAoQYyAKE/MgCh+zIA + oZcyAKEAMgCh/zIAocEyAKGOMgCh2TIAofcyAKH/MgCh/zIAof8yAKH/MgCh7jIAobMyAKFwMgChJjIA + oQoyAKEAMgChADIAoQEyAKEXMgChTTIAoZsyAKHYMgCh/TIAof8yAKH/MgCh/zIAof4yAKHqMgChszIA + oZgyAKH+MgChljIAoQAyAKH/MgCh/zIAof8yAKH/MgCh/zIAof8yAKH0MgChyTIAoYEyAKE/MgChBzIA + oQAAAAAAMgChADIAoSIyAKF2MgChQjIAoRIyAKEAMgChATIAoR4yAKFjMgChrjIAoecyAKH9MgCh/zIA + of8yAKH/MgCh/zIAof8yAKGWMgChADIAof8yAKH/MgCh/zIAofkyAKHWMgChmjIAoUIyAKERMgChATIA + oQAyAKEGMgChFTIAoQMyAKEAMgChKDIAoZUyAKHHMgChxjIAoXcyAKE3MgChBzIAoQAyAKEGMgChKTIA + oXYyAKHDMgCh7jIAof4yAKH/MgCh/zIAoZYyAKEAMgChrjIAoeYyAKH+MgCh0zIAoVcyAKELMgChADIA + oQAyAKEAMgChADIAoVUyAKHAMgChkjIAoVYyAKEUMgChATIAoRYyAKFhMgChqzIAodUyAKGmMgChZTIA + oR8yAKEDMgChBDIAoS0yAKGiMgCh9DIAofUyAKHGMgChWTIAoQAyAKEGMgChKjIAoWsyAKHBMgCh3DIA + ocEyAKFwMgChJTIAoQYyAKEAMgChDDIAoTgyAKF/MgChyjIAocMyAKGUMgChMzIAoQsyAKEEMgChJjIA + oWUyAKG/MgCh0TIAoaYyAKGoMgCh1TIAodYyAKGNMgChQTIAoRAyAKEAMgChAAAAAAAyAKEAMgChADIA + oQ8yAKE8MgChkDIAoc8yAKHfMgChpDIAoVIyAKEcMgChADIAoQEyAKETMgChRzIAoZ8yAKHGMgChvzIA + oWQyAKEtMgChMzIAoY8yAKHvMgCh5zIAoa8yAKFcMgChHDIAoQMyAKEAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAADIAoQAyAKECMgChFTIAoVcyAKGaMgCh3DIAodEyAKGaMgChSDIAoQsyAKEAMgChATIA + oSUyAKGGMgCh6TIAofEyAKHhMgChtzIAoXAyAKErMgChBTIAoQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMgChADIAoQIyAKElMgChXTIAobgyAKHbMgChxTIA + oYUyAKFbMgChqzIAodEyAKHLMgChhDIAoTsyAKELMgChAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAyAKEAMgChCzIA + oTcyAKGTMgCh0zIAofAyAKG2MgChWjIAoRcyAKEBMgChAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAA/+Af//+AB//8AAD/8AAAP8AIAA8AGDABARg+AQEYD4ERGAPxMZgAcTOY + ADEzmDAxM5g8MTKIPzEgCDDxIAgwMSB4MAEgeDgBJHg+ATxAD8E8AAHxOAAAMQAAAAEAAwABABwgAQBE + BAEBwAABAEAAA+AAAA/4AAB//wAD///gD/8= + + + \ No newline at end of file diff --git a/MisDataPlcTagID/MisDataPlcTagID/MisDataWebFunSim.Designer.cs b/MisDataPlcTagID/MisDataPlcTagID/MisDataWebFunSim.Designer.cs new file mode 100644 index 0000000..9ca366d --- /dev/null +++ b/MisDataPlcTagID/MisDataPlcTagID/MisDataWebFunSim.Designer.cs @@ -0,0 +1,1776 @@ +namespace MisDataSaveDateSim +{ + partial class MisData + { + /// + /// 必需的设计器变量。 + /// + 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.components = new System.ComponentModel.Container(); + System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MisData)); + this.comboBox_OpName = new System.Windows.Forms.ComboBox(); + this.label_OpNameList = new System.Windows.Forms.Label(); + this.textBox_tagValue_Read = new System.Windows.Forms.TextBox(); + this.textBox_tagValue = new System.Windows.Forms.TextBox(); + this.textBox_Cmd = new System.Windows.Forms.TextBox(); + this.button_Read = new System.Windows.Forms.Button(); + this.button_Write = new System.Windows.Forms.Button(); + this.listBox1 = new System.Windows.Forms.ListBox(); + this.checkBox_WorkStart = new System.Windows.Forms.CheckBox(); + this.numericUpDown1 = new System.Windows.Forms.NumericUpDown(); + this.button_ReadData = new System.Windows.Forms.Button(); + this.groupBox_SignialSimulatorOld = new System.Windows.Forms.GroupBox(); + this.groupBox_WorkStationStatus = new System.Windows.Forms.GroupBox(); + this.Cbx_StatusDisplay = new System.Windows.Forms.CheckBox(); + this.Tbx_Status_11_EngineType = new System.Windows.Forms.TextBox(); + this.Tbx_Status_9_EngineTypeID = new System.Windows.Forms.TextBox(); + this.label2 = new System.Windows.Forms.Label(); + this.Tbx_Status_10_EngineID = new System.Windows.Forms.TextBox(); + this.label20 = new System.Windows.Forms.Label(); + this.Tbx_Status_80_Pallet = new System.Windows.Forms.TextBox(); + this.label21 = new System.Windows.Forms.Label(); + this.label22 = new System.Windows.Forms.Label(); + this.groupBox_PLC = new System.Windows.Forms.GroupBox(); + this.checkBox_PLCData_Display = new System.Windows.Forms.CheckBox(); + this.Btn_Read_PLC = new System.Windows.Forms.Button(); + this.Tbx_PLC_23_RepairMark = new System.Windows.Forms.TextBox(); + this.Tbx_PLC_22_PalletStatus = new System.Windows.Forms.TextBox(); + this.Tbx_PLC_21_ResultMark = new System.Windows.Forms.TextBox(); + this.Tbx_PLC_80_PalletNum = new System.Windows.Forms.TextBox(); + this.Tbx_PLC_10_EngineID = new System.Windows.Forms.TextBox(); + this.Tbx_PLC_18_Actual = new System.Windows.Forms.TextBox(); + this.Tbx_PLC_9_EngineTypeID = new System.Windows.Forms.TextBox(); + this.Tbx_PLC_17_TargetTime = new System.Windows.Forms.TextBox(); + this.Tbx_PLC_11_Enginetype = new System.Windows.Forms.TextBox(); + this.label3 = new System.Windows.Forms.Label(); + this.label4 = 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.label18 = new System.Windows.Forms.Label(); + this.label17 = new System.Windows.Forms.Label(); + this.label9 = new System.Windows.Forms.Label(); + this.groupBox3 = new System.Windows.Forms.GroupBox(); + this.Btn_Write_PLC = new System.Windows.Forms.Button(); + this.Btn_PLC_1003_ShortFall = new System.Windows.Forms.Button(); + this.Btn_PLC_19_MesRead = new System.Windows.Forms.Button(); + this.Btn_PLC_1002_MachaineBreak = new System.Windows.Forms.Button(); + this.Btn_PLC_59_FixOK = new System.Windows.Forms.Button(); + this.Btn_PLC_1001_CycleStart = new System.Windows.Forms.Button(); + this.Btn_PLC_1000_MachinePowerOn = new System.Windows.Forms.Button(); + this.Btn_PLC_44_EngineTypeGetOver = new System.Windows.Forms.Button(); + this.Btn_PLC_13_PalletIn = new System.Windows.Forms.Button(); + this.Btn_PLC_50_ApplyOffline = new System.Windows.Forms.Button(); + this.Btn_PLC_43_PartLoad = new System.Windows.Forms.Button(); + this.Btn_PLC_16_AllowReadCycleTime = new System.Windows.Forms.Button(); + this.Btn_PLC_1004_Jam = new System.Windows.Forms.Button(); + this.Btn_PLC_14_HeartBeat = new System.Windows.Forms.Button(); + this.Btn_PLC_2_WorkStart = new System.Windows.Forms.Button(); + this.groupBox_MES = new System.Windows.Forms.GroupBox(); + this.checkBox_MESData_Display = new System.Windows.Forms.CheckBox(); + this.Btn_Read_MES = new System.Windows.Forms.Button(); + this.Tbx_MES_88_SocketNum = new System.Windows.Forms.TextBox(); + this.Tbx_MES_77_FixOrder = new System.Windows.Forms.TextBox(); + this.Tbx_MES_74_EngineID = new System.Windows.Forms.TextBox(); + this.Tbx_MES_79_OnlineStatus = new System.Windows.Forms.TextBox(); + this.Tbx_MES_4_WorkStationRepairStr = new System.Windows.Forms.TextBox(); + this.Tbx_MES_93_RepairMark = new System.Windows.Forms.TextBox(); + this.label19 = new System.Windows.Forms.Label(); + this.Tbx_MES_73_EngineTypeID = new System.Windows.Forms.TextBox(); + this.Tbx_MES_75_Enginetype = new System.Windows.Forms.TextBox(); + this.label10 = new System.Windows.Forms.Label(); + this.label11 = new System.Windows.Forms.Label(); + this.label12 = new System.Windows.Forms.Label(); + this.label13 = new System.Windows.Forms.Label(); + this.label14 = new System.Windows.Forms.Label(); + this.label15 = new System.Windows.Forms.Label(); + this.label16 = new System.Windows.Forms.Label(); + this.groupBox5 = new System.Windows.Forms.GroupBox(); + this.Btn_Write_MES = new System.Windows.Forms.Button(); + this.Btn_MES_69_MachResult = new System.Windows.Forms.Button(); + this.Btn_MES_8_FalseGo = new System.Windows.Forms.Button(); + this.Btn_MES_67_FixOver = new System.Windows.Forms.Button(); + this.Btn_MES_7_WorkComplete = new System.Windows.Forms.Button(); + this.Btn_MES_53_OffLineOK = new System.Windows.Forms.Button(); + this.Btn_MES_66_AllowWork = new System.Windows.Forms.Button(); + this.Btn_MES_5_EngineTypeGetOver = new System.Windows.Forms.Button(); + this.Btn_MES_72_MobyClear = new System.Windows.Forms.Button(); + this.Btn_MES_54_ReadCycleTimeOK = new System.Windows.Forms.Button(); + this.Btn_MES_68_MachComplete = new System.Windows.Forms.Button(); + this.Btn_MES_52_ResetEquipment = new System.Windows.Forms.Button(); + this.Btn_MES_6_PalletGo = new System.Windows.Forms.Button(); + this.Btn_MES_20_MesReadOver = new System.Windows.Forms.Button(); + this.Btn_MES_71_IsAuto = new System.Windows.Forms.Button(); + this.Btn_MES_51_ConfirmOkGo = new System.Windows.Forms.Button(); + this.Btn_MES_15_HeartBeat = new System.Windows.Forms.Button(); + this.groupBox_WorkStationQuality = new System.Windows.Forms.GroupBox(); + this.groupBox2 = new System.Windows.Forms.GroupBox(); + this.textBox_Copy_Item = new System.Windows.Forms.TextBox(); + this.textBox_Copy_TagID = new System.Windows.Forms.TextBox(); + this.textBox_Base_Item = new System.Windows.Forms.TextBox(); + this.textBox_Base_TagID = new System.Windows.Forms.TextBox(); + this.radioButton_Copy = new System.Windows.Forms.RadioButton(); + this.radioButton_Base = new System.Windows.Forms.RadioButton(); + this.groupBox1 = new System.Windows.Forms.GroupBox(); + this.radioButton_PlcSignl_Copy = new System.Windows.Forms.RadioButton(); + this.radioButton_PartCodeSanner = new System.Windows.Forms.RadioButton(); + this.radioButton_PlcSignl = new System.Windows.Forms.RadioButton(); + this.cb_QdData = new System.Windows.Forms.CheckBox(); + this.cb_MonitorData = new System.Windows.Forms.CheckBox(); + this.contextMenuStrip_MIS = new System.Windows.Forms.ContextMenuStrip(this.components); + this.toolStripMenuItem_Show = new System.Windows.Forms.ToolStripMenuItem(); + this.toolStripMenuItem_Hide = new System.Windows.Forms.ToolStripMenuItem(); + this.toolStripMenuItem_Exit = new System.Windows.Forms.ToolStripMenuItem(); + this.statusStrip1 = new System.Windows.Forms.StatusStrip(); + this.toolStripStatusLabel_RunningStatu = new System.Windows.Forms.ToolStripStatusLabel(); + this.toolStripStatusLabel_RunningStatus = new System.Windows.Forms.ToolStripStatusLabel(); + this.toolStripStatusLabel2 = new System.Windows.Forms.ToolStripStatusLabel(); + this.toolStripStatusLabel_StartTime = new System.Windows.Forms.ToolStripStatusLabel(); + this.toolStripStatusLabel3 = new System.Windows.Forms.ToolStripStatusLabel(); + this.toolStripStatusLabel_RunTime = new System.Windows.Forms.ToolStripStatusLabel(); + this.toolStripStatusLabel1 = new System.Windows.Forms.ToolStripStatusLabel(); + this.toolStripStatusLabel_WorkStationNum = new System.Windows.Forms.ToolStripStatusLabel(); + this.toolStripStatusLabel6 = new System.Windows.Forms.ToolStripStatusLabel(); + this.toolStripStatusLabel_OnlineNum = new System.Windows.Forms.ToolStripStatusLabel(); + this.toolStripStatusLabel8 = new System.Windows.Forms.ToolStripStatusLabel(); + this.toolStripStatusLabel_DownLine = new System.Windows.Forms.ToolStripStatusLabel(); + this.toolStripStatusLabel4 = new System.Windows.Forms.ToolStripStatusLabel(); + this.toolStripStatusLabel_Version = new System.Windows.Forms.ToolStripStatusLabel(); + this.groupBox_Alarm = new System.Windows.Forms.GroupBox(); + this.timer_ReadTagValues = new System.Windows.Forms.Timer(this.components); + this.groupBox4 = new System.Windows.Forms.GroupBox(); + this.groupBox6 = new System.Windows.Forms.GroupBox(); + this.listView_ShowQualityData = new ListViewDouble.ListViewNF(); + this.columnHeader4 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); + this.columnHeader2 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); + this.columnHeader3 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); + this.columnHeader1 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); + this.columnHeader5 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); + this.groupBox_SignialSimulator = new System.Windows.Forms.GroupBox(); + ((System.ComponentModel.ISupportInitialize)(this.numericUpDown1)).BeginInit(); + this.groupBox_SignialSimulatorOld.SuspendLayout(); + this.groupBox_WorkStationStatus.SuspendLayout(); + this.groupBox_PLC.SuspendLayout(); + this.groupBox_MES.SuspendLayout(); + this.groupBox_WorkStationQuality.SuspendLayout(); + this.groupBox2.SuspendLayout(); + this.groupBox1.SuspendLayout(); + this.contextMenuStrip_MIS.SuspendLayout(); + this.statusStrip1.SuspendLayout(); + this.groupBox4.SuspendLayout(); + this.groupBox6.SuspendLayout(); + this.groupBox_SignialSimulator.SuspendLayout(); + this.SuspendLayout(); + // + // comboBox_OpName + // + this.comboBox_OpName.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; + this.comboBox_OpName.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.comboBox_OpName.FormattingEnabled = true; + this.comboBox_OpName.Location = new System.Drawing.Point(72, 15); + this.comboBox_OpName.Name = "comboBox_OpName"; + this.comboBox_OpName.Size = new System.Drawing.Size(76, 20); + this.comboBox_OpName.TabIndex = 1425; + this.comboBox_OpName.SelectedIndexChanged += new System.EventHandler(this.comboBox_OpName_SelectedIndexChanged); + // + // label_OpNameList + // + this.label_OpNameList.AutoSize = true; + this.label_OpNameList.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.label_OpNameList.Location = new System.Drawing.Point(6, 19); + this.label_OpNameList.Name = "label_OpNameList"; + this.label_OpNameList.Size = new System.Drawing.Size(65, 12); + this.label_OpNameList.TabIndex = 1424; + this.label_OpNameList.Text = "工位编号:"; + this.label_OpNameList.DoubleClick += new System.EventHandler(this.label_OpNameList_DoubleClick); + // + // textBox_tagValue_Read + // + this.textBox_tagValue_Read.Location = new System.Drawing.Point(84, 91); + this.textBox_tagValue_Read.Margin = new System.Windows.Forms.Padding(2); + this.textBox_tagValue_Read.Name = "textBox_tagValue_Read"; + this.textBox_tagValue_Read.ReadOnly = true; + this.textBox_tagValue_Read.Size = new System.Drawing.Size(119, 21); + this.textBox_tagValue_Read.TabIndex = 1464; + // + // textBox_tagValue + // + this.textBox_tagValue.Location = new System.Drawing.Point(84, 124); + this.textBox_tagValue.Margin = new System.Windows.Forms.Padding(2); + this.textBox_tagValue.Name = "textBox_tagValue"; + this.textBox_tagValue.Size = new System.Drawing.Size(119, 21); + this.textBox_tagValue.TabIndex = 1458; + // + // textBox_Cmd + // + this.textBox_Cmd.Location = new System.Drawing.Point(123, 151); + this.textBox_Cmd.Margin = new System.Windows.Forms.Padding(2); + this.textBox_Cmd.Name = "textBox_Cmd"; + this.textBox_Cmd.Size = new System.Drawing.Size(80, 21); + this.textBox_Cmd.TabIndex = 1460; + // + // button_Read + // + this.button_Read.Location = new System.Drawing.Point(17, 89); + this.button_Read.Margin = new System.Windows.Forms.Padding(2); + this.button_Read.Name = "button_Read"; + this.button_Read.Size = new System.Drawing.Size(56, 25); + this.button_Read.TabIndex = 1454; + this.button_Read.Text = "读取"; + this.button_Read.UseVisualStyleBackColor = true; + this.button_Read.Click += new System.EventHandler(this.button_Read_Click); + // + // button_Write + // + this.button_Write.Location = new System.Drawing.Point(17, 122); + this.button_Write.Margin = new System.Windows.Forms.Padding(2); + this.button_Write.Name = "button_Write"; + this.button_Write.Size = new System.Drawing.Size(56, 25); + this.button_Write.TabIndex = 1455; + this.button_Write.Text = "写入"; + this.button_Write.UseVisualStyleBackColor = true; + this.button_Write.Click += new System.EventHandler(this.button_Write_Click); + // + // listBox1 + // + this.listBox1.FormattingEnabled = true; + this.listBox1.ItemHeight = 12; + this.listBox1.Location = new System.Drawing.Point(210, 86); + this.listBox1.Margin = new System.Windows.Forms.Padding(2); + this.listBox1.Name = "listBox1"; + this.listBox1.Size = new System.Drawing.Size(225, 88); + this.listBox1.TabIndex = 1453; + this.listBox1.SelectedValueChanged += new System.EventHandler(this.listBox1_SelectedValueChanged); + // + // checkBox_WorkStart + // + this.checkBox_WorkStart.AutoSize = true; + this.checkBox_WorkStart.Location = new System.Drawing.Point(18, 156); + this.checkBox_WorkStart.Margin = new System.Windows.Forms.Padding(2); + this.checkBox_WorkStart.Name = "checkBox_WorkStart"; + this.checkBox_WorkStart.Size = new System.Drawing.Size(48, 16); + this.checkBox_WorkStart.TabIndex = 1466; + this.checkBox_WorkStart.Text = "模拟"; + this.checkBox_WorkStart.UseVisualStyleBackColor = true; + this.checkBox_WorkStart.CheckedChanged += new System.EventHandler(this.checkBox_WorkStart_CheckedChanged); + // + // numericUpDown1 + // + this.numericUpDown1.Location = new System.Drawing.Point(84, 151); + this.numericUpDown1.Margin = new System.Windows.Forms.Padding(2); + this.numericUpDown1.Name = "numericUpDown1"; + this.numericUpDown1.Size = new System.Drawing.Size(35, 21); + this.numericUpDown1.TabIndex = 1467; + this.numericUpDown1.Value = new decimal(new int[] { + 5, + 0, + 0, + 0}); + this.numericUpDown1.ValueChanged += new System.EventHandler(this.numericUpDown1_ValueChanged); + // + // button_ReadData + // + this.button_ReadData.Location = new System.Drawing.Point(114, 20); + this.button_ReadData.Name = "button_ReadData"; + this.button_ReadData.Size = new System.Drawing.Size(62, 23); + this.button_ReadData.TabIndex = 1470; + this.button_ReadData.Text = "读取数据"; + this.button_ReadData.UseVisualStyleBackColor = true; + this.button_ReadData.Click += new System.EventHandler(this.button_ReadData_Click); + // + // groupBox_SignialSimulatorOld + // + this.groupBox_SignialSimulatorOld.Controls.Add(this.groupBox_WorkStationStatus); + this.groupBox_SignialSimulatorOld.Controls.Add(this.textBox_Cmd); + this.groupBox_SignialSimulatorOld.Controls.Add(this.button_Write); + this.groupBox_SignialSimulatorOld.Controls.Add(this.button_Read); + this.groupBox_SignialSimulatorOld.Controls.Add(this.numericUpDown1); + this.groupBox_SignialSimulatorOld.Controls.Add(this.listBox1); + this.groupBox_SignialSimulatorOld.Controls.Add(this.checkBox_WorkStart); + this.groupBox_SignialSimulatorOld.Controls.Add(this.textBox_tagValue_Read); + this.groupBox_SignialSimulatorOld.Controls.Add(this.textBox_tagValue); + this.groupBox_SignialSimulatorOld.Location = new System.Drawing.Point(489, 160); + this.groupBox_SignialSimulatorOld.Name = "groupBox_SignialSimulatorOld"; + this.groupBox_SignialSimulatorOld.Size = new System.Drawing.Size(447, 190); + this.groupBox_SignialSimulatorOld.TabIndex = 1471; + this.groupBox_SignialSimulatorOld.TabStop = false; + this.groupBox_SignialSimulatorOld.Text = "信号模拟"; + // + // groupBox_WorkStationStatus + // + this.groupBox_WorkStationStatus.Controls.Add(this.Cbx_StatusDisplay); + this.groupBox_WorkStationStatus.Controls.Add(this.label_OpNameList); + this.groupBox_WorkStationStatus.Controls.Add(this.Tbx_Status_11_EngineType); + this.groupBox_WorkStationStatus.Controls.Add(this.Tbx_Status_9_EngineTypeID); + this.groupBox_WorkStationStatus.Controls.Add(this.comboBox_OpName); + this.groupBox_WorkStationStatus.Controls.Add(this.label2); + this.groupBox_WorkStationStatus.Controls.Add(this.Tbx_Status_10_EngineID); + this.groupBox_WorkStationStatus.Controls.Add(this.label20); + this.groupBox_WorkStationStatus.Controls.Add(this.Tbx_Status_80_Pallet); + this.groupBox_WorkStationStatus.Controls.Add(this.label21); + this.groupBox_WorkStationStatus.Controls.Add(this.label22); + this.groupBox_WorkStationStatus.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.groupBox_WorkStationStatus.Location = new System.Drawing.Point(12, 14); + this.groupBox_WorkStationStatus.Name = "groupBox_WorkStationStatus"; + this.groupBox_WorkStationStatus.Size = new System.Drawing.Size(423, 69); + this.groupBox_WorkStationStatus.TabIndex = 1468; + this.groupBox_WorkStationStatus.TabStop = false; + this.groupBox_WorkStationStatus.Text = "WorkStationStatus"; + // + // Cbx_StatusDisplay + // + this.Cbx_StatusDisplay.AutoSize = true; + this.Cbx_StatusDisplay.Enabled = false; + this.Cbx_StatusDisplay.Location = new System.Drawing.Point(355, 17); + this.Cbx_StatusDisplay.Name = "Cbx_StatusDisplay"; + this.Cbx_StatusDisplay.Size = new System.Drawing.Size(48, 16); + this.Cbx_StatusDisplay.TabIndex = 1426; + this.Cbx_StatusDisplay.Text = "同步"; + this.Cbx_StatusDisplay.UseVisualStyleBackColor = true; + // + // Tbx_Status_11_EngineType + // + this.Tbx_Status_11_EngineType.Location = new System.Drawing.Point(309, 41); + this.Tbx_Status_11_EngineType.Name = "Tbx_Status_11_EngineType"; + this.Tbx_Status_11_EngineType.ReadOnly = true; + this.Tbx_Status_11_EngineType.Size = new System.Drawing.Size(94, 21); + this.Tbx_Status_11_EngineType.TabIndex = 3; + this.Tbx_Status_11_EngineType.Text = "加载中..."; + // + // Tbx_Status_9_EngineTypeID + // + this.Tbx_Status_9_EngineTypeID.Location = new System.Drawing.Point(210, 15); + this.Tbx_Status_9_EngineTypeID.Name = "Tbx_Status_9_EngineTypeID"; + this.Tbx_Status_9_EngineTypeID.ReadOnly = true; + this.Tbx_Status_9_EngineTypeID.Size = new System.Drawing.Size(29, 21); + this.Tbx_Status_9_EngineTypeID.TabIndex = 3; + this.Tbx_Status_9_EngineTypeID.Text = "..."; + // + // label2 + // + this.label2.AutoSize = true; + this.label2.Location = new System.Drawing.Point(6, 45); + this.label2.Name = "label2"; + this.label2.Size = new System.Drawing.Size(65, 12); + this.label2.TabIndex = 2; + this.label2.Text = "产品编号:"; + // + // Tbx_Status_10_EngineID + // + this.Tbx_Status_10_EngineID.Location = new System.Drawing.Point(72, 41); + this.Tbx_Status_10_EngineID.Name = "Tbx_Status_10_EngineID"; + this.Tbx_Status_10_EngineID.ReadOnly = true; + this.Tbx_Status_10_EngineID.Size = new System.Drawing.Size(167, 21); + this.Tbx_Status_10_EngineID.TabIndex = 3; + this.Tbx_Status_10_EngineID.Text = "加载中..."; + // + // label20 + // + this.label20.AutoSize = true; + this.label20.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.label20.Location = new System.Drawing.Point(245, 45); + this.label20.Name = "label20"; + this.label20.Size = new System.Drawing.Size(65, 12); + this.label20.TabIndex = 2; + this.label20.Text = "产品型号:"; + // + // Tbx_Status_80_Pallet + // + this.Tbx_Status_80_Pallet.Location = new System.Drawing.Point(309, 15); + this.Tbx_Status_80_Pallet.Name = "Tbx_Status_80_Pallet"; + this.Tbx_Status_80_Pallet.ReadOnly = true; + this.Tbx_Status_80_Pallet.Size = new System.Drawing.Size(31, 21); + this.Tbx_Status_80_Pallet.TabIndex = 5; + this.Tbx_Status_80_Pallet.Text = "..."; + // + // label21 + // + this.label21.AutoSize = true; + this.label21.Location = new System.Drawing.Point(150, 19); + this.label21.Name = "label21"; + this.label21.Size = new System.Drawing.Size(65, 12); + this.label21.TabIndex = 2; + this.label21.Text = "机型代码:"; + // + // label22 + // + this.label22.AutoSize = true; + this.label22.Location = new System.Drawing.Point(245, 19); + this.label22.Name = "label22"; + this.label22.Size = new System.Drawing.Size(65, 12); + this.label22.TabIndex = 2; + this.label22.Text = "托盘编号:"; + // + // groupBox_PLC + // + this.groupBox_PLC.Controls.Add(this.checkBox_PLCData_Display); + this.groupBox_PLC.Controls.Add(this.Btn_Read_PLC); + this.groupBox_PLC.Controls.Add(this.Tbx_PLC_23_RepairMark); + this.groupBox_PLC.Controls.Add(this.Tbx_PLC_22_PalletStatus); + this.groupBox_PLC.Controls.Add(this.Tbx_PLC_21_ResultMark); + this.groupBox_PLC.Controls.Add(this.Tbx_PLC_80_PalletNum); + this.groupBox_PLC.Controls.Add(this.Tbx_PLC_10_EngineID); + this.groupBox_PLC.Controls.Add(this.Tbx_PLC_18_Actual); + this.groupBox_PLC.Controls.Add(this.Tbx_PLC_9_EngineTypeID); + this.groupBox_PLC.Controls.Add(this.Tbx_PLC_17_TargetTime); + this.groupBox_PLC.Controls.Add(this.Tbx_PLC_11_Enginetype); + this.groupBox_PLC.Controls.Add(this.label3); + this.groupBox_PLC.Controls.Add(this.label4); + this.groupBox_PLC.Controls.Add(this.label5); + this.groupBox_PLC.Controls.Add(this.label6); + this.groupBox_PLC.Controls.Add(this.label7); + this.groupBox_PLC.Controls.Add(this.label8); + this.groupBox_PLC.Controls.Add(this.label18); + this.groupBox_PLC.Controls.Add(this.label17); + this.groupBox_PLC.Controls.Add(this.label9); + this.groupBox_PLC.Controls.Add(this.groupBox3); + this.groupBox_PLC.Controls.Add(this.Btn_Write_PLC); + this.groupBox_PLC.Location = new System.Drawing.Point(7, 224); + this.groupBox_PLC.Name = "groupBox_PLC"; + this.groupBox_PLC.Size = new System.Drawing.Size(413, 128); + this.groupBox_PLC.TabIndex = 0; + this.groupBox_PLC.TabStop = false; + this.groupBox_PLC.Text = "PLC"; + // + // checkBox_PLCData_Display + // + this.checkBox_PLCData_Display.AutoSize = true; + this.checkBox_PLCData_Display.Checked = true; + this.checkBox_PLCData_Display.CheckState = System.Windows.Forms.CheckState.Checked; + this.checkBox_PLCData_Display.Location = new System.Drawing.Point(192, 102); + this.checkBox_PLCData_Display.Name = "checkBox_PLCData_Display"; + this.checkBox_PLCData_Display.Size = new System.Drawing.Size(48, 16); + this.checkBox_PLCData_Display.TabIndex = 7; + this.checkBox_PLCData_Display.Text = "同步"; + this.checkBox_PLCData_Display.UseVisualStyleBackColor = true; + // + // Btn_Read_PLC + // + this.Btn_Read_PLC.Location = new System.Drawing.Point(249, 99); + this.Btn_Read_PLC.Name = "Btn_Read_PLC"; + this.Btn_Read_PLC.Size = new System.Drawing.Size(75, 23); + this.Btn_Read_PLC.TabIndex = 6; + this.Btn_Read_PLC.Text = "读取 PLC"; + this.Btn_Read_PLC.UseVisualStyleBackColor = true; + this.Btn_Read_PLC.Click += new System.EventHandler(this.Btn_Read_PLC_Click); + // + // Tbx_PLC_23_RepairMark + // + this.Tbx_PLC_23_RepairMark.Location = new System.Drawing.Point(373, 74); + this.Tbx_PLC_23_RepairMark.Name = "Tbx_PLC_23_RepairMark"; + this.Tbx_PLC_23_RepairMark.Size = new System.Drawing.Size(33, 21); + this.Tbx_PLC_23_RepairMark.TabIndex = 5; + this.Tbx_PLC_23_RepairMark.Text = "0"; + // + // Tbx_PLC_22_PalletStatus + // + this.Tbx_PLC_22_PalletStatus.Location = new System.Drawing.Point(373, 47); + this.Tbx_PLC_22_PalletStatus.Name = "Tbx_PLC_22_PalletStatus"; + this.Tbx_PLC_22_PalletStatus.Size = new System.Drawing.Size(33, 21); + this.Tbx_PLC_22_PalletStatus.TabIndex = 5; + this.Tbx_PLC_22_PalletStatus.Text = "1"; + // + // Tbx_PLC_21_ResultMark + // + this.Tbx_PLC_21_ResultMark.Location = new System.Drawing.Point(259, 75); + this.Tbx_PLC_21_ResultMark.Name = "Tbx_PLC_21_ResultMark"; + this.Tbx_PLC_21_ResultMark.Size = new System.Drawing.Size(37, 21); + this.Tbx_PLC_21_ResultMark.TabIndex = 5; + this.Tbx_PLC_21_ResultMark.Text = "1"; + // + // Tbx_PLC_80_PalletNum + // + this.Tbx_PLC_80_PalletNum.Location = new System.Drawing.Point(259, 48); + this.Tbx_PLC_80_PalletNum.Name = "Tbx_PLC_80_PalletNum"; + this.Tbx_PLC_80_PalletNum.Size = new System.Drawing.Size(37, 21); + this.Tbx_PLC_80_PalletNum.TabIndex = 5; + this.Tbx_PLC_80_PalletNum.Text = "2"; + // + // Tbx_PLC_10_EngineID + // + this.Tbx_PLC_10_EngineID.Location = new System.Drawing.Point(259, 22); + this.Tbx_PLC_10_EngineID.Name = "Tbx_PLC_10_EngineID"; + this.Tbx_PLC_10_EngineID.Size = new System.Drawing.Size(146, 21); + this.Tbx_PLC_10_EngineID.TabIndex = 3; + this.Tbx_PLC_10_EngineID.Text = "H12C3-00001001"; + // + // Tbx_PLC_18_Actual + // + this.Tbx_PLC_18_Actual.Location = new System.Drawing.Point(101, 100); + this.Tbx_PLC_18_Actual.Name = "Tbx_PLC_18_Actual"; + this.Tbx_PLC_18_Actual.Size = new System.Drawing.Size(61, 21); + this.Tbx_PLC_18_Actual.TabIndex = 3; + this.Tbx_PLC_18_Actual.Text = "50"; + // + // Tbx_PLC_9_EngineTypeID + // + this.Tbx_PLC_9_EngineTypeID.Location = new System.Drawing.Point(77, 47); + this.Tbx_PLC_9_EngineTypeID.Name = "Tbx_PLC_9_EngineTypeID"; + this.Tbx_PLC_9_EngineTypeID.Size = new System.Drawing.Size(85, 21); + this.Tbx_PLC_9_EngineTypeID.TabIndex = 3; + this.Tbx_PLC_9_EngineTypeID.Text = "1"; + // + // Tbx_PLC_17_TargetTime + // + this.Tbx_PLC_17_TargetTime.Location = new System.Drawing.Point(101, 74); + this.Tbx_PLC_17_TargetTime.Name = "Tbx_PLC_17_TargetTime"; + this.Tbx_PLC_17_TargetTime.Size = new System.Drawing.Size(61, 21); + this.Tbx_PLC_17_TargetTime.TabIndex = 3; + this.Tbx_PLC_17_TargetTime.Text = "50"; + // + // Tbx_PLC_11_Enginetype + // + this.Tbx_PLC_11_Enginetype.Location = new System.Drawing.Point(77, 22); + this.Tbx_PLC_11_Enginetype.Name = "Tbx_PLC_11_Enginetype"; + this.Tbx_PLC_11_Enginetype.Size = new System.Drawing.Size(85, 21); + this.Tbx_PLC_11_Enginetype.TabIndex = 3; + this.Tbx_PLC_11_Enginetype.Text = "H12C3-00001"; + // + // label3 + // + this.label3.AutoSize = true; + this.label3.Location = new System.Drawing.Point(192, 26); + this.label3.Name = "label3"; + this.label3.Size = new System.Drawing.Size(65, 12); + this.label3.TabIndex = 2; + this.label3.Text = "产品编号:"; + // + // label4 + // + this.label4.AutoSize = true; + this.label4.Location = new System.Drawing.Point(306, 52); + this.label4.Name = "label4"; + this.label4.Size = new System.Drawing.Size(65, 12); + this.label4.TabIndex = 2; + this.label4.Text = "托盘状态:"; + // + // label5 + // + this.label5.AutoSize = true; + this.label5.Location = new System.Drawing.Point(192, 52); + this.label5.Name = "label5"; + this.label5.Size = new System.Drawing.Size(65, 12); + this.label5.TabIndex = 2; + this.label5.Text = "托盘编号:"; + // + // label6 + // + this.label6.AutoSize = true; + this.label6.Location = new System.Drawing.Point(306, 78); + this.label6.Name = "label6"; + this.label6.Size = new System.Drawing.Size(65, 12); + this.label6.TabIndex = 2; + this.label6.Text = "返修标志:"; + // + // label7 + // + this.label7.AutoSize = true; + this.label7.Location = new System.Drawing.Point(192, 78); + this.label7.Name = "label7"; + this.label7.Size = new System.Drawing.Size(65, 12); + this.label7.TabIndex = 2; + this.label7.Text = "合格标志:"; + // + // label8 + // + this.label8.AutoSize = true; + this.label8.Location = new System.Drawing.Point(6, 52); + this.label8.Name = "label8"; + this.label8.Size = new System.Drawing.Size(65, 12); + this.label8.TabIndex = 2; + this.label8.Text = "机型代码:"; + // + // label18 + // + this.label18.AutoSize = true; + this.label18.Location = new System.Drawing.Point(6, 104); + this.label18.Name = "label18"; + this.label18.Size = new System.Drawing.Size(89, 12); + this.label18.TabIndex = 2; + this.label18.Text = "实际运行时间:"; + // + // label17 + // + this.label17.AutoSize = true; + this.label17.Location = new System.Drawing.Point(6, 78); + this.label17.Name = "label17"; + this.label17.Size = new System.Drawing.Size(89, 12); + this.label17.TabIndex = 2; + this.label17.Text = "目标运行时间:"; + // + // label9 + // + this.label9.AutoSize = true; + this.label9.Location = new System.Drawing.Point(6, 26); + this.label9.Name = "label9"; + this.label9.Size = new System.Drawing.Size(65, 12); + this.label9.TabIndex = 2; + this.label9.Text = "产品型号:"; + // + // groupBox3 + // + this.groupBox3.Location = new System.Drawing.Point(3, 100); + this.groupBox3.Name = "groupBox3"; + this.groupBox3.Size = new System.Drawing.Size(415, 1); + this.groupBox3.TabIndex = 1; + this.groupBox3.TabStop = false; + // + // Btn_Write_PLC + // + this.Btn_Write_PLC.Location = new System.Drawing.Point(331, 99); + this.Btn_Write_PLC.Name = "Btn_Write_PLC"; + this.Btn_Write_PLC.Size = new System.Drawing.Size(75, 23); + this.Btn_Write_PLC.TabIndex = 0; + this.Btn_Write_PLC.Text = "写入 PLC"; + this.Btn_Write_PLC.UseVisualStyleBackColor = true; + this.Btn_Write_PLC.Click += new System.EventHandler(this.Btn_Write_PLC_Click); + // + // Btn_PLC_1003_ShortFall + // + this.Btn_PLC_1003_ShortFall.Location = new System.Drawing.Point(334, 195); + this.Btn_PLC_1003_ShortFall.Name = "Btn_PLC_1003_ShortFall"; + this.Btn_PLC_1003_ShortFall.Size = new System.Drawing.Size(75, 23); + this.Btn_PLC_1003_ShortFall.TabIndex = 0; + this.Btn_PLC_1003_ShortFall.Text = "上料无件"; + this.Btn_PLC_1003_ShortFall.UseVisualStyleBackColor = true; + this.Btn_PLC_1003_ShortFall.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_PLC_19_MesRead + // + this.Btn_PLC_19_MesRead.Location = new System.Drawing.Point(87, 45); + this.Btn_PLC_19_MesRead.Name = "Btn_PLC_19_MesRead"; + this.Btn_PLC_19_MesRead.Size = new System.Drawing.Size(75, 23); + this.Btn_PLC_19_MesRead.TabIndex = 0; + this.Btn_PLC_19_MesRead.Text = "允许保存"; + this.Btn_PLC_19_MesRead.UseVisualStyleBackColor = true; + this.Btn_PLC_19_MesRead.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_PLC_1002_MachaineBreak + // + this.Btn_PLC_1002_MachaineBreak.Location = new System.Drawing.Point(6, 127); + this.Btn_PLC_1002_MachaineBreak.Name = "Btn_PLC_1002_MachaineBreak"; + this.Btn_PLC_1002_MachaineBreak.Size = new System.Drawing.Size(75, 23); + this.Btn_PLC_1002_MachaineBreak.TabIndex = 0; + this.Btn_PLC_1002_MachaineBreak.Text = "机床故障"; + this.Btn_PLC_1002_MachaineBreak.UseVisualStyleBackColor = true; + this.Btn_PLC_1002_MachaineBreak.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_PLC_59_FixOK + // + this.Btn_PLC_59_FixOK.Location = new System.Drawing.Point(6, 71); + this.Btn_PLC_59_FixOK.Name = "Btn_PLC_59_FixOK"; + this.Btn_PLC_59_FixOK.Size = new System.Drawing.Size(75, 23); + this.Btn_PLC_59_FixOK.TabIndex = 0; + this.Btn_PLC_59_FixOK.Text = "拧紧完成"; + this.Btn_PLC_59_FixOK.UseVisualStyleBackColor = true; + this.Btn_PLC_59_FixOK.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_PLC_1001_CycleStart + // + this.Btn_PLC_1001_CycleStart.Location = new System.Drawing.Point(87, 195); + this.Btn_PLC_1001_CycleStart.Name = "Btn_PLC_1001_CycleStart"; + this.Btn_PLC_1001_CycleStart.Size = new System.Drawing.Size(75, 23); + this.Btn_PLC_1001_CycleStart.TabIndex = 0; + this.Btn_PLC_1001_CycleStart.Text = "循环开始"; + this.Btn_PLC_1001_CycleStart.UseVisualStyleBackColor = true; + this.Btn_PLC_1001_CycleStart.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_PLC_1000_MachinePowerOn + // + this.Btn_PLC_1000_MachinePowerOn.Location = new System.Drawing.Point(168, 195); + this.Btn_PLC_1000_MachinePowerOn.Name = "Btn_PLC_1000_MachinePowerOn"; + this.Btn_PLC_1000_MachinePowerOn.Size = new System.Drawing.Size(75, 23); + this.Btn_PLC_1000_MachinePowerOn.TabIndex = 0; + this.Btn_PLC_1000_MachinePowerOn.Text = "机床上电"; + this.Btn_PLC_1000_MachinePowerOn.UseVisualStyleBackColor = true; + this.Btn_PLC_1000_MachinePowerOn.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_PLC_44_EngineTypeGetOver + // + this.Btn_PLC_44_EngineTypeGetOver.Location = new System.Drawing.Point(87, 16); + this.Btn_PLC_44_EngineTypeGetOver.Name = "Btn_PLC_44_EngineTypeGetOver"; + this.Btn_PLC_44_EngineTypeGetOver.Size = new System.Drawing.Size(75, 23); + this.Btn_PLC_44_EngineTypeGetOver.TabIndex = 0; + this.Btn_PLC_44_EngineTypeGetOver.Text = "传递机型"; + this.Btn_PLC_44_EngineTypeGetOver.UseVisualStyleBackColor = true; + this.Btn_PLC_44_EngineTypeGetOver.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_PLC_13_PalletIn + // + this.Btn_PLC_13_PalletIn.Location = new System.Drawing.Point(6, 100); + this.Btn_PLC_13_PalletIn.Name = "Btn_PLC_13_PalletIn"; + this.Btn_PLC_13_PalletIn.Size = new System.Drawing.Size(75, 23); + this.Btn_PLC_13_PalletIn.TabIndex = 0; + this.Btn_PLC_13_PalletIn.Text = "托盘到位"; + this.Btn_PLC_13_PalletIn.UseVisualStyleBackColor = true; + this.Btn_PLC_13_PalletIn.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_PLC_50_ApplyOffline + // + this.Btn_PLC_50_ApplyOffline.Location = new System.Drawing.Point(87, 71); + this.Btn_PLC_50_ApplyOffline.Name = "Btn_PLC_50_ApplyOffline"; + this.Btn_PLC_50_ApplyOffline.Size = new System.Drawing.Size(75, 23); + this.Btn_PLC_50_ApplyOffline.TabIndex = 0; + this.Btn_PLC_50_ApplyOffline.Text = "申请下线"; + this.Btn_PLC_50_ApplyOffline.UseVisualStyleBackColor = true; + this.Btn_PLC_50_ApplyOffline.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_PLC_43_PartLoad + // + this.Btn_PLC_43_PartLoad.Location = new System.Drawing.Point(87, 99); + this.Btn_PLC_43_PartLoad.Name = "Btn_PLC_43_PartLoad"; + this.Btn_PLC_43_PartLoad.Size = new System.Drawing.Size(75, 23); + this.Btn_PLC_43_PartLoad.TabIndex = 0; + this.Btn_PLC_43_PartLoad.Text = "申请上线"; + this.Btn_PLC_43_PartLoad.UseVisualStyleBackColor = true; + this.Btn_PLC_43_PartLoad.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_PLC_16_AllowReadCycleTime + // + this.Btn_PLC_16_AllowReadCycleTime.Location = new System.Drawing.Point(87, 128); + this.Btn_PLC_16_AllowReadCycleTime.Name = "Btn_PLC_16_AllowReadCycleTime"; + this.Btn_PLC_16_AllowReadCycleTime.Size = new System.Drawing.Size(75, 23); + this.Btn_PLC_16_AllowReadCycleTime.TabIndex = 0; + this.Btn_PLC_16_AllowReadCycleTime.Text = "允许读节拍"; + this.Btn_PLC_16_AllowReadCycleTime.UseVisualStyleBackColor = true; + this.Btn_PLC_16_AllowReadCycleTime.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_PLC_1004_Jam + // + this.Btn_PLC_1004_Jam.Location = new System.Drawing.Point(252, 195); + this.Btn_PLC_1004_Jam.Name = "Btn_PLC_1004_Jam"; + this.Btn_PLC_1004_Jam.Size = new System.Drawing.Size(75, 23); + this.Btn_PLC_1004_Jam.TabIndex = 0; + this.Btn_PLC_1004_Jam.Text = "下料堵塞"; + this.Btn_PLC_1004_Jam.UseVisualStyleBackColor = true; + this.Btn_PLC_1004_Jam.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_PLC_14_HeartBeat + // + this.Btn_PLC_14_HeartBeat.Location = new System.Drawing.Point(6, 46); + this.Btn_PLC_14_HeartBeat.Name = "Btn_PLC_14_HeartBeat"; + this.Btn_PLC_14_HeartBeat.Size = new System.Drawing.Size(75, 23); + this.Btn_PLC_14_HeartBeat.TabIndex = 0; + this.Btn_PLC_14_HeartBeat.Text = "心跳信号"; + this.Btn_PLC_14_HeartBeat.UseVisualStyleBackColor = true; + this.Btn_PLC_14_HeartBeat.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_PLC_2_WorkStart + // + this.Btn_PLC_2_WorkStart.Location = new System.Drawing.Point(6, 15); + this.Btn_PLC_2_WorkStart.Name = "Btn_PLC_2_WorkStart"; + this.Btn_PLC_2_WorkStart.Size = new System.Drawing.Size(75, 23); + this.Btn_PLC_2_WorkStart.TabIndex = 0; + this.Btn_PLC_2_WorkStart.Text = "工件到位"; + this.Btn_PLC_2_WorkStart.UseVisualStyleBackColor = true; + this.Btn_PLC_2_WorkStart.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // groupBox_MES + // + this.groupBox_MES.Controls.Add(this.checkBox_MESData_Display); + this.groupBox_MES.Controls.Add(this.Btn_Read_MES); + this.groupBox_MES.Controls.Add(this.Tbx_MES_88_SocketNum); + this.groupBox_MES.Controls.Add(this.Tbx_MES_77_FixOrder); + this.groupBox_MES.Controls.Add(this.Tbx_MES_74_EngineID); + this.groupBox_MES.Controls.Add(this.Tbx_MES_79_OnlineStatus); + this.groupBox_MES.Controls.Add(this.Tbx_MES_4_WorkStationRepairStr); + this.groupBox_MES.Controls.Add(this.Tbx_MES_93_RepairMark); + this.groupBox_MES.Controls.Add(this.label19); + this.groupBox_MES.Controls.Add(this.Tbx_MES_73_EngineTypeID); + this.groupBox_MES.Controls.Add(this.Tbx_MES_75_Enginetype); + this.groupBox_MES.Controls.Add(this.label10); + this.groupBox_MES.Controls.Add(this.label11); + this.groupBox_MES.Controls.Add(this.label12); + this.groupBox_MES.Controls.Add(this.label13); + this.groupBox_MES.Controls.Add(this.label14); + this.groupBox_MES.Controls.Add(this.label15); + this.groupBox_MES.Controls.Add(this.label16); + this.groupBox_MES.Controls.Add(this.groupBox5); + this.groupBox_MES.Controls.Add(this.Btn_Write_MES); + this.groupBox_MES.Location = new System.Drawing.Point(3, 51); + this.groupBox_MES.Name = "groupBox_MES"; + this.groupBox_MES.Size = new System.Drawing.Size(411, 125); + this.groupBox_MES.TabIndex = 0; + this.groupBox_MES.TabStop = false; + this.groupBox_MES.Text = "MES"; + // + // checkBox_MESData_Display + // + this.checkBox_MESData_Display.AutoSize = true; + this.checkBox_MESData_Display.Checked = true; + this.checkBox_MESData_Display.CheckState = System.Windows.Forms.CheckState.Checked; + this.checkBox_MESData_Display.Location = new System.Drawing.Point(192, 98); + this.checkBox_MESData_Display.Name = "checkBox_MESData_Display"; + this.checkBox_MESData_Display.Size = new System.Drawing.Size(48, 16); + this.checkBox_MESData_Display.TabIndex = 7; + this.checkBox_MESData_Display.Text = "同步"; + this.checkBox_MESData_Display.UseVisualStyleBackColor = true; + // + // Btn_Read_MES + // + this.Btn_Read_MES.Location = new System.Drawing.Point(249, 95); + this.Btn_Read_MES.Name = "Btn_Read_MES"; + this.Btn_Read_MES.Size = new System.Drawing.Size(75, 23); + this.Btn_Read_MES.TabIndex = 6; + this.Btn_Read_MES.Text = "读取 MES"; + this.Btn_Read_MES.UseVisualStyleBackColor = true; + this.Btn_Read_MES.Click += new System.EventHandler(this.Btn_Read_MES_Click); + // + // Tbx_MES_88_SocketNum + // + this.Tbx_MES_88_SocketNum.Location = new System.Drawing.Point(373, 70); + this.Tbx_MES_88_SocketNum.Name = "Tbx_MES_88_SocketNum"; + this.Tbx_MES_88_SocketNum.Size = new System.Drawing.Size(33, 21); + this.Tbx_MES_88_SocketNum.TabIndex = 3; + this.Tbx_MES_88_SocketNum.Text = "1"; + // + // Tbx_MES_77_FixOrder + // + this.Tbx_MES_77_FixOrder.Location = new System.Drawing.Point(259, 70); + this.Tbx_MES_77_FixOrder.Name = "Tbx_MES_77_FixOrder"; + this.Tbx_MES_77_FixOrder.Size = new System.Drawing.Size(29, 21); + this.Tbx_MES_77_FixOrder.TabIndex = 3; + this.Tbx_MES_77_FixOrder.Text = "1"; + // + // Tbx_MES_74_EngineID + // + this.Tbx_MES_74_EngineID.Location = new System.Drawing.Point(259, 44); + this.Tbx_MES_74_EngineID.Name = "Tbx_MES_74_EngineID"; + this.Tbx_MES_74_EngineID.Size = new System.Drawing.Size(147, 21); + this.Tbx_MES_74_EngineID.TabIndex = 3; + this.Tbx_MES_74_EngineID.Text = "H12C3-00001001"; + // + // Tbx_MES_79_OnlineStatus + // + this.Tbx_MES_79_OnlineStatus.Location = new System.Drawing.Point(373, 17); + this.Tbx_MES_79_OnlineStatus.Name = "Tbx_MES_79_OnlineStatus"; + this.Tbx_MES_79_OnlineStatus.Size = new System.Drawing.Size(33, 21); + this.Tbx_MES_79_OnlineStatus.TabIndex = 3; + this.Tbx_MES_79_OnlineStatus.Text = "1"; + // + // Tbx_MES_4_WorkStationRepairStr + // + this.Tbx_MES_4_WorkStationRepairStr.Location = new System.Drawing.Point(77, 18); + this.Tbx_MES_4_WorkStationRepairStr.Name = "Tbx_MES_4_WorkStationRepairStr"; + this.Tbx_MES_4_WorkStationRepairStr.Size = new System.Drawing.Size(223, 21); + this.Tbx_MES_4_WorkStationRepairStr.TabIndex = 3; + this.Tbx_MES_4_WorkStationRepairStr.Text = "1111111111111111111"; + // + // Tbx_MES_93_RepairMark + // + this.Tbx_MES_93_RepairMark.Location = new System.Drawing.Point(77, 96); + this.Tbx_MES_93_RepairMark.Name = "Tbx_MES_93_RepairMark"; + this.Tbx_MES_93_RepairMark.Size = new System.Drawing.Size(85, 21); + this.Tbx_MES_93_RepairMark.TabIndex = 3; + this.Tbx_MES_93_RepairMark.Text = "0"; + // + // label19 + // + this.label19.AutoSize = true; + this.label19.Location = new System.Drawing.Point(6, 22); + this.label19.Name = "label19"; + this.label19.Size = new System.Drawing.Size(65, 12); + this.label19.TabIndex = 2; + this.label19.Text = "返修工位:"; + // + // Tbx_MES_73_EngineTypeID + // + this.Tbx_MES_73_EngineTypeID.Location = new System.Drawing.Point(77, 70); + this.Tbx_MES_73_EngineTypeID.Name = "Tbx_MES_73_EngineTypeID"; + this.Tbx_MES_73_EngineTypeID.Size = new System.Drawing.Size(85, 21); + this.Tbx_MES_73_EngineTypeID.TabIndex = 3; + this.Tbx_MES_73_EngineTypeID.Text = "1"; + // + // Tbx_MES_75_Enginetype + // + this.Tbx_MES_75_Enginetype.Location = new System.Drawing.Point(77, 44); + this.Tbx_MES_75_Enginetype.Name = "Tbx_MES_75_Enginetype"; + this.Tbx_MES_75_Enginetype.Size = new System.Drawing.Size(85, 21); + this.Tbx_MES_75_Enginetype.TabIndex = 3; + this.Tbx_MES_75_Enginetype.Text = "H12C3-00001"; + // + // label10 + // + this.label10.AutoSize = true; + this.label10.Location = new System.Drawing.Point(192, 48); + this.label10.Name = "label10"; + this.label10.Size = new System.Drawing.Size(65, 12); + this.label10.TabIndex = 2; + this.label10.Text = "产品编号:"; + // + // label11 + // + this.label11.AutoSize = true; + this.label11.Location = new System.Drawing.Point(306, 74); + this.label11.Name = "label11"; + this.label11.Size = new System.Drawing.Size(65, 12); + this.label11.TabIndex = 2; + this.label11.Text = "套筒编号:"; + // + // label12 + // + this.label12.AutoSize = true; + this.label12.Location = new System.Drawing.Point(192, 74); + this.label12.Name = "label12"; + this.label12.Size = new System.Drawing.Size(65, 12); + this.label12.TabIndex = 2; + this.label12.Text = "拧紧序号:"; + // + // label13 + // + this.label13.AutoSize = true; + this.label13.Location = new System.Drawing.Point(306, 21); + this.label13.Name = "label13"; + this.label13.Size = new System.Drawing.Size(65, 12); + this.label13.TabIndex = 2; + this.label13.Text = "工位状态:"; + // + // label14 + // + this.label14.AutoSize = true; + this.label14.Location = new System.Drawing.Point(6, 100); + this.label14.Name = "label14"; + this.label14.Size = new System.Drawing.Size(65, 12); + this.label14.TabIndex = 2; + this.label14.Text = "返修标志:"; + // + // label15 + // + this.label15.AutoSize = true; + this.label15.Location = new System.Drawing.Point(6, 74); + this.label15.Name = "label15"; + this.label15.Size = new System.Drawing.Size(65, 12); + this.label15.TabIndex = 2; + this.label15.Text = "机型代码:"; + // + // label16 + // + this.label16.AutoSize = true; + this.label16.Location = new System.Drawing.Point(6, 48); + this.label16.Name = "label16"; + this.label16.Size = new System.Drawing.Size(65, 12); + this.label16.TabIndex = 2; + this.label16.Text = "产品型号:"; + // + // groupBox5 + // + this.groupBox5.Location = new System.Drawing.Point(3, 128); + this.groupBox5.Name = "groupBox5"; + this.groupBox5.Size = new System.Drawing.Size(415, 1); + this.groupBox5.TabIndex = 1; + this.groupBox5.TabStop = false; + // + // Btn_Write_MES + // + this.Btn_Write_MES.Location = new System.Drawing.Point(331, 95); + this.Btn_Write_MES.Name = "Btn_Write_MES"; + this.Btn_Write_MES.Size = new System.Drawing.Size(75, 23); + this.Btn_Write_MES.TabIndex = 0; + this.Btn_Write_MES.Text = "写入 MES"; + this.Btn_Write_MES.UseVisualStyleBackColor = true; + this.Btn_Write_MES.Click += new System.EventHandler(this.Btn_Write_MES_Click); + // + // Btn_MES_69_MachResult + // + this.Btn_MES_69_MachResult.Location = new System.Drawing.Point(87, 78); + this.Btn_MES_69_MachResult.Name = "Btn_MES_69_MachResult"; + this.Btn_MES_69_MachResult.Size = new System.Drawing.Size(75, 23); + this.Btn_MES_69_MachResult.TabIndex = 0; + this.Btn_MES_69_MachResult.Text = "匹配结果"; + this.Btn_MES_69_MachResult.UseVisualStyleBackColor = true; + this.Btn_MES_69_MachResult.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_MES_8_FalseGo + // + this.Btn_MES_8_FalseGo.Location = new System.Drawing.Point(87, 20); + this.Btn_MES_8_FalseGo.Name = "Btn_MES_8_FalseGo"; + this.Btn_MES_8_FalseGo.Size = new System.Drawing.Size(75, 23); + this.Btn_MES_8_FalseGo.TabIndex = 0; + this.Btn_MES_8_FalseGo.Text = "不合格放行"; + this.Btn_MES_8_FalseGo.UseVisualStyleBackColor = true; + this.Btn_MES_8_FalseGo.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_MES_67_FixOver + // + this.Btn_MES_67_FixOver.Location = new System.Drawing.Point(87, 134); + this.Btn_MES_67_FixOver.Name = "Btn_MES_67_FixOver"; + this.Btn_MES_67_FixOver.Size = new System.Drawing.Size(75, 23); + this.Btn_MES_67_FixOver.TabIndex = 0; + this.Btn_MES_67_FixOver.Text = "完成确认"; + this.Btn_MES_67_FixOver.UseVisualStyleBackColor = true; + this.Btn_MES_67_FixOver.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_MES_7_WorkComplete + // + this.Btn_MES_7_WorkComplete.Location = new System.Drawing.Point(87, 48); + this.Btn_MES_7_WorkComplete.Name = "Btn_MES_7_WorkComplete"; + this.Btn_MES_7_WorkComplete.Size = new System.Drawing.Size(75, 23); + this.Btn_MES_7_WorkComplete.TabIndex = 0; + this.Btn_MES_7_WorkComplete.Text = "工作完成"; + this.Btn_MES_7_WorkComplete.UseVisualStyleBackColor = true; + this.Btn_MES_7_WorkComplete.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_MES_53_OffLineOK + // + this.Btn_MES_53_OffLineOK.Location = new System.Drawing.Point(6, 134); + this.Btn_MES_53_OffLineOK.Name = "Btn_MES_53_OffLineOK"; + this.Btn_MES_53_OffLineOK.Size = new System.Drawing.Size(75, 23); + this.Btn_MES_53_OffLineOK.TabIndex = 0; + this.Btn_MES_53_OffLineOK.Text = "下线完成"; + this.Btn_MES_53_OffLineOK.UseVisualStyleBackColor = true; + this.Btn_MES_53_OffLineOK.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_MES_66_AllowWork + // + this.Btn_MES_66_AllowWork.Location = new System.Drawing.Point(9, 73); + this.Btn_MES_66_AllowWork.Name = "Btn_MES_66_AllowWork"; + this.Btn_MES_66_AllowWork.Size = new System.Drawing.Size(75, 23); + this.Btn_MES_66_AllowWork.TabIndex = 0; + this.Btn_MES_66_AllowWork.Text = "允许工作"; + this.Btn_MES_66_AllowWork.UseVisualStyleBackColor = true; + this.Btn_MES_66_AllowWork.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_MES_5_EngineTypeGetOver + // + this.Btn_MES_5_EngineTypeGetOver.Location = new System.Drawing.Point(9, 48); + this.Btn_MES_5_EngineTypeGetOver.Name = "Btn_MES_5_EngineTypeGetOver"; + this.Btn_MES_5_EngineTypeGetOver.Size = new System.Drawing.Size(75, 23); + this.Btn_MES_5_EngineTypeGetOver.TabIndex = 0; + this.Btn_MES_5_EngineTypeGetOver.Text = "传递机型"; + this.Btn_MES_5_EngineTypeGetOver.UseVisualStyleBackColor = true; + this.Btn_MES_5_EngineTypeGetOver.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_MES_72_MobyClear + // + this.Btn_MES_72_MobyClear.Location = new System.Drawing.Point(168, 14); + this.Btn_MES_72_MobyClear.Name = "Btn_MES_72_MobyClear"; + this.Btn_MES_72_MobyClear.Size = new System.Drawing.Size(75, 23); + this.Btn_MES_72_MobyClear.TabIndex = 0; + this.Btn_MES_72_MobyClear.Text = "清空Moby"; + this.Btn_MES_72_MobyClear.UseVisualStyleBackColor = true; + this.Btn_MES_72_MobyClear.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_MES_54_ReadCycleTimeOK + // + this.Btn_MES_54_ReadCycleTimeOK.Location = new System.Drawing.Point(6, 163); + this.Btn_MES_54_ReadCycleTimeOK.Name = "Btn_MES_54_ReadCycleTimeOK"; + this.Btn_MES_54_ReadCycleTimeOK.Size = new System.Drawing.Size(75, 23); + this.Btn_MES_54_ReadCycleTimeOK.TabIndex = 0; + this.Btn_MES_54_ReadCycleTimeOK.Text = "读节拍完成"; + this.Btn_MES_54_ReadCycleTimeOK.UseVisualStyleBackColor = true; + this.Btn_MES_54_ReadCycleTimeOK.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_MES_68_MachComplete + // + this.Btn_MES_68_MachComplete.Location = new System.Drawing.Point(6, 101); + this.Btn_MES_68_MachComplete.Name = "Btn_MES_68_MachComplete"; + this.Btn_MES_68_MachComplete.Size = new System.Drawing.Size(75, 23); + this.Btn_MES_68_MachComplete.TabIndex = 0; + this.Btn_MES_68_MachComplete.Text = "匹配完成"; + this.Btn_MES_68_MachComplete.UseVisualStyleBackColor = true; + this.Btn_MES_68_MachComplete.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_MES_52_ResetEquipment + // + this.Btn_MES_52_ResetEquipment.Location = new System.Drawing.Point(6, 13); + this.Btn_MES_52_ResetEquipment.Name = "Btn_MES_52_ResetEquipment"; + this.Btn_MES_52_ResetEquipment.Size = new System.Drawing.Size(75, 23); + this.Btn_MES_52_ResetEquipment.TabIndex = 0; + this.Btn_MES_52_ResetEquipment.Text = "复位设备"; + this.Btn_MES_52_ResetEquipment.UseVisualStyleBackColor = true; + this.Btn_MES_52_ResetEquipment.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_MES_6_PalletGo + // + this.Btn_MES_6_PalletGo.Location = new System.Drawing.Point(87, 14); + this.Btn_MES_6_PalletGo.Name = "Btn_MES_6_PalletGo"; + this.Btn_MES_6_PalletGo.Size = new System.Drawing.Size(75, 23); + this.Btn_MES_6_PalletGo.TabIndex = 0; + this.Btn_MES_6_PalletGo.Text = "空托盘放行"; + this.Btn_MES_6_PalletGo.UseVisualStyleBackColor = true; + this.Btn_MES_6_PalletGo.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_MES_20_MesReadOver + // + this.Btn_MES_20_MesReadOver.Location = new System.Drawing.Point(87, 106); + this.Btn_MES_20_MesReadOver.Name = "Btn_MES_20_MesReadOver"; + this.Btn_MES_20_MesReadOver.Size = new System.Drawing.Size(75, 23); + this.Btn_MES_20_MesReadOver.TabIndex = 0; + this.Btn_MES_20_MesReadOver.Text = "保存完成"; + this.Btn_MES_20_MesReadOver.UseVisualStyleBackColor = true; + this.Btn_MES_20_MesReadOver.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_MES_71_IsAuto + // + this.Btn_MES_71_IsAuto.Location = new System.Drawing.Point(252, 14); + this.Btn_MES_71_IsAuto.Name = "Btn_MES_71_IsAuto"; + this.Btn_MES_71_IsAuto.Size = new System.Drawing.Size(75, 23); + this.Btn_MES_71_IsAuto.TabIndex = 0; + this.Btn_MES_71_IsAuto.Text = "自动手动"; + this.Btn_MES_71_IsAuto.UseVisualStyleBackColor = true; + this.Btn_MES_71_IsAuto.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_MES_51_ConfirmOkGo + // + this.Btn_MES_51_ConfirmOkGo.Location = new System.Drawing.Point(87, 160); + this.Btn_MES_51_ConfirmOkGo.Name = "Btn_MES_51_ConfirmOkGo"; + this.Btn_MES_51_ConfirmOkGo.Size = new System.Drawing.Size(75, 23); + this.Btn_MES_51_ConfirmOkGo.TabIndex = 0; + this.Btn_MES_51_ConfirmOkGo.Text = "合格放行"; + this.Btn_MES_51_ConfirmOkGo.UseVisualStyleBackColor = true; + this.Btn_MES_51_ConfirmOkGo.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_MES_15_HeartBeat + // + this.Btn_MES_15_HeartBeat.Location = new System.Drawing.Point(9, 20); + this.Btn_MES_15_HeartBeat.Name = "Btn_MES_15_HeartBeat"; + this.Btn_MES_15_HeartBeat.Size = new System.Drawing.Size(75, 23); + this.Btn_MES_15_HeartBeat.TabIndex = 0; + this.Btn_MES_15_HeartBeat.Text = "心跳信号"; + this.Btn_MES_15_HeartBeat.UseVisualStyleBackColor = true; + this.Btn_MES_15_HeartBeat.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // groupBox_WorkStationQuality + // + this.groupBox_WorkStationQuality.Controls.Add(this.groupBox2); + this.groupBox_WorkStationQuality.Controls.Add(this.groupBox1); + this.groupBox_WorkStationQuality.Controls.Add(this.cb_QdData); + this.groupBox_WorkStationQuality.Controls.Add(this.cb_MonitorData); + this.groupBox_WorkStationQuality.Controls.Add(this.button_ReadData); + this.groupBox_WorkStationQuality.Location = new System.Drawing.Point(489, 9); + this.groupBox_WorkStationQuality.Name = "groupBox_WorkStationQuality"; + this.groupBox_WorkStationQuality.Size = new System.Drawing.Size(447, 149); + this.groupBox_WorkStationQuality.TabIndex = 1472; + this.groupBox_WorkStationQuality.TabStop = false; + this.groupBox_WorkStationQuality.Text = "质量数据"; + // + // groupBox2 + // + this.groupBox2.Controls.Add(this.textBox_Copy_Item); + this.groupBox2.Controls.Add(this.textBox_Copy_TagID); + this.groupBox2.Controls.Add(this.textBox_Base_Item); + this.groupBox2.Controls.Add(this.textBox_Base_TagID); + this.groupBox2.Controls.Add(this.radioButton_Copy); + this.groupBox2.Controls.Add(this.radioButton_Base); + this.groupBox2.Location = new System.Drawing.Point(10, 60); + this.groupBox2.Name = "groupBox2"; + this.groupBox2.Size = new System.Drawing.Size(425, 78); + this.groupBox2.TabIndex = 1474; + this.groupBox2.TabStop = false; + this.groupBox2.Text = "当前选择的信号"; + // + // textBox_Copy_Item + // + this.textBox_Copy_Item.Location = new System.Drawing.Point(283, 47); + this.textBox_Copy_Item.Name = "textBox_Copy_Item"; + this.textBox_Copy_Item.ReadOnly = true; + this.textBox_Copy_Item.Size = new System.Drawing.Size(136, 21); + this.textBox_Copy_Item.TabIndex = 1; + // + // textBox_Copy_TagID + // + this.textBox_Copy_TagID.Location = new System.Drawing.Point(79, 47); + this.textBox_Copy_TagID.Name = "textBox_Copy_TagID"; + this.textBox_Copy_TagID.ReadOnly = true; + this.textBox_Copy_TagID.Size = new System.Drawing.Size(186, 21); + this.textBox_Copy_TagID.TabIndex = 1; + // + // textBox_Base_Item + // + this.textBox_Base_Item.Location = new System.Drawing.Point(283, 20); + this.textBox_Base_Item.Name = "textBox_Base_Item"; + this.textBox_Base_Item.ReadOnly = true; + this.textBox_Base_Item.Size = new System.Drawing.Size(136, 21); + this.textBox_Base_Item.TabIndex = 1; + // + // textBox_Base_TagID + // + this.textBox_Base_TagID.Location = new System.Drawing.Point(79, 20); + this.textBox_Base_TagID.Name = "textBox_Base_TagID"; + this.textBox_Base_TagID.ReadOnly = true; + this.textBox_Base_TagID.Size = new System.Drawing.Size(186, 21); + this.textBox_Base_TagID.TabIndex = 1; + // + // radioButton_Copy + // + this.radioButton_Copy.AutoSize = true; + this.radioButton_Copy.Enabled = false; + this.radioButton_Copy.Location = new System.Drawing.Point(7, 50); + this.radioButton_Copy.Name = "radioButton_Copy"; + this.radioButton_Copy.Size = new System.Drawing.Size(71, 16); + this.radioButton_Copy.TabIndex = 0; + this.radioButton_Copy.Text = "拷贝信号"; + this.radioButton_Copy.UseVisualStyleBackColor = true; + // + // radioButton_Base + // + this.radioButton_Base.AutoSize = true; + this.radioButton_Base.Checked = true; + this.radioButton_Base.Enabled = false; + this.radioButton_Base.Location = new System.Drawing.Point(7, 20); + this.radioButton_Base.Name = "radioButton_Base"; + this.radioButton_Base.Size = new System.Drawing.Size(71, 16); + this.radioButton_Base.TabIndex = 0; + this.radioButton_Base.TabStop = true; + this.radioButton_Base.Text = "基本信号"; + this.radioButton_Base.UseVisualStyleBackColor = true; + // + // groupBox1 + // + this.groupBox1.Controls.Add(this.radioButton_PlcSignl_Copy); + this.groupBox1.Controls.Add(this.radioButton_PartCodeSanner); + this.groupBox1.Controls.Add(this.radioButton_PlcSignl); + this.groupBox1.Location = new System.Drawing.Point(182, 8); + this.groupBox1.Name = "groupBox1"; + this.groupBox1.Size = new System.Drawing.Size(253, 46); + this.groupBox1.TabIndex = 1473; + this.groupBox1.TabStop = false; + // + // radioButton_PlcSignl_Copy + // + this.radioButton_PlcSignl_Copy.AutoSize = true; + this.radioButton_PlcSignl_Copy.Location = new System.Drawing.Point(167, 18); + this.radioButton_PlcSignl_Copy.Name = "radioButton_PlcSignl_Copy"; + this.radioButton_PlcSignl_Copy.Size = new System.Drawing.Size(71, 16); + this.radioButton_PlcSignl_Copy.TabIndex = 1; + this.radioButton_PlcSignl_Copy.TabStop = true; + this.radioButton_PlcSignl_Copy.Text = "拷贝信号"; + this.radioButton_PlcSignl_Copy.UseVisualStyleBackColor = true; + this.radioButton_PlcSignl_Copy.Click += new System.EventHandler(this.radioButton_PlcSignl_Copy_Click); + // + // radioButton_PartCodeSanner + // + this.radioButton_PartCodeSanner.AutoSize = true; + this.radioButton_PartCodeSanner.Location = new System.Drawing.Point(77, 19); + this.radioButton_PartCodeSanner.Name = "radioButton_PartCodeSanner"; + this.radioButton_PartCodeSanner.Size = new System.Drawing.Size(71, 16); + this.radioButton_PartCodeSanner.TabIndex = 0; + this.radioButton_PartCodeSanner.Text = "物料扫描"; + this.radioButton_PartCodeSanner.UseVisualStyleBackColor = true; + this.radioButton_PartCodeSanner.Click += new System.EventHandler(this.radioButton_PartCodeSanner_Click); + // + // radioButton_PlcSignl + // + this.radioButton_PlcSignl.AutoSize = true; + this.radioButton_PlcSignl.Checked = true; + this.radioButton_PlcSignl.Location = new System.Drawing.Point(6, 19); + this.radioButton_PlcSignl.Name = "radioButton_PlcSignl"; + this.radioButton_PlcSignl.Size = new System.Drawing.Size(65, 16); + this.radioButton_PlcSignl.TabIndex = 0; + this.radioButton_PlcSignl.TabStop = true; + this.radioButton_PlcSignl.Text = "PLC信号"; + this.radioButton_PlcSignl.UseVisualStyleBackColor = true; + this.radioButton_PlcSignl.Click += new System.EventHandler(this.radioButton_PlcSignl_Click); + // + // cb_QdData + // + this.cb_QdData.AutoSize = true; + this.cb_QdData.Enabled = false; + this.cb_QdData.Location = new System.Drawing.Point(10, 40); + this.cb_QdData.Name = "cb_QdData"; + this.cb_QdData.Size = new System.Drawing.Size(72, 16); + this.cb_QdData.TabIndex = 1472; + this.cb_QdData.Text = "质量数据"; + this.cb_QdData.UseVisualStyleBackColor = true; + // + // cb_MonitorData + // + this.cb_MonitorData.AutoSize = true; + this.cb_MonitorData.Location = new System.Drawing.Point(10, 20); + this.cb_MonitorData.Name = "cb_MonitorData"; + this.cb_MonitorData.Size = new System.Drawing.Size(72, 16); + this.cb_MonitorData.TabIndex = 1472; + this.cb_MonitorData.Text = "监控数据"; + this.cb_MonitorData.UseVisualStyleBackColor = true; + this.cb_MonitorData.Click += new System.EventHandler(this.cb_MonitorData_Click); + // + // contextMenuStrip_MIS + // + this.contextMenuStrip_MIS.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { + this.toolStripMenuItem_Show, + this.toolStripMenuItem_Hide, + this.toolStripMenuItem_Exit}); + this.contextMenuStrip_MIS.Name = "contextMenuStrip_MIS"; + this.contextMenuStrip_MIS.Size = new System.Drawing.Size(101, 70); + // + // toolStripMenuItem_Show + // + this.toolStripMenuItem_Show.Name = "toolStripMenuItem_Show"; + this.toolStripMenuItem_Show.Size = new System.Drawing.Size(100, 22); + this.toolStripMenuItem_Show.Text = "显示"; + this.toolStripMenuItem_Show.Click += new System.EventHandler(this.toolStripMenuItem_Show_Click); + // + // toolStripMenuItem_Hide + // + this.toolStripMenuItem_Hide.Name = "toolStripMenuItem_Hide"; + this.toolStripMenuItem_Hide.Size = new System.Drawing.Size(100, 22); + this.toolStripMenuItem_Hide.Text = "隐藏"; + this.toolStripMenuItem_Hide.Click += new System.EventHandler(this.toolStripMenuItem_Hide_Click); + // + // toolStripMenuItem_Exit + // + this.toolStripMenuItem_Exit.Name = "toolStripMenuItem_Exit"; + this.toolStripMenuItem_Exit.Size = new System.Drawing.Size(100, 22); + this.toolStripMenuItem_Exit.Text = "退出"; + this.toolStripMenuItem_Exit.Click += new System.EventHandler(this.toolStripMenuItem_Exit_Click); + // + // statusStrip1 + // + this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { + this.toolStripStatusLabel_RunningStatu, + this.toolStripStatusLabel_RunningStatus, + this.toolStripStatusLabel2, + this.toolStripStatusLabel_StartTime, + this.toolStripStatusLabel3, + this.toolStripStatusLabel_RunTime, + this.toolStripStatusLabel1, + this.toolStripStatusLabel_WorkStationNum, + this.toolStripStatusLabel6, + this.toolStripStatusLabel_OnlineNum, + this.toolStripStatusLabel8, + this.toolStripStatusLabel_DownLine, + this.toolStripStatusLabel4, + this.toolStripStatusLabel_Version}); + this.statusStrip1.Location = new System.Drawing.Point(0, 360); + this.statusStrip1.Name = "statusStrip1"; + this.statusStrip1.Size = new System.Drawing.Size(1552, 26); + this.statusStrip1.TabIndex = 1478; + this.statusStrip1.Text = "statusStrip1"; + // + // toolStripStatusLabel_RunningStatu + // + this.toolStripStatusLabel_RunningStatu.Name = "toolStripStatusLabel_RunningStatu"; + this.toolStripStatusLabel_RunningStatu.Size = new System.Drawing.Size(68, 21); + this.toolStripStatusLabel_RunningStatu.Text = "运行状态:"; + // + // toolStripStatusLabel_RunningStatus + // + this.toolStripStatusLabel_RunningStatus.ActiveLinkColor = System.Drawing.Color.Red; + this.toolStripStatusLabel_RunningStatus.AutoSize = false; + this.toolStripStatusLabel_RunningStatus.BackColor = System.Drawing.Color.Yellow; + this.toolStripStatusLabel_RunningStatus.Name = "toolStripStatusLabel_RunningStatus"; + this.toolStripStatusLabel_RunningStatus.Size = new System.Drawing.Size(62, 21); + this.toolStripStatusLabel_RunningStatus.Text = "变量模拟"; + // + // toolStripStatusLabel2 + // + this.toolStripStatusLabel2.BorderSides = System.Windows.Forms.ToolStripStatusLabelBorderSides.Left; + this.toolStripStatusLabel2.Name = "toolStripStatusLabel2"; + this.toolStripStatusLabel2.Size = new System.Drawing.Size(72, 21); + this.toolStripStatusLabel2.Text = "启动时间:"; + // + // toolStripStatusLabel_StartTime + // + this.toolStripStatusLabel_StartTime.AutoSize = false; + this.toolStripStatusLabel_StartTime.BorderSides = System.Windows.Forms.ToolStripStatusLabelBorderSides.Right; + this.toolStripStatusLabel_StartTime.Name = "toolStripStatusLabel_StartTime"; + this.toolStripStatusLabel_StartTime.Size = new System.Drawing.Size(130, 21); + this.toolStripStatusLabel_StartTime.Text = "2018/08/08 08:08:08"; + // + // toolStripStatusLabel3 + // + this.toolStripStatusLabel3.Name = "toolStripStatusLabel3"; + this.toolStripStatusLabel3.Size = new System.Drawing.Size(68, 21); + this.toolStripStatusLabel3.Text = "运行时长:"; + // + // toolStripStatusLabel_RunTime + // + this.toolStripStatusLabel_RunTime.AutoSize = false; + this.toolStripStatusLabel_RunTime.BorderSides = System.Windows.Forms.ToolStripStatusLabelBorderSides.Right; + this.toolStripStatusLabel_RunTime.Name = "toolStripStatusLabel_RunTime"; + this.toolStripStatusLabel_RunTime.Size = new System.Drawing.Size(145, 21); + this.toolStripStatusLabel_RunTime.Text = "0天0小时0分0秒"; + // + // toolStripStatusLabel1 + // + this.toolStripStatusLabel1.Name = "toolStripStatusLabel1"; + this.toolStripStatusLabel1.Size = new System.Drawing.Size(68, 21); + this.toolStripStatusLabel1.Text = "工位数量:"; + // + // toolStripStatusLabel_WorkStationNum + // + this.toolStripStatusLabel_WorkStationNum.AutoSize = false; + this.toolStripStatusLabel_WorkStationNum.BorderSides = System.Windows.Forms.ToolStripStatusLabelBorderSides.Right; + this.toolStripStatusLabel_WorkStationNum.Name = "toolStripStatusLabel_WorkStationNum"; + this.toolStripStatusLabel_WorkStationNum.Size = new System.Drawing.Size(35, 21); + this.toolStripStatusLabel_WorkStationNum.Text = "100"; + // + // toolStripStatusLabel6 + // + this.toolStripStatusLabel6.Name = "toolStripStatusLabel6"; + this.toolStripStatusLabel6.Size = new System.Drawing.Size(68, 21); + this.toolStripStatusLabel6.Text = "在线数量:"; + // + // toolStripStatusLabel_OnlineNum + // + this.toolStripStatusLabel_OnlineNum.AutoSize = false; + this.toolStripStatusLabel_OnlineNum.BorderSides = System.Windows.Forms.ToolStripStatusLabelBorderSides.Right; + this.toolStripStatusLabel_OnlineNum.Name = "toolStripStatusLabel_OnlineNum"; + this.toolStripStatusLabel_OnlineNum.Size = new System.Drawing.Size(35, 21); + this.toolStripStatusLabel_OnlineNum.Text = "0"; + // + // toolStripStatusLabel8 + // + this.toolStripStatusLabel8.Name = "toolStripStatusLabel8"; + this.toolStripStatusLabel8.Size = new System.Drawing.Size(68, 21); + this.toolStripStatusLabel8.Text = "离线数量:"; + // + // toolStripStatusLabel_DownLine + // + this.toolStripStatusLabel_DownLine.AutoSize = false; + this.toolStripStatusLabel_DownLine.BorderSides = System.Windows.Forms.ToolStripStatusLabelBorderSides.Right; + this.toolStripStatusLabel_DownLine.Name = "toolStripStatusLabel_DownLine"; + this.toolStripStatusLabel_DownLine.Size = new System.Drawing.Size(35, 21); + this.toolStripStatusLabel_DownLine.Text = "0"; + // + // toolStripStatusLabel4 + // + this.toolStripStatusLabel4.Name = "toolStripStatusLabel4"; + this.toolStripStatusLabel4.Size = new System.Drawing.Size(44, 21); + this.toolStripStatusLabel4.Text = "版本:"; + // + // toolStripStatusLabel_Version + // + this.toolStripStatusLabel_Version.Name = "toolStripStatusLabel_Version"; + this.toolStripStatusLabel_Version.Size = new System.Drawing.Size(42, 21); + this.toolStripStatusLabel_Version.Text = "8.6.12"; + // + // groupBox_Alarm + // + this.groupBox_Alarm.Location = new System.Drawing.Point(90, 82); + this.groupBox_Alarm.Name = "groupBox_Alarm"; + this.groupBox_Alarm.Size = new System.Drawing.Size(200, 100); + this.groupBox_Alarm.TabIndex = 1; + this.groupBox_Alarm.TabStop = false; + // + // timer_ReadTagValues + // + this.timer_ReadTagValues.Interval = 1000; + this.timer_ReadTagValues.Tick += new System.EventHandler(this.timer_ReadTagValues_Tick); + // + // groupBox4 + // + this.groupBox4.Controls.Add(this.Btn_MES_15_HeartBeat); + this.groupBox4.Controls.Add(this.Btn_MES_20_MesReadOver); + this.groupBox4.Controls.Add(this.Btn_MES_5_EngineTypeGetOver); + this.groupBox4.Controls.Add(this.Btn_MES_68_MachComplete); + this.groupBox4.Controls.Add(this.Btn_MES_51_ConfirmOkGo); + this.groupBox4.Controls.Add(this.Btn_MES_67_FixOver); + this.groupBox4.Controls.Add(this.Btn_MES_54_ReadCycleTimeOK); + this.groupBox4.Controls.Add(this.Btn_MES_66_AllowWork); + this.groupBox4.Controls.Add(this.Btn_MES_53_OffLineOK); + this.groupBox4.Controls.Add(this.Btn_MES_7_WorkComplete); + this.groupBox4.Controls.Add(this.Btn_MES_8_FalseGo); + this.groupBox4.Controls.Add(this.Btn_MES_69_MachResult); + this.groupBox4.Location = new System.Drawing.Point(423, 4); + this.groupBox4.Name = "groupBox4"; + this.groupBox4.Size = new System.Drawing.Size(175, 189); + this.groupBox4.TabIndex = 1479; + this.groupBox4.TabStop = false; + this.groupBox4.Text = "MES信号"; + // + // groupBox6 + // + this.groupBox6.Controls.Add(this.Btn_PLC_14_HeartBeat); + this.groupBox6.Controls.Add(this.Btn_PLC_16_AllowReadCycleTime); + this.groupBox6.Controls.Add(this.Btn_PLC_19_MesRead); + this.groupBox6.Controls.Add(this.Btn_PLC_50_ApplyOffline); + this.groupBox6.Controls.Add(this.Btn_PLC_13_PalletIn); + this.groupBox6.Controls.Add(this.Btn_PLC_59_FixOK); + this.groupBox6.Controls.Add(this.Btn_PLC_1002_MachaineBreak); + this.groupBox6.Controls.Add(this.Btn_PLC_44_EngineTypeGetOver); + this.groupBox6.Controls.Add(this.Btn_PLC_2_WorkStart); + this.groupBox6.Controls.Add(this.Btn_PLC_43_PartLoad); + this.groupBox6.Location = new System.Drawing.Point(426, 195); + this.groupBox6.Name = "groupBox6"; + this.groupBox6.Size = new System.Drawing.Size(175, 160); + this.groupBox6.TabIndex = 1480; + this.groupBox6.TabStop = false; + this.groupBox6.Text = "PLC信号"; + // + // listView_ShowQualityData + // + this.listView_ShowQualityData.AllowColumnReorder = true; + this.listView_ShowQualityData.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { + this.columnHeader4, + this.columnHeader2, + this.columnHeader3, + this.columnHeader1, + this.columnHeader5}); + this.listView_ShowQualityData.FullRowSelect = true; + this.listView_ShowQualityData.GridLines = true; + this.listView_ShowQualityData.HideSelection = false; + this.listView_ShowQualityData.Location = new System.Drawing.Point(0, 9); + this.listView_ShowQualityData.Margin = new System.Windows.Forms.Padding(2); + this.listView_ShowQualityData.MultiSelect = false; + this.listView_ShowQualityData.Name = "listView_ShowQualityData"; + this.listView_ShowQualityData.ShowItemToolTips = true; + this.listView_ShowQualityData.Size = new System.Drawing.Size(484, 341); + this.listView_ShowQualityData.TabIndex = 1469; + this.listView_ShowQualityData.UseCompatibleStateImageBehavior = false; + this.listView_ShowQualityData.View = System.Windows.Forms.View.Details; + this.listView_ShowQualityData.SelectedIndexChanged += new System.EventHandler(this.listView_ShowQualityData_SelectedIndexChanged); + this.listView_ShowQualityData.Click += new System.EventHandler(this.listView_ShowQualityData_Click); + this.listView_ShowQualityData.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(this.listView_ShowQualityData_MouseDoubleClick); + // + // columnHeader4 + // + this.columnHeader4.DisplayIndex = 3; + this.columnHeader4.Text = "工位号"; + this.columnHeader4.Width = 70; + // + // columnHeader2 + // + this.columnHeader2.Text = "测量项目"; + this.columnHeader2.Width = 150; + // + // columnHeader3 + // + this.columnHeader3.Text = "值"; + this.columnHeader3.Width = 180; + // + // columnHeader1 + // + this.columnHeader1.DisplayIndex = 0; + this.columnHeader1.Text = "TagID"; + this.columnHeader1.Width = 70; + // + // columnHeader5 + // + this.columnHeader5.Text = "TagTypeCodeID"; + // + // groupBox_SignialSimulator + // + this.groupBox_SignialSimulator.Controls.Add(this.groupBox_MES); + this.groupBox_SignialSimulator.Controls.Add(this.Btn_MES_71_IsAuto); + this.groupBox_SignialSimulator.Controls.Add(this.Btn_PLC_1004_Jam); + this.groupBox_SignialSimulator.Controls.Add(this.Btn_MES_52_ResetEquipment); + this.groupBox_SignialSimulator.Controls.Add(this.Btn_PLC_1000_MachinePowerOn); + this.groupBox_SignialSimulator.Controls.Add(this.Btn_MES_72_MobyClear); + this.groupBox_SignialSimulator.Controls.Add(this.Btn_PLC_1003_ShortFall); + this.groupBox_SignialSimulator.Controls.Add(this.Btn_PLC_1001_CycleStart); + this.groupBox_SignialSimulator.Controls.Add(this.groupBox6); + this.groupBox_SignialSimulator.Controls.Add(this.groupBox_PLC); + this.groupBox_SignialSimulator.Controls.Add(this.Btn_MES_6_PalletGo); + this.groupBox_SignialSimulator.Controls.Add(this.groupBox4); + this.groupBox_SignialSimulator.Location = new System.Drawing.Point(941, 9); + this.groupBox_SignialSimulator.Name = "groupBox_SignialSimulator"; + this.groupBox_SignialSimulator.Size = new System.Drawing.Size(611, 348); + this.groupBox_SignialSimulator.TabIndex = 1481; + this.groupBox_SignialSimulator.TabStop = false; + // + // MisData + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(1552, 386); + this.Controls.Add(this.groupBox_SignialSimulator); + this.Controls.Add(this.statusStrip1); + this.Controls.Add(this.listView_ShowQualityData); + this.Controls.Add(this.groupBox_WorkStationQuality); + this.Controls.Add(this.groupBox_SignialSimulatorOld); + this.Controls.Add(this.groupBox_Alarm); + this.DoubleBuffered = true; + this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; + this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); + this.Margin = new System.Windows.Forms.Padding(2); + this.Name = "MisData"; + this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; + this.Text = "Demo Mes Work System 仿真虚拟调试信号面板 2022.10.15.001"; + this.TopMost = true; + this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.MisData_FormClosing); + this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.MisData_FormClosed); + this.Load += new System.EventHandler(this.MisData_Load); + ((System.ComponentModel.ISupportInitialize)(this.numericUpDown1)).EndInit(); + this.groupBox_SignialSimulatorOld.ResumeLayout(false); + this.groupBox_SignialSimulatorOld.PerformLayout(); + this.groupBox_WorkStationStatus.ResumeLayout(false); + this.groupBox_WorkStationStatus.PerformLayout(); + this.groupBox_PLC.ResumeLayout(false); + this.groupBox_PLC.PerformLayout(); + this.groupBox_MES.ResumeLayout(false); + this.groupBox_MES.PerformLayout(); + this.groupBox_WorkStationQuality.ResumeLayout(false); + this.groupBox_WorkStationQuality.PerformLayout(); + this.groupBox2.ResumeLayout(false); + this.groupBox2.PerformLayout(); + this.groupBox1.ResumeLayout(false); + this.groupBox1.PerformLayout(); + this.contextMenuStrip_MIS.ResumeLayout(false); + this.statusStrip1.ResumeLayout(false); + this.statusStrip1.PerformLayout(); + this.groupBox4.ResumeLayout(false); + this.groupBox6.ResumeLayout(false); + this.groupBox_SignialSimulator.ResumeLayout(false); + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + private System.Windows.Forms.ComboBox comboBox_OpName; + private System.Windows.Forms.Label label_OpNameList; + private System.Windows.Forms.TextBox textBox_tagValue_Read; + private System.Windows.Forms.TextBox textBox_tagValue; + private System.Windows.Forms.TextBox textBox_Cmd; + private System.Windows.Forms.Button button_Read; + private System.Windows.Forms.Button button_Write; + private System.Windows.Forms.ListBox listBox1; + private System.Windows.Forms.CheckBox checkBox_WorkStart; + private System.Windows.Forms.NumericUpDown numericUpDown1; + private ListViewDouble.ListViewNF listView_ShowQualityData; + private System.Windows.Forms.ColumnHeader columnHeader1; + private System.Windows.Forms.ColumnHeader columnHeader2; + private System.Windows.Forms.ColumnHeader columnHeader3; + private System.Windows.Forms.ColumnHeader columnHeader4; + private System.Windows.Forms.Button button_ReadData; + private System.Windows.Forms.GroupBox groupBox_SignialSimulatorOld; + private System.Windows.Forms.GroupBox groupBox_MES; + private System.Windows.Forms.TextBox Tbx_MES_74_EngineID; + private System.Windows.Forms.TextBox Tbx_MES_75_Enginetype; + private System.Windows.Forms.Label label10; + private System.Windows.Forms.Label label11; + private System.Windows.Forms.Label label12; + private System.Windows.Forms.Label label13; + private System.Windows.Forms.Label label14; + private System.Windows.Forms.Label label15; + private System.Windows.Forms.Label label16; + private System.Windows.Forms.GroupBox groupBox5; + private System.Windows.Forms.Button Btn_MES_69_MachResult; + private System.Windows.Forms.Button Btn_MES_8_FalseGo; + private System.Windows.Forms.Button Btn_MES_67_FixOver; + private System.Windows.Forms.Button Btn_MES_7_WorkComplete; + private System.Windows.Forms.Button Btn_MES_53_OffLineOK; + private System.Windows.Forms.Button Btn_MES_66_AllowWork; + private System.Windows.Forms.Button Btn_MES_5_EngineTypeGetOver; + private System.Windows.Forms.Button Btn_MES_68_MachComplete; + private System.Windows.Forms.Button Btn_MES_52_ResetEquipment; + private System.Windows.Forms.Button Btn_MES_6_PalletGo; + private System.Windows.Forms.Button Btn_Write_MES; + private System.Windows.Forms.Button Btn_MES_71_IsAuto; + private System.Windows.Forms.Button Btn_MES_51_ConfirmOkGo; + private System.Windows.Forms.Button Btn_MES_15_HeartBeat; + private System.Windows.Forms.GroupBox groupBox_PLC; + private System.Windows.Forms.TextBox Tbx_PLC_10_EngineID; + private System.Windows.Forms.TextBox Tbx_PLC_11_Enginetype; + private System.Windows.Forms.Label label3; + private System.Windows.Forms.Label label4; + 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.Label label9; + private System.Windows.Forms.GroupBox groupBox3; + private System.Windows.Forms.Button Btn_PLC_1003_ShortFall; + private System.Windows.Forms.Button Btn_PLC_19_MesRead; + private System.Windows.Forms.Button Btn_PLC_1002_MachaineBreak; + private System.Windows.Forms.Button Btn_PLC_59_FixOK; + private System.Windows.Forms.Button Btn_PLC_1001_CycleStart; + private System.Windows.Forms.Button Btn_PLC_1000_MachinePowerOn; + private System.Windows.Forms.Button Btn_PLC_44_EngineTypeGetOver; + private System.Windows.Forms.Button Btn_PLC_13_PalletIn; + private System.Windows.Forms.Button Btn_PLC_50_ApplyOffline; + private System.Windows.Forms.Button Btn_PLC_43_PartLoad; + private System.Windows.Forms.Button Btn_Write_PLC; + private System.Windows.Forms.Button Btn_PLC_1004_Jam; + private System.Windows.Forms.Button Btn_PLC_14_HeartBeat; + private System.Windows.Forms.Button Btn_PLC_2_WorkStart; + private System.Windows.Forms.Button Btn_MES_20_MesReadOver; + private System.Windows.Forms.Button Btn_MES_72_MobyClear; + private System.Windows.Forms.TextBox Tbx_PLC_18_Actual; + private System.Windows.Forms.TextBox Tbx_PLC_17_TargetTime; + private System.Windows.Forms.Label label18; + private System.Windows.Forms.Label label17; + private System.Windows.Forms.Button Btn_PLC_16_AllowReadCycleTime; + private System.Windows.Forms.Button Btn_MES_54_ReadCycleTimeOK; + private System.Windows.Forms.TextBox Tbx_MES_73_EngineTypeID; + private System.Windows.Forms.TextBox Tbx_MES_79_OnlineStatus; + private System.Windows.Forms.TextBox Tbx_MES_93_RepairMark; + private System.Windows.Forms.TextBox Tbx_MES_88_SocketNum; + private System.Windows.Forms.TextBox Tbx_MES_77_FixOrder; + private System.Windows.Forms.TextBox Tbx_MES_4_WorkStationRepairStr; + private System.Windows.Forms.Label label19; + private System.Windows.Forms.TextBox Tbx_PLC_9_EngineTypeID; + private System.Windows.Forms.TextBox Tbx_PLC_23_RepairMark; + private System.Windows.Forms.TextBox Tbx_PLC_22_PalletStatus; + private System.Windows.Forms.TextBox Tbx_PLC_21_ResultMark; + private System.Windows.Forms.TextBox Tbx_PLC_80_PalletNum; + private System.Windows.Forms.GroupBox groupBox_WorkStationStatus; + private System.Windows.Forms.TextBox Tbx_Status_11_EngineType; + private System.Windows.Forms.TextBox Tbx_Status_9_EngineTypeID; + private System.Windows.Forms.Label label2; + private System.Windows.Forms.Label label20; + private System.Windows.Forms.TextBox Tbx_Status_10_EngineID; + private System.Windows.Forms.TextBox Tbx_Status_80_Pallet; + private System.Windows.Forms.Label label21; + private System.Windows.Forms.Label label22; + private System.Windows.Forms.GroupBox groupBox_WorkStationQuality; + private System.Windows.Forms.CheckBox Cbx_StatusDisplay; + private System.Windows.Forms.Button Btn_Read_PLC; + private System.Windows.Forms.Button Btn_Read_MES; + private System.Windows.Forms.ContextMenuStrip contextMenuStrip_MIS; + private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem_Show; + private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem_Hide; + private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem_Exit; + private System.Windows.Forms.CheckBox checkBox_PLCData_Display; + private System.Windows.Forms.CheckBox checkBox_MESData_Display; + private System.Windows.Forms.StatusStrip statusStrip1; + private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel_RunningStatu; + private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel_RunningStatus; + private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel2; + private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel_StartTime; + private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel3; + private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel_RunTime; + private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel1; + private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel_WorkStationNum; + private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel6; + private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel_OnlineNum; + private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel8; + private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel_DownLine; + private System.Windows.Forms.GroupBox groupBox_Alarm; + private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel4; + private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel_Version; + private System.Windows.Forms.CheckBox cb_QdData; + private System.Windows.Forms.CheckBox cb_MonitorData; + private System.Windows.Forms.GroupBox groupBox1; + private System.Windows.Forms.RadioButton radioButton_PartCodeSanner; + private System.Windows.Forms.RadioButton radioButton_PlcSignl; + private System.Windows.Forms.GroupBox groupBox2; + private System.Windows.Forms.RadioButton radioButton_Copy; + private System.Windows.Forms.RadioButton radioButton_Base; + private System.Windows.Forms.TextBox textBox_Copy_Item; + private System.Windows.Forms.TextBox textBox_Copy_TagID; + private System.Windows.Forms.TextBox textBox_Base_Item; + private System.Windows.Forms.TextBox textBox_Base_TagID; + private System.Windows.Forms.RadioButton radioButton_PlcSignl_Copy; + private System.Windows.Forms.Timer timer_ReadTagValues; + private System.Windows.Forms.ColumnHeader columnHeader5; + private System.Windows.Forms.GroupBox groupBox4; + private System.Windows.Forms.GroupBox groupBox6; + private System.Windows.Forms.GroupBox groupBox_SignialSimulator; + } +} + diff --git a/MisDataPlcTagID/MisDataPlcTagID/MisDataWebFunSim.cs b/MisDataPlcTagID/MisDataPlcTagID/MisDataWebFunSim.cs new file mode 100644 index 0000000..9484500 --- /dev/null +++ b/MisDataPlcTagID/MisDataPlcTagID/MisDataWebFunSim.cs @@ -0,0 +1,1022 @@ +//using BasicData; +using bizFacade; +//using OpcData; +using System; +using System.Collections; +using System.Data; +using System.Threading; +using System.Windows.Forms; +//using SystemFramework; + +using System.Drawing; +//using MesServerWork; +using System.Configuration; +//using MisDataFunction; +using System.Collections.Generic; +using MQTTnet.Client.Connecting; +using MQTTnet.Client.Disconnecting; +using MQTTnet.Client.Receiving; +using System.Linq; +using DoWhatPlc; +/// +/// +/// +namespace MisDataSaveDateSim +{ + + /// + /// + /// + /// + /// + public delegate void RefreshForm(object obj1, EventArgs obj2); + /// + /// + /// + public partial class MisData:Form + { + /// + /// + /// + public static string BasicDataTableFile = ConfigurationManager.AppSettings["BasicDataTableFile"]; + /// + /// + /// + public static int IsDemoMesServer = Convert.ToInt32(ConfigurationManager.AppSettings["IsDemoMesServer"]); + /// + /// + /// + public static string MqttUrl = ConfigurationManager.AppSettings["MqttUrl"]; + public static string MqttUrlPLC = ConfigurationManager.AppSettings["MqttUrlPLC"]; + /// + /// + /// + public static string MqttTargetTopic = ConfigurationManager.AppSettings["MqttTargetTopic"]; + public static string MqttTargetTopicPLC = ConfigurationManager.AppSettings["MqttTargetTopicPLC"]; + /// + /// + /// + public static int IsWriteMonitorLog = Convert.ToInt32(ConfigurationManager.AppSettings["IsWriteMonitorLog"]); + /// + /// + /// + public static string ConnectionString_MES = ConfigurationManager.AppSettings["ConnectionString_MES"]; + /// + /// + /// + public static int WebApiPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["WebApiPort"]); + /// + /// + /// + public static RefreshForm MainFormRefresh, TestPlcStatusDel; + /// + /// 允许使用附加功能的变量,只有在系统开始加载Tag时,才允许读取PLC数据 + /// + public static bool AllowLoad; + /// + /// + /// + public MisData() + { + InitializeComponent(); + + + // CheckForIllegalCrossThreadCalls = false; + + + } + + + + + + private void InitcomboBox_OpNameWebApi() + { + List opNameList; + try + { + //全部工位号 + comboBox_OpName.DataSource = opNameList = DtWebApi.OpcDemo.Get_opNameList(); + + + //FunctionForm_HashiTable.OpName_Hash_Write("OpNameList", opNameList); + toolStripStatusLabel_WorkStationNum.Text = opNameList.Count.ToString(); + toolStripStatusLabel_DownLine.Text = toolStripStatusLabel_WorkStationNum.Text; + if (comboBox_OpName.Items.Count > 0) + { + WorkStationNum_Now = comboBox_OpName.SelectedValue.ToString(); + } + } + catch { } + + + } + + private void listBox1_SelectedValueChanged(object sender, EventArgs e) + { + //try + //{ + // string cmd; + // string opName; + // string tagValue; + // string[] strList; + // if (listBox1.Text != null) + // { + // strList = listBox1.Text.Split('|'); + // if (strList.Length >= 4) + // { + // cmd = strList[1]; + // opName = strList[2]; + // tagValue = strList[3]; + // textBox_Cmd.Text = cmd; + // textBox_tagValue.Text = tagValue; + // } + // } + //} + //catch (Exception err) + //{ + // ApplicationLog.WriteLog(err, err.Message); + + //} + + } + + private void button_Write_Click(object sender, EventArgs e) + { + try + { + short tagValue_int; + string tagValue_str; + byte tagValue_byte; + bool tagValue_bool; + int tagType; + int tagDataType; + string cmd = textBox_Cmd.Text; + string opName = WorkStationNum_Now; + string tagValue = textBox_tagValue.Text; + HashtableList htList = DtWebApi.OpcDemo.GetHashtableList(); + + tagType = Convert.ToInt32(htList.hashtable_TagType[cmd]); + + tagDataType = Convert.ToInt32(htList.hashtable_TagTypeDataType[tagType.ToString()]); + switch (tagDataType) + { + case 2: + tagValue_int = Convert.ToInt16(tagValue); + WriteAnyData_Thread(tagType, opName, tagValue_int); + break; + case 8: + tagValue_str = tagValue.ToString(); + WriteAnyData_Thread(tagType, opName, tagValue_str); + break; + case 17: + tagValue_byte = Convert.ToByte(tagValue); + WriteAnyData_Thread(tagType, opName, tagValue_byte); + break; + case 11: + tagValue_bool = Convert.ToBoolean(Convert.ToInt32(tagValue)); + WriteAnyData_Thread(tagType, opName, tagValue_bool); + break; + } + + } + catch (Exception err) + { + MessageBox.Show("输入命令异常,请重新输入!"); + //ApplicationLog.WriteLog(err, err.Message); + + } + } + + private void button_Read_Click(object sender, EventArgs e) + { + try + { + int tagType; + string cmd = textBox_Cmd.Text; + string opName = WorkStationNum_Now; + string tagValue = textBox_tagValue.Text; + + HashtableList htList = DtWebApi.OpcDemo.GetHashtableList(); + + tagType = Convert.ToInt32(htList.hashtable_TagType[cmd]); + + QualityDataQueryStruct QualityStruct = new QualityDataQueryStruct(opName, tagType, textBox_tagValue_Read); + Thread t = new Thread(new ParameterizedThreadStart(ReadPLC_ByTagType_Thread)); + t.Start(QualityStruct); + } + catch (Exception err) + { + // ApplicationLog.WriteLog(err, err.Message); + + } + } + + void ReadPLC_ByTagType_Thread(object obj) + { + //try + //{ + // QualityDataQueryStruct QualityStruct = (QualityDataQueryStruct)obj; + // TextBox tbx = (TextBox)QualityStruct.Ctrl; + + // tbx.Text = ReadPLC(QualityStruct.tagType, QualityStruct.OpName).ToString(); + //} + //catch (Exception err) + //{ + // ApplicationLog.WriteLog(err, err.Message); + //} + } + + + bool isWorkStart; + private void timer_WorkStart_Tick(object sender, EventArgs e) + { + //if (isWorkStart) + // isWorkStart = false; + //else + // isWorkStart = true; + //if (isWorkStart) + //{ + // textBox_tagValue.Text = "1"; + // button_Write_Click(null, null); + //} + //else + //{ + // textBox_tagValue.Text = "0"; + // button_Write_Click(null, null); + //} + } + + private void checkBox_WorkStart_CheckedChanged(object sender, EventArgs e) + { + //if (textBox_Cmd.Text == "" && checkBox_WorkStart.Checked) + //{ + // MessageBox.Show("请选择命令"); + // checkBox_WorkStart.Checked = false; + // return; + //} + //if (checkBox_WorkStart.Checked) + //{ + // timer_WorkStart.Enabled = true; + // listBox1.Enabled = false; + // textBox_Cmd.ReadOnly = true; + //} + //else + //{ + // timer_WorkStart.Enabled = false; + // listBox1.Enabled = true; + // textBox_Cmd.ReadOnly = false; + //} + + } + + private void numericUpDown1_ValueChanged(object sender, EventArgs e) + { + //timer_WorkStart.Interval = Convert.ToInt32(numericUpDown1.Value) * 1000; + } + + static Thread ReadQuality_t = null; + private void ReadQualityData(string opName) + { + try + { + if (ReadQualityRunning) return; + ReadQualityRunning = true; + QualityDataQueryStruct QltyQueryStr = new QualityDataQueryStruct(opName, listView_ShowQualityData); + + ReadQuality_t = new Thread(new ParameterizedThreadStart(ReadQualityData_Thread)); + ReadQuality_t.Start(QltyQueryStr); + + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, err.Message); + + } + } + private void ReadQualityDataUpdate(string opName) + { + try + { + if (ReadQualityRunning) return; + ReadQualityRunning = true; + QualityDataQueryStruct QltyQueryStr = new QualityDataQueryStruct(opName, listView_ShowQualityData); + + ReadQuality_t = new Thread(new ParameterizedThreadStart(ReadQualityData_Thread_Update)); + ReadQuality_t.Start(QltyQueryStr); + + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, err.Message); + + } + } + public QualityDataType[] ThisWorkStationData + { get; set; } + static bool ReadQualityRunning = false; + void ReadQualityData_Thread(object obj) + { + int fTime = 0; + try + { + + QualityDataQueryStruct QualityStruct = (QualityDataQueryStruct)obj; + + ListView listViewTemp = (ListView)QualityStruct.Ctrl; + ListViewItem listViewItem = null; + string[] listViewItemString = new string[5]; + if (listViewTemp.InvokeRequired) + { + Action ActionDelegate = () => { listViewTemp.Items.Clear(); }; + listViewTemp.Invoke(ActionDelegate); + } + else + { + listViewTemp.Items.Clear(); + } + + System.Collections.Concurrent.ConcurrentDictionary cd = new System.Collections.Concurrent.ConcurrentDictionary(); + List cdTagIDTagFormat = null; + //if (cb_MonitorData.Checked) + //{ + + // cdTagIDTagFormat = DtWebApi.OpcDemo.ReadPLC_GroupMonitor(QualityStruct.OpName); + // //cd = MesWork.PlcLinkForm.ReadPLC_GroupMonitor(QualityStruct.OpName); + //} + //if (cb_QdData.Checked) + //{ + // cdTagIDTagFormat = DtWebApi.OpcDemo.ReadPLC_GroupData_Qd(QualityStruct.OpName); + // //cd = MesWork.PlcLinkForm.ReadPLC_GroupData_Qd(QualityStruct.OpName); + //} + //if (cb_MonitorData.Checked == false & cb_QdData.Checked == false) + //{ + // cdTagIDTagFormat = DtWebApi.OpcDemo.ReadPLC_GroupData(QualityStruct.OpName); + // //cd = MesWork.PlcLinkForm.ReadPLC_GroupData(QualityStruct.OpName); + //} + //if (cb_MonitorData.Checked == true & cb_QdData.Checked == true) + //{ + // cdTagIDTagFormat = DtWebApi.OpcDemo.ReadPLC_GroupData(QualityStruct.OpName); + // //cd = MesWork.PlcLinkForm.ReadPLC_GroupData(QualityStruct.OpName); + //} + + cdTagIDTagFormat = DtWebApi.OpcDemo.ReadPLC_GroupData(QualityStruct.OpName); + + if (cdTagIDTagFormat == null) return; + foreach (var item in cdTagIDTagFormat) + { + if (!cd.ContainsKey(item.TagID)) + { + cd.TryAdd(item.TagID, item.TF); + } + } + //排序 + var result2 = from pair in cd orderby pair.Key select pair; + ThisWorkStationData = new QualityDataType[cd.Count]; + var sortResult2 = from pair in cd orderby pair.Key descending select pair; + //cd.o.OrderBy(p => p.Value.Speed); + //foreach (KeyValuePair _cd in cd) + foreach (KeyValuePair _cd in result2) + { + var tagID = _cd.Key; + var TF = (DoWhatPlc.TagFormat)_cd.Value; + + listViewItemString[0] = TF.OpName; + listViewItemString[3] = TF.TagID; + listViewItemString[1] = TF.ItemName; + listViewItemString[2] = TF.TagValue.ToString(); + listViewItemString[4] = TF.TagTypeCodeID.ToString(); + + listViewItem = new ListViewItem(listViewItemString); + //if (TF.IsMonitor == 1) + //{ + // // listViewItem.BackColor = Color.LimeGreen; + //} + //if (listViewTemp.InvokeRequired) + //{ + // Action ActionDelegate = (x) => { listViewTemp.Items.Add(x); }; + // listViewTemp.BeginInvoke(ActionDelegate, listViewItem); + //} + //else + { + listViewTemp.Items.Add(listViewItem); + } + + QualityDataType t00 = new QualityDataType(); + t00.opName = TF.OpName; + t00.tagID = TF.TagID; + t00.tagTypeID = TF.TagTypeID; + t00.tagValue = TF.TagValue; + ThisWorkStationData[fTime] = t00; + //ThisWorkStationData[fTime].opName = TF.OpName; + //ThisWorkStationData[fTime].tagID = TF.TagID; + //ThisWorkStationData[fTime].tagTypeID = TF.TagTypeID; + //ThisWorkStationData[fTime].tagValue = TF.TagValue; + + + fTime++; + + } + InitFormBtnColorUpdate(); + ReadQualityRunning = false; + } + catch (Exception err) + { + ReadQualityRunning = false; + // ApplicationLog.WriteLog(err, err.Message); + + } + + + + } + + void ReadQualityData_Thread_Update(object obj) + { + try + { + + QualityDataQueryStruct QualityStruct = (QualityDataQueryStruct)obj; + + ListView listViewTemp = (ListView)QualityStruct.Ctrl; + ListViewItem listViewItem = null; + string[] listViewItemString = new string[4]; + + + System.Collections.Concurrent.ConcurrentDictionary cd = new System.Collections.Concurrent.ConcurrentDictionary(); + List cdTagIDTagFormat = null; + //if (cb_MonitorData.Checked) + //{ + + // cdTagIDTagFormat = DtWebApi.OpcDemo.ReadPLC_GroupMonitor(QualityStruct.OpName); + // //cd = MesWork.PlcLinkForm.ReadPLC_GroupMonitor(QualityStruct.OpName); + //} + //if (cb_QdData.Checked) + //{ + // cdTagIDTagFormat = DtWebApi.OpcDemo.ReadPLC_GroupData_Qd(QualityStruct.OpName); + // //cd = MesWork.PlcLinkForm.ReadPLC_GroupData_Qd(QualityStruct.OpName); + //} + //if (cb_MonitorData.Checked == false & cb_QdData.Checked == false) + //{ + // cdTagIDTagFormat = DtWebApi.OpcDemo.ReadPLC_GroupData(QualityStruct.OpName); + // //cd = MesWork.PlcLinkForm.ReadPLC_GroupData(QualityStruct.OpName); + //} + //if (cb_MonitorData.Checked == true & cb_QdData.Checked == true) + //{ + // cdTagIDTagFormat = DtWebApi.OpcDemo.ReadPLC_GroupData(QualityStruct.OpName); + // //cd = MesWork.PlcLinkForm.ReadPLC_GroupData(QualityStruct.OpName); + //} + cdTagIDTagFormat = DtWebApi.OpcDemo.ReadPLC_GroupData(QualityStruct.OpName); + + if (cdTagIDTagFormat == null) return; + foreach (var item in cdTagIDTagFormat) + { + if (!cd.ContainsKey(item.TagID)) + { + cd.TryAdd(item.TagID, item.TF); + } + } + //listView_ShowQualityData + string tagID; + for(int i=0;i< listView_ShowQualityData.Items.Count;i++) + { + tagID = listView_ShowQualityData.Items[i].SubItems[3].Text; + var TF = (DoWhatPlc.TagFormat)cd[tagID]; + listView_ShowQualityData.Items[i].SubItems[2].Text = TF.TagValue.ToString(); + } + + listView_ShowQualityData.Invalidate(); + ReadQualityRunning = false; + InitFormBtnColorUpdate(); + } + catch (Exception err) + { + ReadQualityRunning = false; + // ApplicationLog.WriteLog(err, err.Message); + + } + } + + + public void InitFormBtnColorUpdate() + { + try + { + //if (!Cbx_StatusDisplay.Checked) return; + string OpName = WorkStationNum_Now; + foreach (Control GroupBox in this.groupBox_SignialSimulator.Controls) + { + foreach (Control Btn in GroupBox.Controls) + { + if (Btn.Name.Length < 8) continue; + if (Btn.Name.Substring(0, 8) == "Btn_PLC_" || Btn.Name.Substring(0, 8) == "Btn_MES_") + { + ControlData Ctrl1 = new ControlData(Btn, OpName); + Thread t = new Thread(new ParameterizedThreadStart(InitFormBtn_Thread_Update)); + t.Start(Ctrl1); + } + } + } + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, err.Message); + + } + + + } + + void InitFormBtn_Thread_Update(Object obj) + { + try + { + ControlData Btn = (ControlData)obj; + + //test = ReadPLC(Btn.TagType, Btn.opName); + + //bool Result = Convert.ToBoolean(test); + ListViewItem li = listView_ShowQualityData.Items.Cast().First(x => x.SubItems[4].Text == Btn.TagType.ToString() && x.SubItems[0].Text == Btn.opName); + var result = li.SubItems[2].Text; + bool Result = false; + switch (result.ToLower()) + { + case "true": + case "1": + Result = true; + break; + } + if (Btn.btn.InvokeRequired) + { + Action actionDelegate = (x) => { Btn.btn.BackColor = x; }; + if (Result) + { + Btn.btn.BeginInvoke(actionDelegate, System.Drawing.Color.Green); + } + else + { + Btn.btn.BeginInvoke(actionDelegate, System.Drawing.Color.SlateGray); + } + } + else + { + if (Result) + { + Btn.btn.BackColor = System.Drawing.Color.Green; + } + else + { + Btn.btn.BackColor = System.Drawing.Color.SlateGray; + } + } + } + catch (Exception err) + { + ControlData Btn = (ControlData)obj; + //ApplicationLog.WriteLog(err, err.Message + "采集数据值:" + ";按钮名称:" + test + Btn.btn.Name + "工位号" + WorkStationNum_Now); + } + } + + + private void button_ReadData_Click(object sender, EventArgs e) + { + WorkStationNum_Now = comboBox_OpName.SelectedValue.ToString(); + ReadQualityData(WorkStationNum_Now); + + } + + + private void comboBox_OpName_SelectedIndexChanged(object sender, EventArgs e) + { + WorkStationNum_Now = comboBox_OpName.SelectedValue.ToString(); + ReadQualityData(WorkStationNum_Now); + + } + + + private void listView_ShowQualityData_MouseDoubleClick(object sender, MouseEventArgs e) + { + try + { + var items = listView_ShowQualityData.SelectedItems; + QualityDataType SelectData = new QualityDataType(); + ListView.SelectedIndexCollection index = new ListView.SelectedIndexCollection(listView_ShowQualityData); + SelectData = ThisWorkStationData[index[0]]; + WriteQualityValueForm WriteForm = new WriteQualityValueForm(SelectData, this); + WriteForm.ShowDialog(); + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, err.Message); + + } + } + + private void groupBox_SignialSimulatorBtn_Click(object sender, EventArgs e) + { + WriteBoolSignalByFormBtn(sender); + } + + private void Btn_Write_PLC_Click(object sender, EventArgs e) + { + WriteNormalDataBygroupBox_SignialSimulatorWriteBtn(sender); + } + + private void Btn_Write_MES_Click(object sender, EventArgs e) + { + WriteNormalDataBygroupBox_SignialSimulatorWriteBtn(sender); + } + + + + + private void Btn_Read_PLC_Click(object sender, EventArgs e) + { + ReadPLC_ProductInfo(); + + } + + private void Btn_Read_MES_Click(object sender, EventArgs e) + { + ReadMES_ProductInfo(); + } + + private void MisData_FormClosed(object sender, FormClosedEventArgs e) + { + //notifyIcon_MIS.Visible = false; + //this.Dispose(); + //Application.Exit(); + //System.Environment.Exit(0); + } + + private void toolStripMenuItem_Show_Click(object sender, EventArgs e) + { + //this.Show(); + //this.WindowState = FormWindowState.Normal; + //this.Activate(); + } + + private void toolStripMenuItem_Hide_Click(object sender, EventArgs e) + { + //this.Hide(); + //if (PlcChange != null) + //{ + + // Sencondform.Invoke(SecondFormClose); + // ToolStripMenuItem_VWSStatus.Checked = false; + + //} + + } + + private void toolStripMenuItem_Exit_Click(object sender, EventArgs e) + { + //this.Close(); + } + + + + public static string WorkStationNum_Now; + private void MisData_FormClosing(object sender, FormClosingEventArgs e) + { + //notifyIcon_MIS.Visible = false; + //if (MessageBox.Show("你确定要退出程序吗?", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.OK) + //{ + // notifyIcon_MIS.Visible = false; + // e.Cancel = false; + + // //判断SecondForm是否关闭 + // if (PlcChange != null) + // { + // Sencondform.BeginInvoke(SecondFormClose); + // } + + // StopServer(); + // MesWork.Mqtt.StopAsync(); + + //} + //else + //{ + // notifyIcon_MIS.Visible = true; + // e.Cancel = true; + + //} + } + + + private void ToolStripMenuItem_PrintScreen_Click(object sender, EventArgs e) + { + + //PrintMainForm_Thread(); + + } + + private void ToolStripMenuItem_Quit_Click(object sender, EventArgs e) + { + //this.Close(); + } + + private void ToolStripMenuItem_SaveLog_Click(object sender, EventArgs e) + { + //SavePLCMessage SavePlcMSG = new SavePLCMessage(); + //SavePlcMSG.SavePlcMessage_Thread(richTextBox_MessagePLC.Text); + } + + + private void ToolStripMenuItem_LockForm_Click(object sender, EventArgs e) + { + //MainFormLock = new MainAct(LockMainForm); + //MainFormUnlock = new MainAct(UnLockForm); + //MainLockConfirm LockConfirm = new MainLockConfirm(this, Sencondform); + //LockConfirm.ShowDialog(); + + + + } + + private void ToolStripMenuItem_VWSStatus_Click(object sender, EventArgs e) + { + //if (PlcChange == null) + //{ + // OpenSecondForm_Thread(); + + //} + //else + //{ + // Sencondform.BeginInvoke(SecondFormClose); + // ToolStripMenuItem_VWSStatus.Checked = false; + //} + + } + + + + + private void MToolStripMenuItem_AboutMacroinf_Click(object sender, EventArgs e) + { + //System.Diagnostics.Process.Start("https://www.meswork.com"); + } + + private void toolStripMenuItem_HVersion_Click(object sender, EventArgs e) + { + //VersionsInformation VersionForm = new VersionsInformation(); + //VersionForm.ShowDialog(); + } + + + private void MisData_Load(object sender, EventArgs e) + { + + InitcomboBox_OpNameWebApi(); + + + + //MesWork.Mqtt.StartAsync(MqttUrl); + //MesWork.Mqtt.mqttClient.ConnectedHandler = new MqttClientConnectedHandlerDelegate(OnSubscriberConnected); + //MesWork.Mqtt.mqttClient.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(OnSubscriberDisconnected); + //MesWork.Mqtt.mqttClient.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(OnSubscriberMessageReceived); + } + + + + + + bool EToolStripMenuItem_EquipAlarm_Visiable = false; + + + + private void ToolStripMenuItem_HHelp_Click(object sender, EventArgs e) + { + //string file = Environment.CurrentDirectory + "\\MisData操作手册.pdf"; + //string str = file.Replace("\\bin\\Debug", "\\PDF\\MisData说明文档.pdf"); + //System.Diagnostics.Process.Start(file); + } + + /// + /// 程序集界面 + /// + /// + /// + private void ToolStripMenuItem_Assembly_Click(object sender, EventArgs e) + { + //AssemblyManagement AssemblyView = new AssemblyManagement(); + //AssemblyView.ShowDialog(); + } + //MesWork.OpcForm opcForm = null; + private void TSM_DebugPage_Click(object sender, EventArgs e) + { + //if (opcForm != null) + //{ + // opcForm.Close(); + // opcForm.Dispose(); + // opcForm = null; + //} + + //opcForm = new MesWork.OpcForm(IsDemoMesServer); + //opcForm.Show(); + + + } + + private void button1_Click(object sender, EventArgs e) + { + //WritePLC("71015001", 1); + //WritePLC("71015002", 1.1); + //WritePLC("71015003", 2.2); + + //WritePLC("71015004", 0); + //WritePLC("71015005", 3.3); + //WritePLC("71015006", 4.4); + + } + + private void label_OpNameList_DoubleClick(object sender, EventArgs e) + { + InitcomboBox_OpNameWebApi(); + } + + private void listView_ShowQualityData_Click(object sender, EventArgs e) + { + //if (GlobalEventInterface.E_DeviceSignalSimGantt_TransmitTagToDeviceSignalSim != null) + //{ + // GlobalEventInterface.E_DeviceSignalSimGantt_TransmitTagToDeviceSignalSim(currTagID, currTagName); + //} + } + + private void listView_ShowQualityData_SelectedIndexChanged(object sender, EventArgs e) + { + if(listView_ShowQualityData.SelectedItems.Count>0) + { + string opName = listView_ShowQualityData.SelectedItems[0].SubItems[0].Text; + string itemName = listView_ShowQualityData.SelectedItems[0].SubItems[1].Text; + string tagName = opName + "-"+ itemName; + string tagID = listView_ShowQualityData.SelectedItems[0].SubItems[3].Text; + int tagFrom = 2; + string tagIDCopy = ""; + if (radioButton_PlcSignl.Checked) + { + textBox_Base_TagID.Text = tagID; + //textBox_Base_Item.Text = itemName; + //if (GlobalEventInterface.E_MisDataPlcTagIDSignal_TransmitTagToDeviceSignalSim != null) + //{ + // GlobalEventInterface.E_MisDataPlcTagIDSignal_TransmitTagToDeviceSignalSim(tagID, tagName, tagFrom, opName, tagIDCopy); + //} + } + else if(radioButton_PlcSignl_Copy.Checked) + { + tagFrom = 4; + if (radioButton_Base.Checked) + { + textBox_Base_TagID.Text = tagID; + textBox_Base_Item.Text = itemName; + } + else if(radioButton_Copy.Checked) + { + textBox_Copy_TagID.Text = tagID; + textBox_Copy_Item.Text = itemName; + } + tagID = textBox_Base_TagID.Text; + tagName = opName + "-" + textBox_Base_Item.Text+"[拷贝信号:"+ textBox_Copy_Item.Text+"]"; + tagIDCopy = textBox_Copy_TagID.Text; + //if (GlobalEventInterface.E_MisDataPlcTagIDSignal_TransmitTagToDeviceSignalSim != null) + //{ + // GlobalEventInterface.E_MisDataPlcTagIDSignal_TransmitTagToDeviceSignalSim(tagID, tagName, tagFrom, opName, tagIDCopy); + //} + } + } + } + + private void radioButton_PartCodeSanner_Click(object sender, EventArgs e) + { + radioButton_Base.Checked = true; + radioButton_Base.Enabled = false; + radioButton_Copy.Enabled = false; + if (radioButton_PartCodeSanner.Checked) + { + var tagID = Guid.NewGuid().ToString(); + string opName = comboBox_OpName.Text; + string tagName = opName + "-" + "扫描条码"; + int tagFrom = 3; + string tagIDCopy = ""; + //GlobalEventInterface.E_MisDataPlcTagIDSignal_TransmitTagToDeviceSignalSim(tagID, tagName, tagFrom, opName,tagIDCopy); + } + } + + private void radioButton_PlcSignl_CheckedChanged(object sender, EventArgs e) + { + radioButton_Base.Checked = true; + radioButton_Base.Enabled = false; + radioButton_Copy.Enabled = false; + } + + + + private void radioButton_PlcSignl_Click(object sender, EventArgs e) + { + radioButton_Base.Checked = true; + radioButton_Base.Enabled = false; + radioButton_Copy.Enabled = false; + } + + private void radioButton_PlcSignl_Copy_Click(object sender, EventArgs e) + { + radioButton_Base.Enabled = true; + radioButton_Copy.Enabled = true; + if (listView_ShowQualityData.SelectedItems.Count < 1) return; + string opName = listView_ShowQualityData.SelectedItems[0].SubItems[0].Text; + string tagName; + string tagID ; + int tagFrom ; + string tagIDCopy ; + + if (radioButton_PlcSignl_Copy.Checked) + { + tagFrom = 4; + tagID = textBox_Base_TagID.Text; + tagName = opName + "-" + textBox_Base_Item.Text; + tagIDCopy = textBox_Copy_TagID.Text; + //if (GlobalEventInterface.E_MisDataPlcTagIDSignal_TransmitTagToDeviceSignalSim != null) + //{ + // GlobalEventInterface.E_MisDataPlcTagIDSignal_TransmitTagToDeviceSignalSim(tagID, tagName, tagFrom, opName, tagIDCopy); + //} + } + } + + private void cb_MonitorData_Click(object sender, EventArgs e) + { + + if (cb_MonitorData.Checked) + { + UpdateForm_IsRun = true; + Thread mythread = new Thread(new ThreadStart(UpdateForm)); + //将线程设为后台运行 + mythread.IsBackground = true; + mythread.Start(); + } + else + { + UpdateForm_IsRun = false; + } + + } + + private void timer_ReadTagValues_Tick(object sender, EventArgs e) + { + // UpdateForm(); + } + bool UpdateForm_IsRun = false; + private void UpdateForm() + { + while(UpdateForm_IsRun) + { + if (listView_ShowQualityData.Items.Count > 0) + { + ReadQualityDataUpdate(WorkStationNum_Now); + } + else + { + ReadQualityData(WorkStationNum_Now); + } + InitFormBtnColorUpdate(); + Thread.Sleep(1500); + + } + + } + private void EToolStripMenuItem_EquipAlarm_Click(object sender, EventArgs e) + { + //try + //{ + // if (!EToolStripMenuItem_EquipAlarm.Checked) + // { + + // groupBox_WorkStationQuality.Width = 307; + // groupBox_WorkStationQuality.Height = 313; + // listView_ShowQualityData.Width = 294; + // listView_ShowQualityData.Height = 234; + // button_ReadData_Click(null, null); + // groupBox_Alarm.Visible = true; + // EToolStripMenuItem_EquipAlarm.Checked = true; + // EToolStripMenuItem_EquipAlarm_Visiable = true; + // } + // else + // { + // groupBox_Alarm.Visible = false; + + // groupBox_WorkStationQuality.Width = 307; + // groupBox_WorkStationQuality.Height = 642; + // listView_ShowQualityData.Width = 294; + // listView_ShowQualityData.Height = 572; + // button_ReadData_Click(null, null); + // EToolStripMenuItem_EquipAlarm.Checked = false; + // } + //} + //catch (Exception err) + //{ + // ApplicationLog.WriteLog(err, err.Message); + + //} + } + + } +} diff --git a/MisDataPlcTagID/MisDataPlcTagID/MisDataWebFunSim.resx b/MisDataPlcTagID/MisDataPlcTagID/MisDataWebFunSim.resx new file mode 100644 index 0000000..b5093bc --- /dev/null +++ b/MisDataPlcTagID/MisDataPlcTagID/MisDataWebFunSim.resx @@ -0,0 +1,209 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 423, 5 + + + 749, 3 + + + 870, 3 + + + 45 + + + + + AAABAAEAICAAAAEAIACoEAAAFgAAACgAAAAgAAAAQAAAAAEAIAAAAAAAABAAABMLAAATCwAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMgChADIAoQIyAKEgMgChczIA + occyAKHqMgChmTIAoTwyAKEJMgChAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMgChADIAoQQyAKEvMgChdzIA + odYyAKH7MgCh/zIAof8yAKH/MgCh6jIAoacyAKFJMgChEjIAoQAyAKEAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAyAKEAMgChADIAoQoyAKE+MgChkTIA + oeoyAKH+MgCh+TIAoe0yAKH+MgCh/zIAofwyAKH3MgCh/jIAofgyAKHBMgChZDIAoR4yAKEBMgChAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAyAKEAMgChATIAoRUyAKFcMgChujIA + ofEyAKH/MgCh9DIAobcyAKFPMgChfjIAof8yAKH/MgCh5TIAoVUyAKGLMgCh4jIAofwyAKH9MgCh2TIA + oYcyAKEoMgChBTIAoQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAyAKEAMgChAjIAoSYyAKF2MgCh0DIA + ofcyAKH+MgCh8zIAof8yAKGjMgChDTIAoQAyAKFpMgCh/zIAof8yAKHhMgChHjIAoQIyAKEiMgChbjIA + ocoyAKH3MgCh/jIAoeUyAKGfMgChQTIAoQsyAKEAAAAAAAAAAAAAAAAAMgChCDIAoUEyAKGXMgCh4jIA + of4yAKH/MgChzzIAoW0yAKFoMgCh+zIAoZcyAKEAMgChADIAoWkyAKH/MgCh/zIAoeEyAKEeMgChADIA + oQAyAKEBMgChETIAoVAyAKGiMgCh8DIAof8yAKH0MgChuTIAoW0yAKEVMgChADIAoQAyAKG2MgCh7TIA + of8yAKHvMgCh7jIAofgyAKFLMgChADIAoTcyAKH1MgChlzIAoQAyAKEAMgChaTIAof8yAKH/MgCh4TIA + oR4yAKEAAAAAAAAAAAAAAAAAMgChADIAoQcyAKE4MgChijIAod8yAKH9MgCh+zIAoc4yAKFdMgChADIA + of8yAKHlMgChlDIAoToyAKGgMgCh7jIAoSwyAKEAMgChFzIAodgyAKGZMgChADIAoQAyAKFpMgCh/zIA + of8yAKHxMgChfDIAoSkyAKEBMgChAAAAAAAAAAAAAAAAADIAoQAyAKECMgChITIAoW8yAKG/MgCh/zIA + oZYyAKEAMgCh/zIAoZoyAKEBMgChADIAoZkyAKHSMgChEjIAoQAyAKEGMgChujIAoZoyAKEAMgChADIA + oWkyAKH/MgCh/zIAof0yAKH+MgCh4TIAoZIyAKFEMgChDjIAoQAyAKEAAAAAAAAAAAAAAAAAMgChADIA + oUIyAKH7MgChlzIAoQAyAKH/MgChlzIAoQAyAKEAMgChmjIAobMyAKEEMgChADIAoQAyAKGcMgChmzIA + oQAyAKEAMgChaTIAof8yAKH/MgCh4zIAoZYyAKHRMgCh+zIAofQyAKHDMgChZDIAoSIyAKEBMgChAAAA + AAAyAKEAMgChPzIAofsyAKGXMgChADIAof8yAKGXMgChADIAoQAyAKGaMgChiDIAoQAAAAAAMgChADIA + oYgyAKGaMgChADIAoQAyAKFpMgCh/zIAof8yAKHhMgChIDIAoRIyAKFeMgChqzIAoe0yAKH+MgCh3jIA + oYYyAKEqMgChADIAoQAyAKE/MgCh+zIAoZcyAKEAMgCh/zIAoZcyAKEAMgChADIAoZgyAKFtMgChAAAA + AAAyAKEAMgChXDIAoZQyAKEAMgChADIAoWkyAKH/MgCh/zIAoeEyAKEeMgChADIAoQAyAKEGMgChMDIA + oX8yAKHTMgCh+jIAoWkyAKEAMgChADIAoT8yAKH7MgChlzIAoQAyAKH/MgChlzIAoQAyAKEAMgChlTIA + oWMyAKEAAAAAADIAoQAyAKE2MgChhTIAoQAyAKEAMgChaTIAof8yAKH/MgCh4TIAoR4yAKEAAAAAAAAA + AAAyAKEAMgChATIAoRUyAKFYMgChQDIAoQAyAKEAMgChPzIAofsyAKGXMgChADIAof8yAKGXMgChADIA + oQAyAKGLMgChQTIAoQAyAKEFMgChADIAoSMyAKF4MgChADIAoQAyAKFpMgCh/zIAof8yAKHhMgChHjIA + oQAAAAAAAAAAAAAAAAAAAAAAMgChADIAoQAyAKEBMgChADIAoQAyAKE/MgCh+zIAoZcyAKEAMgCh/zIA + oZcyAKEAMgChADIAoXcyAKEkMgChBzIAoUIyAKEBMgChFjIAoWUyAKEBMgChADIAoWkyAKH/MgCh/zIA + oeEyAKEeMgChADIAoQAyAKE5MgChSTIAoQ8yAKEBMgChAAAAAAAAAAAAMgChADIAoT8yAKH7MgChlzIA + oQAyAKH/MgChlzIAoQAyAKECMgChWzIAoQ8yAKEVMgChhTIAoQoyAKEHMgChMzIAoQEyAKEAMgChaTIA + of8yAKH/MgCh4TIAoR4yAKEAMgChADIAoWkyAKH1MgChyzIAoX8yAKE4MgChBTIAoQAyAKEAMgChPzIA + ofsyAKGXMgChADIAof8yAKGXMgChADIAoQMyAKFZMgChCzIAoS4yAKHDMgChGjIAoQAAAAAAAAAAADIA + oQAyAKFpMgCh/zIAof8yAKHhMgChHjIAoQAyAKEAMgChLDIAoaEyAKHkMgCh/DIAoe8yAKGrMgChUzIA + oREyAKFBMgCh+zIAoZcyAKEAMgCh/zIAoZcyAKEAMgChBzIAoVAyAKEEMgChQTIAodoyAKEjMgChAAAA + AAAAAAAAMgChADIAoWkyAKH/MgCh/zIAoeEyAKEeMgChAAAAAAAyAKEAMgChBjIAoSAyAKFyMgChwjIA + ofMyAKH4MgCh0zIAobMyAKH9MgChljIAoQAyAKH/MgChlzIAoQAyAKEBMgChBDIAoQAyAKFKMgCh7jIA + oT0yAKEAAAAAADIAoQAyAKEAMgChbDIAof8yAKH/MgCh4TIAoR8yAKEAAAAAAAAAAAAAAAAAMgChADIA + oQEyAKELMgChRzIAoZYyAKHeMgCh/TIAof8yAKGWMgChADIAof8yAKGXMgChAAAAAAAAAAAAMgChADIA + oW0yAKH/MgChZDIAoQAyAKEEMgChHDIAoWAyAKHPMgCh/zIAof8yAKH3MgChkTIAoS8yAKELMgChADIA + oQAAAAAAAAAAAAAAAAAyAKEAMgChATIAoSAyAKF2MgCh/zIAoZYyAKEAMgCh/zIAoZcyAKEAAAAAADIA + oQAyAKEAMgChljIAof8yAKGeMgChOTIAoZEyAKHcMgCh+TIAof8yAKH/MgCh/zIAof8yAKH+MgCh6jIA + obgyAKFXMgChITIAoQEyAKEAAAAAAAAAAAAAAAAAMgChADIAoT8yAKH7MgChlzIAoQAyAKH/MgChlzIA + oQAAAAAAMgChADIAoQwyAKG9MgCh/zIAofMyAKHyMgCh/jIAof8yAKH/MgCh/zIAofoyAKH3MgCh/jIA + of8yAKH/MgCh/zIAofsyAKHbMgChmzIAoUwyAKENMgChATIAoQAyAKEAMgChPzIAofsyAKGXMgChADIA + of8yAKGXMgChATIAoRkyAKFbMgChsTIAofAyAKH/MgCh/zIAof8yAKH/MgCh/DIAoeYyAKGxMgChVTIA + oUIyAKGFMgCh1TIAofUyAKH/MgCh/zIAof8yAKH/MgCh9DIAocUyAKGDMgChMDIAoQYyAKE/MgCh+zIA + oZcyAKEAMgCh/zIAocEyAKGOMgCh2TIAofcyAKH/MgCh/zIAof8yAKH/MgCh7jIAobMyAKFwMgChJjIA + oQoyAKEAMgChADIAoQEyAKEXMgChTTIAoZsyAKHYMgCh/TIAof8yAKH/MgCh/zIAof4yAKHqMgChszIA + oZgyAKH+MgChljIAoQAyAKH/MgCh/zIAof8yAKH/MgCh/zIAof8yAKH0MgChyTIAoYEyAKE/MgChBzIA + oQAAAAAAMgChADIAoSIyAKF2MgChQjIAoRIyAKEAMgChATIAoR4yAKFjMgChrjIAoecyAKH9MgCh/zIA + of8yAKH/MgCh/zIAof8yAKGWMgChADIAof8yAKH/MgCh/zIAofkyAKHWMgChmjIAoUIyAKERMgChATIA + oQAyAKEGMgChFTIAoQMyAKEAMgChKDIAoZUyAKHHMgChxjIAoXcyAKE3MgChBzIAoQAyAKEGMgChKTIA + oXYyAKHDMgCh7jIAof4yAKH/MgCh/zIAoZYyAKEAMgChrjIAoeYyAKH+MgCh0zIAoVcyAKELMgChADIA + oQAyAKEAMgChADIAoVUyAKHAMgChkjIAoVYyAKEUMgChATIAoRYyAKFhMgChqzIAodUyAKGmMgChZTIA + oR8yAKEDMgChBDIAoS0yAKGiMgCh9DIAofUyAKHGMgChWTIAoQAyAKEGMgChKjIAoWsyAKHBMgCh3DIA + ocEyAKFwMgChJTIAoQYyAKEAMgChDDIAoTgyAKF/MgChyjIAocMyAKGUMgChMzIAoQsyAKEEMgChJjIA + oWUyAKG/MgCh0TIAoaYyAKGoMgCh1TIAodYyAKGNMgChQTIAoRAyAKEAMgChAAAAAAAyAKEAMgChADIA + oQ8yAKE8MgChkDIAoc8yAKHfMgChpDIAoVIyAKEcMgChADIAoQEyAKETMgChRzIAoZ8yAKHGMgChvzIA + oWQyAKEtMgChMzIAoY8yAKHvMgCh5zIAoa8yAKFcMgChHDIAoQMyAKEAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAADIAoQAyAKECMgChFTIAoVcyAKGaMgCh3DIAodEyAKGaMgChSDIAoQsyAKEAMgChATIA + oSUyAKGGMgCh6TIAofEyAKHhMgChtzIAoXAyAKErMgChBTIAoQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMgChADIAoQIyAKElMgChXTIAobgyAKHbMgChxTIA + oYUyAKFbMgChqzIAodEyAKHLMgChhDIAoTsyAKELMgChAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAyAKEAMgChCzIA + oTcyAKGTMgCh0zIAofAyAKG2MgChWjIAoRcyAKEBMgChAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAA/+Af//+AB//8AAD/8AAAP8AIAA8AGDABARg+AQEYD4ERGAPxMZgAcTOY + ADEzmDAxM5g8MTKIPzEgCDDxIAgwMSB4MAEgeDgBJHg+ATxAD8E8AAHxOAAAMQAAAAEAAwABABwgAQBE + BAEBwAABAEAAA+AAAA/4AAB//wAD///gD/8= + + + \ No newline at end of file diff --git a/MisDataPlcTagID/MisDataPlcTagID/Properties/AssemblyInfo.cs b/MisDataPlcTagID/MisDataPlcTagID/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..d18821c --- /dev/null +++ b/MisDataPlcTagID/MisDataPlcTagID/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// 有关程序集的一般信息由以下 +// 控制。更改这些特性值可修改 +// 与程序集关联的信息。 +[assembly: AssemblyTitle("MisDataPlcTagID")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("MisDataPlcTagID")] +[assembly: AssemblyCopyright("Copyright © 2022")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// 将 ComVisible 设置为 false 会使此程序集中的类型 +//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型 +//请将此类型的 ComVisible 特性设置为 true。 +[assembly: ComVisible(false)] + +// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID +[assembly: Guid("0f887ab8-1bc5-4ef0-9240-e7afd91a9911")] + +// 程序集的版本信息由下列四个值组成: +// +// 主版本 +// 次版本 +// 生成号 +// 修订号 +// +//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值 +//通过使用 "*",如下所示: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/MisDataPlcTagID/MisDataPlcTagID/ReadThisStationProductInfo.cs b/MisDataPlcTagID/MisDataPlcTagID/ReadThisStationProductInfo.cs new file mode 100644 index 0000000..204e766 --- /dev/null +++ b/MisDataPlcTagID/MisDataPlcTagID/ReadThisStationProductInfo.cs @@ -0,0 +1,107 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading; +using System.Windows.Forms; +//using SystemFramework; + +namespace MisDataSaveDate +{ + public partial class MisData + { + + void ReadPLC_ProductInfo() + { + try + { + foreach (Control Tbx in this.groupBox_PLC.Controls) + { + + Thread t = new Thread(new ParameterizedThreadStart(ReadPLC_ProductInfo_Thread)); + t.Start(Tbx); + } + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, err.Message); + + } + } + + + + void ReadPLC_ProductInfo_Thread(object obj) + { + try + { + Control Tbx = (Control)obj; + if (Tbx.Name.Length < 12) return; + if (Tbx.Name.Substring(0, 8) != "Tbx_PLC_") return; + string[] TbxName_Split = Tbx.Name.Split('_'); + int TagType = Convert.ToInt32(TbxName_Split[2]); + if (Tbx.InvokeRequired ) + { + Action actionDelegate = (x) => { Tbx.Text = x; }; + Tbx.BeginInvoke(actionDelegate, DtWebApi.ReadWritePLC.ReadPLC(TagType.ToString(), WorkStationNum_Now).ToString()); + } + else + { + Tbx.Text = DtWebApi.ReadWritePLC.ReadPLC(TagType.ToString(), WorkStationNum_Now).ToString(); + } + + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, err.Message); + } + } + + + void ReadMES_ProductInfo() + { + try + { + foreach (Control Tbx in this.groupBox_MES.Controls) + { + Thread t = new Thread(new ParameterizedThreadStart(ReadMES_ProductInfo_Thread)); + t.Start(Tbx); + } + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, err.Message); + + } + } + void ReadMES_ProductInfo_Thread(object obj) + { + try + { + Control Tbx = (Control)obj; + + if (Tbx.Name.Length < 12) return; + if (Tbx.Name.Substring(0, 8) != "Tbx_MES_") return; + + string[] TbxName_Split = Tbx.Name.Split('_'); + int TagType = Convert.ToInt32(TbxName_Split[2]); + if (Tbx .InvokeRequired ) + { + Action ActionDelegate = (x) => { Tbx.Text = x; }; + Tbx.BeginInvoke(ActionDelegate, DtWebApi.ReadWritePLC.ReadPLC(TagType.ToString(), WorkStationNum_Now).ToString()); + } + else + { + Tbx.Text = DtWebApi.ReadWritePLC.ReadPLC(TagType.ToString(), WorkStationNum_Now).ToString(); + } + + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, err.Message); + } + } + + + } +} diff --git a/MisDataPlcTagID/MisDataPlcTagID/ReadThisStationProductInfoSim.cs b/MisDataPlcTagID/MisDataPlcTagID/ReadThisStationProductInfoSim.cs new file mode 100644 index 0000000..3d6c9e6 --- /dev/null +++ b/MisDataPlcTagID/MisDataPlcTagID/ReadThisStationProductInfoSim.cs @@ -0,0 +1,107 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading; +using System.Windows.Forms; +//using SystemFramework; + +namespace MisDataSaveDateSim +{ + public partial class MisData + { + + void ReadPLC_ProductInfo() + { + try + { + foreach (Control Tbx in this.groupBox_PLC.Controls) + { + + Thread t = new Thread(new ParameterizedThreadStart(ReadPLC_ProductInfo_Thread)); + t.Start(Tbx); + } + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, err.Message); + + } + } + + + + void ReadPLC_ProductInfo_Thread(object obj) + { + try + { + Control Tbx = (Control)obj; + if (Tbx.Name.Length < 12) return; + if (Tbx.Name.Substring(0, 8) != "Tbx_PLC_") return; + string[] TbxName_Split = Tbx.Name.Split('_'); + int TagType = Convert.ToInt32(TbxName_Split[2]); + if (Tbx.InvokeRequired ) + { + Action actionDelegate = (x) => { Tbx.Text = x; }; + Tbx.BeginInvoke(actionDelegate, DtWebApi.ReadWritePLC.ReadPLC(TagType.ToString(), WorkStationNum_Now).ToString()); + } + else + { + Tbx.Text = DtWebApi.ReadWritePLC.ReadPLC(TagType.ToString(), WorkStationNum_Now).ToString(); + } + + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, err.Message); + } + } + + + void ReadMES_ProductInfo() + { + try + { + foreach (Control Tbx in this.groupBox_MES.Controls) + { + Thread t = new Thread(new ParameterizedThreadStart(ReadMES_ProductInfo_Thread)); + t.Start(Tbx); + } + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, err.Message); + + } + } + void ReadMES_ProductInfo_Thread(object obj) + { + try + { + Control Tbx = (Control)obj; + + if (Tbx.Name.Length < 12) return; + if (Tbx.Name.Substring(0, 8) != "Tbx_MES_") return; + + string[] TbxName_Split = Tbx.Name.Split('_'); + int TagType = Convert.ToInt32(TbxName_Split[2]); + if (Tbx .InvokeRequired ) + { + Action ActionDelegate = (x) => { Tbx.Text = x; }; + Tbx.BeginInvoke(ActionDelegate, DtWebApi.ReadWritePLC.ReadPLC(TagType.ToString(), WorkStationNum_Now).ToString()); + } + else + { + Tbx.Text = DtWebApi.ReadWritePLC.ReadPLC(TagType.ToString(), WorkStationNum_Now).ToString(); + } + + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, err.Message); + } + } + + + } +} diff --git a/MisDataPlcTagID/MisDataPlcTagID/WriteQualityValueForm.Designer.cs b/MisDataPlcTagID/MisDataPlcTagID/WriteQualityValueForm.Designer.cs new file mode 100644 index 0000000..88655c4 --- /dev/null +++ b/MisDataPlcTagID/MisDataPlcTagID/WriteQualityValueForm.Designer.cs @@ -0,0 +1,115 @@ +namespace MisDataSaveDate +{ + partial class WriteQualityValueForm + { + /// + /// 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.label_Message = new System.Windows.Forms.Label(); + this.textBox_InputValue = new System.Windows.Forms.TextBox(); + this.button_OK = new System.Windows.Forms.Button(); + this.button_Cancle = new System.Windows.Forms.Button(); + this.comboBox_InputValue = new System.Windows.Forms.ComboBox(); + this.SuspendLayout(); + // + // label_Message + // + this.label_Message.AutoSize = true; + this.label_Message.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.label_Message.Location = new System.Drawing.Point(15, 10); + this.label_Message.Name = "label_Message"; + this.label_Message.Size = new System.Drawing.Size(41, 12); + this.label_Message.TabIndex = 0; + this.label_Message.Text = "label1"; + // + // textBox_InputValue + // + this.textBox_InputValue.Location = new System.Drawing.Point(10, 50); + this.textBox_InputValue.Name = "textBox_InputValue"; + this.textBox_InputValue.Size = new System.Drawing.Size(475, 21); + this.textBox_InputValue.TabIndex = 1; + // + // button_OK + // + this.button_OK.Location = new System.Drawing.Point(268, 81); + this.button_OK.Name = "button_OK"; + this.button_OK.Size = new System.Drawing.Size(95, 25); + this.button_OK.TabIndex = 2; + this.button_OK.Text = "OK"; + this.button_OK.UseVisualStyleBackColor = true; + this.button_OK.Click += new System.EventHandler(this.button_OK_Click); + // + // button_Cancle + // + this.button_Cancle.Location = new System.Drawing.Point(369, 81); + this.button_Cancle.Name = "button_Cancle"; + this.button_Cancle.Size = new System.Drawing.Size(95, 25); + this.button_Cancle.TabIndex = 2; + this.button_Cancle.Text = "Cancel"; + this.button_Cancle.UseVisualStyleBackColor = true; + this.button_Cancle.Click += new System.EventHandler(this.button_Cancle_Click); + // + // comboBox_InputValue + // + this.comboBox_InputValue.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; + this.comboBox_InputValue.FormattingEnabled = true; + this.comboBox_InputValue.Items.AddRange(new object[] { + "false", + "true"}); + this.comboBox_InputValue.Location = new System.Drawing.Point(10, 50); + this.comboBox_InputValue.Name = "comboBox_InputValue"; + this.comboBox_InputValue.Size = new System.Drawing.Size(475, 20); + this.comboBox_InputValue.TabIndex = 3; + // + // WriteQualityValueForm + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(494, 111); + this.Controls.Add(this.comboBox_InputValue); + this.Controls.Add(this.button_Cancle); + this.Controls.Add(this.button_OK); + this.Controls.Add(this.textBox_InputValue); + this.Controls.Add(this.label_Message); + this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow; + this.Name = "WriteQualityValueForm"; + this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; + this.Text = "Write value"; + this.TopMost = true; + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private System.Windows.Forms.Label label_Message; + private System.Windows.Forms.TextBox textBox_InputValue; + private System.Windows.Forms.Button button_OK; + private System.Windows.Forms.Button button_Cancle; + private System.Windows.Forms.ComboBox comboBox_InputValue; + } +} \ No newline at end of file diff --git a/MisDataPlcTagID/MisDataPlcTagID/WriteQualityValueForm.cs b/MisDataPlcTagID/MisDataPlcTagID/WriteQualityValueForm.cs new file mode 100644 index 0000000..0cd266f --- /dev/null +++ b/MisDataPlcTagID/MisDataPlcTagID/WriteQualityValueForm.cs @@ -0,0 +1,267 @@ +using System; +using System.Windows.Forms; +//using BasicData; +using System.Text.RegularExpressions; +//using SystemFramework; +using System.Threading; +using DoWhatPlc; + +namespace MisDataSaveDate +{ + public partial class WriteQualityValueForm : Form + { + QualityDataType SelectListData; + Form MainForm; + public WriteQualityValueForm(QualityDataType SelectData,Form Mainform) + { + try + { + InitializeComponent(); + SelectListData = new QualityDataType(); + SelectListData = SelectData; + SetForm(SelectData.tagTypeID, SelectData.tagValue); + MainForm = Mainform; + this.Parent = Mainform; + + + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, err.Message); + } + } + + private void button_OK_Click(object sender, EventArgs e) + { + try + { + if (!TagTypeID_Confirm(SelectListData.tagTypeID)) return; + + this.Hide () ; + + QualityDataQueryStruct QualityStruct = new QualityDataQueryStruct(SelectListData.tagID , SelectListData.tagTypeID , comboBox_InputValue.SelectedIndex.ToString(), textBox_InputValue.Text,this); + Thread t = new Thread(new ParameterizedThreadStart(WriteQualityDataByTagID_Thread)); + t.Start(QualityStruct); + + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, err.Message); + + } + } + + + void WriteQualityDataByTagID_Thread(object obj) + { + try + { + QualityDataQueryStruct QualityStruct = (QualityDataQueryStruct)obj; + Form ThisForm = (Form)QualityStruct.tempForm; + + + if (QualityStruct.tagTypeID == 11) + { + DtWebApi.ReadWritePLC.WritePLC(QualityStruct.tagID, QualityStruct.tagValue.ToString()); + } + else + { + DtWebApi.ReadWritePLC.WritePLC(SelectListData.tagID, QualityStruct.tagValue2.ToString()); + } + MainForm.BeginInvoke (MisData.MainFormRefresh, null, null); + Action ActionDelete = () => { this.Close();this.Dispose(); }; + if(this.InvokeRequired ) + { + ThisForm.BeginInvoke(ActionDelete); + } + else + { + ActionDelete(); + } + + + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, err.Message); + + } + + } + + + + + private void button_Cancle_Click(object sender, EventArgs e) + { + this.Close(); + this.Dispose(); + } + + + + void SetForm( int TagTypeID,object TagValue) + { + try + { + switch (TagTypeID) + { + case 11://BOOL + comboBox_InputValue.Enabled = true; + comboBox_InputValue.Visible = true; + textBox_InputValue.Enabled = false; + textBox_InputValue.Visible = false; + label_Message.Text = "Data type: Boolean"; + if (Convert.ToBoolean(TagValue)) + { + comboBox_InputValue.SelectedIndex = 1; + } + else + { + comboBox_InputValue.SelectedIndex = 0; + } + + break; + + case 2://INT. + label_Message.Text = "Data type: Int16 Range from -32768 to 32767"; + comboBox_InputValue.Enabled = false; + comboBox_InputValue.Visible = false; + textBox_InputValue.Enabled = true; + textBox_InputValue.Visible = true; + textBox_InputValue.Text = TagValue.ToString(); + + break; + case 17://BYTE + label_Message.Text = "Data type: Byte Range from 0 to 255"; + comboBox_InputValue.Enabled = false; + comboBox_InputValue.Visible = false; + textBox_InputValue.Enabled = true; + textBox_InputValue.Visible = true; + textBox_InputValue.Text = TagValue.ToString(); + + break; + case 8://STRING + label_Message.Text = "Data type: String"; + comboBox_InputValue.Enabled = false; + comboBox_InputValue.Visible = false; + textBox_InputValue.Enabled = true; + textBox_InputValue.Visible = true; + textBox_InputValue.Text = TagValue.ToString(); + + break; + case 18://Word + label_Message.Text = "Data type: UInt16 Range from 0 to 65535"; + comboBox_InputValue.Enabled = false; + comboBox_InputValue.Visible = false; + textBox_InputValue.Enabled = true; + textBox_InputValue.Visible = true; + textBox_InputValue.Text = TagValue.ToString(); + + break; + case 4://real + label_Message.Text = "Data type: Single Range from -3.402823E+38 to 3.402823E+38"; + comboBox_InputValue.Enabled = false; + comboBox_InputValue.Visible = false; + textBox_InputValue.Enabled = true; + textBox_InputValue.Visible = true; + textBox_InputValue.Text = TagValue.ToString(); + + break; + default://Unknow + label_Message.Text = "Data type: Unknow"; + comboBox_InputValue.Enabled = false; + comboBox_InputValue.Visible = false; + textBox_InputValue.Enabled = true; + textBox_InputValue.Visible = true; + textBox_InputValue.Text = TagValue.ToString(); + + break; + + } + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, err.Message); + + } + + + } + + bool TagTypeID_Confirm( int TagTypeID) + { + try + { + switch (TagTypeID) + { + + + case 2://INT + //TextBox存在非数字字符 报错 + if (!Regex.IsMatch(textBox_InputValue.Text, @"^[-]?\d*$")) + { + MessageBox.Show("输入不是整数!"); + return false; + } + if (textBox_InputValue.Text.Length > 9) + { + MessageBox.Show("输入数据不在范围内"); + return false; + } + break; + case 17://BYTE + //TextBox存在非数字字符 报错 + if (!Regex.IsMatch(textBox_InputValue.Text, @"^[-]?\d*$")) + { + MessageBox.Show("输入不是整数!"); + return false; + } + if (Convert.ToInt32(textBox_InputValue.Text.Trim()) > 255) + { + MessageBox.Show("输入数据不在范围内"); + return false; + } + break; + case 8://STRING + + break; + case 18://Word + //TextBox存在非数字字符 报错 + if (!Regex.IsMatch(textBox_InputValue.Text, @"^[-]?\d*$")) + { + MessageBox.Show("输入不是整数!"); + return false; + } + if (textBox_InputValue.Text.Trim().Length > 4) + { + MessageBox.Show("输入数据不在范围内"); + return false; + } + break; + case 4://real + //TextBox存在非数字字符 报错 + //TextBox存在非数字字符 报错 + if (!Regex.IsMatch(textBox_InputValue.Text, @"^-?\d+\.?\d*$")) + { + MessageBox.Show("输入不是实数!"); + return false; + } + + break; + default: + break; + + } + + return true; + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, err.Message); + return true; + } + } + + } +} diff --git a/MisDataPlcTagID/MisDataPlcTagID/WriteQualityValueForm.resx b/MisDataPlcTagID/MisDataPlcTagID/WriteQualityValueForm.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/MisDataPlcTagID/MisDataPlcTagID/WriteQualityValueForm.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/MisDataPlcTagID/MisDataPlcTagID/WriteQualityValueFormSim.Designer.cs b/MisDataPlcTagID/MisDataPlcTagID/WriteQualityValueFormSim.Designer.cs new file mode 100644 index 0000000..e4c6210 --- /dev/null +++ b/MisDataPlcTagID/MisDataPlcTagID/WriteQualityValueFormSim.Designer.cs @@ -0,0 +1,115 @@ +namespace MisDataSaveDateSim +{ + partial class WriteQualityValueForm + { + /// + /// 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.label_Message = new System.Windows.Forms.Label(); + this.textBox_InputValue = new System.Windows.Forms.TextBox(); + this.button_OK = new System.Windows.Forms.Button(); + this.button_Cancle = new System.Windows.Forms.Button(); + this.comboBox_InputValue = new System.Windows.Forms.ComboBox(); + this.SuspendLayout(); + // + // label_Message + // + this.label_Message.AutoSize = true; + this.label_Message.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.label_Message.Location = new System.Drawing.Point(15, 10); + this.label_Message.Name = "label_Message"; + this.label_Message.Size = new System.Drawing.Size(41, 12); + this.label_Message.TabIndex = 0; + this.label_Message.Text = "label1"; + // + // textBox_InputValue + // + this.textBox_InputValue.Location = new System.Drawing.Point(10, 50); + this.textBox_InputValue.Name = "textBox_InputValue"; + this.textBox_InputValue.Size = new System.Drawing.Size(475, 21); + this.textBox_InputValue.TabIndex = 1; + // + // button_OK + // + this.button_OK.Location = new System.Drawing.Point(268, 81); + this.button_OK.Name = "button_OK"; + this.button_OK.Size = new System.Drawing.Size(95, 25); + this.button_OK.TabIndex = 2; + this.button_OK.Text = "OK"; + this.button_OK.UseVisualStyleBackColor = true; + this.button_OK.Click += new System.EventHandler(this.button_OK_Click); + // + // button_Cancle + // + this.button_Cancle.Location = new System.Drawing.Point(369, 81); + this.button_Cancle.Name = "button_Cancle"; + this.button_Cancle.Size = new System.Drawing.Size(95, 25); + this.button_Cancle.TabIndex = 2; + this.button_Cancle.Text = "Cancel"; + this.button_Cancle.UseVisualStyleBackColor = true; + this.button_Cancle.Click += new System.EventHandler(this.button_Cancle_Click); + // + // comboBox_InputValue + // + this.comboBox_InputValue.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; + this.comboBox_InputValue.FormattingEnabled = true; + this.comboBox_InputValue.Items.AddRange(new object[] { + "false", + "true"}); + this.comboBox_InputValue.Location = new System.Drawing.Point(10, 50); + this.comboBox_InputValue.Name = "comboBox_InputValue"; + this.comboBox_InputValue.Size = new System.Drawing.Size(475, 20); + this.comboBox_InputValue.TabIndex = 3; + // + // WriteQualityValueForm + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(494, 111); + this.Controls.Add(this.comboBox_InputValue); + this.Controls.Add(this.button_Cancle); + this.Controls.Add(this.button_OK); + this.Controls.Add(this.textBox_InputValue); + this.Controls.Add(this.label_Message); + this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow; + this.Name = "WriteQualityValueForm"; + this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; + this.Text = "Write value"; + this.TopMost = true; + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private System.Windows.Forms.Label label_Message; + private System.Windows.Forms.TextBox textBox_InputValue; + private System.Windows.Forms.Button button_OK; + private System.Windows.Forms.Button button_Cancle; + private System.Windows.Forms.ComboBox comboBox_InputValue; + } +} \ No newline at end of file diff --git a/MisDataPlcTagID/MisDataPlcTagID/WriteQualityValueFormSim.cs b/MisDataPlcTagID/MisDataPlcTagID/WriteQualityValueFormSim.cs new file mode 100644 index 0000000..b9daa98 --- /dev/null +++ b/MisDataPlcTagID/MisDataPlcTagID/WriteQualityValueFormSim.cs @@ -0,0 +1,267 @@ +using System; +using System.Windows.Forms; +//using BasicData; +using System.Text.RegularExpressions; +//using SystemFramework; +using System.Threading; +using DoWhatPlc; + +namespace MisDataSaveDateSim +{ + public partial class WriteQualityValueForm : Form + { + QualityDataType SelectListData; + Form MainForm; + public WriteQualityValueForm(QualityDataType SelectData,Form Mainform) + { + try + { + InitializeComponent(); + SelectListData = new QualityDataType(); + SelectListData = SelectData; + SetForm(SelectData.tagTypeID, SelectData.tagValue); + MainForm = Mainform; + this.Parent = Mainform; + + + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, err.Message); + } + } + + private void button_OK_Click(object sender, EventArgs e) + { + try + { + if (!TagTypeID_Confirm(SelectListData.tagTypeID)) return; + + this.Hide () ; + + QualityDataQueryStruct QualityStruct = new QualityDataQueryStruct(SelectListData.tagID , SelectListData.tagTypeID , comboBox_InputValue.SelectedIndex.ToString(), textBox_InputValue.Text,this); + Thread t = new Thread(new ParameterizedThreadStart(WriteQualityDataByTagID_Thread)); + t.Start(QualityStruct); + + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, err.Message); + + } + } + + + void WriteQualityDataByTagID_Thread(object obj) + { + try + { + QualityDataQueryStruct QualityStruct = (QualityDataQueryStruct)obj; + Form ThisForm = (Form)QualityStruct.tempForm; + + + if (QualityStruct.tagTypeID == 11) + { + DtWebApi.ReadWritePLC.WritePLC(QualityStruct.tagID, QualityStruct.tagValue.ToString()); + } + else + { + DtWebApi.ReadWritePLC.WritePLC(SelectListData.tagID, QualityStruct.tagValue2.ToString()); + } + MainForm.BeginInvoke (MisData.MainFormRefresh, null, null); + Action ActionDelete = () => { this.Close();this.Dispose(); }; + if(this.InvokeRequired ) + { + ThisForm.BeginInvoke(ActionDelete); + } + else + { + ActionDelete(); + } + + + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, err.Message); + + } + + } + + + + + private void button_Cancle_Click(object sender, EventArgs e) + { + this.Close(); + this.Dispose(); + } + + + + void SetForm( int TagTypeID,object TagValue) + { + try + { + switch (TagTypeID) + { + case 11://BOOL + comboBox_InputValue.Enabled = true; + comboBox_InputValue.Visible = true; + textBox_InputValue.Enabled = false; + textBox_InputValue.Visible = false; + label_Message.Text = "Data type: Boolean"; + if (Convert.ToBoolean(TagValue)) + { + comboBox_InputValue.SelectedIndex = 1; + } + else + { + comboBox_InputValue.SelectedIndex = 0; + } + + break; + + case 2://INT. + label_Message.Text = "Data type: Int16 Range from -32768 to 32767"; + comboBox_InputValue.Enabled = false; + comboBox_InputValue.Visible = false; + textBox_InputValue.Enabled = true; + textBox_InputValue.Visible = true; + textBox_InputValue.Text = TagValue.ToString(); + + break; + case 17://BYTE + label_Message.Text = "Data type: Byte Range from 0 to 255"; + comboBox_InputValue.Enabled = false; + comboBox_InputValue.Visible = false; + textBox_InputValue.Enabled = true; + textBox_InputValue.Visible = true; + textBox_InputValue.Text = TagValue.ToString(); + + break; + case 8://STRING + label_Message.Text = "Data type: String"; + comboBox_InputValue.Enabled = false; + comboBox_InputValue.Visible = false; + textBox_InputValue.Enabled = true; + textBox_InputValue.Visible = true; + textBox_InputValue.Text = TagValue.ToString(); + + break; + case 18://Word + label_Message.Text = "Data type: UInt16 Range from 0 to 65535"; + comboBox_InputValue.Enabled = false; + comboBox_InputValue.Visible = false; + textBox_InputValue.Enabled = true; + textBox_InputValue.Visible = true; + textBox_InputValue.Text = TagValue.ToString(); + + break; + case 4://real + label_Message.Text = "Data type: Single Range from -3.402823E+38 to 3.402823E+38"; + comboBox_InputValue.Enabled = false; + comboBox_InputValue.Visible = false; + textBox_InputValue.Enabled = true; + textBox_InputValue.Visible = true; + textBox_InputValue.Text = TagValue.ToString(); + + break; + default://Unknow + label_Message.Text = "Data type: Unknow"; + comboBox_InputValue.Enabled = false; + comboBox_InputValue.Visible = false; + textBox_InputValue.Enabled = true; + textBox_InputValue.Visible = true; + textBox_InputValue.Text = TagValue.ToString(); + + break; + + } + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, err.Message); + + } + + + } + + bool TagTypeID_Confirm( int TagTypeID) + { + try + { + switch (TagTypeID) + { + + + case 2://INT + //TextBox存在非数字字符 报错 + if (!Regex.IsMatch(textBox_InputValue.Text, @"^[-]?\d*$")) + { + MessageBox.Show("输入不是整数!"); + return false; + } + if (textBox_InputValue.Text.Length > 9) + { + MessageBox.Show("输入数据不在范围内"); + return false; + } + break; + case 17://BYTE + //TextBox存在非数字字符 报错 + if (!Regex.IsMatch(textBox_InputValue.Text, @"^[-]?\d*$")) + { + MessageBox.Show("输入不是整数!"); + return false; + } + if (Convert.ToInt32(textBox_InputValue.Text.Trim()) > 255) + { + MessageBox.Show("输入数据不在范围内"); + return false; + } + break; + case 8://STRING + + break; + case 18://Word + //TextBox存在非数字字符 报错 + if (!Regex.IsMatch(textBox_InputValue.Text, @"^[-]?\d*$")) + { + MessageBox.Show("输入不是整数!"); + return false; + } + if (textBox_InputValue.Text.Trim().Length > 4) + { + MessageBox.Show("输入数据不在范围内"); + return false; + } + break; + case 4://real + //TextBox存在非数字字符 报错 + //TextBox存在非数字字符 报错 + if (!Regex.IsMatch(textBox_InputValue.Text, @"^-?\d+\.?\d*$")) + { + MessageBox.Show("输入不是实数!"); + return false; + } + + break; + default: + break; + + } + + return true; + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, err.Message); + return true; + } + } + + } +} diff --git a/MisDataPlcTagID/MisDataPlcTagID/WriteQualityValueFormSim.resx b/MisDataPlcTagID/MisDataPlcTagID/WriteQualityValueFormSim.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/MisDataPlcTagID/MisDataPlcTagID/WriteQualityValueFormSim.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/MisDataPlcTagID/Properties/AssemblyInfo.cs b/MisDataPlcTagID/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..d18821c --- /dev/null +++ b/MisDataPlcTagID/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// 有关程序集的一般信息由以下 +// 控制。更改这些特性值可修改 +// 与程序集关联的信息。 +[assembly: AssemblyTitle("MisDataPlcTagID")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("MisDataPlcTagID")] +[assembly: AssemblyCopyright("Copyright © 2022")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// 将 ComVisible 设置为 false 会使此程序集中的类型 +//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型 +//请将此类型的 ComVisible 特性设置为 true。 +[assembly: ComVisible(false)] + +// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID +[assembly: Guid("0f887ab8-1bc5-4ef0-9240-e7afd91a9911")] + +// 程序集的版本信息由下列四个值组成: +// +// 主版本 +// 次版本 +// 生成号 +// 修订号 +// +//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值 +//通过使用 "*",如下所示: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/MisDataSaveDate/MisDataSaveDate.sln b/MisDataSaveDate/MisDataSaveDate.sln new file mode 100644 index 0000000..9ba2ab9 --- /dev/null +++ b/MisDataSaveDate/MisDataSaveDate.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.32602.291 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MisDataSaveDate", "MisDataSaveDate\MisDataSaveDate.csproj", "{9AEDE061-8490-436A-B38B-9495DC908F19}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {9AEDE061-8490-436A-B38B-9495DC908F19}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {9AEDE061-8490-436A-B38B-9495DC908F19}.Debug|Any CPU.Build.0 = Debug|Any CPU + {9AEDE061-8490-436A-B38B-9495DC908F19}.Release|Any CPU.ActiveCfg = Release|Any CPU + {9AEDE061-8490-436A-B38B-9495DC908F19}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {AC76E79B-C576-4AF6-889E-57D1B50CC4F4} + EndGlobalSection +EndGlobal diff --git a/MisDataSaveDate/MisDataSaveDate/App.config b/MisDataSaveDate/MisDataSaveDate/App.config new file mode 100644 index 0000000..094a107 --- /dev/null +++ b/MisDataSaveDate/MisDataSaveDate/App.config @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/MisDataSaveDate/MisDataSaveDate/Funtion .Mqtt.cs b/MisDataSaveDate/MisDataSaveDate/Funtion .Mqtt.cs new file mode 100644 index 0000000..54a5b9f --- /dev/null +++ b/MisDataSaveDate/MisDataSaveDate/Funtion .Mqtt.cs @@ -0,0 +1,55 @@ +using bizFacade; +using DoWhatPlc; +using MesServerWork; +using MesWorkMqtt; +using MQTTnet; +using MQTTnet.Client.Connecting; +using MQTTnet.Client.Disconnecting; +using MQTTnet.Client.Receiving; +using Newtonsoft.Json; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Data; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +namespace MisDataSaveDate +{ + public partial class Funtion + { + + public Mqtt2 mqtt2; + public void InitMqtt2(string url, string topic) + { + mqtt2 = new Mqtt2(); + mqtt2.MqttUrl = url; + mqtt2.topic = topic; + mqtt2.StartAsync(); + mqtt2.mqttClient.ConnectedHandler = new MqttClientConnectedHandlerDelegate(OnSubscriberConnected); + mqtt2.mqttClient.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(OnSubscriberDisconnected); + mqtt2.mqttClient.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(OnSubscriberMessageReceived); + + MesServerWork.MIS_BASE.InitHashtable_MesServerCode(); + } + private void OnSubscriberConnected(MqttClientConnectedEventArgs x) + { + var rec = x.AuthenticateResult.ResultCode.ToString(); + //label_State.Text = rec; + } + + private void OnSubscriberDisconnected(MqttClientDisconnectedEventArgs x) + { + //var rec = x.AuthenticateResult.ResultCode.ToString(); + //label_State.Text = rec; + } + + private void OnSubscriberMessageReceived(MqttApplicationMessageReceivedEventArgs x) + { + var rec = x.ApplicationMessage.ConvertPayloadToString(); + ThreadPool.QueueUserWorkItem(MIS_Funtion, rec); + } + } +} diff --git a/MisDataSaveDate/MisDataSaveDate/Funtion.Alarm.cs b/MisDataSaveDate/MisDataSaveDate/Funtion.Alarm.cs new file mode 100644 index 0000000..59b63ce --- /dev/null +++ b/MisDataSaveDate/MisDataSaveDate/Funtion.Alarm.cs @@ -0,0 +1,75 @@ +using bizFacade; +using DataLinkMesWork; +using DoWhatPlc; +using MesServerWork; +using Newtonsoft.Json; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Data; +using System.Data.SqlClient; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MisDataSaveDate +{ + public partial class Funtion + { + + private static void Alarm_Insert(ReturnValueString rv) + { + string TagID; + string opName; + string tagTypeID; + int TagValue; + + DateTime alarmStartTime; + DateTime alarmEndTime; + int TimeDiff; + string TagOrderBy; + string Text1; + string Text2; + TagID = rv.TagID; + tagTypeID = rv.TagTypeID; + opName = rv.OpName; + TagValue = Convert.ToInt32(rv.TagValue); + + alarmStartTime = Convert.ToDateTime(rv.TimeStampBefore); + alarmEndTime = Convert.ToDateTime(rv.TimeStamp); + TimeDiff = Convert.ToInt32(rv.TagKeepTime); + TagOrderBy = rv.TagOrderBy; + Text1 = rv.ItemName; + Text2 = rv.ShaftID; + + Alarm_Insert(TagID, tagTypeID, opName, TagValue, + alarmStartTime, alarmEndTime, TimeDiff, Text1, Text2, TagOrderBy); + } + + public static bool Alarm_Insert(string TagID, string tagTypeID, string opName, int TagValue, + DateTime alarmStartTime, DateTime alarmEndTime, int TimeDiff, + string Text1, string Text2, string TagOrderBy) + { + + + string produceName = "测量数据工位报警全部_增加数据"; + SqlParameter[] thisParms = new SqlParameter[10]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@TagID", TagID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@TagTypeID", tagTypeID); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@opName", opName); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@TagValue", TagValue); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@alarmStartTime", alarmStartTime); + thisParms[5] = new System.Data.SqlClient.SqlParameter("@alarmEndTime", alarmEndTime); + thisParms[6] = new System.Data.SqlClient.SqlParameter("@TimeDiff", TimeDiff); + thisParms[7] = new System.Data.SqlClient.SqlParameter("@Text1", Text1); + thisParms[8] = new System.Data.SqlClient.SqlParameter("@Text2", Text2); + thisParms[9] = new System.Data.SqlClient.SqlParameter("@TagOrderBy", TagOrderBy); + if (DataAccess.ExecuteStoredProcedure(produceName, ref thisParms)) + { + + return true; + } + return false; + } + } +} diff --git a/MisDataSaveDate/MisDataSaveDate/Funtion.EngTypeGetOver.cs b/MisDataSaveDate/MisDataSaveDate/Funtion.EngTypeGetOver.cs new file mode 100644 index 0000000..dff0beb --- /dev/null +++ b/MisDataSaveDate/MisDataSaveDate/Funtion.EngTypeGetOver.cs @@ -0,0 +1,104 @@ +using bizFacade; +using DataLinkMesWork; +using DoWhatPlc; +using MesServerWork; +using Newtonsoft.Json; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Data; +using System.Data.SqlClient; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MisDataSaveDate +{ + public partial class Funtion + { + private static void EngTypeGetOver(string opName,string tagValue) + { + if (hashtable_EngineGetOver.Contains(opName)) + { + hashtable_EngineGetOver.Remove(opName); + } + hashtable_EngineGetOver.Add(opName, tagValue); + if (tagValue == "1") + { + + int EngineTypeID; + string EngineType; + string EngineID; + int PartPalletCode; + // 1 读取机型等信息,保存到监控表 + + DtWebApi.ReadWritePLC.GetEngineTypeFromPLC(opName, out EngineTypeID, out EngineType, out EngineID, out PartPalletCode); + + if (hashtable_EngineGetOver_EngineTypeID.Contains(opName)) + { + hashtable_EngineGetOver_EngineTypeID.Remove(opName); + } + hashtable_EngineGetOver_EngineTypeID.Add(opName, EngineTypeID); + + if (hashtable_EngineGetOver_EngineType.Contains(opName)) + { + hashtable_EngineGetOver_EngineType.Remove(opName); + } + hashtable_EngineGetOver_EngineType.Add(opName, EngineType); + + + if (hashtable_EngineGetOver_EngineID.Contains(opName)) + { + hashtable_EngineGetOver_EngineID.Remove(opName); + } + hashtable_EngineGetOver_EngineID.Add(opName, EngineID); + if (hashtable_PartPalletCode.Contains(opName)) + { + hashtable_PartPalletCode.Remove(opName); + } + hashtable_PartPalletCode.Add(opName, PartPalletCode); + + EngTypeGetOverInsert(opName, EngineTypeID, EngineType, EngineID, PartPalletCode); + + + // 2 保存工件到位信息 + + } + } + + // + /// + /// @工位号 nvarchar(50)=null, + ///@产品型号代码 int=1 , + ///@发动机型号 nvarchar(50)=null , + ///@发动机号 nvarchar(50)=null , + ///@托盘号 nvarchar(50)='0' + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + public static bool EngTypeGetOverInsert(string opName, int EngineTypeID, string EngineType,string EngineID, int PartPalletCode) + { + string procedureName; + procedureName = "测量数据工位_监控系统_增加"; + SqlParameter[] thisParms = new SqlParameter[5]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@产品型号代码", EngineTypeID); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@发动机型号", EngineType); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@发动机号", EngineID); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@托盘编号", PartPalletCode); + + if (DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms)) + { + return true; + } + return false; + } + } +} diff --git a/MisDataSaveDate/MisDataSaveDate/Funtion.MesRead.cs b/MisDataSaveDate/MisDataSaveDate/Funtion.MesRead.cs new file mode 100644 index 0000000..6ca2c17 --- /dev/null +++ b/MisDataSaveDate/MisDataSaveDate/Funtion.MesRead.cs @@ -0,0 +1,351 @@ +using bizFacade; +using DataLinkMesWork; +using DoWhatPlc; +using MesServerWork; +using Newtonsoft.Json; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Data; +using System.Data.SqlClient; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MisDataSaveDate +{ + public partial class Funtion + { + + + /// + /// 允许保存(针对半自动和手动压装工位) + /// + /// + /// + private static void MesRead(string opName, string tagValue, int tagid) + { + if (tagValue == "0") + { + MIS_BASE.Write_TagTypeID(20, opName, false); + } + else + { + if(MIS_BASE.hashtable_tagTable_OpName_SaveData==null) + { + MesServerWork.MIS_BASE.InitHashtable_MesServerCode(); + } + if(MIS_BASE.hashtable_tagTable_OpName_SaveData.Contains(opName)) + { + if (MIS_BASE.hashtable_tagTable_OpName_SaveData[opName].ToString() == "1") + { + SaveQualityData(opName, Convert.ToInt32(tagValue), tagid); + MIS_BASE.Write_TagTypeID(20, opName, true); + + } + else + { + //MIS_BASE.Write_TagTypeID(20, opName, true); + } + } + else + { + // MIS_BASE.Write_TagTypeID(20, opName, true); + } + + } + } + + private static void SaveQualityData(string opName, int tagValue, int tagID) + { + try + { + int id_tagCF; + int qualityMask = 0; + int engineTypeID = 0; + string engineID = ""; + string engineType = ""; + string engineTraceCode = ""; + string engineCap = ""; + string partPallet = ""; + DataTable dt_WWW; + dt_WWW = BaseDataSystemMES.BuildDataTables_WWW(); + Hashtable valueList; + //valueList = ReadPLC_Sync_DataList_MesRead(opName); + ReadPLC_Sync_DataList_MesRead(opName, out valueList, out MIS_BASE.BasicDataTagValue, out MIS_BASE.BasicDataTagValueUpDown, out MIS_BASE.hashtable_EngineTypeID, out MIS_BASE.hashtable_tagTable_OpName_SaveData); + valueList = GetQualityData_GoodBad_Values(valueList); + int mes_MustTest = 0; + int onLineState = 0; + int partMoveDirection = 0; + int pressIsOK = 0; + int pressIsNoOK = 0; + BaseDataSystemMES.GetQualityDataTable_B5A(valueList, opName, MIS_BASE.BasicDataTagValue, + MIS_BASE.BasicDataTagValueUpDown, + out dt_WWW,//数据列表 + out qualityMask,//工位合格标志 + out engineTypeID,//发动机类型代码 + out engineID,//发动机编号 + out engineType, //发动机型号 + out partPallet,//托盘编号 + out engineTraceCode, //发动机条码 + out engineCap,//缸盖号, + MIS_BASE.hashtable_EngineTypeID,//发动机类型转换表 + out mes_MustTest, out onLineState, out partMoveDirection, out pressIsOK, out pressIsNoOK); + + + + + // 1:通过监控系统保存采集的质量数据;0:不通过监控系统保存采集的质量数据 + if (Convert.ToInt32(MIS_BASE.hashtable_tagTable_OpName_SaveData[opName]) != 0) + { + DateTime lastupdatetime = DateTime.Now; + + BaseData_tagTable_QualityData_B5A_IndexInsert(engineID, tagID, engineType, engineTypeID, opName, qualityMask, partPallet, out id_tagCF); + BaseData_tagTable_QualityData_B5A_Insert(id_tagCF, engineTypeID, engineID, opName, dt_WWW); + + } + + //启动线程保存过站信息 + + + + MIS_BASE.Write_TagTypeID(20, opName, true); + #region + //string orderForm = ""; + //string operatorCode = ""; + //int shiftCode = 1; + //DateTime arrivedTime; + //DateTime leavedTime; + //int TimeDiff; + //int targetTime = 0; + //string lineType = ""; + //string isPass; + //int machineWorkOn = 0; + //int arrivedOrLeaved = 2; + //int cartColorOpName = 0; + //int cartColorConfirm = 0; + //// int partMoveDirection; + //int partGoOver = 0; + //if (qualityMask == 1) + //{ + // isPass = "PASS"; + //} + //else + //{ + // isPass = "FAIL"; + //} + + ////工位上下线类型 + ////(0普通工位)(1正常上线)(2正常下线)(3返修上线)(4返修下线) + //int OpNameUpDownType; + //OpNameUpDownType = Convert.ToInt32(hashtableOpName_OpType[opName]); + //arrivedTime = (DateTime)m_WorkStart_OpName_Time[opName]; + //leavedTime = DateTime.Now; + //TimeDiff = Convert.ToInt32(leavedTime.Subtract(arrivedTime).TotalSeconds); + + //lineType = hashtableOpName_LineType[opName].ToString(); + + //string isHaveComputer = hashtableOpName_IsHaveComputer[opName].ToString(); + ////isHaveComputer = MIS_BASE.hashtable_tagTable_OpName_SaveData[opName].ToString(); + ////有计算机的工位,通过工位计算机保存[测量数据发动机在线状态]。 + //if (Convert.ToInt32(isHaveComputer) == 0) + //{ + // //1->0 工件离开 工件刚刚离开 + // if (Convert.ToInt32(m_WorkStart_OpName[opName]) == 1) + // { + + // //[测量数据发动机在线状态] + // QualityDataSystem.WorkStartInsert + // (opName, orderForm, engineTypeID, engineType, engineID, partPallet.ToString(), operatorCode, shiftCode, + // arrivedTime, leavedTime, TimeDiff, targetTime, lineType, isPass, machineWorkOn, + // arrivedOrLeaved, cartColorOpName, cartColorConfirm, partMoveDirection, partGoOver, mes_MustTest, onLineState, OpNameUpDownType); + // } + //} + #endregion + } + catch (Exception err) + { + MIS_BASE.Write_TagTypeID(20, opName, true); + ////ApplicationLog.WriteLog(err, err.Message); + } + + } + public static bool BaseData_tagTable_QualityData_B5A_IndexInsert + (string EngineID, int tagID, string EngineType, int EngineTypeID, string opName, + int isGoodBad, string PartPalletCode, out int Id_tagCF) + { + string procedureName; + procedureName = "测量数据合格索引_增加"; + Id_tagCF = 0; + SqlParameter[] thisParms = new SqlParameter[8]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@EngineID", EngineID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@TagID_CF", tagID); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@EngineType", EngineType); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@EngineTypeID", EngineTypeID); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[5] = new System.Data.SqlClient.SqlParameter("@托盘编号", PartPalletCode); + thisParms[6] = new System.Data.SqlClient.SqlParameter("@合格标志", isGoodBad); + thisParms[7] = new System.Data.SqlClient.SqlParameter("@Id_tagCF", Id_tagCF); + thisParms[7].Direction = ParameterDirection.Output; + + if (DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms)) + { + Id_tagCF = Convert.ToInt32(thisParms[7].Value.ToString()); + return true; + } + return false; + } + public static bool BaseData_tagTable_QualityData_B5A_Insert + (int Id_tagCF, int engineTypeID, string engineID, string opName, DataTable dt) + { + string procedureName; + procedureName = "测量数据合格_增加"; + SqlParameter[] thisParms = new SqlParameter[6]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@Id_tagCF", Id_tagCF); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@EngineTypeID", engineTypeID); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@EngineID", engineID); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@TagID", SqlDbType.Int, 4, "TagID"); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@TagValue", SqlDbType.NVarChar, 100, "TagValue"); + thisParms[5] = new System.Data.SqlClient.SqlParameter("@IsGoodBad", SqlDbType.Int, 4, "IsGoodBad"); + //thisParms[6] = new System.Data.SqlClient.SqlParameter("@测量位置", SqlDbType.NVarChar, 50, "测量位置"); + //thisParms[7] = new System.Data.SqlClient.SqlParameter("@测量项目", SqlDbType.NVarChar, 50, "测量项目"); + //thisParms[8] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + //thisParms[9] = new System.Data.SqlClient.SqlParameter("@理论值", SqlDbType.NVarChar, 50, "理论值"); + //thisParms[10] = new System.Data.SqlClient.SqlParameter("@上限值", SqlDbType.NVarChar, 50, "上限值"); + //thisParms[11] = new System.Data.SqlClient.SqlParameter("@下限值", SqlDbType.NVarChar, 50, "下限值"); + //thisParms[12] = new System.Data.SqlClient.SqlParameter("@测量单位", SqlDbType.NVarChar, 50, "测量单位"); + //thisParms[13] = new System.Data.SqlClient.SqlParameter("@列位置", SqlDbType.Int, 4, "列位置"); + //thisParms[14] = new System.Data.SqlClient.SqlParameter("@变量排序", SqlDbType.Int, 4, "变量排序"); + //table.Columns.Add("TagID", typeof(System.Int32)); + //table.Columns.Add("TagValue", typeof(System.String)); + //table.Columns.Add("IsGoodBad", typeof(System.Int32)); + //table.Columns.Add("测量位置", typeof(System.String)); + //table.Columns.Add("测量项目", typeof(System.String)); + //table.Columns.Add("工位号", typeof(System.String)); + //table.Columns.Add("理论值", typeof(System.String)); + //table.Columns.Add("上限值", typeof(System.String)); + //table.Columns.Add("下限值", typeof(System.String)); + //table.Columns.Add("测量单位", typeof(System.String)); + //table.Columns.Add("列位置", typeof(System.Int32)); + //table.Columns.Add("变量排序", typeof(System.Int32)); + return DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, dt); + } + public static void ReadPLC_Sync_DataList_MesRead(string opName, out Hashtable valueList, out DataTable BasicDataTagValue, out DataTable BasicDataTagValueUpDown, out Hashtable hashtable_EngineTypeID, out Hashtable hashtable_tagTable_OpName_SaveData) + { + //QualityDataSaveList QualityDataType + valueList = new Hashtable(); + var qualityDataSaveList = DtWebApi.SaveData.ReadPLC_Sync_DataList_MesRead(opName); + foreach (DictionaryEntry de in qualityDataSaveList.valuList) + { + valueList.Add(de.Key, JsonConvert.DeserializeObject(de.Value.ToString())); + } + BasicDataTagValue = qualityDataSaveList.BasicDataTagValue; + BasicDataTagValueUpDown = qualityDataSaveList.BasicDataTagValueUpDown; + hashtable_EngineTypeID = qualityDataSaveList.hashtable_EngineTypeID; + hashtable_tagTable_OpName_SaveData = qualityDataSaveList.hashtable_tagTable_OpName_SaveData; + } + /// + /// 确定合格标志 + /// + /// + /// + static public Hashtable GetQualityData_GoodBad_Values(Hashtable valuList) + { + try + { + Hashtable valuList_Temp; + valuList_Temp = (Hashtable)valuList.Clone(); + int[] value_GoodBad_New = new int[128]; + int tagID; + QualityDataType value; + //1:获得合格标志 + foreach (DictionaryEntry de in valuList) //ht为一个Hashtable实例 + { + tagID = Convert.ToInt32(de.Key); + value = (QualityDataType)de.Value; + + //拧紧数据合格标志 + if (value.tagProperty == 1) + { + if (value.tagTypeID == 8203) + { + value_GoodBad_New = (int[])value.tagValue; + break; + } + else + { + value_GoodBad_New[value.tagOrderBy - 1] = Convert.ToInt32(value.tagValue); + } + } + //拧紧数据合格标志 + if (value.tagProperty == 8) + { + if (value.tagTypeID == 8203) + { + value_GoodBad_New = (int[])value.tagValue; + break; + } + else + { + value_GoodBad_New[value.tagOrderBy - 1] = Convert.ToInt32(value.tagValue); + } + } + //压装数据合格标志 + if (value.tagProperty == 7) + { + value_GoodBad_New[value.tagOrderBy - 1] = Convert.ToInt32(value.tagValue); + } + } + //将合格标志赋予每个变量 + foreach (DictionaryEntry de in valuList) //ht为一个Hashtable实例 + { + tagID = Convert.ToInt32(de.Key); + value = (QualityDataType)de.Value; + //201706061720新加 + if (value.tagTypeID == 11) + { + if (value.tagValue.ToString() == "False") + { + value.tagValue = "0"; + } + else + { + value.tagValue = "1"; + } + valuList_Temp[tagID] = value; + //value.tagValue = Convert.ToInt32(value.tagValue); + } + + + //测量变量 + if (value.tagProperty == 2 || value.tagProperty == 6) + { + try + { + if (value_GoodBad_New != null) + { + value.isGoodBad = Convert.ToInt32(value_GoodBad_New[value.tagOrderBy - 1]); + valuList_Temp[tagID] = value; + } + else + { + value.isGoodBad = 0; + valuList_Temp[tagID] = value; + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, err.Message); + + } + } + } + return valuList_Temp; + } + catch//转换出了故障时 + { + return valuList; + } + } + } +} diff --git a/MisDataSaveDate/MisDataSaveDate/Funtion.WorkStart.cs b/MisDataSaveDate/MisDataSaveDate/Funtion.WorkStart.cs new file mode 100644 index 0000000..7049308 --- /dev/null +++ b/MisDataSaveDate/MisDataSaveDate/Funtion.WorkStart.cs @@ -0,0 +1,228 @@ +using bizFacade; +using DataLinkMesWork; +using DoWhatPlc; +using MesServerWork; +using Newtonsoft.Json; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Data; +using System.Data.SqlClient; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MisDataSaveDate +{ + public partial class Funtion + { + + private static void WorkStart(ReturnValueString rv) + { + var ro = rv.ReturnValueToObject(); + + string opName = ro.OpName; + DateTime arrivedTime = ro.TimeStampBefore; + DateTime leavedTime = ro.TimeStamp; + int TimeDiff = ro.TagKeepTime; + int targetTime = 0; + string isPass = ""; + + int QualityMark = 0; + string tagValue = "0"; + switch (ro.TagValue.ToString().ToLower()) + { + case "1": + case "true": + tagValue = "1"; + break; + default: + tagValue = "0"; + break; + } + + + + int EngineTypeID=-1;//机型代码 + int PartPalletCode=-1;//托盘编号 + string EngineType="-1";//机型 + string EngineID="-1";//工件编号 + if (hashtable_EngineGetOver_EngineTypeID.Contains(opName)) + { + EngineTypeID = Convert.ToInt32( hashtable_EngineGetOver_EngineTypeID[opName]); + } + if (hashtable_EngineGetOver_EngineType.Contains(opName)) + { + EngineType = hashtable_EngineGetOver_EngineType[opName].ToString(); + } + if (hashtable_EngineGetOver_EngineID.Contains(opName)) + { + EngineID = hashtable_EngineGetOver_EngineID[opName].ToString(); + } + if (hashtable_PartPalletCode.Contains(opName)) + { + PartPalletCode = Convert.ToInt32(hashtable_PartPalletCode[opName]); + } + + //MIS_BASE.GetEngineTypeFromPLC(opName, out EngineTypeID, out EngineType, out EngineID, out PartPallet_Code); + + //EngineData Enginedata = (EngineData)EngineData_Hash_Read(opName); + //WorkStartInsert_AutoWorkStation(opName, EngineID, PartPalletCode, arrivedTime, leavedTime, TimeDiff, targetTime, null, isPass, 0); + + if (tagValue == "0") + { + QualityMark = Convert.ToInt32(DtWebApi.ReadWritePLC.ReadPLC("21", opName)); + + if (QualityMark == 1) + { + isPass = "1"; + } + else + { + isPass = "0"; + } + + WorkStartInsert_V2022(opName, arrivedTime, leavedTime, TimeDiff, isPass); + + MIS_BASE.Write_TagTypeID(5, opName, false);//MES传递机型 + MIS_BASE.Write_TagTypeID(66, opName, false);//允许工作 + MIS_BASE.Write_TagTypeID(51, opName, false);//合格放行 + MIS_BASE.Write_TagTypeID(8, opName, false);//不合格放行 + MIS_BASE.Write_TagTypeID(7, opName, false);//工作完成 + MIS_BASE.Write_TagTypeID(20, opName, false);//保存完成 + + + + //string isHaveComputer = hashtableOpName_IsHaveComputer[opName].ToString(); + //if (Convert.ToInt32(isHaveComputer) == 0)//自动工位 读合格标志 + //{ + // if (IsEngTypeGetOver_Read(opName)) + // { + // //PLC未传递机型 不保存过站信息 + // SaveProductLeaveData_AutoWorkStation(opName, Convert.ToInt32(DtWebApi.ReadWritePLC.ReadPLC("21", opName))); + // //SaveProductLeaveData_AutoWorkStation(opName, Convert.ToInt32(MesDataFunction.OpcOperation.ReadPLC(21, opName))); + // } + + //} + + ////清空信号 + ////m_WorkStart_OpName[opName] = 0;//清空工件到位标志 + + } + + //通知WEB更新产量 + SendActuallyCount(opName, 0); + } + /// + /// 发送在线产量、在线节拍 + /// + /// + /// + static void SendActuallyCount(string OpName, int tagValue) + { + //当工件离开时,更新在线产量、在线节拍 + if (tagValue == 0) + { + try + { + int opNameCount = 0;//在线产量 + int opNameCountTime = 0;//在线节拍 + //基本数据_工作日历_班次产量查询_New + OpNameCount_New(OpName, out opNameCount, out opNameCountTime); + + string SendMessage; + SendMessage = "MES|ActuallyCount|" + OpName + "|" + opNameCount.ToString() + "&" + opNameCountTime.ToString(); + + MIS_BASE.asyncSendMessage(SendMessage); + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function01:SendActuallyCount"); + } + } + } + /// + /// 基本数据_工作日历_班次产量查询_New + /// + /// + /// 在线产量 + /// 在线节拍 + static public void OpNameCount_New(string opName, out int opNameCount, out int opNameCountTime) + { + opNameCount = 0; + opNameCountTime = 0; + string procedureName; + procedureName = "基本数据_工作日历_班次产量查询_New"; + SqlParameter[] thisParms = new SqlParameter[3]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@在线产量", 0); + thisParms[1].Direction = ParameterDirection.Output; + thisParms[2] = new System.Data.SqlClient.SqlParameter("@在线节拍", 0); + thisParms[2].Direction = ParameterDirection.Output; + if (DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms)) + { + opNameCount = Convert.ToInt32(thisParms[1].Value); + opNameCountTime = Convert.ToInt32(thisParms[2].Value); + } + } + /// + /// 测量数据发动机在线状态_增加数据_自动工位 + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + static public void WorkStartInsert_AutoWorkStation(string opName, string EngineID, int Pallet, DateTime arrivedTime, DateTime leavedTime, int TimeDiff, int Target, string lineType, string isPass, int OpNameUpDownType) + { + string procedureName; + procedureName = "测量数据发动机在线状态_增加数据_自动工位"; + SqlParameter[] thisParms = new SqlParameter[10]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@发动机号", EngineID); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@托盘编号", Pallet); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@到达时间", arrivedTime); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@离开时间", leavedTime); + thisParms[5] = new System.Data.SqlClient.SqlParameter("@在线时间", TimeDiff); + thisParms[6] = new System.Data.SqlClient.SqlParameter("@目标时间", Target); + thisParms[7] = new System.Data.SqlClient.SqlParameter("@线体类型", lineType); + thisParms[8] = new System.Data.SqlClient.SqlParameter("@是否合格", isPass); + thisParms[9] = new System.Data.SqlClient.SqlParameter("@工位上下线类型", OpNameUpDownType); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } + + static public void WorkStartInsert_V2022(string opName, DateTime arrivedTime, DateTime leavedTime, int TimeDiff, string isPass) + { + string procedureName; + procedureName = "测量数据发动机在线状态_增加数据_V2022"; + SqlParameter[] thisParms = new SqlParameter[5]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@到达时间", arrivedTime); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@离开时间", leavedTime); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@在线时间", TimeDiff); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@是否合格", isPass); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } + + static public void WorkStartInsert(string opName, DateTime arrivedTime, DateTime leavedTime, int TimeDiff, int Target, string lineType, string isPass, int OpNameUpDownType) + { + string procedureName; + procedureName = "测量数据发动机在线状态_增加数据"; + SqlParameter[] thisParms = new SqlParameter[8]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@到达时间", arrivedTime); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@离开时间", leavedTime); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@在线时间", TimeDiff); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@目标时间", Target); + thisParms[5] = new System.Data.SqlClient.SqlParameter("@线体类型", lineType); + thisParms[6] = new System.Data.SqlClient.SqlParameter("@是否合格", isPass); + thisParms[7] = new System.Data.SqlClient.SqlParameter("@工位上下线类型", OpNameUpDownType); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } + } +} diff --git a/MisDataSaveDate/MisDataSaveDate/Funtion.cs b/MisDataSaveDate/MisDataSaveDate/Funtion.cs new file mode 100644 index 0000000..704cbbf --- /dev/null +++ b/MisDataSaveDate/MisDataSaveDate/Funtion.cs @@ -0,0 +1,152 @@ +using bizFacade; +using DoWhatPlc; +using MesServerWork; +using Newtonsoft.Json; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Data; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MisDataSaveDate +{ + public partial class Funtion + { + + /// + /// 发动机类型转换表 + /// SELECT ID,发动机机型代码 FROM MES_计划BOM_发动机型号代码 + /// + public static Hashtable hashtable_EngineTypeID=new Hashtable (); + /// + /// 记录工件到位的发动机机型代码 + /// + public static Hashtable hashtable_EngineGetOver_EngineTypeID = new Hashtable(); + /// + /// 记录工件到位的发动机机型 + /// + public static Hashtable hashtable_EngineGetOver_EngineType = new Hashtable(); + /// + /// 记录工件到位的发动机号 + /// + public static Hashtable hashtable_EngineGetOver_EngineID = new Hashtable(); + /// + /// 记录工件到位的订单号 + /// + public static Hashtable hashtable_EngineGetOver_OrderForm = new Hashtable(); + + public static Hashtable hashtable_EngineGetOver = new Hashtable(); + + public static Hashtable hashtable_PartPalletCode = new Hashtable(); + + public static void MIS_Funtion(object e) + { + try + { + + string recData = e.ToString(); + string[] dataArray = recData.Split('|'); + if (dataArray.Length != 4) + return; + //消息来源 + string m_Source = dataArray[0].ToString(); + //消息类型 + string m_Command = dataArray[1].ToString(); + //工位号 + string m_OpName = dataArray[2].ToString(); + //消息参数 + string m_Value = dataArray[3].ToString(); + + DoWhatPlc.ReturnValueString rv = Newtonsoft.Json.JsonConvert.DeserializeObject(m_Value); + //Console.WriteLine($"【【{rv.TagID}【【【【{ rv.TagKeepTime}"); + + int tagType; + string opName; + string tagValue; + int tagid; + DoWhatPlc.ReturnValueString msgEvent = rv; + if (msgEvent.TagValue == null) return; + tagType = Convert.ToInt32(msgEvent.TagTypeID); + opName = msgEvent.OpName.ToString(); + tagid = Convert.ToInt32(msgEvent.TagID); + + + + switch (Convert.ToInt32(msgEvent.TagTypeCodeID)) + { + case 11: + switch (msgEvent.TagValue.ToLower()) + { + case "1": + case "true": + tagValue = "1"; + break; + default: + tagValue = "0"; + break; + } + break; + default: + tagValue = msgEvent.TagValue.ToString(); + break; + } + ///根据信号处理逻辑 + switch (tagType) + { + case 19: + //允许保存 + MesRead(opName, tagValue, tagid); + break; + case 14: + //心跳 + //Heartbeat(opName, tagValue); + break; + case 44://PLC传递机型过后 才允许保存过站信息,否则不允许保存 + EngTypeGetOver(opName, tagValue); + break; + case 2://工件到位 离开信息 + + if (tagValue == "0") + { + //传递机型 + if (hashtable_EngineGetOver.Contains(opName)) + { + if (hashtable_EngineGetOver[opName].ToString() == "1") + { + WorkStart(rv); + } + } + } + break; + case 51: + //if (hashtableOpName_IsHaveComputer[opName].ToString() == "1") + //{ + // SaveProductLeaveData(opName, 1); + //} + + break; + case 8: + //if (hashtableOpName_IsHaveComputer[opName].ToString() == "1") + //{ + // SaveProductLeaveData(opName, 2); + //} + break; + case 103: + + Alarm_Insert(rv); + + break; + } + + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, err.Message); + } + } + + + } +} diff --git a/MisDataSaveDate/MisDataSaveDate/MisDataSaveDate.csproj b/MisDataSaveDate/MisDataSaveDate/MisDataSaveDate.csproj new file mode 100644 index 0000000..5488309 --- /dev/null +++ b/MisDataSaveDate/MisDataSaveDate/MisDataSaveDate.csproj @@ -0,0 +1,159 @@ + + + + + Debug + AnyCPU + {9AEDE061-8490-436A-B38B-9495DC908F19} + WinExe + MisDataSaveDate + MisDataSaveDate + v4.6.1 + 512 + true + true + + + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + False + ..\..\Common\dll\MQTTnet.dll + + + False + ..\..\Common\dll\MQTTnet.Extensions.ManagedClient.dll + + + + + + ..\packages\System.Net.Security.4.3.2\lib\net46\System.Net.Security.dll + + + ..\packages\System.Net.WebSockets.4.3.0\lib\net46\System.Net.WebSockets.dll + + + ..\packages\System.Net.WebSockets.Client.4.3.2\lib\net46\System.Net.WebSockets.Client.dll + + + ..\packages\System.Security.Cryptography.Algorithms.4.3.0\lib\net461\System.Security.Cryptography.Algorithms.dll + + + ..\packages\System.Security.Cryptography.Encoding.4.3.0\lib\net46\System.Security.Cryptography.Encoding.dll + + + ..\packages\System.Security.Cryptography.Primitives.4.3.0\lib\net46\System.Security.Cryptography.Primitives.dll + + + ..\packages\System.Security.Cryptography.X509Certificates.4.3.0\lib\net461\System.Security.Cryptography.X509Certificates.dll + + + + + + + + + + + + + + + + + + + + Form + + + SaveData.cs + + + + + ResXFileCodeGenerator + Resources.Designer.cs + Designer + + + True + Resources.resx + + + SaveData.cs + + + + SettingsSingleFileGenerator + Settings.Designer.cs + + + True + Settings.settings + True + + + + + + + + {1a10fdb2-1a6a-44a8-ab4d-33387563247e} + 00-0Json8.3.1 + + + {f55da1a0-a982-4479-8c47-0d9a5aaf3e18} + 00MesWorkMqtt + + + {0d1af432-439a-4920-8692-43ae139f5530} + 01_01DoWhatPlc + + + {3e6d1dd5-01c9-435f-9941-61f906ce35bb} + 02_02WebApiCallPLC + + + {f434e066-4c59-47c8-aa82-6f48cc84501a} + 04-DataBaseAccess + + + {f0a0c525-03fd-428a-9b17-7f54aa0e4475} + 07BusinessFacade + + + {90e76fb4-646d-45e2-95db-0b8ab4e465d6} + 09-MesDataFunction + + + + + + + 这台计算机上缺少此项目引用的 NuGet 程序包。使用“NuGet 程序包还原”可下载这些程序包。有关更多信息,请参见 http://go.microsoft.com/fwlink/?LinkID=322105。缺少的文件是 {0}。 + + + + \ No newline at end of file diff --git a/MisDataSaveDate/MisDataSaveDate/Program.cs b/MisDataSaveDate/MisDataSaveDate/Program.cs new file mode 100644 index 0000000..18e46e1 --- /dev/null +++ b/MisDataSaveDate/MisDataSaveDate/Program.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace MisDataSaveDate +{ + static class Program + { + /// + /// 应用程序的主入口点。 + /// + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + Application.Run(new SaveData()); + } + } +} diff --git a/MisDataSaveDate/MisDataSaveDate/Properties/AssemblyInfo.cs b/MisDataSaveDate/MisDataSaveDate/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..08faa00 --- /dev/null +++ b/MisDataSaveDate/MisDataSaveDate/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// 有关程序集的一般信息由以下 +// 控制。更改这些特性值可修改 +// 与程序集关联的信息。 +[assembly: AssemblyTitle("MisDataSaveDate")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("MisDataSaveDate")] +[assembly: AssemblyCopyright("Copyright © 2022")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// 将 ComVisible 设置为 false 会使此程序集中的类型 +//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型 +//请将此类型的 ComVisible 特性设置为 true。 +[assembly: ComVisible(false)] + +// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID +[assembly: Guid("9aede061-8490-436a-b38b-9495dc908f19")] + +// 程序集的版本信息由下列四个值组成: +// +// 主版本 +// 次版本 +// 生成号 +// 修订号 +// +//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值 +//通过使用 "*",如下所示: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/MisDataSaveDate/MisDataSaveDate/Properties/Resources.Designer.cs b/MisDataSaveDate/MisDataSaveDate/Properties/Resources.Designer.cs new file mode 100644 index 0000000..d21d7e1 --- /dev/null +++ b/MisDataSaveDate/MisDataSaveDate/Properties/Resources.Designer.cs @@ -0,0 +1,70 @@ +//------------------------------------------------------------------------------ +// +// 此代码由工具生成。 +// 运行时版本: 4.0.30319.42000 +// +// 对此文件的更改可能导致不正确的行为,如果 +// 重新生成代码,则所做更改将丢失。 +// +//------------------------------------------------------------------------------ + + +namespace MisDataSaveDate.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("MisDataSaveDate.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/MisDataSaveDate/MisDataSaveDate/Properties/Resources.resx b/MisDataSaveDate/MisDataSaveDate/Properties/Resources.resx new file mode 100644 index 0000000..af7dbeb --- /dev/null +++ b/MisDataSaveDate/MisDataSaveDate/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/MisDataSaveDate/MisDataSaveDate/Properties/Settings.Designer.cs b/MisDataSaveDate/MisDataSaveDate/Properties/Settings.Designer.cs new file mode 100644 index 0000000..54d0109 --- /dev/null +++ b/MisDataSaveDate/MisDataSaveDate/Properties/Settings.Designer.cs @@ -0,0 +1,29 @@ +//------------------------------------------------------------------------------ +// +// 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 MisDataSaveDate.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/MisDataSaveDate/MisDataSaveDate/Properties/Settings.settings b/MisDataSaveDate/MisDataSaveDate/Properties/Settings.settings new file mode 100644 index 0000000..3964565 --- /dev/null +++ b/MisDataSaveDate/MisDataSaveDate/Properties/Settings.settings @@ -0,0 +1,7 @@ + + + + + + + diff --git a/MisDataSaveDate/MisDataSaveDate/SaveData.Designer.cs b/MisDataSaveDate/MisDataSaveDate/SaveData.Designer.cs new file mode 100644 index 0000000..489b045 --- /dev/null +++ b/MisDataSaveDate/MisDataSaveDate/SaveData.Designer.cs @@ -0,0 +1,49 @@ + +namespace MisDataSaveDate +{ + partial class SaveData + { + /// + /// 必需的设计器变量。 + /// + 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.SuspendLayout(); + // + // SaveData + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(800, 450); + this.Name = "SaveData"; + this.Text = "Form1"; + this.Load += new System.EventHandler(this.SaveData_Load); + this.ResumeLayout(false); + + } + + #endregion + } +} + diff --git a/MisDataSaveDate/MisDataSaveDate/SaveData.cs b/MisDataSaveDate/MisDataSaveDate/SaveData.cs new file mode 100644 index 0000000..65d1af0 --- /dev/null +++ b/MisDataSaveDate/MisDataSaveDate/SaveData.cs @@ -0,0 +1,69 @@ +using MesWorkMqtt; +using MisDataFunction; +using MQTTnet; +using MQTTnet.Client.Connecting; +using MQTTnet.Client.Disconnecting; +using MQTTnet.Client.Receiving; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Configuration; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace MisDataSaveDate +{ + public partial class SaveData : Form + { + public SaveData() + { + InitializeComponent(); + } + + private void SaveData_Load(object sender, EventArgs e) + { + //Task.Run(() => StartAsync()); + + Mqtt.StartAsync(); + Mqtt.mqttClient.ConnectedHandler = new MqttClientConnectedHandlerDelegate(OnSubscriberConnected); + Mqtt.mqttClient.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(OnSubscriberDisconnected); + Mqtt.mqttClient.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(OnSubscriberMessageReceived); + + string url; + string topic; + url = ConfigurationManager.AppSettings["MqttUrl"]; + topic = ConfigurationManager.AppSettings["MqttTargetTopicTagTypeCodeID"]; + new InitMqtt2(url, topic); + + + MesServerWork.MIS_BASE.InitHashtable_MesServerCode(); + + + } + private void OnSubscriberConnected(MqttClientConnectedEventArgs x) + { + var rec = x.AuthenticateResult.ResultCode.ToString(); + //label_State.Text = rec; + } + + private void OnSubscriberDisconnected(MqttClientDisconnectedEventArgs x) + { + //var rec = x.AuthenticateResult.ResultCode.ToString(); + //label_State.Text = rec; + } + + private void OnSubscriberMessageReceived(MqttApplicationMessageReceivedEventArgs x) + { + var rec = x.ApplicationMessage.ConvertPayloadToString(); + ThreadPool.QueueUserWorkItem(MisDataSaveDate.Funtion.MIS_Funtion, rec); + } + + + + } +} diff --git a/MisDataSaveDate/MisDataSaveDate/SaveData.resx b/MisDataSaveDate/MisDataSaveDate/SaveData.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/MisDataSaveDate/MisDataSaveDate/SaveData.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/MisDataSaveDate/MisDataSaveDate/packages.config b/MisDataSaveDate/MisDataSaveDate/packages.config new file mode 100644 index 0000000..fb59d33 --- /dev/null +++ b/MisDataSaveDate/MisDataSaveDate/packages.config @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/MisDataSaveDate/dll/00MesWorkMqtt.dll b/MisDataSaveDate/dll/00MesWorkMqtt.dll new file mode 100644 index 0000000..15cb845 Binary files /dev/null and b/MisDataSaveDate/dll/00MesWorkMqtt.dll differ diff --git a/MisDataSaveDate/dll/00MesWorkMqtt.pdb b/MisDataSaveDate/dll/00MesWorkMqtt.pdb new file mode 100644 index 0000000..5dc65cb Binary files /dev/null and b/MisDataSaveDate/dll/00MesWorkMqtt.pdb differ diff --git a/MisDataSaveDate/dll/01DoWhatPlc.dll b/MisDataSaveDate/dll/01DoWhatPlc.dll new file mode 100644 index 0000000..25c33ee Binary files /dev/null and b/MisDataSaveDate/dll/01DoWhatPlc.dll differ diff --git a/MisDataSaveDate/dll/01DoWhatPlc.pdb b/MisDataSaveDate/dll/01DoWhatPlc.pdb new file mode 100644 index 0000000..e75a71b Binary files /dev/null and b/MisDataSaveDate/dll/01DoWhatPlc.pdb differ diff --git a/MisDataSaveDate/dll/02WebApiCall.dll b/MisDataSaveDate/dll/02WebApiCall.dll new file mode 100644 index 0000000..9a3f5b0 Binary files /dev/null and b/MisDataSaveDate/dll/02WebApiCall.dll differ diff --git a/MisDataSaveDate/dll/02WebApiCall.dll.config b/MisDataSaveDate/dll/02WebApiCall.dll.config new file mode 100644 index 0000000..6035ea8 --- /dev/null +++ b/MisDataSaveDate/dll/02WebApiCall.dll.config @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/MisDataSaveDate/dll/02WebApiCall.pdb b/MisDataSaveDate/dll/02WebApiCall.pdb new file mode 100644 index 0000000..16b7902 Binary files /dev/null and b/MisDataSaveDate/dll/02WebApiCall.pdb differ diff --git a/MisDataSaveDate/dll/04DataBaseAccess.dll b/MisDataSaveDate/dll/04DataBaseAccess.dll new file mode 100644 index 0000000..1378ec9 Binary files /dev/null and b/MisDataSaveDate/dll/04DataBaseAccess.dll differ diff --git a/MisDataSaveDate/dll/04DataBaseAccess.pdb b/MisDataSaveDate/dll/04DataBaseAccess.pdb new file mode 100644 index 0000000..740cc80 Binary files /dev/null and b/MisDataSaveDate/dll/04DataBaseAccess.pdb differ diff --git a/MisDataSaveDate/dll/07BusinessFacade.dll b/MisDataSaveDate/dll/07BusinessFacade.dll new file mode 100644 index 0000000..02e2595 Binary files /dev/null and b/MisDataSaveDate/dll/07BusinessFacade.dll differ diff --git a/MisDataSaveDate/dll/07BusinessFacade.pdb b/MisDataSaveDate/dll/07BusinessFacade.pdb new file mode 100644 index 0000000..dcb0c1b Binary files /dev/null and b/MisDataSaveDate/dll/07BusinessFacade.pdb differ diff --git a/MisDataSaveDate/dll/08WebFun_base.dll b/MisDataSaveDate/dll/08WebFun_base.dll new file mode 100644 index 0000000..e088df4 Binary files /dev/null and b/MisDataSaveDate/dll/08WebFun_base.dll differ diff --git a/MisDataSaveDate/dll/08WebFun_base.pdb b/MisDataSaveDate/dll/08WebFun_base.pdb new file mode 100644 index 0000000..b4db747 Binary files /dev/null and b/MisDataSaveDate/dll/08WebFun_base.pdb differ diff --git a/MisDataSaveDate/dll/09MesDataFunction.dll b/MisDataSaveDate/dll/09MesDataFunction.dll new file mode 100644 index 0000000..e31947c Binary files /dev/null and b/MisDataSaveDate/dll/09MesDataFunction.dll differ diff --git a/MisDataSaveDate/dll/09MesDataFunction.pdb b/MisDataSaveDate/dll/09MesDataFunction.pdb new file mode 100644 index 0000000..8c336b4 Binary files /dev/null and b/MisDataSaveDate/dll/09MesDataFunction.pdb differ diff --git a/MisDataSaveDate/dll/BusinessFacade.pdb b/MisDataSaveDate/dll/BusinessFacade.pdb new file mode 100644 index 0000000..2e1bfcb Binary files /dev/null and b/MisDataSaveDate/dll/BusinessFacade.pdb differ diff --git a/MisDataSaveDate/dll/MQTTnet.Extensions.ManagedClient.dll b/MisDataSaveDate/dll/MQTTnet.Extensions.ManagedClient.dll new file mode 100644 index 0000000..99035f6 Binary files /dev/null and b/MisDataSaveDate/dll/MQTTnet.Extensions.ManagedClient.dll differ diff --git a/MisDataSaveDate/dll/MQTTnet.dll b/MisDataSaveDate/dll/MQTTnet.dll new file mode 100644 index 0000000..2951433 Binary files /dev/null and b/MisDataSaveDate/dll/MQTTnet.dll differ diff --git a/MisDataSaveDate/dll/Newtonsoft.Json.dll b/MisDataSaveDate/dll/Newtonsoft.Json.dll new file mode 100644 index 0000000..597a1ce Binary files /dev/null and b/MisDataSaveDate/dll/Newtonsoft.Json.dll differ diff --git a/MisDataSaveDateDll/MisDataSaveDate.sln b/MisDataSaveDateDll/MisDataSaveDate.sln new file mode 100644 index 0000000..9ba2ab9 --- /dev/null +++ b/MisDataSaveDateDll/MisDataSaveDate.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.32602.291 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MisDataSaveDate", "MisDataSaveDate\MisDataSaveDate.csproj", "{9AEDE061-8490-436A-B38B-9495DC908F19}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {9AEDE061-8490-436A-B38B-9495DC908F19}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {9AEDE061-8490-436A-B38B-9495DC908F19}.Debug|Any CPU.Build.0 = Debug|Any CPU + {9AEDE061-8490-436A-B38B-9495DC908F19}.Release|Any CPU.ActiveCfg = Release|Any CPU + {9AEDE061-8490-436A-B38B-9495DC908F19}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {AC76E79B-C576-4AF6-889E-57D1B50CC4F4} + EndGlobalSection +EndGlobal diff --git a/MisDataSaveDateDll/MisDataSaveDate/App.config b/MisDataSaveDateDll/MisDataSaveDate/App.config new file mode 100644 index 0000000..094a107 --- /dev/null +++ b/MisDataSaveDateDll/MisDataSaveDate/App.config @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/MisDataSaveDateDll/MisDataSaveDate/Funtion.Alarm.cs b/MisDataSaveDateDll/MisDataSaveDate/Funtion.Alarm.cs new file mode 100644 index 0000000..59b63ce --- /dev/null +++ b/MisDataSaveDateDll/MisDataSaveDate/Funtion.Alarm.cs @@ -0,0 +1,75 @@ +using bizFacade; +using DataLinkMesWork; +using DoWhatPlc; +using MesServerWork; +using Newtonsoft.Json; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Data; +using System.Data.SqlClient; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MisDataSaveDate +{ + public partial class Funtion + { + + private static void Alarm_Insert(ReturnValueString rv) + { + string TagID; + string opName; + string tagTypeID; + int TagValue; + + DateTime alarmStartTime; + DateTime alarmEndTime; + int TimeDiff; + string TagOrderBy; + string Text1; + string Text2; + TagID = rv.TagID; + tagTypeID = rv.TagTypeID; + opName = rv.OpName; + TagValue = Convert.ToInt32(rv.TagValue); + + alarmStartTime = Convert.ToDateTime(rv.TimeStampBefore); + alarmEndTime = Convert.ToDateTime(rv.TimeStamp); + TimeDiff = Convert.ToInt32(rv.TagKeepTime); + TagOrderBy = rv.TagOrderBy; + Text1 = rv.ItemName; + Text2 = rv.ShaftID; + + Alarm_Insert(TagID, tagTypeID, opName, TagValue, + alarmStartTime, alarmEndTime, TimeDiff, Text1, Text2, TagOrderBy); + } + + public static bool Alarm_Insert(string TagID, string tagTypeID, string opName, int TagValue, + DateTime alarmStartTime, DateTime alarmEndTime, int TimeDiff, + string Text1, string Text2, string TagOrderBy) + { + + + string produceName = "测量数据工位报警全部_增加数据"; + SqlParameter[] thisParms = new SqlParameter[10]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@TagID", TagID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@TagTypeID", tagTypeID); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@opName", opName); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@TagValue", TagValue); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@alarmStartTime", alarmStartTime); + thisParms[5] = new System.Data.SqlClient.SqlParameter("@alarmEndTime", alarmEndTime); + thisParms[6] = new System.Data.SqlClient.SqlParameter("@TimeDiff", TimeDiff); + thisParms[7] = new System.Data.SqlClient.SqlParameter("@Text1", Text1); + thisParms[8] = new System.Data.SqlClient.SqlParameter("@Text2", Text2); + thisParms[9] = new System.Data.SqlClient.SqlParameter("@TagOrderBy", TagOrderBy); + if (DataAccess.ExecuteStoredProcedure(produceName, ref thisParms)) + { + + return true; + } + return false; + } + } +} diff --git a/MisDataSaveDateDll/MisDataSaveDate/Funtion.EngTypeGetOver.cs b/MisDataSaveDateDll/MisDataSaveDate/Funtion.EngTypeGetOver.cs new file mode 100644 index 0000000..dff0beb --- /dev/null +++ b/MisDataSaveDateDll/MisDataSaveDate/Funtion.EngTypeGetOver.cs @@ -0,0 +1,104 @@ +using bizFacade; +using DataLinkMesWork; +using DoWhatPlc; +using MesServerWork; +using Newtonsoft.Json; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Data; +using System.Data.SqlClient; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MisDataSaveDate +{ + public partial class Funtion + { + private static void EngTypeGetOver(string opName,string tagValue) + { + if (hashtable_EngineGetOver.Contains(opName)) + { + hashtable_EngineGetOver.Remove(opName); + } + hashtable_EngineGetOver.Add(opName, tagValue); + if (tagValue == "1") + { + + int EngineTypeID; + string EngineType; + string EngineID; + int PartPalletCode; + // 1 读取机型等信息,保存到监控表 + + DtWebApi.ReadWritePLC.GetEngineTypeFromPLC(opName, out EngineTypeID, out EngineType, out EngineID, out PartPalletCode); + + if (hashtable_EngineGetOver_EngineTypeID.Contains(opName)) + { + hashtable_EngineGetOver_EngineTypeID.Remove(opName); + } + hashtable_EngineGetOver_EngineTypeID.Add(opName, EngineTypeID); + + if (hashtable_EngineGetOver_EngineType.Contains(opName)) + { + hashtable_EngineGetOver_EngineType.Remove(opName); + } + hashtable_EngineGetOver_EngineType.Add(opName, EngineType); + + + if (hashtable_EngineGetOver_EngineID.Contains(opName)) + { + hashtable_EngineGetOver_EngineID.Remove(opName); + } + hashtable_EngineGetOver_EngineID.Add(opName, EngineID); + if (hashtable_PartPalletCode.Contains(opName)) + { + hashtable_PartPalletCode.Remove(opName); + } + hashtable_PartPalletCode.Add(opName, PartPalletCode); + + EngTypeGetOverInsert(opName, EngineTypeID, EngineType, EngineID, PartPalletCode); + + + // 2 保存工件到位信息 + + } + } + + // + /// + /// @工位号 nvarchar(50)=null, + ///@产品型号代码 int=1 , + ///@发动机型号 nvarchar(50)=null , + ///@发动机号 nvarchar(50)=null , + ///@托盘号 nvarchar(50)='0' + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + public static bool EngTypeGetOverInsert(string opName, int EngineTypeID, string EngineType,string EngineID, int PartPalletCode) + { + string procedureName; + procedureName = "测量数据工位_监控系统_增加"; + SqlParameter[] thisParms = new SqlParameter[5]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@产品型号代码", EngineTypeID); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@发动机型号", EngineType); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@发动机号", EngineID); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@托盘编号", PartPalletCode); + + if (DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms)) + { + return true; + } + return false; + } + } +} diff --git a/MisDataSaveDateDll/MisDataSaveDate/Funtion.MesRead.cs b/MisDataSaveDateDll/MisDataSaveDate/Funtion.MesRead.cs new file mode 100644 index 0000000..6ca2c17 --- /dev/null +++ b/MisDataSaveDateDll/MisDataSaveDate/Funtion.MesRead.cs @@ -0,0 +1,351 @@ +using bizFacade; +using DataLinkMesWork; +using DoWhatPlc; +using MesServerWork; +using Newtonsoft.Json; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Data; +using System.Data.SqlClient; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MisDataSaveDate +{ + public partial class Funtion + { + + + /// + /// 允许保存(针对半自动和手动压装工位) + /// + /// + /// + private static void MesRead(string opName, string tagValue, int tagid) + { + if (tagValue == "0") + { + MIS_BASE.Write_TagTypeID(20, opName, false); + } + else + { + if(MIS_BASE.hashtable_tagTable_OpName_SaveData==null) + { + MesServerWork.MIS_BASE.InitHashtable_MesServerCode(); + } + if(MIS_BASE.hashtable_tagTable_OpName_SaveData.Contains(opName)) + { + if (MIS_BASE.hashtable_tagTable_OpName_SaveData[opName].ToString() == "1") + { + SaveQualityData(opName, Convert.ToInt32(tagValue), tagid); + MIS_BASE.Write_TagTypeID(20, opName, true); + + } + else + { + //MIS_BASE.Write_TagTypeID(20, opName, true); + } + } + else + { + // MIS_BASE.Write_TagTypeID(20, opName, true); + } + + } + } + + private static void SaveQualityData(string opName, int tagValue, int tagID) + { + try + { + int id_tagCF; + int qualityMask = 0; + int engineTypeID = 0; + string engineID = ""; + string engineType = ""; + string engineTraceCode = ""; + string engineCap = ""; + string partPallet = ""; + DataTable dt_WWW; + dt_WWW = BaseDataSystemMES.BuildDataTables_WWW(); + Hashtable valueList; + //valueList = ReadPLC_Sync_DataList_MesRead(opName); + ReadPLC_Sync_DataList_MesRead(opName, out valueList, out MIS_BASE.BasicDataTagValue, out MIS_BASE.BasicDataTagValueUpDown, out MIS_BASE.hashtable_EngineTypeID, out MIS_BASE.hashtable_tagTable_OpName_SaveData); + valueList = GetQualityData_GoodBad_Values(valueList); + int mes_MustTest = 0; + int onLineState = 0; + int partMoveDirection = 0; + int pressIsOK = 0; + int pressIsNoOK = 0; + BaseDataSystemMES.GetQualityDataTable_B5A(valueList, opName, MIS_BASE.BasicDataTagValue, + MIS_BASE.BasicDataTagValueUpDown, + out dt_WWW,//数据列表 + out qualityMask,//工位合格标志 + out engineTypeID,//发动机类型代码 + out engineID,//发动机编号 + out engineType, //发动机型号 + out partPallet,//托盘编号 + out engineTraceCode, //发动机条码 + out engineCap,//缸盖号, + MIS_BASE.hashtable_EngineTypeID,//发动机类型转换表 + out mes_MustTest, out onLineState, out partMoveDirection, out pressIsOK, out pressIsNoOK); + + + + + // 1:通过监控系统保存采集的质量数据;0:不通过监控系统保存采集的质量数据 + if (Convert.ToInt32(MIS_BASE.hashtable_tagTable_OpName_SaveData[opName]) != 0) + { + DateTime lastupdatetime = DateTime.Now; + + BaseData_tagTable_QualityData_B5A_IndexInsert(engineID, tagID, engineType, engineTypeID, opName, qualityMask, partPallet, out id_tagCF); + BaseData_tagTable_QualityData_B5A_Insert(id_tagCF, engineTypeID, engineID, opName, dt_WWW); + + } + + //启动线程保存过站信息 + + + + MIS_BASE.Write_TagTypeID(20, opName, true); + #region + //string orderForm = ""; + //string operatorCode = ""; + //int shiftCode = 1; + //DateTime arrivedTime; + //DateTime leavedTime; + //int TimeDiff; + //int targetTime = 0; + //string lineType = ""; + //string isPass; + //int machineWorkOn = 0; + //int arrivedOrLeaved = 2; + //int cartColorOpName = 0; + //int cartColorConfirm = 0; + //// int partMoveDirection; + //int partGoOver = 0; + //if (qualityMask == 1) + //{ + // isPass = "PASS"; + //} + //else + //{ + // isPass = "FAIL"; + //} + + ////工位上下线类型 + ////(0普通工位)(1正常上线)(2正常下线)(3返修上线)(4返修下线) + //int OpNameUpDownType; + //OpNameUpDownType = Convert.ToInt32(hashtableOpName_OpType[opName]); + //arrivedTime = (DateTime)m_WorkStart_OpName_Time[opName]; + //leavedTime = DateTime.Now; + //TimeDiff = Convert.ToInt32(leavedTime.Subtract(arrivedTime).TotalSeconds); + + //lineType = hashtableOpName_LineType[opName].ToString(); + + //string isHaveComputer = hashtableOpName_IsHaveComputer[opName].ToString(); + ////isHaveComputer = MIS_BASE.hashtable_tagTable_OpName_SaveData[opName].ToString(); + ////有计算机的工位,通过工位计算机保存[测量数据发动机在线状态]。 + //if (Convert.ToInt32(isHaveComputer) == 0) + //{ + // //1->0 工件离开 工件刚刚离开 + // if (Convert.ToInt32(m_WorkStart_OpName[opName]) == 1) + // { + + // //[测量数据发动机在线状态] + // QualityDataSystem.WorkStartInsert + // (opName, orderForm, engineTypeID, engineType, engineID, partPallet.ToString(), operatorCode, shiftCode, + // arrivedTime, leavedTime, TimeDiff, targetTime, lineType, isPass, machineWorkOn, + // arrivedOrLeaved, cartColorOpName, cartColorConfirm, partMoveDirection, partGoOver, mes_MustTest, onLineState, OpNameUpDownType); + // } + //} + #endregion + } + catch (Exception err) + { + MIS_BASE.Write_TagTypeID(20, opName, true); + ////ApplicationLog.WriteLog(err, err.Message); + } + + } + public static bool BaseData_tagTable_QualityData_B5A_IndexInsert + (string EngineID, int tagID, string EngineType, int EngineTypeID, string opName, + int isGoodBad, string PartPalletCode, out int Id_tagCF) + { + string procedureName; + procedureName = "测量数据合格索引_增加"; + Id_tagCF = 0; + SqlParameter[] thisParms = new SqlParameter[8]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@EngineID", EngineID); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@TagID_CF", tagID); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@EngineType", EngineType); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@EngineTypeID", EngineTypeID); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[5] = new System.Data.SqlClient.SqlParameter("@托盘编号", PartPalletCode); + thisParms[6] = new System.Data.SqlClient.SqlParameter("@合格标志", isGoodBad); + thisParms[7] = new System.Data.SqlClient.SqlParameter("@Id_tagCF", Id_tagCF); + thisParms[7].Direction = ParameterDirection.Output; + + if (DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms)) + { + Id_tagCF = Convert.ToInt32(thisParms[7].Value.ToString()); + return true; + } + return false; + } + public static bool BaseData_tagTable_QualityData_B5A_Insert + (int Id_tagCF, int engineTypeID, string engineID, string opName, DataTable dt) + { + string procedureName; + procedureName = "测量数据合格_增加"; + SqlParameter[] thisParms = new SqlParameter[6]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@Id_tagCF", Id_tagCF); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@EngineTypeID", engineTypeID); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@EngineID", engineID); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@TagID", SqlDbType.Int, 4, "TagID"); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@TagValue", SqlDbType.NVarChar, 100, "TagValue"); + thisParms[5] = new System.Data.SqlClient.SqlParameter("@IsGoodBad", SqlDbType.Int, 4, "IsGoodBad"); + //thisParms[6] = new System.Data.SqlClient.SqlParameter("@测量位置", SqlDbType.NVarChar, 50, "测量位置"); + //thisParms[7] = new System.Data.SqlClient.SqlParameter("@测量项目", SqlDbType.NVarChar, 50, "测量项目"); + //thisParms[8] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + //thisParms[9] = new System.Data.SqlClient.SqlParameter("@理论值", SqlDbType.NVarChar, 50, "理论值"); + //thisParms[10] = new System.Data.SqlClient.SqlParameter("@上限值", SqlDbType.NVarChar, 50, "上限值"); + //thisParms[11] = new System.Data.SqlClient.SqlParameter("@下限值", SqlDbType.NVarChar, 50, "下限值"); + //thisParms[12] = new System.Data.SqlClient.SqlParameter("@测量单位", SqlDbType.NVarChar, 50, "测量单位"); + //thisParms[13] = new System.Data.SqlClient.SqlParameter("@列位置", SqlDbType.Int, 4, "列位置"); + //thisParms[14] = new System.Data.SqlClient.SqlParameter("@变量排序", SqlDbType.Int, 4, "变量排序"); + //table.Columns.Add("TagID", typeof(System.Int32)); + //table.Columns.Add("TagValue", typeof(System.String)); + //table.Columns.Add("IsGoodBad", typeof(System.Int32)); + //table.Columns.Add("测量位置", typeof(System.String)); + //table.Columns.Add("测量项目", typeof(System.String)); + //table.Columns.Add("工位号", typeof(System.String)); + //table.Columns.Add("理论值", typeof(System.String)); + //table.Columns.Add("上限值", typeof(System.String)); + //table.Columns.Add("下限值", typeof(System.String)); + //table.Columns.Add("测量单位", typeof(System.String)); + //table.Columns.Add("列位置", typeof(System.Int32)); + //table.Columns.Add("变量排序", typeof(System.Int32)); + return DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, dt); + } + public static void ReadPLC_Sync_DataList_MesRead(string opName, out Hashtable valueList, out DataTable BasicDataTagValue, out DataTable BasicDataTagValueUpDown, out Hashtable hashtable_EngineTypeID, out Hashtable hashtable_tagTable_OpName_SaveData) + { + //QualityDataSaveList QualityDataType + valueList = new Hashtable(); + var qualityDataSaveList = DtWebApi.SaveData.ReadPLC_Sync_DataList_MesRead(opName); + foreach (DictionaryEntry de in qualityDataSaveList.valuList) + { + valueList.Add(de.Key, JsonConvert.DeserializeObject(de.Value.ToString())); + } + BasicDataTagValue = qualityDataSaveList.BasicDataTagValue; + BasicDataTagValueUpDown = qualityDataSaveList.BasicDataTagValueUpDown; + hashtable_EngineTypeID = qualityDataSaveList.hashtable_EngineTypeID; + hashtable_tagTable_OpName_SaveData = qualityDataSaveList.hashtable_tagTable_OpName_SaveData; + } + /// + /// 确定合格标志 + /// + /// + /// + static public Hashtable GetQualityData_GoodBad_Values(Hashtable valuList) + { + try + { + Hashtable valuList_Temp; + valuList_Temp = (Hashtable)valuList.Clone(); + int[] value_GoodBad_New = new int[128]; + int tagID; + QualityDataType value; + //1:获得合格标志 + foreach (DictionaryEntry de in valuList) //ht为一个Hashtable实例 + { + tagID = Convert.ToInt32(de.Key); + value = (QualityDataType)de.Value; + + //拧紧数据合格标志 + if (value.tagProperty == 1) + { + if (value.tagTypeID == 8203) + { + value_GoodBad_New = (int[])value.tagValue; + break; + } + else + { + value_GoodBad_New[value.tagOrderBy - 1] = Convert.ToInt32(value.tagValue); + } + } + //拧紧数据合格标志 + if (value.tagProperty == 8) + { + if (value.tagTypeID == 8203) + { + value_GoodBad_New = (int[])value.tagValue; + break; + } + else + { + value_GoodBad_New[value.tagOrderBy - 1] = Convert.ToInt32(value.tagValue); + } + } + //压装数据合格标志 + if (value.tagProperty == 7) + { + value_GoodBad_New[value.tagOrderBy - 1] = Convert.ToInt32(value.tagValue); + } + } + //将合格标志赋予每个变量 + foreach (DictionaryEntry de in valuList) //ht为一个Hashtable实例 + { + tagID = Convert.ToInt32(de.Key); + value = (QualityDataType)de.Value; + //201706061720新加 + if (value.tagTypeID == 11) + { + if (value.tagValue.ToString() == "False") + { + value.tagValue = "0"; + } + else + { + value.tagValue = "1"; + } + valuList_Temp[tagID] = value; + //value.tagValue = Convert.ToInt32(value.tagValue); + } + + + //测量变量 + if (value.tagProperty == 2 || value.tagProperty == 6) + { + try + { + if (value_GoodBad_New != null) + { + value.isGoodBad = Convert.ToInt32(value_GoodBad_New[value.tagOrderBy - 1]); + valuList_Temp[tagID] = value; + } + else + { + value.isGoodBad = 0; + valuList_Temp[tagID] = value; + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, err.Message); + + } + } + } + return valuList_Temp; + } + catch//转换出了故障时 + { + return valuList; + } + } + } +} diff --git a/MisDataSaveDateDll/MisDataSaveDate/Funtion.WorkStart.cs b/MisDataSaveDateDll/MisDataSaveDate/Funtion.WorkStart.cs new file mode 100644 index 0000000..7049308 --- /dev/null +++ b/MisDataSaveDateDll/MisDataSaveDate/Funtion.WorkStart.cs @@ -0,0 +1,228 @@ +using bizFacade; +using DataLinkMesWork; +using DoWhatPlc; +using MesServerWork; +using Newtonsoft.Json; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Data; +using System.Data.SqlClient; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MisDataSaveDate +{ + public partial class Funtion + { + + private static void WorkStart(ReturnValueString rv) + { + var ro = rv.ReturnValueToObject(); + + string opName = ro.OpName; + DateTime arrivedTime = ro.TimeStampBefore; + DateTime leavedTime = ro.TimeStamp; + int TimeDiff = ro.TagKeepTime; + int targetTime = 0; + string isPass = ""; + + int QualityMark = 0; + string tagValue = "0"; + switch (ro.TagValue.ToString().ToLower()) + { + case "1": + case "true": + tagValue = "1"; + break; + default: + tagValue = "0"; + break; + } + + + + int EngineTypeID=-1;//机型代码 + int PartPalletCode=-1;//托盘编号 + string EngineType="-1";//机型 + string EngineID="-1";//工件编号 + if (hashtable_EngineGetOver_EngineTypeID.Contains(opName)) + { + EngineTypeID = Convert.ToInt32( hashtable_EngineGetOver_EngineTypeID[opName]); + } + if (hashtable_EngineGetOver_EngineType.Contains(opName)) + { + EngineType = hashtable_EngineGetOver_EngineType[opName].ToString(); + } + if (hashtable_EngineGetOver_EngineID.Contains(opName)) + { + EngineID = hashtable_EngineGetOver_EngineID[opName].ToString(); + } + if (hashtable_PartPalletCode.Contains(opName)) + { + PartPalletCode = Convert.ToInt32(hashtable_PartPalletCode[opName]); + } + + //MIS_BASE.GetEngineTypeFromPLC(opName, out EngineTypeID, out EngineType, out EngineID, out PartPallet_Code); + + //EngineData Enginedata = (EngineData)EngineData_Hash_Read(opName); + //WorkStartInsert_AutoWorkStation(opName, EngineID, PartPalletCode, arrivedTime, leavedTime, TimeDiff, targetTime, null, isPass, 0); + + if (tagValue == "0") + { + QualityMark = Convert.ToInt32(DtWebApi.ReadWritePLC.ReadPLC("21", opName)); + + if (QualityMark == 1) + { + isPass = "1"; + } + else + { + isPass = "0"; + } + + WorkStartInsert_V2022(opName, arrivedTime, leavedTime, TimeDiff, isPass); + + MIS_BASE.Write_TagTypeID(5, opName, false);//MES传递机型 + MIS_BASE.Write_TagTypeID(66, opName, false);//允许工作 + MIS_BASE.Write_TagTypeID(51, opName, false);//合格放行 + MIS_BASE.Write_TagTypeID(8, opName, false);//不合格放行 + MIS_BASE.Write_TagTypeID(7, opName, false);//工作完成 + MIS_BASE.Write_TagTypeID(20, opName, false);//保存完成 + + + + //string isHaveComputer = hashtableOpName_IsHaveComputer[opName].ToString(); + //if (Convert.ToInt32(isHaveComputer) == 0)//自动工位 读合格标志 + //{ + // if (IsEngTypeGetOver_Read(opName)) + // { + // //PLC未传递机型 不保存过站信息 + // SaveProductLeaveData_AutoWorkStation(opName, Convert.ToInt32(DtWebApi.ReadWritePLC.ReadPLC("21", opName))); + // //SaveProductLeaveData_AutoWorkStation(opName, Convert.ToInt32(MesDataFunction.OpcOperation.ReadPLC(21, opName))); + // } + + //} + + ////清空信号 + ////m_WorkStart_OpName[opName] = 0;//清空工件到位标志 + + } + + //通知WEB更新产量 + SendActuallyCount(opName, 0); + } + /// + /// 发送在线产量、在线节拍 + /// + /// + /// + static void SendActuallyCount(string OpName, int tagValue) + { + //当工件离开时,更新在线产量、在线节拍 + if (tagValue == 0) + { + try + { + int opNameCount = 0;//在线产量 + int opNameCountTime = 0;//在线节拍 + //基本数据_工作日历_班次产量查询_New + OpNameCount_New(OpName, out opNameCount, out opNameCountTime); + + string SendMessage; + SendMessage = "MES|ActuallyCount|" + OpName + "|" + opNameCount.ToString() + "&" + opNameCountTime.ToString(); + + MIS_BASE.asyncSendMessage(SendMessage); + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function01:SendActuallyCount"); + } + } + } + /// + /// 基本数据_工作日历_班次产量查询_New + /// + /// + /// 在线产量 + /// 在线节拍 + static public void OpNameCount_New(string opName, out int opNameCount, out int opNameCountTime) + { + opNameCount = 0; + opNameCountTime = 0; + string procedureName; + procedureName = "基本数据_工作日历_班次产量查询_New"; + SqlParameter[] thisParms = new SqlParameter[3]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@在线产量", 0); + thisParms[1].Direction = ParameterDirection.Output; + thisParms[2] = new System.Data.SqlClient.SqlParameter("@在线节拍", 0); + thisParms[2].Direction = ParameterDirection.Output; + if (DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms)) + { + opNameCount = Convert.ToInt32(thisParms[1].Value); + opNameCountTime = Convert.ToInt32(thisParms[2].Value); + } + } + /// + /// 测量数据发动机在线状态_增加数据_自动工位 + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + static public void WorkStartInsert_AutoWorkStation(string opName, string EngineID, int Pallet, DateTime arrivedTime, DateTime leavedTime, int TimeDiff, int Target, string lineType, string isPass, int OpNameUpDownType) + { + string procedureName; + procedureName = "测量数据发动机在线状态_增加数据_自动工位"; + SqlParameter[] thisParms = new SqlParameter[10]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@发动机号", EngineID); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@托盘编号", Pallet); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@到达时间", arrivedTime); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@离开时间", leavedTime); + thisParms[5] = new System.Data.SqlClient.SqlParameter("@在线时间", TimeDiff); + thisParms[6] = new System.Data.SqlClient.SqlParameter("@目标时间", Target); + thisParms[7] = new System.Data.SqlClient.SqlParameter("@线体类型", lineType); + thisParms[8] = new System.Data.SqlClient.SqlParameter("@是否合格", isPass); + thisParms[9] = new System.Data.SqlClient.SqlParameter("@工位上下线类型", OpNameUpDownType); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } + + static public void WorkStartInsert_V2022(string opName, DateTime arrivedTime, DateTime leavedTime, int TimeDiff, string isPass) + { + string procedureName; + procedureName = "测量数据发动机在线状态_增加数据_V2022"; + SqlParameter[] thisParms = new SqlParameter[5]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@到达时间", arrivedTime); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@离开时间", leavedTime); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@在线时间", TimeDiff); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@是否合格", isPass); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } + + static public void WorkStartInsert(string opName, DateTime arrivedTime, DateTime leavedTime, int TimeDiff, int Target, string lineType, string isPass, int OpNameUpDownType) + { + string procedureName; + procedureName = "测量数据发动机在线状态_增加数据"; + SqlParameter[] thisParms = new SqlParameter[8]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@到达时间", arrivedTime); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@离开时间", leavedTime); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@在线时间", TimeDiff); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@目标时间", Target); + thisParms[5] = new System.Data.SqlClient.SqlParameter("@线体类型", lineType); + thisParms[6] = new System.Data.SqlClient.SqlParameter("@是否合格", isPass); + thisParms[7] = new System.Data.SqlClient.SqlParameter("@工位上下线类型", OpNameUpDownType); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } + } +} diff --git a/MisDataSaveDateDll/MisDataSaveDate/Funtion.cs b/MisDataSaveDateDll/MisDataSaveDate/Funtion.cs new file mode 100644 index 0000000..9159833 --- /dev/null +++ b/MisDataSaveDateDll/MisDataSaveDate/Funtion.cs @@ -0,0 +1,151 @@ +using bizFacade; +using DoWhatPlc; +using MesServerWork; +using Newtonsoft.Json; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Data; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MisDataSaveDate +{ + public partial class Funtion + { + /// + /// 发动机类型转换表 + /// SELECT ID,发动机机型代码 FROM MES_计划BOM_发动机型号代码 + /// + public static Hashtable hashtable_EngineTypeID=new Hashtable (); + /// + /// 记录工件到位的发动机机型代码 + /// + public static Hashtable hashtable_EngineGetOver_EngineTypeID = new Hashtable(); + /// + /// 记录工件到位的发动机机型 + /// + public static Hashtable hashtable_EngineGetOver_EngineType = new Hashtable(); + /// + /// 记录工件到位的发动机号 + /// + public static Hashtable hashtable_EngineGetOver_EngineID = new Hashtable(); + /// + /// 记录工件到位的订单号 + /// + public static Hashtable hashtable_EngineGetOver_OrderForm = new Hashtable(); + + public static Hashtable hashtable_EngineGetOver = new Hashtable(); + + public static Hashtable hashtable_PartPalletCode = new Hashtable(); + + public static void MIS_Funtion(object e) + { + try + { + + string recData = e.ToString(); + string[] dataArray = recData.Split('|'); + if (dataArray.Length != 4) + return; + //消息来源 + string m_Source = dataArray[0].ToString(); + //消息类型 + string m_Command = dataArray[1].ToString(); + //工位号 + string m_OpName = dataArray[2].ToString(); + //消息参数 + string m_Value = dataArray[3].ToString(); + + DoWhatPlc.ReturnValueString rv = Newtonsoft.Json.JsonConvert.DeserializeObject(m_Value); + //Console.WriteLine($"【【{rv.TagID}【【【【{ rv.TagKeepTime}"); + + int tagType; + string opName; + string tagValue; + int tagid; + DoWhatPlc.ReturnValueString msgEvent = rv; + if (msgEvent.TagValue == null) return; + tagType = Convert.ToInt32(msgEvent.TagTypeID); + opName = msgEvent.OpName.ToString(); + tagid = Convert.ToInt32(msgEvent.TagID); + + + + switch (Convert.ToInt32(msgEvent.TagTypeCodeID)) + { + case 11: + switch (msgEvent.TagValue.ToLower()) + { + case "1": + case "true": + tagValue = "1"; + break; + default: + tagValue = "0"; + break; + } + break; + default: + tagValue = msgEvent.TagValue.ToString(); + break; + } + ///根据信号处理逻辑 + switch (tagType) + { + case 19: + //允许保存 + MesRead(opName, tagValue, tagid); + break; + case 14: + //心跳 + //Heartbeat(opName, tagValue); + break; + case 44://PLC传递机型过后 才允许保存过站信息,否则不允许保存 + EngTypeGetOver(opName, tagValue); + break; + case 2://工件到位 离开信息 + + if (tagValue == "0") + { + //传递机型 + if (hashtable_EngineGetOver.Contains(opName)) + { + if (hashtable_EngineGetOver[opName].ToString() == "1") + { + WorkStart(rv); + } + } + } + break; + case 51: + //if (hashtableOpName_IsHaveComputer[opName].ToString() == "1") + //{ + // SaveProductLeaveData(opName, 1); + //} + + break; + case 8: + //if (hashtableOpName_IsHaveComputer[opName].ToString() == "1") + //{ + // SaveProductLeaveData(opName, 2); + //} + break; + case 103: + + Alarm_Insert(rv); + + break; + } + + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, err.Message); + } + } + + + } +} diff --git a/MisDataSaveDateDll/MisDataSaveDate/MisDataSaveDateDll.csproj b/MisDataSaveDateDll/MisDataSaveDate/MisDataSaveDateDll.csproj new file mode 100644 index 0000000..c5ae48f --- /dev/null +++ b/MisDataSaveDateDll/MisDataSaveDate/MisDataSaveDateDll.csproj @@ -0,0 +1,162 @@ + + + + + Debug + AnyCPU + {9AEDE061-8490-436A-B38B-9495DC908F19} + WinExe + MisDataSaveDate + MisDataSaveDate + v4.6.1 + 512 + true + true + + + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + False + ..\..\Common\dll\MQTTnet.dll + + + False + ..\..\Common\dll\MQTTnet.Extensions.ManagedClient.dll + + + + + + ..\packages\System.Net.Security.4.3.2\lib\net46\System.Net.Security.dll + + + ..\packages\System.Net.WebSockets.4.3.0\lib\net46\System.Net.WebSockets.dll + + + ..\packages\System.Net.WebSockets.Client.4.3.2\lib\net46\System.Net.WebSockets.Client.dll + + + ..\packages\System.Security.Cryptography.Algorithms.4.3.0\lib\net461\System.Security.Cryptography.Algorithms.dll + + + ..\packages\System.Security.Cryptography.Encoding.4.3.0\lib\net46\System.Security.Cryptography.Encoding.dll + + + ..\packages\System.Security.Cryptography.Primitives.4.3.0\lib\net46\System.Security.Cryptography.Primitives.dll + + + ..\packages\System.Security.Cryptography.X509Certificates.4.3.0\lib\net461\System.Security.Cryptography.X509Certificates.dll + + + + + + + + + + + + + + + + + + + Form + + + SaveData.cs + + + + + ResXFileCodeGenerator + Resources.Designer.cs + Designer + + + True + Resources.resx + + + SaveData.cs + + + + SettingsSingleFileGenerator + Settings.Designer.cs + + + True + Settings.settings + True + + + + + + + + {1a10fdb2-1a6a-44a8-ab4d-33387563247e} + 00-0Json8.3.1 + + + {f55da1a0-a982-4479-8c47-0d9a5aaf3e18} + 00MesWorkMqtt + + + {0d1af432-439a-4920-8692-43ae139f5530} + 01_01DoWhatPlc + + + {3e6d1dd5-01c9-435f-9941-61f906ce35bb} + 02_02WebApiCallPLC + + + {f434e066-4c59-47c8-aa82-6f48cc84501a} + 04-DataBaseAccess + + + {f0a0c525-03fd-428a-9b17-7f54aa0e4475} + 07BusinessFacade + + + {90e76fb4-646d-45e2-95db-0b8ab4e465d6} + 09-MesDataFunction + + + {807fcc00-d1d5-45df-a60d-e295640eb6aa} + 10TagTypeCodeID + + + + + + + 这台计算机上缺少此项目引用的 NuGet 程序包。使用“NuGet 程序包还原”可下载这些程序包。有关更多信息,请参见 http://go.microsoft.com/fwlink/?LinkID=322105。缺少的文件是 {0}。 + + + + \ No newline at end of file diff --git a/MisDataSaveDateDll/MisDataSaveDate/Program.cs b/MisDataSaveDateDll/MisDataSaveDate/Program.cs new file mode 100644 index 0000000..18e46e1 --- /dev/null +++ b/MisDataSaveDateDll/MisDataSaveDate/Program.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace MisDataSaveDate +{ + static class Program + { + /// + /// 应用程序的主入口点。 + /// + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + Application.Run(new SaveData()); + } + } +} diff --git a/MisDataSaveDateDll/MisDataSaveDate/Properties/AssemblyInfo.cs b/MisDataSaveDateDll/MisDataSaveDate/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..08faa00 --- /dev/null +++ b/MisDataSaveDateDll/MisDataSaveDate/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// 有关程序集的一般信息由以下 +// 控制。更改这些特性值可修改 +// 与程序集关联的信息。 +[assembly: AssemblyTitle("MisDataSaveDate")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("MisDataSaveDate")] +[assembly: AssemblyCopyright("Copyright © 2022")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// 将 ComVisible 设置为 false 会使此程序集中的类型 +//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型 +//请将此类型的 ComVisible 特性设置为 true。 +[assembly: ComVisible(false)] + +// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID +[assembly: Guid("9aede061-8490-436a-b38b-9495dc908f19")] + +// 程序集的版本信息由下列四个值组成: +// +// 主版本 +// 次版本 +// 生成号 +// 修订号 +// +//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值 +//通过使用 "*",如下所示: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/MisDataSaveDateDll/MisDataSaveDate/Properties/Resources.Designer.cs b/MisDataSaveDateDll/MisDataSaveDate/Properties/Resources.Designer.cs new file mode 100644 index 0000000..d21d7e1 --- /dev/null +++ b/MisDataSaveDateDll/MisDataSaveDate/Properties/Resources.Designer.cs @@ -0,0 +1,70 @@ +//------------------------------------------------------------------------------ +// +// 此代码由工具生成。 +// 运行时版本: 4.0.30319.42000 +// +// 对此文件的更改可能导致不正确的行为,如果 +// 重新生成代码,则所做更改将丢失。 +// +//------------------------------------------------------------------------------ + + +namespace MisDataSaveDate.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("MisDataSaveDate.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/MisDataSaveDateDll/MisDataSaveDate/Properties/Resources.resx b/MisDataSaveDateDll/MisDataSaveDate/Properties/Resources.resx new file mode 100644 index 0000000..af7dbeb --- /dev/null +++ b/MisDataSaveDateDll/MisDataSaveDate/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/MisDataSaveDateDll/MisDataSaveDate/Properties/Settings.Designer.cs b/MisDataSaveDateDll/MisDataSaveDate/Properties/Settings.Designer.cs new file mode 100644 index 0000000..54d0109 --- /dev/null +++ b/MisDataSaveDateDll/MisDataSaveDate/Properties/Settings.Designer.cs @@ -0,0 +1,29 @@ +//------------------------------------------------------------------------------ +// +// 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 MisDataSaveDate.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/MisDataSaveDateDll/MisDataSaveDate/Properties/Settings.settings b/MisDataSaveDateDll/MisDataSaveDate/Properties/Settings.settings new file mode 100644 index 0000000..3964565 --- /dev/null +++ b/MisDataSaveDateDll/MisDataSaveDate/Properties/Settings.settings @@ -0,0 +1,7 @@ + + + + + + + diff --git a/MisDataSaveDateDll/MisDataSaveDate/SaveData.Designer.cs b/MisDataSaveDateDll/MisDataSaveDate/SaveData.Designer.cs new file mode 100644 index 0000000..489b045 --- /dev/null +++ b/MisDataSaveDateDll/MisDataSaveDate/SaveData.Designer.cs @@ -0,0 +1,49 @@ + +namespace MisDataSaveDate +{ + partial class SaveData + { + /// + /// 必需的设计器变量。 + /// + 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.SuspendLayout(); + // + // SaveData + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(800, 450); + this.Name = "SaveData"; + this.Text = "Form1"; + this.Load += new System.EventHandler(this.SaveData_Load); + this.ResumeLayout(false); + + } + + #endregion + } +} + diff --git a/MisDataSaveDateDll/MisDataSaveDate/SaveData.cs b/MisDataSaveDateDll/MisDataSaveDate/SaveData.cs new file mode 100644 index 0000000..65d1af0 --- /dev/null +++ b/MisDataSaveDateDll/MisDataSaveDate/SaveData.cs @@ -0,0 +1,69 @@ +using MesWorkMqtt; +using MisDataFunction; +using MQTTnet; +using MQTTnet.Client.Connecting; +using MQTTnet.Client.Disconnecting; +using MQTTnet.Client.Receiving; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Configuration; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace MisDataSaveDate +{ + public partial class SaveData : Form + { + public SaveData() + { + InitializeComponent(); + } + + private void SaveData_Load(object sender, EventArgs e) + { + //Task.Run(() => StartAsync()); + + Mqtt.StartAsync(); + Mqtt.mqttClient.ConnectedHandler = new MqttClientConnectedHandlerDelegate(OnSubscriberConnected); + Mqtt.mqttClient.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(OnSubscriberDisconnected); + Mqtt.mqttClient.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(OnSubscriberMessageReceived); + + string url; + string topic; + url = ConfigurationManager.AppSettings["MqttUrl"]; + topic = ConfigurationManager.AppSettings["MqttTargetTopicTagTypeCodeID"]; + new InitMqtt2(url, topic); + + + MesServerWork.MIS_BASE.InitHashtable_MesServerCode(); + + + } + private void OnSubscriberConnected(MqttClientConnectedEventArgs x) + { + var rec = x.AuthenticateResult.ResultCode.ToString(); + //label_State.Text = rec; + } + + private void OnSubscriberDisconnected(MqttClientDisconnectedEventArgs x) + { + //var rec = x.AuthenticateResult.ResultCode.ToString(); + //label_State.Text = rec; + } + + private void OnSubscriberMessageReceived(MqttApplicationMessageReceivedEventArgs x) + { + var rec = x.ApplicationMessage.ConvertPayloadToString(); + ThreadPool.QueueUserWorkItem(MisDataSaveDate.Funtion.MIS_Funtion, rec); + } + + + + } +} diff --git a/MisDataSaveDateDll/MisDataSaveDate/SaveData.resx b/MisDataSaveDateDll/MisDataSaveDate/SaveData.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/MisDataSaveDateDll/MisDataSaveDate/SaveData.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/MisDataSaveDateDll/MisDataSaveDate/packages.config b/MisDataSaveDateDll/MisDataSaveDate/packages.config new file mode 100644 index 0000000..fb59d33 --- /dev/null +++ b/MisDataSaveDateDll/MisDataSaveDate/packages.config @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/MisDataSaveDateDll/dll/00MesWorkMqtt.dll b/MisDataSaveDateDll/dll/00MesWorkMqtt.dll new file mode 100644 index 0000000..15cb845 Binary files /dev/null and b/MisDataSaveDateDll/dll/00MesWorkMqtt.dll differ diff --git a/MisDataSaveDateDll/dll/00MesWorkMqtt.pdb b/MisDataSaveDateDll/dll/00MesWorkMqtt.pdb new file mode 100644 index 0000000..5dc65cb Binary files /dev/null and b/MisDataSaveDateDll/dll/00MesWorkMqtt.pdb differ diff --git a/MisDataSaveDateDll/dll/01DoWhatPlc.dll b/MisDataSaveDateDll/dll/01DoWhatPlc.dll new file mode 100644 index 0000000..25c33ee Binary files /dev/null and b/MisDataSaveDateDll/dll/01DoWhatPlc.dll differ diff --git a/MisDataSaveDateDll/dll/01DoWhatPlc.pdb b/MisDataSaveDateDll/dll/01DoWhatPlc.pdb new file mode 100644 index 0000000..e75a71b Binary files /dev/null and b/MisDataSaveDateDll/dll/01DoWhatPlc.pdb differ diff --git a/MisDataSaveDateDll/dll/02WebApiCall.dll b/MisDataSaveDateDll/dll/02WebApiCall.dll new file mode 100644 index 0000000..9a3f5b0 Binary files /dev/null and b/MisDataSaveDateDll/dll/02WebApiCall.dll differ diff --git a/MisDataSaveDateDll/dll/02WebApiCall.dll.config b/MisDataSaveDateDll/dll/02WebApiCall.dll.config new file mode 100644 index 0000000..6035ea8 --- /dev/null +++ b/MisDataSaveDateDll/dll/02WebApiCall.dll.config @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/MisDataSaveDateDll/dll/02WebApiCall.pdb b/MisDataSaveDateDll/dll/02WebApiCall.pdb new file mode 100644 index 0000000..16b7902 Binary files /dev/null and b/MisDataSaveDateDll/dll/02WebApiCall.pdb differ diff --git a/MisDataSaveDateDll/dll/04DataBaseAccess.dll b/MisDataSaveDateDll/dll/04DataBaseAccess.dll new file mode 100644 index 0000000..1378ec9 Binary files /dev/null and b/MisDataSaveDateDll/dll/04DataBaseAccess.dll differ diff --git a/MisDataSaveDateDll/dll/04DataBaseAccess.pdb b/MisDataSaveDateDll/dll/04DataBaseAccess.pdb new file mode 100644 index 0000000..740cc80 Binary files /dev/null and b/MisDataSaveDateDll/dll/04DataBaseAccess.pdb differ diff --git a/MisDataSaveDateDll/dll/07BusinessFacade.dll b/MisDataSaveDateDll/dll/07BusinessFacade.dll new file mode 100644 index 0000000..02e2595 Binary files /dev/null and b/MisDataSaveDateDll/dll/07BusinessFacade.dll differ diff --git a/MisDataSaveDateDll/dll/07BusinessFacade.pdb b/MisDataSaveDateDll/dll/07BusinessFacade.pdb new file mode 100644 index 0000000..dcb0c1b Binary files /dev/null and b/MisDataSaveDateDll/dll/07BusinessFacade.pdb differ diff --git a/MisDataSaveDateDll/dll/08WebFun_base.dll b/MisDataSaveDateDll/dll/08WebFun_base.dll new file mode 100644 index 0000000..e088df4 Binary files /dev/null and b/MisDataSaveDateDll/dll/08WebFun_base.dll differ diff --git a/MisDataSaveDateDll/dll/08WebFun_base.pdb b/MisDataSaveDateDll/dll/08WebFun_base.pdb new file mode 100644 index 0000000..b4db747 Binary files /dev/null and b/MisDataSaveDateDll/dll/08WebFun_base.pdb differ diff --git a/MisDataSaveDateDll/dll/09MesDataFunction.dll b/MisDataSaveDateDll/dll/09MesDataFunction.dll new file mode 100644 index 0000000..e31947c Binary files /dev/null and b/MisDataSaveDateDll/dll/09MesDataFunction.dll differ diff --git a/MisDataSaveDateDll/dll/09MesDataFunction.pdb b/MisDataSaveDateDll/dll/09MesDataFunction.pdb new file mode 100644 index 0000000..8c336b4 Binary files /dev/null and b/MisDataSaveDateDll/dll/09MesDataFunction.pdb differ diff --git a/MisDataSaveDateDll/dll/BusinessFacade.pdb b/MisDataSaveDateDll/dll/BusinessFacade.pdb new file mode 100644 index 0000000..2e1bfcb Binary files /dev/null and b/MisDataSaveDateDll/dll/BusinessFacade.pdb differ diff --git a/MisDataSaveDateDll/dll/MQTTnet.Extensions.ManagedClient.dll b/MisDataSaveDateDll/dll/MQTTnet.Extensions.ManagedClient.dll new file mode 100644 index 0000000..99035f6 Binary files /dev/null and b/MisDataSaveDateDll/dll/MQTTnet.Extensions.ManagedClient.dll differ diff --git a/MisDataSaveDateDll/dll/MQTTnet.dll b/MisDataSaveDateDll/dll/MQTTnet.dll new file mode 100644 index 0000000..2951433 Binary files /dev/null and b/MisDataSaveDateDll/dll/MQTTnet.dll differ diff --git a/MisDataSaveDateDll/dll/Newtonsoft.Json.dll b/MisDataSaveDateDll/dll/Newtonsoft.Json.dll new file mode 100644 index 0000000..597a1ce Binary files /dev/null and b/MisDataSaveDateDll/dll/Newtonsoft.Json.dll differ diff --git a/PrintBarCode/21PrintBarCode.csproj b/PrintBarCode/21PrintBarCode.csproj new file mode 100644 index 0000000..72deacb --- /dev/null +++ b/PrintBarCode/21PrintBarCode.csproj @@ -0,0 +1,92 @@ + + + + + Debug + AnyCPU + {269C9CBC-4958-4E4D-B43B-307C1D09D87F} + Library + PrintBarCode + PrintBarCode + v4.8 + 512 + true + true + + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + + Form + + + Form + + + PrintBarCodeForm.cs + + + + + PrintBarCodeForm.cs + + + ResXFileCodeGenerator + Resources.Designer.cs + Designer + + + True + Resources.resx + True + + + SettingsSingleFileGenerator + Settings.Designer.cs + + + True + Settings.settings + True + + + + + + + \ No newline at end of file diff --git a/PrintBarCode/App.config b/PrintBarCode/App.config new file mode 100644 index 0000000..56ea425 --- /dev/null +++ b/PrintBarCode/App.config @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/PrintBarCode/DB.cs b/PrintBarCode/DB.cs new file mode 100644 index 0000000..913f0f6 --- /dev/null +++ b/PrintBarCode/DB.cs @@ -0,0 +1,168 @@ +using System; +using System.Collections.Generic; +using System.Data.SqlClient; +using System.Data; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PrintBarCode +{ + public partial class PrintBarCodeForm + { + private DataTable PrintLogInset(string partNo, int partCount, int beginNumber, DateTime proDate) + { + // ALTER PROCEDURE[dbo].[北汽福田打印条码日志_增加] + // @零件号 nvarchar(50), + //@数量 int, + //@开始号码 int, + //@日期 date + DataTable dt = new DataTable(); + string procedureName = "北汽福田打印条码日志_增加"; + SqlParameter[] sqlParameters = new SqlParameter[4]; + //string columnPartName = "column18"; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@零件号", partNo); + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@数量", partCount); + sqlParameters[2] = new System.Data.SqlClient.SqlParameter("@开始号码", beginNumber); + sqlParameters[3] = new System.Data.SqlClient.SqlParameter("@日期", proDate); + + ExecuteStoredProcedure(procedureName, ConnectString_MES, ref sqlParameters, out dt); + + return dt; + + } + private DataTable PrintSnInset(string sn, string partNo, int partCount, int beginNumber, DateTime proDate) + { + // ALTER PROCEDURE[dbo].[北汽福田打印条码变速器序列号_增加] + // @变速器序列号 nvarchar(50), + //@零件号 nvarchar(50), + //@数量 int, + //@开始号码 int, + //@日期 date + DataTable dt = new DataTable(); + string procedureName = "北汽福田打印条码变速器序列号_增加"; + SqlParameter[] sqlParameters = new SqlParameter[5]; + //string columnPartName = "column18"; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@变速器序列号", sn); + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@零件号", partNo); + sqlParameters[2] = new System.Data.SqlClient.SqlParameter("@数量", partCount); + sqlParameters[3] = new System.Data.SqlClient.SqlParameter("@开始号码", beginNumber); + sqlParameters[4] = new System.Data.SqlClient.SqlParameter("@日期", proDate); + + ExecuteStoredProcedure(procedureName, ConnectString_MES, ref sqlParameters, out dt); + + return dt; + + } + private DataTable PrintSnUpdate(string sn, string partNo, int partCount, int beginNumber, DateTime proDate) + { + DataTable dt = new DataTable(); + string procedureName = "北汽福田打印条码变速器序列号_更新"; + SqlParameter[] sqlParameters = new SqlParameter[5]; + //string columnPartName = "column18"; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@变速器序列号", sn); + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@零件号", partNo); + sqlParameters[2] = new System.Data.SqlClient.SqlParameter("@数量", partCount); + sqlParameters[3] = new System.Data.SqlClient.SqlParameter("@开始号码", beginNumber); + sqlParameters[4] = new System.Data.SqlClient.SqlParameter("@日期", proDate); + + ExecuteStoredProcedure(procedureName, ConnectString_MES, ref sqlParameters, out dt); + + return dt; + + } + /// + /// 0:没有打印过 + /// 1:打印过 + /// + /// + /// + private int PrintSnIsPrinted(string sn) + { + //北汽福田打印条码变速器序列号_是否打印过 + // @变速器序列号 nvarchar(50), + + DataTable dt = new DataTable(); + string procedureName = "北汽福田打印条码变速器序列号_是否打印过"; + SqlParameter[] sqlParameters = new SqlParameter[1]; + //string columnPartName = "column18"; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@变速器序列号", sn); + + + ExecuteStoredProcedure(procedureName, ConnectString_MES, ref sqlParameters, out dt); + int count; + count = Convert.ToInt32(dt.Rows[0][0]); + return count; + } + + /// + /// @工位号 nvarchar(50), + /// @TagValue nvarchar(50), + /// @变量类型代码 nvarchar(50) + /// + /// + /// + /// + private void OpNameMonitorInsert(string opName,string tagValue,string tagTypeID) + { + string procedureName = "北汽福田工位状态监控_增加"; + SqlParameter[] sqlParameters = new SqlParameter[3]; + sqlParameters[0] = new System.Data.SqlClient.SqlParameter("@opName", opName); + sqlParameters[1] = new System.Data.SqlClient.SqlParameter("@tagValue", tagValue); + sqlParameters[2] = new System.Data.SqlClient.SqlParameter("@tagTypeID", tagTypeID); + + + ExecuteStoredProcedure(procedureName, ConnectString_MES, ref sqlParameters); + } + public static bool ExecuteStoredProcedure(string procedureName, string connectionString, ref SqlParameter[] sqlParameters) + { + DataTable dt; + return ExecuteStoredProcedure(procedureName, connectionString, ref sqlParameters, out dt); + + } + public static bool ExecuteStoredProcedure(string procedureName, string connectionString, ref SqlParameter[] sqlParameters, out DataTable dt) + { + + bool result = false; + string errorMessage; + errorMessage = ""; + dt = new DataTable(); + using (SqlConnection conn = new SqlConnection(connectionString)) + { + try + { + conn.Open(); + using (SqlDataAdapter dsCommand = new SqlDataAdapter()) + { + dsCommand.SelectCommand = new SqlCommand(procedureName, conn); + dsCommand.SelectCommand.CommandType = CommandType.StoredProcedure; + dsCommand.SelectCommand.CommandTimeout = 0; + if (sqlParameters != null) + { + for (int i = 0; i < sqlParameters.Length; i++) + { + dsCommand.SelectCommand.Parameters.Add(sqlParameters[i]); + } + } + + dsCommand.Fill(dt); + } + result = true; + } + catch (Exception e) + { + errorMessage = e.ToString(); + } + finally + { + if (conn.State == ConnectionState.Open) + conn.Close(); + } + } + return result; + } + + + + } +} diff --git a/PrintBarCode/PrintBarCodeForm.Designer.cs b/PrintBarCode/PrintBarCodeForm.Designer.cs new file mode 100644 index 0000000..46560da --- /dev/null +++ b/PrintBarCode/PrintBarCodeForm.Designer.cs @@ -0,0 +1,261 @@ +namespace PrintBarCode +{ + partial class PrintBarCodeForm + { + /// + /// 必需的设计器变量。 + /// + 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.label1 = new System.Windows.Forms.Label(); + this.comboBox_PartNNo = new System.Windows.Forms.ComboBox(); + this.label2 = new System.Windows.Forms.Label(); + this.numericUpDown_Count = new System.Windows.Forms.NumericUpDown(); + this.numericUpDown_BeginNumber = new System.Windows.Forms.NumericUpDown(); + this.label3 = new System.Windows.Forms.Label(); + this.listBox1 = new System.Windows.Forms.ListBox(); + this.button_Print = new System.Windows.Forms.Button(); + this.button_PreView = new System.Windows.Forms.Button(); + this.dateTimePicker1 = new System.Windows.Forms.DateTimePicker(); + this.button_M_SnOne = new System.Windows.Forms.Button(); + this.textBox_SN = new System.Windows.Forms.TextBox(); + this.label4 = new System.Windows.Forms.Label(); + this.label5 = new System.Windows.Forms.Label(); + this.button_SaveToProductPlan = new System.Windows.Forms.Button(); + ((System.ComponentModel.ISupportInitialize)(this.numericUpDown_Count)).BeginInit(); + ((System.ComponentModel.ISupportInitialize)(this.numericUpDown_BeginNumber)).BeginInit(); + this.SuspendLayout(); + // + // label1 + // + this.label1.AutoSize = true; + this.label1.Location = new System.Drawing.Point(29, 35); + this.label1.Name = "label1"; + this.label1.Size = new System.Drawing.Size(41, 12); + this.label1.TabIndex = 0; + this.label1.Text = "零件号"; + // + // comboBox_PartNNo + // + this.comboBox_PartNNo.FormattingEnabled = true; + this.comboBox_PartNNo.Location = new System.Drawing.Point(90, 32); + this.comboBox_PartNNo.Name = "comboBox_PartNNo"; + this.comboBox_PartNNo.Size = new System.Drawing.Size(219, 20); + this.comboBox_PartNNo.TabIndex = 1; + this.comboBox_PartNNo.Text = "1335 001 016"; + // + // label2 + // + this.label2.AutoSize = true; + this.label2.Location = new System.Drawing.Point(332, 35); + this.label2.Name = "label2"; + this.label2.Size = new System.Drawing.Size(29, 12); + this.label2.TabIndex = 0; + this.label2.Text = "数量"; + // + // numericUpDown_Count + // + this.numericUpDown_Count.Location = new System.Drawing.Point(368, 30); + this.numericUpDown_Count.Maximum = new decimal(new int[] { + 10000, + 0, + 0, + 0}); + this.numericUpDown_Count.Minimum = new decimal(new int[] { + 1, + 0, + 0, + 0}); + this.numericUpDown_Count.Name = "numericUpDown_Count"; + this.numericUpDown_Count.Size = new System.Drawing.Size(120, 21); + this.numericUpDown_Count.TabIndex = 2; + this.numericUpDown_Count.Value = new decimal(new int[] { + 10, + 0, + 0, + 0}); + // + // numericUpDown_BeginNumber + // + this.numericUpDown_BeginNumber.Location = new System.Drawing.Point(90, 69); + this.numericUpDown_BeginNumber.Maximum = new decimal(new int[] { + 1000000000, + 0, + 0, + 0}); + this.numericUpDown_BeginNumber.Minimum = new decimal(new int[] { + 1, + 0, + 0, + 0}); + this.numericUpDown_BeginNumber.Name = "numericUpDown_BeginNumber"; + this.numericUpDown_BeginNumber.Size = new System.Drawing.Size(219, 21); + this.numericUpDown_BeginNumber.TabIndex = 2; + this.numericUpDown_BeginNumber.Value = new decimal(new int[] { + 30000001, + 0, + 0, + 0}); + // + // label3 + // + this.label3.AutoSize = true; + this.label3.Location = new System.Drawing.Point(29, 78); + this.label3.Name = "label3"; + this.label3.Size = new System.Drawing.Size(53, 12); + this.label3.TabIndex = 0; + this.label3.Text = "开始号码"; + // + // listBox1 + // + this.listBox1.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed; + this.listBox1.FormattingEnabled = true; + this.listBox1.Location = new System.Drawing.Point(31, 137); + this.listBox1.Name = "listBox1"; + this.listBox1.ScrollAlwaysVisible = true; + this.listBox1.Size = new System.Drawing.Size(457, 290); + this.listBox1.TabIndex = 3; + this.listBox1.DrawItem += new System.Windows.Forms.DrawItemEventHandler(this.listBox1_DrawItem); + this.listBox1.SelectedIndexChanged += new System.EventHandler(this.listBox1_SelectedIndexChanged); + // + // button_Print + // + this.button_Print.Location = new System.Drawing.Point(545, 327); + this.button_Print.Name = "button_Print"; + this.button_Print.Size = new System.Drawing.Size(149, 91); + this.button_Print.TabIndex = 4; + this.button_Print.Text = "打印条码"; + this.button_Print.UseVisualStyleBackColor = true; + this.button_Print.Click += new System.EventHandler(this.button_Print_Click); + // + // button_PreView + // + this.button_PreView.Location = new System.Drawing.Point(368, 69); + this.button_PreView.Name = "button_PreView"; + this.button_PreView.Size = new System.Drawing.Size(120, 23); + this.button_PreView.TabIndex = 5; + this.button_PreView.Text = "预览"; + this.button_PreView.UseVisualStyleBackColor = true; + this.button_PreView.Click += new System.EventHandler(this.button_PreView_Click); + // + // dateTimePicker1 + // + this.dateTimePicker1.Location = new System.Drawing.Point(582, 29); + this.dateTimePicker1.Name = "dateTimePicker1"; + this.dateTimePicker1.Size = new System.Drawing.Size(138, 21); + this.dateTimePicker1.TabIndex = 6; + // + // button_M_SnOne + // + this.button_M_SnOne.Location = new System.Drawing.Point(545, 137); + this.button_M_SnOne.Name = "button_M_SnOne"; + this.button_M_SnOne.Size = new System.Drawing.Size(149, 91); + this.button_M_SnOne.TabIndex = 4; + this.button_M_SnOne.Text = "手动单条打印条码"; + this.button_M_SnOne.UseVisualStyleBackColor = true; + this.button_M_SnOne.Click += new System.EventHandler(this.button_M_SnOne_Click); + // + // textBox_SN + // + this.textBox_SN.Location = new System.Drawing.Point(90, 101); + this.textBox_SN.Name = "textBox_SN"; + this.textBox_SN.Size = new System.Drawing.Size(398, 21); + this.textBox_SN.TabIndex = 7; + // + // label4 + // + this.label4.AutoSize = true; + this.label4.Location = new System.Drawing.Point(29, 104); + this.label4.Name = "label4"; + this.label4.Size = new System.Drawing.Size(41, 12); + this.label4.TabIndex = 0; + this.label4.Text = "序列号"; + // + // label5 + // + this.label5.AutoSize = true; + this.label5.Location = new System.Drawing.Point(513, 35); + this.label5.Name = "label5"; + this.label5.Size = new System.Drawing.Size(53, 12); + this.label5.TabIndex = 0; + this.label5.Text = "生产日期"; + // + // button_SaveToProductPlan + // + this.button_SaveToProductPlan.Location = new System.Drawing.Point(582, 66); + this.button_SaveToProductPlan.Name = "button_SaveToProductPlan"; + this.button_SaveToProductPlan.Size = new System.Drawing.Size(138, 23); + this.button_SaveToProductPlan.TabIndex = 8; + this.button_SaveToProductPlan.Text = "保存到生产计划"; + this.button_SaveToProductPlan.UseVisualStyleBackColor = true; + // + // Form1 + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(741, 450); + this.Controls.Add(this.button_SaveToProductPlan); + this.Controls.Add(this.textBox_SN); + this.Controls.Add(this.dateTimePicker1); + this.Controls.Add(this.button_PreView); + this.Controls.Add(this.button_M_SnOne); + this.Controls.Add(this.button_Print); + this.Controls.Add(this.listBox1); + this.Controls.Add(this.numericUpDown_BeginNumber); + this.Controls.Add(this.numericUpDown_Count); + this.Controls.Add(this.comboBox_PartNNo); + this.Controls.Add(this.label4); + this.Controls.Add(this.label3); + this.Controls.Add(this.label2); + this.Controls.Add(this.label5); + this.Controls.Add(this.label1); + this.Name = "Form1"; + this.Text = "打印变速器序列号条码"; + ((System.ComponentModel.ISupportInitialize)(this.numericUpDown_Count)).EndInit(); + ((System.ComponentModel.ISupportInitialize)(this.numericUpDown_BeginNumber)).EndInit(); + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private System.Windows.Forms.Label label1; + private System.Windows.Forms.ComboBox comboBox_PartNNo; + private System.Windows.Forms.Label label2; + private System.Windows.Forms.NumericUpDown numericUpDown_Count; + private System.Windows.Forms.NumericUpDown numericUpDown_BeginNumber; + private System.Windows.Forms.Label label3; + private System.Windows.Forms.ListBox listBox1; + private System.Windows.Forms.Button button_Print; + private System.Windows.Forms.Button button_PreView; + private System.Windows.Forms.DateTimePicker dateTimePicker1; + private System.Windows.Forms.Button button_M_SnOne; + private System.Windows.Forms.TextBox textBox_SN; + private System.Windows.Forms.Label label4; + private System.Windows.Forms.Label label5; + private System.Windows.Forms.Button button_SaveToProductPlan; + } +} + diff --git a/PrintBarCode/PrintBarCodeForm.cs b/PrintBarCode/PrintBarCodeForm.cs new file mode 100644 index 0000000..71077c0 --- /dev/null +++ b/PrintBarCode/PrintBarCodeForm.cs @@ -0,0 +1,214 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel; +using System.Configuration; +using System.Data; +using System.Data.SqlClient; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace PrintBarCode +{ + public partial class PrintBarCodeForm : Form + { + public static string ConnectString_MES = ConfigurationManager.AppSettings["ConnectionString_MES"]; + Hashtable hsSnIsPrinted = new Hashtable (); + bool IsSnIsPrintedOK=true; + public PrintBarCodeForm() + { + InitializeComponent(); + dateTimePicker1.Value= DateTime.Now; + + } + + private void button_Print_Click(object sender, EventArgs e) + { + string partNo; + int partCount; + int beginNumber; + DateTime proDate; + + partNo = comboBox_PartNNo.Text; + partCount =(int) numericUpDown_Count.Value; + beginNumber = (int)numericUpDown_BeginNumber.Value; + proDate = dateTimePicker1.Value; + if(listBox1.Items.Count<1) + { + MessageBox.Show("请先点击变速器序列号预览按钮"); + return; + } + if(!IsSnIsPrintedOK) + { + MessageBox.Show("变速器序列号有重复打印的,请选择手动方式打印"); + return; + } + PrintLogInset(partNo, partCount, beginNumber, proDate); + + //InitLiatBox1(); + PrintSnList(); + + + } + + + private void PrintSnList() + { + + + foreach(var sn in listBox1.Items) + { + PrintSnToPrinter(sn.ToString()); + } + + } + + + + private void PrintSnToPrinter(string sn) + { + + string partNo; + int partCount; + int beginNumber; + DateTime proDate; + + partNo = comboBox_PartNNo.Text; + partCount = (int)numericUpDown_Count.Value; + beginNumber = (int)numericUpDown_BeginNumber.Value; + proDate = dateTimePicker1.Value; + + if (IsSnIsCanPrinted(sn.ToString())) + { + PrintBarCode(sn.ToString()); + PrintSnInset(sn.ToString(), partNo, partCount, beginNumber, proDate); + + } + else + { + if (MessageBox.Show("变速器序列号已经打印过", "变速器序列号已经打印过,是否重复打印", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) + { + PrintBarCode(sn.ToString()); + PrintSnUpdate(sn.ToString(), partNo, partCount, beginNumber, proDate); + } + + } + + } + + + private void PrintBarCode(string barCode) { } + private void InitLiatBox1() + { + string partNo; + int partCount; + int beginNumber; + DateTime proDate; + + partNo = comboBox_PartNNo.Text; + partCount = (int)numericUpDown_Count.Value; + beginNumber = (int)numericUpDown_BeginNumber.Value; + proDate = dateTimePicker1.Value; + + List list = CreatePartList(partNo, partCount, beginNumber, proDate); + hsSnIsPrinted.Clear(); + listBox1.Items.Clear(); + foreach (var item in list) + { + listBox1.Items.Add(item); + if(!IsSnIsCanPrinted(item)) + { + IsSnIsPrintedOK = false; + } + int count; + count = PrintSnIsPrinted(item); + hsSnIsPrinted.Add(item, count); + } + } + + private bool IsSnIsCanPrinted(string sn) + { + int count; + count = PrintSnIsPrinted(sn); + if (count > 0) + { + IsSnIsPrintedOK = false; + return false; + } + return true; + } + private List CreatePartList(string partNo, int partCount, int beginNumber, DateTime proDate) + { + List list = new List(); + string proDateString; + string sn; + proDateString = proDate.ToString("ddMMyyyy"); + for(int i = beginNumber;i< beginNumber+ partCount;i++) + { + sn = i.ToString("00000000"); + + list.Add(partNo + "*" + proDateString + "*" + sn); + } + + return list; + + } + + + private void button_PreView_Click(object sender, EventArgs e) + { + InitLiatBox1(); + + } + + private void listBox1_DrawItem(object sender, DrawItemEventArgs e) + { + e.DrawBackground(); //先调用基类实现 + + if (e.Index < 0) //form load 的时候return + + return; + int count = Convert.ToInt32( hsSnIsPrinted[listBox1.Items[e.Index].ToString()]); + if(count > 0 ) { + + e.Graphics.DrawString(listBox1.Items[e.Index].ToString(), + + e.Font, Brushes.Red, e.Bounds); + } + else + { + e.Graphics.DrawString(listBox1.Items[e.Index].ToString(), + + e.Font, Brushes.Black, e.Bounds); + } + + + } + + private void listBox1_SelectedIndexChanged(object sender, EventArgs e) + { + //form load 的时候return + string item; + item = ((ListBox) sender).SelectedItem.ToString(); + textBox_SN.Text = item; + } + + private void button_M_SnOne_Click(object sender, EventArgs e) + { + string sn; + sn = textBox_SN.Text; + if(sn.Length > 10) + { + PrintSnToPrinter(sn); + } + else + { + MessageBox.Show("请选择打印条码变速器序列号"); + } + + } + } +} diff --git a/PrintBarCode/PrintBarCodeForm.resx b/PrintBarCode/PrintBarCodeForm.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/PrintBarCode/PrintBarCodeForm.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/PrintBarCode/Program.cs b/PrintBarCode/Program.cs new file mode 100644 index 0000000..97d51a5 --- /dev/null +++ b/PrintBarCode/Program.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace PrintBarCode +{ + internal static class Program + { + /// + /// 应用程序的主入口点。 + /// + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + Application.Run(new PrintBarCodeForm()); + } + } +} diff --git a/PrintBarCode/Properties/AssemblyInfo.cs b/PrintBarCode/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..705be34 --- /dev/null +++ b/PrintBarCode/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// 有关程序集的一般信息由以下 +// 控制。更改这些特性值可修改 +// 与程序集关联的信息。 +[assembly: AssemblyTitle("PrintBarCode")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("PrintBarCode")] +[assembly: AssemblyCopyright("Copyright © 2023")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// 将 ComVisible 设置为 false 会使此程序集中的类型 +//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型 +//请将此类型的 ComVisible 特性设置为 true。 +[assembly: ComVisible(false)] + +// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID +[assembly: Guid("269c9cbc-4958-4e4d-b43b-307c1d09d87f")] + +// 程序集的版本信息由下列四个值组成: +// +// 主版本 +// 次版本 +// 生成号 +// 修订号 +// +//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值 +//通过使用 "*",如下所示: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/PrintBarCode/Properties/Resources.Designer.cs b/PrintBarCode/Properties/Resources.Designer.cs new file mode 100644 index 0000000..cca1fdd --- /dev/null +++ b/PrintBarCode/Properties/Resources.Designer.cs @@ -0,0 +1,63 @@ +//------------------------------------------------------------------------------ +// +// 此代码由工具生成。 +// 运行时版本:4.0.30319.42000 +// +// 对此文件的更改可能会导致不正确的行为,并且如果 +// 重新生成代码,这些更改将会丢失。 +// +//------------------------------------------------------------------------------ + +namespace PrintBarCode.Properties { + using System; + + + /// + /// 一个强类型的资源类,用于查找本地化的字符串等。 + /// + // 此类是由 StronglyTypedResourceBuilder + // 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。 + // 若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen + // (以 /str 作为命令选项),或重新生成 VS 项目。 + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.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 (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("PrintBarCode.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/PrintBarCode/Properties/Resources.resx b/PrintBarCode/Properties/Resources.resx new file mode 100644 index 0000000..af7dbeb --- /dev/null +++ b/PrintBarCode/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/PrintBarCode/Properties/Settings.Designer.cs b/PrintBarCode/Properties/Settings.Designer.cs new file mode 100644 index 0000000..1695d43 --- /dev/null +++ b/PrintBarCode/Properties/Settings.Designer.cs @@ -0,0 +1,26 @@ +//------------------------------------------------------------------------------ +// +// 此代码由工具生成。 +// 运行时版本:4.0.30319.42000 +// +// 对此文件的更改可能会导致不正确的行为,并且如果 +// 重新生成代码,这些更改将会丢失。 +// +//------------------------------------------------------------------------------ + +namespace PrintBarCode.Properties { + + + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "17.0.3.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/PrintBarCode/Properties/Settings.settings b/PrintBarCode/Properties/Settings.settings new file mode 100644 index 0000000..3964565 --- /dev/null +++ b/PrintBarCode/Properties/Settings.settings @@ -0,0 +1,7 @@ + + + + + + + diff --git a/SyUpLoad/SyUpLoad.sln b/SyUpLoad/SyUpLoad.sln new file mode 100644 index 0000000..1cce0b7 --- /dev/null +++ b/SyUpLoad/SyUpLoad.sln @@ -0,0 +1,73 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.32602.291 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SyUpLoad", "SyUpLoad\SyUpLoad.csproj", "{81604748-73C5-43FA-8E27-BE0AB28618C3}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "00-0Json8.3.1", "..\Common\00-1Json8.3\Json8.3\00-0Json8.3.1.csproj", "{1A10FDB2-1A6A-44A8-AB4D-33387563247E}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "00MesWorkMqtt", "..\Common\00MesWorkMqtt\MesWorkMqtt\00MesWorkMqtt.csproj", "{F55DA1A0-A982-4479-8C47-0D9A5AAF3E18}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "01_01DoWhatPlc", "..\Common\01DoWhatPlc\01_01DoWhatPlc.csproj", "{0D1AF432-439A-4920-8692-43AE139F5530}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "02_02WebApiCallPLC", "..\Common\02WebApiCall\02_02WebApiCallPLC.csproj", "{3E6D1DD5-01C9-435F-9941-61F906CE35BB}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "04-DataBaseAccess", "..\Common\04DataBaseAccess\DataBaseAccess\04-DataBaseAccess.csproj", "{F434E066-4C59-47C8-AA82-6F48CC84501A}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "07BusinessFacade", "..\Common\07WebBusinessFacade\BusinessFacade\07BusinessFacade.csproj", "{F0A0C525-03FD-428A-9B17-7F54AA0E4475}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "08-WebFun_base", "..\Common\08WebFun_base\WebFun_base\08-WebFun_base.csproj", "{D98BE764-ADEB-488D-9714-61E308AA8201}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "09-MesDataFunction", "..\Common\09MesDataFunction\MesDataFunction\09-MesDataFunction.csproj", "{90E76FB4-646D-45E2-95DB-0B8AB4E465D6}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {81604748-73C5-43FA-8E27-BE0AB28618C3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {81604748-73C5-43FA-8E27-BE0AB28618C3}.Debug|Any CPU.Build.0 = Debug|Any CPU + {81604748-73C5-43FA-8E27-BE0AB28618C3}.Release|Any CPU.ActiveCfg = Release|Any CPU + {81604748-73C5-43FA-8E27-BE0AB28618C3}.Release|Any CPU.Build.0 = Release|Any CPU + {1A10FDB2-1A6A-44A8-AB4D-33387563247E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {1A10FDB2-1A6A-44A8-AB4D-33387563247E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {1A10FDB2-1A6A-44A8-AB4D-33387563247E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {1A10FDB2-1A6A-44A8-AB4D-33387563247E}.Release|Any CPU.Build.0 = Release|Any CPU + {F55DA1A0-A982-4479-8C47-0D9A5AAF3E18}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F55DA1A0-A982-4479-8C47-0D9A5AAF3E18}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F55DA1A0-A982-4479-8C47-0D9A5AAF3E18}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F55DA1A0-A982-4479-8C47-0D9A5AAF3E18}.Release|Any CPU.Build.0 = Release|Any CPU + {0D1AF432-439A-4920-8692-43AE139F5530}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {0D1AF432-439A-4920-8692-43AE139F5530}.Debug|Any CPU.Build.0 = Debug|Any CPU + {0D1AF432-439A-4920-8692-43AE139F5530}.Release|Any CPU.ActiveCfg = Release|Any CPU + {0D1AF432-439A-4920-8692-43AE139F5530}.Release|Any CPU.Build.0 = Release|Any CPU + {3E6D1DD5-01C9-435F-9941-61F906CE35BB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {3E6D1DD5-01C9-435F-9941-61F906CE35BB}.Debug|Any CPU.Build.0 = Debug|Any CPU + {3E6D1DD5-01C9-435F-9941-61F906CE35BB}.Release|Any CPU.ActiveCfg = Release|Any CPU + {3E6D1DD5-01C9-435F-9941-61F906CE35BB}.Release|Any CPU.Build.0 = Release|Any CPU + {F434E066-4C59-47C8-AA82-6F48CC84501A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F434E066-4C59-47C8-AA82-6F48CC84501A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F434E066-4C59-47C8-AA82-6F48CC84501A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F434E066-4C59-47C8-AA82-6F48CC84501A}.Release|Any CPU.Build.0 = Release|Any CPU + {F0A0C525-03FD-428A-9B17-7F54AA0E4475}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F0A0C525-03FD-428A-9B17-7F54AA0E4475}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F0A0C525-03FD-428A-9B17-7F54AA0E4475}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F0A0C525-03FD-428A-9B17-7F54AA0E4475}.Release|Any CPU.Build.0 = Release|Any CPU + {D98BE764-ADEB-488D-9714-61E308AA8201}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {D98BE764-ADEB-488D-9714-61E308AA8201}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D98BE764-ADEB-488D-9714-61E308AA8201}.Release|Any CPU.ActiveCfg = Release|Any CPU + {D98BE764-ADEB-488D-9714-61E308AA8201}.Release|Any CPU.Build.0 = Release|Any CPU + {90E76FB4-646D-45E2-95DB-0B8AB4E465D6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {90E76FB4-646D-45E2-95DB-0B8AB4E465D6}.Debug|Any CPU.Build.0 = Debug|Any CPU + {90E76FB4-646D-45E2-95DB-0B8AB4E465D6}.Release|Any CPU.ActiveCfg = Release|Any CPU + {90E76FB4-646D-45E2-95DB-0B8AB4E465D6}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {AC76E79B-C576-4AF6-889E-57D1B50CC4F4} + EndGlobalSection +EndGlobal diff --git a/SyUpLoad/SyUpLoad/App.config b/SyUpLoad/SyUpLoad/App.config new file mode 100644 index 0000000..877bfae --- /dev/null +++ b/SyUpLoad/SyUpLoad/App.config @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/SyUpLoad/SyUpLoad/BarCode/MESPC.BarCode.Read.cs b/SyUpLoad/SyUpLoad/BarCode/MESPC.BarCode.Read.cs new file mode 100644 index 0000000..581926c --- /dev/null +++ b/SyUpLoad/SyUpLoad/BarCode/MESPC.BarCode.Read.cs @@ -0,0 +1,325 @@ +using System; +using System.Collections; +using System.Runtime.InteropServices; +using System.Drawing; +using System.ComponentModel; +using System.Windows.Forms; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Data; +using System.Net; +using System.IO; + +using System.IO.Ports; + +using System.Collections.Generic; +using System.Text; + +using System.Threading; + + +namespace SyUpLoad +{ + partial class PartLoad + { + /// + /// DataReceivedɨǹ뵽 + /// BarCode(string barCode) + /// + /// + public delegate void BarCodeInvoke(string barCode); + /// + /// BarCode(string barCode) + /// DataReceivedɨǹ뵽 + /// + BarCodeInvoke barCodeInvoke; + + + /// + /// ǰɨǹ + /// 1:ֳ֣2̶ + /// + string ScannerType_Current = "1"; + + //ֳɨǹ + private System.IO.Ports.SerialPort serialPort1 = new SerialPort(); + /// + /// ʼCOMͨѶ + /// + public void SetCOM() + { + try + { + //ѡɨǹ + barCodeInvoke = new BarCodeInvoke(BarCode); + SetCOM1(); + } + catch (Exception err) + { + // ApplicationLog.WriteLog(err, err.Message); + } + } + /// + /// ʼCOMͨѶ + /// + public void SetCOM1() + { + try + { + //if (ApplicationConfig.PortName.Length < 3) + //{ + // return; + //} + serialPort1.PortName = PortName; //˿ں + serialPort1.BaudRate = BaudRate; //ʣĬΪ9600 + serialPort1.Parity = Parity.None;//żУ + serialPort1.StopBits = StopBits.One;//ֹͣλ + serialPort1.ReadTimeout = ReadTimeout; //ʱ1000δݾʱ쳣 + serialPort1.DtrEnable = true; + serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived); + + OpenSerialPort(); + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, err.Message); + } + finally + { + + } + } + + /// + /// رɨǹ + /// + private void OpenSerialPortAll() + { + SetCOM1(); + } + /// + /// ɨǹ + /// + private bool OpenSerialPort() + { + try + { + //if (ApplicationConfig.PortName.Length < 4) + //{ + // return true; + //} + if (serialPort1 == null) return true; + if (!serialPort1.IsOpen) + { + serialPort1.Open(); + SerialPort_Closing = false; + } + return true; + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, err.Message); + return false; + } + } + /// + /// رɨǹ + /// + private bool CloseSerialPort() + { + try + { + //if (ApplicationConfig.PortName.Length < 4) + //{ + // return true; + //} + if (serialPort1 == null) return true; + + //ݵǰڶжϲ + if (serialPort1.IsOpen) + { + SerialPort_Closing = true; + while (SerialPort_Listening) Application.DoEvents(); + serialPort1.Close(); + } + return true; + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, "CloseSerialPort"); + return false; + } + } + /// + /// رɨǹ + /// + private void CloseSerialPortAll() + { + CloseSerialPort(); + } + /// + /// Ƿûִinvokeز + /// + private bool SerialPort_Listening = false; + /// + /// ǷڹرմڣִApplication.DoEvents + /// + private bool SerialPort_Closing = false; + /// + /// ֳɨǹ + /// ߸׸߹λɨǹǹ̶ɨǹF102 + /// + /// + /// + void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e) + { + //byte[] readBuf; + //int HowTime = ApplicationConfig.HowTime; + //int ByteTime = ApplicationConfig.ByteTime; + string barCode; + //ȡһֵֵڴͨŹն˾ (DTR) źš + //Ϊ trueն˾ (DTR)Ϊ falseĬΪ false + bool DtrEnable = serialPort1.DtrEnable; + //ѽþźŷ͵ö˿ڣΪ trueΪ false + bool DsrHolding = serialPort1.DsrHolding; + //˿ڴж״̬Ϊ trueΪ false + bool BreakState = serialPort1.BreakState; ; + + if (SerialPort_Closing) return; + //ڹرգԲֱӷأ ɴڼ̵߳һѭ + try + { + //ñǣ˵ѾʼݣһҪʹϵͳUIġ + SerialPort_Listening = true; + //20110225 zhangji + //ȡɨǹϢʱʱ޷ȫȡɨϢ + Thread.Sleep(200); + int n = serialPort1.BytesToRead; + byte[] buf = new byte[n]; + //һʱ洢ǰĴ + serialPort1.Read(buf, 0, n); + n = n - ScannerTrim; + barCode = Encoding.UTF8.GetString(buf, 0, n); + BeginInvoke(barCodeInvoke, new Object[] { barCode }); + } + catch (Exception err) + { + + barCode = ""; + //ApplicationLog.WriteLog(err, err.Message); + } + finally + { + //ɨǹ + serialPort1.DiscardInBuffer(); + SerialPort_Listening = false;//ˣuiԹرմˡ + + //ȹرմڣȻٴ򿪴 + CloseSerialPort(); + OpenSerialPort(); + } + } + + /// + /// ַתַ16 + /// + /// ֽ + /// "01 02 0F" + public static string ByteToString(byte[] InBytes) + { + string StringOut = ""; + foreach (byte InByte in InBytes) + { + StringOut = StringOut + String.Format("{0:X2}", InByte) + " "; + } + + return StringOut.Trim(); + } + /// + /// strhex תֽ + /// + /// "01 02 0F" ÿոֿ + /// + public static byte[] StringToByte_Int(string InString) + { + string[] ByteStrings; + ByteStrings = InString.Split("|".ToCharArray()); + byte[] ByteOut; + ByteOut = new byte[ByteStrings.Length]; + try + { + for (int i = 0; i <= ByteStrings.Length - 1; i++) + { + ByteOut[i] = byte.Parse(ByteStrings[i]); + } + } + catch (Exception err) + { + + //ApplicationLog.WriteLog(err, err.Message); + } + return ByteOut; + } + /// + /// strhex תֽ + /// + /// "01 02 0F" ÿոֿ + /// + public static byte[] StringToByte(string InString) + { + string[] ByteStrings; + ByteStrings = InString.Split(" ".ToCharArray()); + byte[] ByteOut; + ByteOut = new byte[ByteStrings.Length]; + for (int i = 0; i <= ByteStrings.Length - 1; i++) + { + ByteOut[i] = byte.Parse(ByteStrings[i], System.Globalization.NumberStyles.HexNumber); + } + return ByteOut; + } + + /// + /// strhex תֽ + /// + /// "01 02 0F" м޿ո + /// + public static byte[] StringToByte_2(string InString) + { + byte[] ByteOut; + InString = InString.Replace(" ", ""); + try + { + string[] ByteStrings = new string[InString.Length / 2]; + int j = 0; + for (int i = 0; i < ByteStrings.Length; i++) + { + + ByteStrings[i] = InString.Substring(j, 2); + j += 2; + } + + ByteOut = new byte[ByteStrings.Length]; + for (int i = 0; i <= ByteStrings.Length - 1; i++) + { + ByteOut[i] = byte.Parse(ByteStrings[i], System.Globalization.NumberStyles.HexNumber); + } + } + catch (Exception ex) + { + + throw new Exception(ex.Message); + } + + return ByteOut; + } + /// + /// ַ ת16ַ + /// + /// unico + /// ơ01 0f + public static string Str_To_0X(string InString) + { + return ByteToString(UnicodeEncoding.Default.GetBytes(InString)); + } + } +} diff --git a/SyUpLoad/SyUpLoad/BarCode/MESPC.BarCode.cs b/SyUpLoad/SyUpLoad/BarCode/MESPC.BarCode.cs new file mode 100644 index 0000000..27c2cc2 --- /dev/null +++ b/SyUpLoad/SyUpLoad/BarCode/MESPC.BarCode.cs @@ -0,0 +1,57 @@ +using System; +using System.Collections; +using System.Runtime.InteropServices; +using System.Drawing; +using System.ComponentModel; +using System.Windows.Forms; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Data; +using System.Net; +using System.IO; + +using System.IO.Ports; + +using System.Collections.Generic; +using System.Text; + +using System.Threading; +using System.Configuration; + +namespace SyUpLoad +{ + /// + /// 扫描枪 + /// + partial class PartLoad + { + string PortName = ConfigurationManager.AppSettings["PortName"]; + int ReadTimeout = Convert.ToInt32( ConfigurationManager.AppSettings["ReadTimeout"]); + int BaudRate = Convert.ToInt32(ConfigurationManager.AppSettings["BaudRate"]); + int ScannerTrim = Convert.ToInt32(ConfigurationManager.AppSettings["ScannerTrim"]); + + + /// + /// 处理条码信息 + /// + /// + private void BarCode(string barCode) + { + try + { + barCode = barCode.Replace("\r\n", ""); + textBox_barcode.Text = barCode; + + button_barcode_Click(null, null); + //string sendStr = "BarCode|Bar|" + ApplicationConfig.OpName + "|" + barCode; + //发送UDP到MES通讯服务器 + //ApplicationLog.WriteLog("11111111111111"); + //asySendMessage(sendStr); + } + catch (Exception err) + { + // ApplicationLog.WriteLog(err, "BarCode"); + } + } + } +} diff --git a/SyUpLoad/SyUpLoad/BarCode/_system~.ini b/SyUpLoad/SyUpLoad/BarCode/_system~.ini new file mode 100644 index 0000000..e69de29 diff --git a/SyUpLoad/SyUpLoad/Fun1.EngineTypeGetOverPLC.cs b/SyUpLoad/SyUpLoad/Fun1.EngineTypeGetOverPLC.cs new file mode 100644 index 0000000..1bb5cc3 --- /dev/null +++ b/SyUpLoad/SyUpLoad/Fun1.EngineTypeGetOverPLC.cs @@ -0,0 +1,174 @@ +using bizFacade; +using MesServerWork; +using System; +using System.Collections.Generic; +using System.Data; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace SyUpLoad +{ + class SyUpLoadFun1 + { + public static void MesServerFunction(string msgValue) + { + try + { + DoWhatPlc.ReturnValueString rv = Newtonsoft.Json.JsonConvert.DeserializeObject(msgValue); + + string OpName; + string tagValue; + string fun; + string mesServerCode; + string mesServerdllName; + + OpName = rv.OpName; + switch (rv.TagValue.ToLower()) + { + case "false": + tagValue = "0"; + break; + case "true": + tagValue = "1"; + break; + default: + tagValue = rv.TagValue; + break; + } + switch (rv.TagTypeCodeID) + { + //PLC 申请发动机编号 PartLoad + case "43": + PartLoad(OpName, tagValue); + break; + //PLC 传递机型 EngineTypeGetOverPLC + case "44": + EngineTypeGetOverPLC(OpName, tagValue); + break; + + + } + + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "MesServerFunction"); + } + } + + /// + /// MES将盆子码(DB24-63)[74]、小车号(DBB20)[112]、机型代码(DBB22)[73]、机型(DBB64-103)[75]信息写到交互DB块中 + /// (DBX0.1=1)[5] MES传递机型 + /// + public static void PartLoad(string OpName,string tagValue) + { + //获得 盆子码(发动机号)、小车号、机型代码、机型 + try + { + + + + int engineTypeID; + string engineID; + string engineType; + byte kuweiNum; + if (tagValue == "1") + { + // BaseDataSystemMES.MesServer_Process_EngineTypeOver(OpName); + DataTable dt; + BaseDataSystemMES.GetUpLoadBarCodeEngineID(OpName, out dt); + if (dt.Rows.Count < 1) + { + + //button_ManualPartLoad.Invoke(new Action(() => { + // button_ManualPartLoad.Enabled = true; + //})); + MessageBox.Show("虚拟库存无件,请扫描上线工位小车上的工件条码"); + return; + } + engineTypeID = Convert.ToInt32(dt.Rows[0]["机型代码"]); + engineID = dt.Rows[0]["发动机号"].ToString(); + engineType = dt.Rows[0]["发动机型号"].ToString(); + kuweiNum = Convert.ToByte(dt.Rows[0]["库位号"]); + string OrderForm = dt.Rows[0]["订单号"].ToString(); + MIS_BASE.Read_PalletCode(OpName, out int PartPallet_Code); + + //BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, OrderForm, engineTypeID, engineType, engineID, PartPallet_Code, 0, 0, ""); + + + ////将产品信息写入PLC + MIS_BASE.Write_EngineTypeID_MES(OpName, engineTypeID); + MIS_BASE.Write_EngineType_MES(OpName, engineType); + MIS_BASE.Write_EngineID_MES(OpName, engineID); + DtWebApi.ReadWritePLC.WritePLC("112", OpName, kuweiNum); + + MIS_BASE.Write_EngineTypeGetOver_MES(OpName, true); + } + + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function03:PartLoad"); + } + } + /// + /// 44 + /// 1 : 保存数据 + /// 0 :复位 + /// + /// + public static void EngineTypeGetOverPLC(string opName,string tagValue) + { + switch (tagValue) + { + case "0": + MIS_BASE.Write_EngineTypeGetOver_MES(opName, false); + MIS_BASE.Write_MaterialVerifyOver(opName, false); + break; + case "1": + //string opName; + string orderForm=""; + int PartPalletCode; + string engineType; + int engineTypeID; + string engineID; + string barCodeType="1"; + + // BaseDataSystemMES.MesServer_Process_EngineTypeOver(OpName); + + ////将产品信息从PLC读取 + MIS_BASE.Read_EngineTypeID(opName,out engineTypeID); + MIS_BASE.Read_EngineType(opName, out engineType); + MIS_BASE.Read_EngineID(opName, out engineID); + MIS_BASE.Read_PalletCode(opName, out PartPalletCode); + string kuweiNum = DtWebApi.ReadWritePLC.ReadPLC("112", opName).ToString(); + + + BaseDataSystemMES.GetUpLoadEngineIDOrderForm(opName,kuweiNum, out DataTable dt); + if(dt.Rows.Count>0) + { + orderForm = dt.Rows[0]["订单号"].ToString(); + } + + BaseDataSystemMES.OpName_MIS_MOBY_Insert(opName, orderForm, engineTypeID, engineType, engineID, PartPalletCode, 0, 0, ""); + + //MES保存数据 减掉盆子库存 + /// + /// 电子看板_发动机号_线首工位_增加 + /// + /// 工位号 + /// 订单号 + /// 托盘号 + /// 工件机型 + /// 工件机型,机型代码,工件编号, 壳体编号型号,工件流水号,QR码,基本流水号 + BaseDataSystemMES.GetEngineID_Save_Outline(opName, orderForm, PartPalletCode.ToString(), engineType, engineTypeID, engineID, barCodeType); + BaseDataSystemMES.GetUpLoadBarCode_0utUpdate(opName, kuweiNum); + MIS_BASE.Write_MaterialVerifyOver(opName, true); + + break; + } + } + } +} diff --git a/SyUpLoad/SyUpLoad/Fun2.cs b/SyUpLoad/SyUpLoad/Fun2.cs new file mode 100644 index 0000000..f9ac1ed --- /dev/null +++ b/SyUpLoad/SyUpLoad/Fun2.cs @@ -0,0 +1,229 @@ +using bizFacade; +using MesServerWork; +using System; +using System.Collections.Generic; +using System.Data; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace SyUpLoad +{ + class SyUpLoadFun2 + { + public static void MesServerFunction(string msgValue) + { + try + { + DoWhatPlc.ReturnValueString rv = Newtonsoft.Json.JsonConvert.DeserializeObject(msgValue); + + string OpName; + string tagValue; + string fun; + string mesServerCode; + string mesServerdllName; + + OpName = rv.OpName; + switch (rv.TagValue.ToLower()) + { + case "false": + tagValue = "0"; + break; + case "true": + tagValue = "1"; + break; + default: + tagValue = rv.TagValue; + break; + } + switch (rv.TagTypeCodeID) + { + ////PLC 申请发动机编号 PartLoad + //case "43": + // PartLoad(OpName, tagValue); + // break; + ////PLC 传递机型 EngineTypeGetOverPLC + //case "44": + // EngineTypeGetOverPLC(OpName, tagValue); + // break; + //MES 申请下线 PalletDown + case "50": + PalletDown(OpName, tagValue); + break; + } + + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "MesServerFunction"); + } + } + public static void PalletDown(string opName, string tagValue) + { + switch (tagValue) + { + case "0": + DtWebApi.ReadWritePLC.WritePLC("35", opName, false); + + break; + case "1": + //保存数据 + //string opName; + string orderForm = ""; + int PartPalletCode; + string engineType; + int engineTypeID; + string engineID; + string barCodeType = "1"; + + // BaseDataSystemMES.MesServer_Process_EngineTypeOver(OpName); + + ////将产品信息从PLC读取 + MIS_BASE.Read_EngineTypeID(opName, out engineTypeID); + MIS_BASE.Read_EngineType(opName, out engineType); + MIS_BASE.Read_EngineID(opName, out engineID); + MIS_BASE.Read_PalletCode(opName, out PartPalletCode); + string kuweiNum = DtWebApi.ReadWritePLC.ReadPLC("112", opName).ToString(); + + //第一步,查询订单号,保存机型、机型代码、总成号、托盘号、订单号到数据库 + BaseDataSystemMES.GetEngineID_Select(opName, engineID, out DataTable dt); + if (dt != null && dt.Rows.Count > 0) + { + orderForm = Convert.ToString(dt.Rows[0]["订单号"]); + } + //BaseDataSystemMES.GetUpLoadEngineIDOrderForm(opName, kuweiNum, out DataTable dt); + //if (dt.Rows.Count > 0) + //{ + // orderForm = dt.Rows[0]["订单号"].ToString(); + //} + + BaseDataSystemMES.OpName_MIS_MOBY_Insert(opName, orderForm, engineTypeID, engineType, engineID, PartPalletCode, 0, 0, ""); + + + DtWebApi.ReadWritePLC.WritePLC("35", opName, true); + break; + } + } + /// + /// PartLoad(DBX500.3=1)[43] + /// + public static void PartLoad(string OpName,string tagValue) + { + //获得 盆子码(发动机号)、小车号、机型代码、机型 + try + { + int engineTypeID; + string engineID; + string engineType; + string PartCode_engineType; + byte kuweiNum; + if (tagValue == "1") + { + ////将产品信息读PLC + MIS_BASE.Read_EngineTypeID(OpName,out engineTypeID); + MIS_BASE.Read_EngineType(OpName,out engineType); + MIS_BASE.Read_EngineID(OpName,out engineID); + string PartCode1; + string[] PartCodeList = new string[6]; + string PartCode2; + string PartCode3; + string PartCode4; + string PartCode5; + string PartCode6; + PartCodeList[0] = DtWebApi.ReadWritePLC.ReadPLC("2001", OpName).ToString(); + PartCodeList[1] = DtWebApi.ReadWritePLC.ReadPLC("2002", OpName).ToString(); + PartCodeList[2] = DtWebApi.ReadWritePLC.ReadPLC("2003", OpName).ToString(); + PartCodeList[3] = DtWebApi.ReadWritePLC.ReadPLC("2004", OpName).ToString(); + PartCodeList[4] = DtWebApi.ReadWritePLC.ReadPLC("2005", OpName).ToString(); + PartCodeList[5] = DtWebApi.ReadWritePLC.ReadPLC("2006", OpName).ToString(); + int codeID=2007;//2007 2008 2009 2010 2011 2012 + bool IsMath=false; + for (int i = 0; i < PartCodeList.Length; i++) + { + codeID = codeID + i; + //处理字符串 + PartCode_engineType = GetEngineType(PartCodeList[i]); + if (PartCode_engineType != null) + { + if (PartCode_engineType == engineType) + { + DtWebApi.ReadWritePLC.WritePLC(codeID.ToString(), OpName, 1); + IsMath = true; + } + else + { + DtWebApi.ReadWritePLC.WritePLC(codeID.ToString(), OpName, 2); + } + + } + } + + if(IsMath) + { + DtWebApi.ReadWritePLC.WritePLC("2014", OpName, 1); + + } + else + { + DtWebApi.ReadWritePLC.WritePLC("2014", OpName, 2); + + } + } + + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function03:PartLoad"); + } + } + + private static string GetEngineType(string PartCode) + { + return PartCode; + } + /// + /// 44 + /// 1 : 保存数据 + /// 0 :复位 + /// + /// + public static void EngineTypeGetOverPLC(string opName,string tagValue) + { + switch (tagValue) + { + case "0": + DtWebApi.ReadWritePLC.WritePLC("2014", opName, 0); + MIS_BASE.Write_MaterialVerifyOver(opName, false); + break; + case "1": + string engineType; + int engineTypeID; + string engineID; + + string engineType_MES; + int engineTypeID_MES; + string engineID_MES; + // BaseDataSystemMES.MesServer_Process_EngineTypeOver(OpName); + + ////将产品信息从PLC读取 + MIS_BASE.Read_EngineTypeID(opName,out engineTypeID); + MIS_BASE.Read_EngineType(opName, out engineType); + MIS_BASE.Read_EngineID(opName, out engineID); + //将分线数据,汇总到总线 + ////将产品信息从PLC读取 + MIS_BASE.Read_EngineTypeID_MES(opName, out engineTypeID_MES); + MIS_BASE.Read_EngineType_MES(opName, out engineType_MES); + MIS_BASE.Read_EngineID_MES(opName, out engineID_MES); + + //1转移数据到总线 + BaseDataSystemMES.MailLineAndSubLineData_Insert(engineID, engineTypeID, engineType, engineID_MES);//分线上总线数据转移 + + + MIS_BASE.Write_MaterialVerifyOver(opName, true); + + break; + } + } + } +} diff --git a/SyUpLoad/SyUpLoad/Fun3.EngineTypeGetOverPLC.cs b/SyUpLoad/SyUpLoad/Fun3.EngineTypeGetOverPLC.cs new file mode 100644 index 0000000..4343e6a --- /dev/null +++ b/SyUpLoad/SyUpLoad/Fun3.EngineTypeGetOverPLC.cs @@ -0,0 +1,222 @@ +using bizFacade; +using MesServerWork; +using System; +using System.Collections.Generic; +using System.Data; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace SyUpLoad +{ + class SyUpLoadFun3 + { + public static void MesServerFunction(string msgValue) + { + try + { + DoWhatPlc.ReturnValueString rv = Newtonsoft.Json.JsonConvert.DeserializeObject(msgValue); + + string OpName; + string tagValue; + string fun; + string mesServerCode; + string mesServerdllName; + + OpName = rv.OpName; + switch (rv.TagValue.ToLower()) + { + case "false": + tagValue = "0"; + break; + case "true": + tagValue = "1"; + break; + default: + tagValue = rv.TagValue; + break; + } + switch (rv.TagTypeCodeID) + { + //PLC 申请发动机编号 PartLoad + case "43": + PartLoad(OpName, tagValue); + break; + //PLC 传递机型 EngineTypeGetOverPLC + case "44": + EngineTypeGetOverPLC(OpName, tagValue); + break; + //MES 申请下线 PalletDown + case "50": + PalletDown(OpName, tagValue); + break; + + } + + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "MesServerFunction"); + } + } + public static void PalletDown(string opName, string tagValue) + { + switch (tagValue) + { + case "0": + DtWebApi.ReadWritePLC.WritePLC("35", opName, false); + + break; + case "1": + //保存数据 + //string opName; + string orderForm = ""; + int PartPalletCode; + string engineType; + int engineTypeID; + string engineID; + string barCodeType = "1"; + + // BaseDataSystemMES.MesServer_Process_EngineTypeOver(OpName); + + ////将产品信息从PLC读取 + MIS_BASE.Read_EngineTypeID(opName, out engineTypeID); + MIS_BASE.Read_EngineType(opName, out engineType); + MIS_BASE.Read_EngineID(opName, out engineID); + MIS_BASE.Read_PalletCode(opName, out PartPalletCode); + string kuweiNum = DtWebApi.ReadWritePLC.ReadPLC("112", opName).ToString(); + + //第一步,查询订单号,保存机型、机型代码、总成号、托盘号、订单号到数据库 + BaseDataSystemMES.GetEngineID_Select(opName, engineID, out DataTable dt); + if (dt != null && dt.Rows.Count > 0) + { + orderForm = Convert.ToString(dt.Rows[0]["订单号"]); + } + //BaseDataSystemMES.GetUpLoadEngineIDOrderForm(opName, kuweiNum, out DataTable dt); + //if (dt.Rows.Count > 0) + //{ + // orderForm = dt.Rows[0]["订单号"].ToString(); + //} + + BaseDataSystemMES.OpName_MIS_MOBY_Insert(opName, orderForm, engineTypeID, engineType, engineID, PartPalletCode, 0, 0, ""); + + + DtWebApi.ReadWritePLC.WritePLC("35", opName, true); + break; + } + } + /// + /// MES将盆子码(DB24-63)[74]、小车号(DBB20)[112]、机型代码(DBB22)[73]、机型(DBB64-103)[75]信息写到交互DB块中 + /// (DBX0.1=1)[5] MES传递机型 + /// + public static void PartLoad(string OpName,string tagValue) + { + //获得 盆子码(发动机号)、小车号、机型代码、机型 + try + { + + + + int engineTypeID; + string engineID; + string engineType; + byte kuweiNum; + if (tagValue == "1") + { + // BaseDataSystemMES.MesServer_Process_EngineTypeOver(OpName); + DataTable dt; + BaseDataSystemMES.GetUpLoadBarCodeEngineID(OpName, out dt); + if (dt.Rows.Count < 1) + { + + //button_ManualPartLoad.Invoke(new Action(() => { + // button_ManualPartLoad.Enabled = true; + //})); + MessageBox.Show("虚拟库存无件,请扫描上线工位小车上的工件条码"); + return; + } + engineTypeID = Convert.ToInt32(dt.Rows[0]["机型代码"]); + engineID = dt.Rows[0]["发动机号"].ToString(); + engineType = dt.Rows[0]["发动机型号"].ToString(); + kuweiNum = Convert.ToByte(dt.Rows[0]["库位号"]); + string OrderForm = dt.Rows[0]["订单号"].ToString(); + MIS_BASE.Read_PalletCode(OpName, out int PartPallet_Code); + + //BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, OrderForm, engineTypeID, engineType, engineID, PartPallet_Code, 0, 0, ""); + + + ////将产品信息写入PLC + MIS_BASE.Write_EngineTypeID_MES(OpName, engineTypeID); + MIS_BASE.Write_EngineType_MES(OpName, engineType); + MIS_BASE.Write_EngineID_MES(OpName, engineID); + DtWebApi.ReadWritePLC.WritePLC("112", OpName, kuweiNum); + + MIS_BASE.Write_EngineTypeGetOver_MES(OpName, true); + } + + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function03:PartLoad"); + } + } + /// + /// 44 + /// 1 : 保存数据 + /// 0 :复位 + /// + /// + public static void EngineTypeGetOverPLC(string opName,string tagValue) + { + switch (tagValue) + { + case "0": + MIS_BASE.Write_EngineTypeGetOver_MES(opName, false); + MIS_BASE.Write_MaterialVerifyOver(opName, false); + break; + case "1": + //string opName; + string orderForm=""; + int PartPalletCode; + string engineType; + int engineTypeID; + string engineID; + string barCodeType="1"; + + // BaseDataSystemMES.MesServer_Process_EngineTypeOver(OpName); + + ////将产品信息从PLC读取 + MIS_BASE.Read_EngineTypeID(opName,out engineTypeID); + MIS_BASE.Read_EngineType(opName, out engineType); + MIS_BASE.Read_EngineID(opName, out engineID); + MIS_BASE.Read_PalletCode(opName, out PartPalletCode); + string kuweiNum = DtWebApi.ReadWritePLC.ReadPLC("112", opName).ToString(); + + + BaseDataSystemMES.GetUpLoadEngineIDOrderForm(opName,kuweiNum, out DataTable dt); + if(dt.Rows.Count>0) + { + orderForm = dt.Rows[0]["订单号"].ToString(); + } + + BaseDataSystemMES.OpName_MIS_MOBY_Insert(opName, orderForm, engineTypeID, engineType, engineID, PartPalletCode, 0, 0, ""); + + //MES保存数据 减掉盆子库存 + /// + /// 电子看板_发动机号_线首工位_增加 + /// + /// 工位号 + /// 订单号 + /// 托盘号 + /// 工件机型 + /// 工件机型,机型代码,工件编号, 壳体编号型号,工件流水号,QR码,基本流水号 + BaseDataSystemMES.GetEngineID_Save_Outline(opName, orderForm, PartPalletCode.ToString(), engineType, engineTypeID, engineID, barCodeType); + BaseDataSystemMES.GetUpLoadBarCode_0utUpdate(opName, kuweiNum); + MIS_BASE.Write_MaterialVerifyOver(opName, true); + + break; + } + } + } +} diff --git a/SyUpLoad/SyUpLoad/Methods/EngineGetOverBaseWork.cs b/SyUpLoad/SyUpLoad/Methods/EngineGetOverBaseWork.cs new file mode 100644 index 0000000..4587a89 --- /dev/null +++ b/SyUpLoad/SyUpLoad/Methods/EngineGetOverBaseWork.cs @@ -0,0 +1,134 @@ +using System; +using System.Data; +using bizFacade; +using MesServerWork; + +namespace SyUpLoad +{ + partial class PartLoad + { + /// + /// 正常逻辑工作(传递机型) + /// + /// + /// + /// + /// + /// + private void EngineTypeGetOver_PLC_Work(string OpName, int EngineTypeID, string EngineType, string EngineID, int PartPallet_Code) + { + int IsAllowWork; + int IsrepairBarcode = 0;//拆解返修标志 + int RepairPartStatusPLC = 0; + int MES_QualityMask = 1; + + string OrderForm = "";//订单号 + string EngineID_MES; + string repairBarcode = "";//拆解返修条码 + bool MesRead = false; + bool MesReadOver = false; + DataTable dt; + + MIS_BASE.Read_EngineID_MES(OpName, out EngineID_MES);//获取MES总成号 + MIS_BASE.Read_MesReadOver(OpName, out MesReadOver); //保存完成 + MIS_BASE.Read_QualityData_Read_CF(OpName, out MesRead); //允许保存 + MIS_BASE.Read_PalletInfo(OpName, out MES_QualityMask);//合格标志 + MIS_BASE.Read_RepairStatus_PLC(OpName, out RepairPartStatusPLC);//返修标志 + + BaseDataSystemMES.GetEngineID_Select(OpName, EngineID, out dt);//查询订单信息 + + if (dt != null&&dt.Rows.Count > 0) + { + OrderForm = Convert.ToString(dt.Rows[0]["订单号"]); + IsrepairBarcode = Convert.ToInt32(dt.Rows[0]["拆解标志"]); + repairBarcode = Convert.ToString(dt.Rows[0]["拆解返修条码"]); + } + + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, OrderForm, EngineTypeID, EngineType, EngineID, PartPallet_Code, 0, IsrepairBarcode, repairBarcode); + SaveMobyMessage(OpName, EngineTypeID, EngineType, EngineID, OrderForm); + Sendmessage("5", "1", OpName); + SendInfomation("QualityMask", Convert.ToString(MES_QualityMask), OpName); + SendInfomation("RepairPartStatusPLC", Convert.ToString(RepairPartStatusPLC), OpName); + + BaseDataSystemMES.MaterialPush_EngineIDStatus_Insert(OpName); + + if (EngineID_MES == EngineID) + { + string kuweiNum; + kuweiNum = DtWebApi.ReadWritePLC.ReadPLC(warehouseLocation.ToString(), OpName).ToString(); + BaseDataSystemMES.GetUpLoadBarCode_0utUpdate(OpName, kuweiNum); + MIS_BASE.Write_FixAllow(OpName, true); + InitOpname01(); + } + else + { + AsyncSendMessage_Notice(OpName, "PLC与MES不一致"); + } + } + private void InitOpname01() + { + BaseDataSystemMES.GetUpLoadBarCode(OPName01, out DataTable dt_OPName01); + + dataGridView_OPA1001.Invoke(new Action(() => { + dataGridView_OPA1001.DataSource = dt_OPName01; + })); + } + + + + /// + /// 保存MOBY信息 + /// + /// + /// + /// + /// + private void SaveMobyMessage(string OpName, int engineTypeID, string engineType, string engineID, string orderForm) + { + if (MIS_BASE.hashtable_EngineGetOver_EngineTypeID == null) + { + MIS_BASE.InitHashtable_MesServerCode(); + } + if (MIS_BASE.hashtable_EngineGetOver_EngineTypeID.ContainsKey(OpName)) + { + MIS_BASE.hashtable_EngineGetOver_EngineTypeID[OpName] = engineTypeID; + } + if (MIS_BASE.hashtable_EngineGetOver_EngineType.ContainsKey(OpName)) + { + MIS_BASE.hashtable_EngineGetOver_EngineType[OpName] = engineType; + } + if (MIS_BASE.hashtable_EngineGetOver_EngineID.ContainsKey(OpName)) + { + MIS_BASE.hashtable_EngineGetOver_EngineID[OpName] = engineID; + } + if (MIS_BASE.hashtable_EngineGetOver_OrderForm.ContainsKey(OpName)) + { + MIS_BASE.hashtable_EngineGetOver_OrderForm[OpName] = orderForm; + } + } + + /// + /// 返修件需要工作 + /// + /// 工位号 + private void IsNeedRepaire_OK(string OpName) + { + + int isRepair; + int engineTypeID; + + string engineType = ""; + string engineID = ""; + string palletCode = ""; + string orderForm = ""; + string repairCode = ""; + //从监控系统中查询出本工位信息 + BaseDataSystemMES.OpName_MIS_Moby_Select(OpName, + out orderForm, out engineTypeID, out engineType, + out engineID, out palletCode, out isRepair, out repairCode); + + EngineTypeGetOver_PLC_Work(OpName, engineTypeID, engineType, engineID, Convert.ToInt32(palletCode)); + } + + } +} diff --git a/SyUpLoad/SyUpLoad/Methods/SubmitToMisweb.cs b/SyUpLoad/SyUpLoad/Methods/SubmitToMisweb.cs new file mode 100644 index 0000000..c9beba1 --- /dev/null +++ b/SyUpLoad/SyUpLoad/Methods/SubmitToMisweb.cs @@ -0,0 +1,139 @@ +using System; +using bizFacade; +//using SystemFramework; + +namespace SyUpLoad +{ + + /// + /// 此类用于向WEB发送各种类型消息 + /// + partial class PartLoad + { + + /// + /// 批量发送WEB消息(Value为BOOL值) + /// + /// 消息编号组合 + /// 消息值组合 + /// 工位号 + void Sendmessage(string MessageNumm, string Value, string OpName) + { + for (int i = 0; i < MessageNumm.Length; i++) + { + Sendmessage(MessageNumm[i], Value[i].ToString(), OpName); + + } + } + + /// + /// 选择发送给WEB的消息 + /// + /// 消息类型 + /// 消息工位 + void Sendmessage(char Num, string Value, string OpName) + { + string SendMessage; + switch (Num) + { + case '1': + //1(直接在界面通过选择机型确认工序内容) + SendMessage = "MES|ProcessList|" + OpName + "|" + Value; + AsyncSendMessage(SendMessage); + break; + + case '2': + //2显示物料 + SendMessage = "MES|MaterialList|" + OpName + "|" + Value; + AsyncSendMessage(SendMessage); + break; + + case '3': + //3显示操作指导图片 + SendMessage = "MES|PicShow|" + OpName + "|" + Value; + AsyncSendMessage(SendMessage); + break; + case '4': + //4显示订单完工数量 + SendMessage = "MES|OrderFormList|" + OpName + "|" + Value; + AsyncSendMessage(SendMessage); + break; + + case '5': + SendMessage = "MES|ShowMoby|" + OpName + "|" + Value; + AsyncSendMessage(SendMessage); + break; + case '6': + SendMessage = "MES|MaterialCheckPosition|" + OpName + "|" + Value; + AsyncSendMessage(SendMessage); + break; + case '7': + SendMessage = "MES|WorkStart|" + OpName + "|" + Value; + AsyncSendMessage(SendMessage); + break; + case '8': + + break; + case '9': + SendMessage = "MES|ConfirmOkGo|" + OpName + "|" + Value; + AsyncSendMessage(SendMessage); + break; + case 'a': + SendMessage = "MES|FixAllow|" + OpName + "|" + Value; + AsyncSendMessage(SendMessage); + break; + } + } + + /// + /// 向WEB发送信息(value为字符串) + /// + /// 消息种类 + /// 消息内容 + /// 工位号 + void SendInfomation(string Command, string Value, string OpName) + { + + string SendMessage = "MES|" + Command + "|" + OpName + "|" + Value; + AsyncSendMessage(SendMessage); + } + + + /// + /// 发送在线产量、在线节拍 + /// + /// + /// + private void SendActuallyCount(string OpName, int tagValue) + { + //当工件离开时,更新在线产量、在线节拍 + if (tagValue == 0) + { + try + { + int opNameCount = 0;//在线产量 + int opNameCountTime = 0;//在线节拍 + //基本数据_工作日历_班次产量查询_New + BaseDataSystemMES.OpNameCount_New(OpName, out opNameCount, out opNameCountTime); + + string SendMessage; + SendMessage = "MES|ActuallyCount|" + OpName + "|" + opNameCount.ToString() + "&" + opNameCountTime.ToString(); + AsyncSendMessage(SendMessage); + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function03:SendActuallyCount"); + } + } + } + + + + + + + + + + } +} diff --git a/SyUpLoad/SyUpLoad/Methods/UDP.Send.cs b/SyUpLoad/SyUpLoad/Methods/UDP.Send.cs new file mode 100644 index 0000000..87b2f72 --- /dev/null +++ b/SyUpLoad/SyUpLoad/Methods/UDP.Send.cs @@ -0,0 +1,57 @@ +using bizFacade; +//using SystemFramework; +using MesServerWork; + +namespace SyUpLoad +{ + partial class PartLoad + { + /// + /// 发送信息到MES通讯服务器或者其他的 + /// + /// + private void AsyncSendMessage(string Message) + { + // asyncSendMessage(Message); + MIS_BASE.asyncSendMessage(Message); + //Thread t = new Thread(delegate() { asyncSendMessage(Message); }); + //t.Start(); + } + + /// + /// 发送提示消息 + /// + /// + private void AsyncSendMessage_Notice(string opname, string notice) + { + //通知Web界面 + BaseDataSystemMES.Web_Notice_Insert(opname, notice); + string SendMessage = "MES|Notice|" + opname + "|" + "1"; + MIS_BASE.asyncSendMessage(SendMessage); + } + + /// + /// 发送信息到打印机 + /// + /// + private void asyncSendMessageToMark(string Message) + { + //System.Threading.Thread.Sleep(10); + string messageSend = (string)Message; + //UDPClientSend.Send_ALL(ApplicationConfig.MES_MarkPortNum, messageSend); + } + + /// + /// 发送信息到LED + /// + /// + private void asyncSendMessageLED(string OpName) + { + + //发送到大屏幕显示 41104 + string strMessage = "MIS|" + OpName + "|" + "0" + "|" + "1"; + //UDPClientSend.Send_ALL(ApplicationConfig.Port_ShowLED_ProductCount, strMessage); + + } + } +} diff --git a/SyUpLoad/SyUpLoad/Methods/vssver2.scc b/SyUpLoad/SyUpLoad/Methods/vssver2.scc new file mode 100644 index 0000000..ab9ce10 Binary files /dev/null and b/SyUpLoad/SyUpLoad/Methods/vssver2.scc differ diff --git a/SyUpLoad/SyUpLoad/PartLoad.CreateEngineID.cs b/SyUpLoad/SyUpLoad/PartLoad.CreateEngineID.cs new file mode 100644 index 0000000..34def74 --- /dev/null +++ b/SyUpLoad/SyUpLoad/PartLoad.CreateEngineID.cs @@ -0,0 +1,180 @@ +using bizFacade; +using System; +using System.Collections.Generic; +using System.Data; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SyUpLoad +{ + public partial class PartLoad + { + /// + /// 获取自动或手动,并以对应的方式创建总成号 + /// + /// 工位号 + /// 产品型号 + /// 产品编号 + private void CreateEngineID(string OpName, out string engineType, out int engineTypeID, out string engineID, out string orderForm) + { + //string orderForm = "";//订单号 + string repairCode = "";//返修代码 + string engineID2 = ""; + string palletCode = "";//托盘编号 + + int palletCode_PLC = 0; + int isRepair = 0; + int engineNumber = 0; + int IsAutoOrManul = 0;//0为自动方式,1为手动方式 + + DataTable dt_EngineType = null; + DataTable dt_temp_isAutoOrManul;//查询创建总成编号的table + + engineType = ""; + engineID = ""; + + //获取订单号,发动机型号,发动机型号代码(在线首工位将选择的订单,机型等信息保存到监控表中) + BaseDataSystemMES.OpName_MIS_Moby_Select(OpName, out orderForm, out engineTypeID, out engineType, out engineID2, out palletCode, out isRepair, out repairCode); + //MIS_BASE.Read_PalletCode(OpName, out palletCode_PLC);//获取托盘编号 + + + + //以自动或手动方式创建发动机号 + CreateEngineID(OpName, IsAutoOrManul, orderForm, engineType, engineTypeID, palletCode_PLC.ToString(), engineNumber, out dt_EngineType, out engineID); + + } + + + /// + /// 以自动或手动方式创建工件编号 + /// + /// 工位号 + /// 自动手动 + /// 订单号 + /// 产品型号 + /// 产品型号代码 + /// 托盘编号 + /// 手动创建_年 + /// 手动创建_月 + /// 手动创建_日 + /// 流水号 + /// 返回信息 + /// 产品编号 + /// + /// + private void CreateEngineID(string opName, int IsAutoOrManul, string orderForm, string engineType, int engineTypeID, string palletCode, int engineNumber, out DataTable dt_EngineType, out string engineID) + { + string engineYear = ""; + string engineMoon = ""; + string engineDay = ""; + + DataTable dt_MaualPrint; + + dt_EngineType = null; + engineID = ""; + + //自动方式创建工件编号 + CreateEngineID_Auto(opName, orderForm, engineType, engineTypeID, palletCode, out dt_EngineType, out engineID); + + + if (!GetEngineID_Save(opName, IsAutoOrManul, orderForm, engineType, engineTypeID, engineID, palletCode.ToString(), dt_EngineType, engineYear, engineMoon, engineDay)) + { + engineID = ""; + engineTypeID = -1; + engineType = ""; + //AsyncSendMessage_Notice(opName, "保存工件信息出错..."); + return; + } + } + + /// + /// 自动方式创建工件编号 + /// + /// + /// + /// + /// + /// 托盘号 + /// + /// 发动机号 + private void CreateEngineID_Auto(string opName, string orderForm, string engineType, int engineTypeID, string palletCode, out DataTable dt_EngineType, out string engineID) + { + dt_EngineType = null; + engineID = ""; + BaseDataSystemMES.GetEngineID_Auto_branch(opName, engineType, palletCode, out dt_EngineType); + + if (dt_EngineType != null && dt_EngineType.Rows.Count > 0) + { + engineID = dt_EngineType.Rows[0]["发动机号"].ToString(); + + } + } + + /// + /// 手动方式创建总成号 + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + private void CreateEngineID_Manul(string opName, string orderForm, string engineType, int engineTypeID, string palletCode, + string engineYear, string engineMoon, string engineDay, int engineNumber, out DataTable dt_EngineType, out string engineID) + { + dt_EngineType = null; + engineID = ""; + + //手动方式创建 + BaseDataSystemMES.GetEngineID_Manual_branch(opName, engineType, engineYear, engineMoon, engineDay, engineNumber, true, out dt_EngineType); + if (dt_EngineType != null) + { + if (dt_EngineType.Rows.Count > 0) + { + engineID = dt_EngineType.Rows[0]["发动机号"].ToString(); + } + } + } + + + /// + /// 电子看板_发动机号_线首工位_增加 + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + private bool GetEngineID_Save(string opName, int IsAutoOrManul, + string orderForm, string engineType, int engineTypeID, string engineID, string partPalletCode, DataTable dt_EngineType, + string year, string month, string day + ) + { + if (IsAutoOrManul == 1) + { + string EngineID_DateTime = year + "-" + month + "-" + day + " 00:00:00"; + return BaseDataSystemMES.GetEngineID_ManulEngine_Save(opName, orderForm, partPalletCode, engineType, EngineID_DateTime, dt_EngineType); + } + else + { + + return BaseDataSystemMES.GetEngineID_Save(opName, orderForm, partPalletCode, engineType, dt_EngineType); + + + } + } + } +} diff --git a/SyUpLoad/SyUpLoad/PartLoad.Designer.cs b/SyUpLoad/SyUpLoad/PartLoad.Designer.cs new file mode 100644 index 0000000..59f2b87 --- /dev/null +++ b/SyUpLoad/SyUpLoad/PartLoad.Designer.cs @@ -0,0 +1,786 @@ + +namespace SyUpLoad +{ + partial class PartLoad + { + /// + /// 必需的设计器变量。 + /// + 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.button_barcode = new System.Windows.Forms.Button(); + this.textBox_barcode = new System.Windows.Forms.TextBox(); + this.dataGridView_OPA1001 = new System.Windows.Forms.DataGridView(); + this.dataGridView_OPA1002 = new System.Windows.Forms.DataGridView(); + this.groupBox1 = new System.Windows.Forms.GroupBox(); + this.button_ManualPartLoad3 = new System.Windows.Forms.Button(); + this.button_ManualPartLoad2 = new System.Windows.Forms.Button(); + this.textBox__PlcPosition3 = new System.Windows.Forms.TextBox(); + this.label12 = new System.Windows.Forms.Label(); + this.textBox__PlcPosition2 = new System.Windows.Forms.TextBox(); + this.textBox_PlcEngineID3 = new System.Windows.Forms.TextBox(); + this.label9 = new System.Windows.Forms.Label(); + this.textBox_PlcType3 = new System.Windows.Forms.TextBox(); + this.textBox_PlcEngineID2 = new System.Windows.Forms.TextBox(); + this.label11 = new System.Windows.Forms.Label(); + this.textBox_PlcType2 = new System.Windows.Forms.TextBox(); + this.label10 = new System.Windows.Forms.Label(); + this.label7 = new System.Windows.Forms.Label(); + this.label8 = new System.Windows.Forms.Label(); + this.groupBox5 = new System.Windows.Forms.GroupBox(); + this.checkBox_MesReadOver3 = new System.Windows.Forms.CheckBox(); + this.checkBox_WorkStart3 = new System.Windows.Forms.CheckBox(); + this.checkBox_MesRead3 = new System.Windows.Forms.CheckBox(); + this.checkBox_MesGoOver3 = new System.Windows.Forms.CheckBox(); + this.checkBox_PlcEngineTypeGetOver3 = new System.Windows.Forms.CheckBox(); + this.groupBox4 = new System.Windows.Forms.GroupBox(); + this.checkBox_WorkStart2 = new System.Windows.Forms.CheckBox(); + this.checkBox_MesReadOver2 = new System.Windows.Forms.CheckBox(); + this.checkBox_MesRead2 = new System.Windows.Forms.CheckBox(); + this.checkBox_MesGoOver2 = new System.Windows.Forms.CheckBox(); + this.checkBox_PlcEngineTypeGetOver2 = new System.Windows.Forms.CheckBox(); + this.groupBox2 = new System.Windows.Forms.GroupBox(); + this.button_ManualPartLoad = new System.Windows.Forms.Button(); + this.textBox__PlcPosition = new System.Windows.Forms.TextBox(); + this.textBox_PlcEngineID = new System.Windows.Forms.TextBox(); + this.textBox_MesPosition = new System.Windows.Forms.TextBox(); + this.label6 = new System.Windows.Forms.Label(); + this.textBox_MesEngineID = new System.Windows.Forms.TextBox(); + this.textBox_PlcType = new System.Windows.Forms.TextBox(); + this.label3 = new System.Windows.Forms.Label(); + this.label5 = new System.Windows.Forms.Label(); + this.textBox_MesType = new System.Windows.Forms.TextBox(); + this.label4 = new System.Windows.Forms.Label(); + this.label2 = new System.Windows.Forms.Label(); + this.label1 = new System.Windows.Forms.Label(); + this.groupBox3 = new System.Windows.Forms.GroupBox(); + this.checkBox_WorkStart = new System.Windows.Forms.CheckBox(); + this.checkBox_MesGoOver = new System.Windows.Forms.CheckBox(); + this.checkBox_PlcEngineTypeGetOver = new System.Windows.Forms.CheckBox(); + this.checkBox_MesEngineTypeGetOver = new System.Windows.Forms.CheckBox(); + this.checkBox_PartLoad = new System.Windows.Forms.CheckBox(); + this.button_OrderForm = new System.Windows.Forms.Button(); + this.radioButton6 = new System.Windows.Forms.RadioButton(); + this.radioButton5 = new System.Windows.Forms.RadioButton(); + this.radioButton4 = new System.Windows.Forms.RadioButton(); + this.radioButton3 = new System.Windows.Forms.RadioButton(); + this.radioButton2 = new System.Windows.Forms.RadioButton(); + this.radioButton1 = new System.Windows.Forms.RadioButton(); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView_OPA1001)).BeginInit(); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView_OPA1002)).BeginInit(); + this.groupBox1.SuspendLayout(); + this.groupBox5.SuspendLayout(); + this.groupBox4.SuspendLayout(); + this.groupBox2.SuspendLayout(); + this.groupBox3.SuspendLayout(); + this.SuspendLayout(); + // + // button_barcode + // + this.button_barcode.Location = new System.Drawing.Point(677, 59); + this.button_barcode.Name = "button_barcode"; + this.button_barcode.Size = new System.Drawing.Size(61, 23); + this.button_barcode.TabIndex = 4; + this.button_barcode.Text = "扫描条码"; + this.button_barcode.UseVisualStyleBackColor = true; + this.button_barcode.Click += new System.EventHandler(this.button_barcode_Click); + // + // textBox_barcode + // + this.textBox_barcode.Location = new System.Drawing.Point(530, 20); + this.textBox_barcode.Name = "textBox_barcode"; + this.textBox_barcode.Size = new System.Drawing.Size(208, 21); + this.textBox_barcode.TabIndex = 3; + // + // dataGridView_OPA1001 + // + this.dataGridView_OPA1001.AllowUserToAddRows = false; + this.dataGridView_OPA1001.AllowUserToDeleteRows = false; + this.dataGridView_OPA1001.AllowUserToResizeColumns = false; + this.dataGridView_OPA1001.AllowUserToResizeRows = false; + this.dataGridView_OPA1001.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; + this.dataGridView_OPA1001.Location = new System.Drawing.Point(6, 107); + this.dataGridView_OPA1001.MultiSelect = false; + this.dataGridView_OPA1001.Name = "dataGridView_OPA1001"; + this.dataGridView_OPA1001.RowTemplate.Height = 23; + this.dataGridView_OPA1001.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect; + this.dataGridView_OPA1001.Size = new System.Drawing.Size(384, 201); + this.dataGridView_OPA1001.TabIndex = 5; + // + // dataGridView_OPA1002 + // + this.dataGridView_OPA1002.AllowUserToAddRows = false; + this.dataGridView_OPA1002.AllowUserToDeleteRows = false; + this.dataGridView_OPA1002.AllowUserToResizeColumns = false; + this.dataGridView_OPA1002.AllowUserToResizeRows = false; + this.dataGridView_OPA1002.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; + this.dataGridView_OPA1002.Location = new System.Drawing.Point(6, 20); + this.dataGridView_OPA1002.MultiSelect = false; + this.dataGridView_OPA1002.Name = "dataGridView_OPA1002"; + this.dataGridView_OPA1002.RowTemplate.Height = 23; + this.dataGridView_OPA1002.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect; + this.dataGridView_OPA1002.Size = new System.Drawing.Size(384, 193); + this.dataGridView_OPA1002.TabIndex = 5; + // + // groupBox1 + // + this.groupBox1.Controls.Add(this.button_ManualPartLoad3); + this.groupBox1.Controls.Add(this.button_ManualPartLoad2); + this.groupBox1.Controls.Add(this.textBox__PlcPosition3); + this.groupBox1.Controls.Add(this.label12); + this.groupBox1.Controls.Add(this.textBox__PlcPosition2); + this.groupBox1.Controls.Add(this.textBox_PlcEngineID3); + this.groupBox1.Controls.Add(this.label9); + this.groupBox1.Controls.Add(this.textBox_PlcType3); + this.groupBox1.Controls.Add(this.textBox_PlcEngineID2); + this.groupBox1.Controls.Add(this.label11); + this.groupBox1.Controls.Add(this.textBox_PlcType2); + this.groupBox1.Controls.Add(this.label10); + this.groupBox1.Controls.Add(this.label7); + this.groupBox1.Controls.Add(this.label8); + this.groupBox1.Controls.Add(this.groupBox5); + this.groupBox1.Controls.Add(this.groupBox4); + this.groupBox1.Controls.Add(this.dataGridView_OPA1002); + this.groupBox1.Location = new System.Drawing.Point(12, 332); + this.groupBox1.Name = "groupBox1"; + this.groupBox1.Size = new System.Drawing.Size(776, 309); + this.groupBox1.TabIndex = 8; + this.groupBox1.TabStop = false; + this.groupBox1.Text = "分线上线"; + // + // button_ManualPartLoad3 + // + this.button_ManualPartLoad3.Location = new System.Drawing.Point(315, 253); + this.button_ManualPartLoad3.Name = "button_ManualPartLoad3"; + this.button_ManualPartLoad3.Size = new System.Drawing.Size(75, 40); + this.button_ManualPartLoad3.TabIndex = 19; + this.button_ManualPartLoad3.Text = "手动转线"; + this.button_ManualPartLoad3.UseVisualStyleBackColor = true; + // + // button_ManualPartLoad2 + // + this.button_ManualPartLoad2.Enabled = false; + this.button_ManualPartLoad2.Location = new System.Drawing.Point(633, 200); + this.button_ManualPartLoad2.Name = "button_ManualPartLoad2"; + this.button_ManualPartLoad2.Size = new System.Drawing.Size(124, 36); + this.button_ManualPartLoad2.TabIndex = 18; + this.button_ManualPartLoad2.Text = "手动入库"; + this.button_ManualPartLoad2.UseVisualStyleBackColor = true; + this.button_ManualPartLoad2.Click += new System.EventHandler(this.button_ManualPartLoad2_Click); + // + // textBox__PlcPosition3 + // + this.textBox__PlcPosition3.Location = new System.Drawing.Point(167, 282); + this.textBox__PlcPosition3.Name = "textBox__PlcPosition3"; + this.textBox__PlcPosition3.Size = new System.Drawing.Size(141, 21); + this.textBox__PlcPosition3.TabIndex = 17; + // + // label12 + // + this.label12.AutoSize = true; + this.label12.Location = new System.Drawing.Point(100, 285); + this.label12.Name = "label12"; + this.label12.Size = new System.Drawing.Size(47, 12); + this.label12.TabIndex = 16; + this.label12.Text = "PLC库位"; + // + // textBox__PlcPosition2 + // + this.textBox__PlcPosition2.Location = new System.Drawing.Point(475, 89); + this.textBox__PlcPosition2.Name = "textBox__PlcPosition2"; + this.textBox__PlcPosition2.Size = new System.Drawing.Size(141, 21); + this.textBox__PlcPosition2.TabIndex = 17; + // + // textBox_PlcEngineID3 + // + this.textBox_PlcEngineID3.Location = new System.Drawing.Point(167, 255); + this.textBox_PlcEngineID3.Name = "textBox_PlcEngineID3"; + this.textBox_PlcEngineID3.Size = new System.Drawing.Size(141, 21); + this.textBox_PlcEngineID3.TabIndex = 14; + // + // label9 + // + this.label9.AutoSize = true; + this.label9.Location = new System.Drawing.Point(408, 92); + this.label9.Name = "label9"; + this.label9.Size = new System.Drawing.Size(47, 12); + this.label9.TabIndex = 16; + this.label9.Text = "PLC库位"; + // + // textBox_PlcType3 + // + this.textBox_PlcType3.Location = new System.Drawing.Point(167, 228); + this.textBox_PlcType3.Name = "textBox_PlcType3"; + this.textBox_PlcType3.Size = new System.Drawing.Size(141, 21); + this.textBox_PlcType3.TabIndex = 15; + // + // textBox_PlcEngineID2 + // + this.textBox_PlcEngineID2.Location = new System.Drawing.Point(475, 62); + this.textBox_PlcEngineID2.Name = "textBox_PlcEngineID2"; + this.textBox_PlcEngineID2.Size = new System.Drawing.Size(141, 21); + this.textBox_PlcEngineID2.TabIndex = 14; + // + // label11 + // + this.label11.AutoSize = true; + this.label11.Location = new System.Drawing.Point(100, 258); + this.label11.Name = "label11"; + this.label11.Size = new System.Drawing.Size(59, 12); + this.label11.TabIndex = 12; + this.label11.Text = "PLC流水号"; + // + // textBox_PlcType2 + // + this.textBox_PlcType2.Location = new System.Drawing.Point(475, 35); + this.textBox_PlcType2.Name = "textBox_PlcType2"; + this.textBox_PlcType2.Size = new System.Drawing.Size(141, 21); + this.textBox_PlcType2.TabIndex = 15; + // + // label10 + // + this.label10.AutoSize = true; + this.label10.Location = new System.Drawing.Point(100, 231); + this.label10.Name = "label10"; + this.label10.Size = new System.Drawing.Size(47, 12); + this.label10.TabIndex = 13; + this.label10.Text = "PLC机型"; + // + // label7 + // + this.label7.AutoSize = true; + this.label7.Location = new System.Drawing.Point(408, 65); + this.label7.Name = "label7"; + this.label7.Size = new System.Drawing.Size(59, 12); + this.label7.TabIndex = 12; + this.label7.Text = "PLC流水号"; + // + // label8 + // + this.label8.AutoSize = true; + this.label8.Location = new System.Drawing.Point(408, 38); + this.label8.Name = "label8"; + this.label8.Size = new System.Drawing.Size(47, 12); + this.label8.TabIndex = 13; + this.label8.Text = "PLC机型"; + // + // groupBox5 + // + this.groupBox5.Controls.Add(this.checkBox_MesReadOver3); + this.groupBox5.Controls.Add(this.checkBox_WorkStart3); + this.groupBox5.Controls.Add(this.checkBox_MesRead3); + this.groupBox5.Controls.Add(this.checkBox_MesGoOver3); + this.groupBox5.Controls.Add(this.checkBox_PlcEngineTypeGetOver3); + this.groupBox5.Location = new System.Drawing.Point(410, 155); + this.groupBox5.Name = "groupBox5"; + this.groupBox5.Size = new System.Drawing.Size(124, 144); + this.groupBox5.TabIndex = 10; + this.groupBox5.TabStop = false; + this.groupBox5.Text = "PLC通讯"; + // + // checkBox_MesReadOver3 + // + this.checkBox_MesReadOver3.AutoSize = true; + this.checkBox_MesReadOver3.Location = new System.Drawing.Point(20, 122); + this.checkBox_MesReadOver3.Name = "checkBox_MesReadOver3"; + this.checkBox_MesReadOver3.Size = new System.Drawing.Size(72, 16); + this.checkBox_MesReadOver3.TabIndex = 19; + this.checkBox_MesReadOver3.Text = "保存完成"; + this.checkBox_MesReadOver3.UseVisualStyleBackColor = true; + // + // checkBox_WorkStart3 + // + this.checkBox_WorkStart3.AutoSize = true; + this.checkBox_WorkStart3.Location = new System.Drawing.Point(20, 20); + this.checkBox_WorkStart3.Name = "checkBox_WorkStart3"; + this.checkBox_WorkStart3.Size = new System.Drawing.Size(72, 16); + this.checkBox_WorkStart3.TabIndex = 8; + this.checkBox_WorkStart3.Text = "工件到位"; + this.checkBox_WorkStart3.UseVisualStyleBackColor = true; + // + // checkBox_MesRead3 + // + this.checkBox_MesRead3.AutoSize = true; + this.checkBox_MesRead3.Location = new System.Drawing.Point(20, 89); + this.checkBox_MesRead3.Name = "checkBox_MesRead3"; + this.checkBox_MesRead3.Size = new System.Drawing.Size(72, 16); + this.checkBox_MesRead3.TabIndex = 20; + this.checkBox_MesRead3.Text = "允许保存"; + this.checkBox_MesRead3.UseVisualStyleBackColor = true; + // + // checkBox_MesGoOver3 + // + this.checkBox_MesGoOver3.AutoSize = true; + this.checkBox_MesGoOver3.Location = new System.Drawing.Point(20, 67); + this.checkBox_MesGoOver3.Name = "checkBox_MesGoOver3"; + this.checkBox_MesGoOver3.Size = new System.Drawing.Size(90, 16); + this.checkBox_MesGoOver3.TabIndex = 8; + this.checkBox_MesGoOver3.Text = "MES工作完成"; + this.checkBox_MesGoOver3.UseVisualStyleBackColor = true; + // + // checkBox_PlcEngineTypeGetOver3 + // + this.checkBox_PlcEngineTypeGetOver3.AutoSize = true; + this.checkBox_PlcEngineTypeGetOver3.Location = new System.Drawing.Point(20, 45); + this.checkBox_PlcEngineTypeGetOver3.Name = "checkBox_PlcEngineTypeGetOver3"; + this.checkBox_PlcEngineTypeGetOver3.Size = new System.Drawing.Size(90, 16); + this.checkBox_PlcEngineTypeGetOver3.TabIndex = 8; + this.checkBox_PlcEngineTypeGetOver3.Text = "PLC传递机型"; + this.checkBox_PlcEngineTypeGetOver3.UseVisualStyleBackColor = true; + // + // groupBox4 + // + this.groupBox4.Controls.Add(this.checkBox_WorkStart2); + this.groupBox4.Controls.Add(this.checkBox_MesReadOver2); + this.groupBox4.Controls.Add(this.checkBox_MesRead2); + this.groupBox4.Controls.Add(this.checkBox_MesGoOver2); + this.groupBox4.Controls.Add(this.checkBox_PlcEngineTypeGetOver2); + this.groupBox4.Location = new System.Drawing.Point(633, 20); + this.groupBox4.Name = "groupBox4"; + this.groupBox4.Size = new System.Drawing.Size(124, 169); + this.groupBox4.TabIndex = 10; + this.groupBox4.TabStop = false; + this.groupBox4.Text = "PLC通讯"; + // + // checkBox_WorkStart2 + // + this.checkBox_WorkStart2.AutoSize = true; + this.checkBox_WorkStart2.Location = new System.Drawing.Point(20, 20); + this.checkBox_WorkStart2.Name = "checkBox_WorkStart2"; + this.checkBox_WorkStart2.Size = new System.Drawing.Size(72, 16); + this.checkBox_WorkStart2.TabIndex = 8; + this.checkBox_WorkStart2.Text = "工件到位"; + this.checkBox_WorkStart2.UseVisualStyleBackColor = true; + // + // checkBox_MesReadOver2 + // + this.checkBox_MesReadOver2.AutoSize = true; + this.checkBox_MesReadOver2.Location = new System.Drawing.Point(20, 135); + this.checkBox_MesReadOver2.Name = "checkBox_MesReadOver2"; + this.checkBox_MesReadOver2.Size = new System.Drawing.Size(72, 16); + this.checkBox_MesReadOver2.TabIndex = 8; + this.checkBox_MesReadOver2.Text = "保存完成"; + this.checkBox_MesReadOver2.UseVisualStyleBackColor = true; + // + // checkBox_MesRead2 + // + this.checkBox_MesRead2.AutoSize = true; + this.checkBox_MesRead2.Location = new System.Drawing.Point(20, 96); + this.checkBox_MesRead2.Name = "checkBox_MesRead2"; + this.checkBox_MesRead2.Size = new System.Drawing.Size(72, 16); + this.checkBox_MesRead2.TabIndex = 8; + this.checkBox_MesRead2.Text = "允许保存"; + this.checkBox_MesRead2.UseVisualStyleBackColor = true; + // + // checkBox_MesGoOver2 + // + this.checkBox_MesGoOver2.AutoSize = true; + this.checkBox_MesGoOver2.Location = new System.Drawing.Point(20, 74); + this.checkBox_MesGoOver2.Name = "checkBox_MesGoOver2"; + this.checkBox_MesGoOver2.Size = new System.Drawing.Size(90, 16); + this.checkBox_MesGoOver2.TabIndex = 8; + this.checkBox_MesGoOver2.Text = "MES工作完成"; + this.checkBox_MesGoOver2.UseVisualStyleBackColor = true; + // + // checkBox_PlcEngineTypeGetOver2 + // + this.checkBox_PlcEngineTypeGetOver2.AutoSize = true; + this.checkBox_PlcEngineTypeGetOver2.Location = new System.Drawing.Point(20, 47); + this.checkBox_PlcEngineTypeGetOver2.Name = "checkBox_PlcEngineTypeGetOver2"; + this.checkBox_PlcEngineTypeGetOver2.Size = new System.Drawing.Size(90, 16); + this.checkBox_PlcEngineTypeGetOver2.TabIndex = 8; + this.checkBox_PlcEngineTypeGetOver2.Text = "PLC传递机型"; + this.checkBox_PlcEngineTypeGetOver2.UseVisualStyleBackColor = true; + // + // groupBox2 + // + this.groupBox2.Controls.Add(this.button_ManualPartLoad); + this.groupBox2.Controls.Add(this.textBox__PlcPosition); + this.groupBox2.Controls.Add(this.textBox_PlcEngineID); + this.groupBox2.Controls.Add(this.textBox_MesPosition); + this.groupBox2.Controls.Add(this.label6); + this.groupBox2.Controls.Add(this.textBox_MesEngineID); + this.groupBox2.Controls.Add(this.textBox_PlcType); + this.groupBox2.Controls.Add(this.label3); + this.groupBox2.Controls.Add(this.label5); + this.groupBox2.Controls.Add(this.textBox_MesType); + this.groupBox2.Controls.Add(this.label4); + this.groupBox2.Controls.Add(this.label2); + this.groupBox2.Controls.Add(this.label1); + this.groupBox2.Controls.Add(this.groupBox3); + this.groupBox2.Controls.Add(this.button_OrderForm); + this.groupBox2.Controls.Add(this.radioButton6); + this.groupBox2.Controls.Add(this.radioButton5); + this.groupBox2.Controls.Add(this.radioButton4); + this.groupBox2.Controls.Add(this.radioButton3); + this.groupBox2.Controls.Add(this.radioButton2); + this.groupBox2.Controls.Add(this.radioButton1); + this.groupBox2.Controls.Add(this.dataGridView_OPA1001); + this.groupBox2.Controls.Add(this.textBox_barcode); + this.groupBox2.Controls.Add(this.button_barcode); + this.groupBox2.Location = new System.Drawing.Point(12, 12); + this.groupBox2.Name = "groupBox2"; + this.groupBox2.Size = new System.Drawing.Size(776, 314); + this.groupBox2.TabIndex = 9; + this.groupBox2.TabStop = false; + this.groupBox2.Text = "分线上线"; + // + // button_ManualPartLoad + // + this.button_ManualPartLoad.Enabled = false; + this.button_ManualPartLoad.Location = new System.Drawing.Point(633, 262); + this.button_ManualPartLoad.Name = "button_ManualPartLoad"; + this.button_ManualPartLoad.Size = new System.Drawing.Size(124, 36); + this.button_ManualPartLoad.TabIndex = 12; + this.button_ManualPartLoad.Text = "手动上线"; + this.button_ManualPartLoad.UseVisualStyleBackColor = true; + //this.button_ManualPartLoad.Click += new System.EventHandler(this.button_ManualPartLoad_Click); + // + // textBox__PlcPosition + // + this.textBox__PlcPosition.Location = new System.Drawing.Point(475, 259); + this.textBox__PlcPosition.Name = "textBox__PlcPosition"; + this.textBox__PlcPosition.Size = new System.Drawing.Size(141, 21); + this.textBox__PlcPosition.TabIndex = 11; + // + // textBox_PlcEngineID + // + this.textBox_PlcEngineID.Location = new System.Drawing.Point(475, 232); + this.textBox_PlcEngineID.Name = "textBox_PlcEngineID"; + this.textBox_PlcEngineID.Size = new System.Drawing.Size(141, 21); + this.textBox_PlcEngineID.TabIndex = 11; + // + // textBox_MesPosition + // + this.textBox_MesPosition.Location = new System.Drawing.Point(475, 169); + this.textBox_MesPosition.Name = "textBox_MesPosition"; + this.textBox_MesPosition.Size = new System.Drawing.Size(141, 21); + this.textBox_MesPosition.TabIndex = 11; + // + // label6 + // + this.label6.AutoSize = true; + this.label6.Location = new System.Drawing.Point(408, 262); + this.label6.Name = "label6"; + this.label6.Size = new System.Drawing.Size(47, 12); + this.label6.TabIndex = 10; + this.label6.Text = "PLC库位"; + // + // textBox_MesEngineID + // + this.textBox_MesEngineID.Location = new System.Drawing.Point(475, 142); + this.textBox_MesEngineID.Name = "textBox_MesEngineID"; + this.textBox_MesEngineID.Size = new System.Drawing.Size(141, 21); + this.textBox_MesEngineID.TabIndex = 11; + // + // textBox_PlcType + // + this.textBox_PlcType.Location = new System.Drawing.Point(475, 205); + this.textBox_PlcType.Name = "textBox_PlcType"; + this.textBox_PlcType.Size = new System.Drawing.Size(141, 21); + this.textBox_PlcType.TabIndex = 11; + // + // label3 + // + this.label3.AutoSize = true; + this.label3.Location = new System.Drawing.Point(408, 172); + this.label3.Name = "label3"; + this.label3.Size = new System.Drawing.Size(47, 12); + this.label3.TabIndex = 10; + this.label3.Text = "MES库位"; + // + // label5 + // + this.label5.AutoSize = true; + this.label5.Location = new System.Drawing.Point(408, 235); + this.label5.Name = "label5"; + this.label5.Size = new System.Drawing.Size(59, 12); + this.label5.TabIndex = 10; + this.label5.Text = "PLC流水号"; + // + // textBox_MesType + // + this.textBox_MesType.Location = new System.Drawing.Point(475, 115); + this.textBox_MesType.Name = "textBox_MesType"; + this.textBox_MesType.Size = new System.Drawing.Size(141, 21); + this.textBox_MesType.TabIndex = 11; + // + // label4 + // + this.label4.AutoSize = true; + this.label4.Location = new System.Drawing.Point(408, 208); + this.label4.Name = "label4"; + this.label4.Size = new System.Drawing.Size(47, 12); + this.label4.TabIndex = 10; + this.label4.Text = "PLC机型"; + // + // label2 + // + this.label2.AutoSize = true; + this.label2.Location = new System.Drawing.Point(408, 145); + this.label2.Name = "label2"; + this.label2.Size = new System.Drawing.Size(59, 12); + this.label2.TabIndex = 10; + this.label2.Text = "MES流水号"; + // + // label1 + // + this.label1.AutoSize = true; + this.label1.Location = new System.Drawing.Point(408, 118); + this.label1.Name = "label1"; + this.label1.Size = new System.Drawing.Size(47, 12); + this.label1.TabIndex = 10; + this.label1.Text = "MES机型"; + // + // groupBox3 + // + this.groupBox3.Controls.Add(this.checkBox_WorkStart); + this.groupBox3.Controls.Add(this.checkBox_MesGoOver); + this.groupBox3.Controls.Add(this.checkBox_PlcEngineTypeGetOver); + this.groupBox3.Controls.Add(this.checkBox_MesEngineTypeGetOver); + this.groupBox3.Controls.Add(this.checkBox_PartLoad); + this.groupBox3.Location = new System.Drawing.Point(633, 107); + this.groupBox3.Name = "groupBox3"; + this.groupBox3.Size = new System.Drawing.Size(124, 146); + this.groupBox3.TabIndex = 9; + this.groupBox3.TabStop = false; + this.groupBox3.Text = "PLC通讯"; + // + // checkBox_WorkStart + // + this.checkBox_WorkStart.AutoSize = true; + this.checkBox_WorkStart.Location = new System.Drawing.Point(20, 20); + this.checkBox_WorkStart.Name = "checkBox_WorkStart"; + this.checkBox_WorkStart.Size = new System.Drawing.Size(72, 16); + this.checkBox_WorkStart.TabIndex = 8; + this.checkBox_WorkStart.Text = "工件到位"; + this.checkBox_WorkStart.UseVisualStyleBackColor = true; + // + // checkBox_MesGoOver + // + this.checkBox_MesGoOver.AutoSize = true; + this.checkBox_MesGoOver.Location = new System.Drawing.Point(20, 111); + this.checkBox_MesGoOver.Name = "checkBox_MesGoOver"; + this.checkBox_MesGoOver.Size = new System.Drawing.Size(90, 16); + this.checkBox_MesGoOver.TabIndex = 8; + this.checkBox_MesGoOver.Text = "MES工作完成"; + this.checkBox_MesGoOver.UseVisualStyleBackColor = true; + // + // checkBox_PlcEngineTypeGetOver + // + this.checkBox_PlcEngineTypeGetOver.AutoSize = true; + this.checkBox_PlcEngineTypeGetOver.Location = new System.Drawing.Point(20, 89); + this.checkBox_PlcEngineTypeGetOver.Name = "checkBox_PlcEngineTypeGetOver"; + this.checkBox_PlcEngineTypeGetOver.Size = new System.Drawing.Size(90, 16); + this.checkBox_PlcEngineTypeGetOver.TabIndex = 8; + this.checkBox_PlcEngineTypeGetOver.Text = "PLC传递机型"; + this.checkBox_PlcEngineTypeGetOver.UseVisualStyleBackColor = true; + // + // checkBox_MesEngineTypeGetOver + // + this.checkBox_MesEngineTypeGetOver.AutoSize = true; + this.checkBox_MesEngineTypeGetOver.Location = new System.Drawing.Point(20, 67); + this.checkBox_MesEngineTypeGetOver.Name = "checkBox_MesEngineTypeGetOver"; + this.checkBox_MesEngineTypeGetOver.Size = new System.Drawing.Size(90, 16); + this.checkBox_MesEngineTypeGetOver.TabIndex = 8; + this.checkBox_MesEngineTypeGetOver.Text = "MES传递机型"; + this.checkBox_MesEngineTypeGetOver.UseVisualStyleBackColor = true; + // + // checkBox_PartLoad + // + this.checkBox_PartLoad.AutoSize = true; + this.checkBox_PartLoad.Location = new System.Drawing.Point(20, 42); + this.checkBox_PartLoad.Name = "checkBox_PartLoad"; + this.checkBox_PartLoad.Size = new System.Drawing.Size(72, 16); + this.checkBox_PartLoad.TabIndex = 8; + this.checkBox_PartLoad.Text = "申请上线"; + this.checkBox_PartLoad.UseVisualStyleBackColor = true; + // + // button_OrderForm + // + this.button_OrderForm.Location = new System.Drawing.Point(530, 59); + this.button_OrderForm.Name = "button_OrderForm"; + this.button_OrderForm.Size = new System.Drawing.Size(75, 23); + this.button_OrderForm.TabIndex = 7; + this.button_OrderForm.Text = "下订单"; + this.button_OrderForm.UseVisualStyleBackColor = true; + // + // radioButton6 + // + this.radioButton6.AutoSize = true; + this.radioButton6.Font = new System.Drawing.Font("宋体", 21.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.radioButton6.Location = new System.Drawing.Point(304, 68); + this.radioButton6.Name = "radioButton6"; + this.radioButton6.Size = new System.Drawing.Size(104, 33); + this.radioButton6.TabIndex = 6; + this.radioButton6.Text = "库位6"; + this.radioButton6.UseVisualStyleBackColor = true; + // + // radioButton5 + // + this.radioButton5.AutoSize = true; + this.radioButton5.Font = new System.Drawing.Font("宋体", 21.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.radioButton5.Location = new System.Drawing.Point(304, 29); + this.radioButton5.Name = "radioButton5"; + this.radioButton5.Size = new System.Drawing.Size(104, 33); + this.radioButton5.TabIndex = 6; + this.radioButton5.Text = "库位5"; + this.radioButton5.UseVisualStyleBackColor = true; + // + // radioButton4 + // + this.radioButton4.AutoSize = true; + this.radioButton4.Font = new System.Drawing.Font("宋体", 21.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.radioButton4.Location = new System.Drawing.Point(158, 68); + this.radioButton4.Name = "radioButton4"; + this.radioButton4.Size = new System.Drawing.Size(104, 33); + this.radioButton4.TabIndex = 6; + this.radioButton4.Text = "库位4"; + this.radioButton4.UseVisualStyleBackColor = true; + // + // radioButton3 + // + this.radioButton3.AutoSize = true; + this.radioButton3.Font = new System.Drawing.Font("宋体", 21.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.radioButton3.Location = new System.Drawing.Point(158, 29); + this.radioButton3.Name = "radioButton3"; + this.radioButton3.Size = new System.Drawing.Size(104, 33); + this.radioButton3.TabIndex = 6; + this.radioButton3.Text = "库位3"; + this.radioButton3.UseVisualStyleBackColor = true; + // + // radioButton2 + // + this.radioButton2.AutoSize = true; + this.radioButton2.Font = new System.Drawing.Font("宋体", 21.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.radioButton2.Location = new System.Drawing.Point(19, 68); + this.radioButton2.Name = "radioButton2"; + this.radioButton2.Size = new System.Drawing.Size(104, 33); + this.radioButton2.TabIndex = 6; + this.radioButton2.Text = "库位2"; + this.radioButton2.UseVisualStyleBackColor = true; + // + // radioButton1 + // + this.radioButton1.AutoSize = true; + this.radioButton1.Checked = true; + this.radioButton1.Font = new System.Drawing.Font("宋体", 21.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.radioButton1.Location = new System.Drawing.Point(19, 29); + this.radioButton1.Name = "radioButton1"; + this.radioButton1.Size = new System.Drawing.Size(104, 33); + this.radioButton1.TabIndex = 6; + this.radioButton1.TabStop = true; + this.radioButton1.Text = "库位1"; + this.radioButton1.UseVisualStyleBackColor = true; + // + // PartLoad + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(800, 653); + this.Controls.Add(this.groupBox2); + this.Controls.Add(this.groupBox1); + this.DoubleBuffered = true; + this.Name = "PartLoad"; + this.Text = "Form1"; + this.Load += new System.EventHandler(this.PartLoad_Load); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView_OPA1001)).EndInit(); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView_OPA1002)).EndInit(); + this.groupBox1.ResumeLayout(false); + this.groupBox1.PerformLayout(); + this.groupBox5.ResumeLayout(false); + this.groupBox5.PerformLayout(); + this.groupBox4.ResumeLayout(false); + this.groupBox4.PerformLayout(); + this.groupBox2.ResumeLayout(false); + this.groupBox2.PerformLayout(); + this.groupBox3.ResumeLayout(false); + this.groupBox3.PerformLayout(); + this.ResumeLayout(false); + + } + + #endregion + + private System.Windows.Forms.Button button_barcode; + private System.Windows.Forms.TextBox textBox_barcode; + private System.Windows.Forms.DataGridView dataGridView_OPA1001; + private System.Windows.Forms.DataGridView dataGridView_OPA1002; + private System.Windows.Forms.GroupBox groupBox1; + private System.Windows.Forms.GroupBox groupBox2; + private System.Windows.Forms.RadioButton radioButton6; + private System.Windows.Forms.RadioButton radioButton5; + private System.Windows.Forms.RadioButton radioButton4; + private System.Windows.Forms.RadioButton radioButton3; + private System.Windows.Forms.RadioButton radioButton2; + private System.Windows.Forms.RadioButton radioButton1; + private System.Windows.Forms.Button button_OrderForm; + private System.Windows.Forms.CheckBox checkBox_PartLoad; + private System.Windows.Forms.GroupBox groupBox3; + private System.Windows.Forms.CheckBox checkBox_WorkStart; + private System.Windows.Forms.CheckBox checkBox_MesGoOver; + private System.Windows.Forms.CheckBox checkBox_PlcEngineTypeGetOver; + private System.Windows.Forms.CheckBox checkBox_MesEngineTypeGetOver; + private System.Windows.Forms.TextBox textBox__PlcPosition; + private System.Windows.Forms.TextBox textBox_PlcEngineID; + private System.Windows.Forms.TextBox textBox_MesPosition; + private System.Windows.Forms.Label label6; + private System.Windows.Forms.TextBox textBox_MesEngineID; + private System.Windows.Forms.TextBox textBox_PlcType; + private System.Windows.Forms.Label label3; + private System.Windows.Forms.Label label5; + private System.Windows.Forms.TextBox textBox_MesType; + private System.Windows.Forms.Label label4; + private System.Windows.Forms.Label label2; + private System.Windows.Forms.Label label1; + private System.Windows.Forms.Button button_ManualPartLoad; + private System.Windows.Forms.TextBox textBox_PlcEngineID2; + private System.Windows.Forms.TextBox textBox_PlcType2; + private System.Windows.Forms.Label label7; + private System.Windows.Forms.Label label8; + private System.Windows.Forms.GroupBox groupBox4; + private System.Windows.Forms.CheckBox checkBox_WorkStart2; + private System.Windows.Forms.CheckBox checkBox_MesGoOver2; + private System.Windows.Forms.CheckBox checkBox_PlcEngineTypeGetOver2; + private System.Windows.Forms.GroupBox groupBox5; + private System.Windows.Forms.CheckBox checkBox_WorkStart3; + private System.Windows.Forms.CheckBox checkBox_MesGoOver3; + private System.Windows.Forms.CheckBox checkBox_PlcEngineTypeGetOver3; + private System.Windows.Forms.TextBox textBox__PlcPosition2; + private System.Windows.Forms.Label label9; + private System.Windows.Forms.CheckBox checkBox_MesReadOver2; + private System.Windows.Forms.CheckBox checkBox_MesRead2; + private System.Windows.Forms.Button button_ManualPartLoad2; + private System.Windows.Forms.TextBox textBox__PlcPosition3; + private System.Windows.Forms.Label label12; + private System.Windows.Forms.TextBox textBox_PlcEngineID3; + private System.Windows.Forms.TextBox textBox_PlcType3; + private System.Windows.Forms.Label label11; + private System.Windows.Forms.Label label10; + private System.Windows.Forms.CheckBox checkBox_MesReadOver3; + private System.Windows.Forms.CheckBox checkBox_MesRead3; + private System.Windows.Forms.Button button_ManualPartLoad3; + } +} + diff --git a/SyUpLoad/SyUpLoad/PartLoad.Fun1.BarCode.cs b/SyUpLoad/SyUpLoad/PartLoad.Fun1.BarCode.cs new file mode 100644 index 0000000..c7bebf7 --- /dev/null +++ b/SyUpLoad/SyUpLoad/PartLoad.Fun1.BarCode.cs @@ -0,0 +1,93 @@ +using MesWorkMqtt; +using MQTTnet.Client.Connecting; +using MQTTnet.Client.Disconnecting; +using MQTTnet.Client.Receiving; + +using bizFacade; +using MesWorkMqtt; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Configuration; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; +using MQTTnet; +using System.Threading; +using DoWhatPlc; +using MesServerWork; + +namespace SyUpLoad +{ + public partial class PartLoad + { + private void button_barcode_Click(object sender, EventArgs e) + { + string opName; + string kuweiNum; + string barCode; + string orderForm; + string engineID; + string engineType; + int engineTypeID; + opName = OPName01; + barCode = textBox_barcode.Text.Replace("\r\n", ""); + kuweiNum = Get_kuweiNum(); + if (kuweiNum == "0") return; + + CreateEngineID(opName, out engineType, out engineTypeID, out engineID, out orderForm); + if(engineID.Length<1) + { + MessageBox.Show("入库失败"); + return; + } + BaseDataSystemMES.GetUpLoadBarCode_Update(opName, kuweiNum, barCode, orderForm, + engineID, engineType, engineTypeID); + + BaseDataSystemMES.GetUpLoadBarCode(OPName01, out DataTable dt_OPName01); + dataGridView_OPA1001.DataSource = dt_OPName01; + + } + + private string Get_kuweiNum() + { + string kuweiNum = "0"; + + if (radioButton1.Checked) + { + kuweiNum = "1"; + } + else if (radioButton2.Checked) + { + kuweiNum = "2"; + + } + else if (radioButton3.Checked) + { + kuweiNum = "3"; + + } + else if (radioButton4.Checked) + { + kuweiNum = "4"; + + } + else if (radioButton5.Checked) + { + kuweiNum = "5"; + + } + else if (radioButton6.Checked) + { + kuweiNum = "6"; + + } + + return kuweiNum; + } + + } +} diff --git a/SyUpLoad/SyUpLoad/PartLoad.Fun1.PartLoad.cs b/SyUpLoad/SyUpLoad/PartLoad.Fun1.PartLoad.cs new file mode 100644 index 0000000..44293d3 --- /dev/null +++ b/SyUpLoad/SyUpLoad/PartLoad.Fun1.PartLoad.cs @@ -0,0 +1,160 @@ +using MesWorkMqtt; +using MQTTnet.Client.Connecting; +using MQTTnet.Client.Disconnecting; +using MQTTnet.Client.Receiving; + +using bizFacade; +using MesWorkMqtt; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Configuration; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; +using MQTTnet; +using System.Threading; +using DoWhatPlc; +using MesServerWork; + +namespace SyUpLoad +{ + public partial class PartLoad + { + /// + /// 申请上线 + /// + /// + /// + + /// + /// 申请上线 + /// + /// + /// + private void fun_PartLoadManual(string OpName) + { + try + { + bool engineTypeGetOver_MES; + bool partLoad; + MIS_BASE.Read_EngineTypeGetOver_MES(OpName, out engineTypeGetOver_MES); + + MIS_BASE.Read_PartLoad(OpName, out partLoad); + + if(partLoad == false || engineTypeGetOver_MES==true) + { + MessageBox.Show("检查申请上线信号"); + return; + } + + //DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + //string OpName = OPName01; + //int tagValue = Convert.ToInt32(msgEvent.TagValue); + + //SetChekcBox(tagValue, checkBox_PartLoad); + + + int engineTypeID; + string engineID; + string engineType; + byte kuweiNum; + //if (tagValue == 1) + { + // BaseDataSystemMES.MesServer_Process_EngineTypeOver(OpName); + DataTable dt; + BaseDataSystemMES.GetUpLoadBarCodeEngineID(OpName, out dt); + if (dt.Rows.Count < 1) + { + + button_ManualPartLoad.Invoke(new Action(() => { + button_ManualPartLoad.Enabled = true; + })); + MessageBox.Show("虚拟库存无件,请扫描上线工位小车上的工件条码"); + return; + } + engineTypeID = Convert.ToInt32(dt.Rows[0]["机型代码"]); + engineID = dt.Rows[0]["发动机号"].ToString(); + engineType = dt.Rows[0]["发动机型号"].ToString(); + kuweiNum = Convert.ToByte(dt.Rows[0]["库位号"]); + + + + + ////将产品信息写入PLC + MIS_BASE.Write_EngineTypeID_MES(OpName, engineTypeID); + MIS_BASE.Write_EngineType_MES(OpName, engineType); + MIS_BASE.Write_EngineID_MES(OpName, engineID); + DtWebApi.ReadWritePLC.WritePLC(warehouseLocation.ToString(), OpName, kuweiNum); + + MIS_BASE.Write_EngineTypeGetOver_MES(OpName, true); + + ////将产品信息写入PLC + MIS_BASE.Read_EngineTypeID_MES(OpName, out engineTypeID); + MIS_BASE.Read_EngineType_MES(OpName, out engineType); + MIS_BASE.Read_EngineID_MES(OpName, out engineID); + + kuweiNum = Convert.ToByte(DtWebApi.ReadWritePLC.ReadPLC(warehouseLocation.ToString(), OpName)); + + SetTextBox(engineType, textBox_MesType); + SetTextBox(engineID, textBox_MesEngineID); + SetTextBox(kuweiNum.ToString(), textBox_MesPosition); + + } + + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function03:PartLoad"); + } + } + + private void fun_PartLoadManual2(string OpName) + { + try + { + bool engineTypeGetOver; + bool partLoad; + + int engineTypeID; + string engineID; + string engineType; + byte kuweiNum; + + MIS_BASE.Read_EngineGetOver_PLC(OpName, out engineTypeGetOver); + + + if (engineTypeGetOver == false) + { + MessageBox.Show("检查传递机型信号"); + return; + } + + DataTable dt; + BaseDataSystemMES.GetUnLoadWarehouseNo(OpName, out dt); + if (dt.Rows.Count == 0) + { + MessageBox.Show("下线库位已满"); + button_ManualPartLoad2.Invoke(new Action(() => { + button_ManualPartLoad2.Enabled = true; + })); + return; + } + else + { + kuweiNum = Convert.ToByte(dt.Rows[0]["库位号"]); + DtWebApi.ReadWritePLC.WritePLC(warehouseLocation.ToString(), OpName, kuweiNum); + MIS_BASE.Write_FixAllow(OpName, true); + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function03:PartLoad"); + } + } + + } +} diff --git a/SyUpLoad/SyUpLoad/PartLoad.Fun1.cs b/SyUpLoad/SyUpLoad/PartLoad.Fun1.cs new file mode 100644 index 0000000..03d959f --- /dev/null +++ b/SyUpLoad/SyUpLoad/PartLoad.Fun1.cs @@ -0,0 +1,105 @@ +using MesWorkMqtt; +using MQTTnet.Client.Connecting; +using MQTTnet.Client.Disconnecting; +using MQTTnet.Client.Receiving; + +using bizFacade; +using MesWorkMqtt; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Configuration; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; +using MQTTnet; +using System.Threading; +using DoWhatPlc; +using MesServerWork; + +namespace SyUpLoad +{ + public partial class PartLoad + { + private void MesServerFunction1(string msgValue) + { + try + { + DoWhatPlc.ReturnValueString rv = Newtonsoft.Json.JsonConvert.DeserializeObject(msgValue); + + string OpName; + string tagValue; + string fun; + string mesServerCode; + string mesServerdllName; + + OpName = rv.OpName; + switch (rv.TagValue.ToLower()) + { + case "false": + tagValue = "0"; + break; + case "true": + tagValue = "1"; + break; + default: + tagValue = rv.TagValue; + break; + } + switch(rv.TagTypeCodeID) + { + //PLC 申请发动机编号 PartLoad + case "43": + break; + //PLC 传递机型 EngineTypeGetOverPLC + case "44": + break; + //MES 传递机型 EngineTypeGetOverMES + case "5": + break; + //MES 工作完成 MaterialVerifyOver + case "7": + break; + } + + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "MesServerFunction"); + } + } + + + private void fun_EngineTypeGetOverMES(object e) + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + var cb = button_ManualPartLoad; + cb.Invoke(new Action(() => { + if (tagValue == 1) + { + cb.Enabled = false; + } + else + { + cb.Enabled = true; + } + })); + SetChekcBox(tagValue, checkBox_MesEngineTypeGetOver); + + } + + + + + + private void button_ManualPartLoad_Click(object sender, EventArgs e) + { + fun_PartLoadManual(OPName01); + } + } +} diff --git a/SyUpLoad/SyUpLoad/PartLoad.SetControl.cs b/SyUpLoad/SyUpLoad/PartLoad.SetControl.cs new file mode 100644 index 0000000..380647b --- /dev/null +++ b/SyUpLoad/SyUpLoad/PartLoad.SetControl.cs @@ -0,0 +1,53 @@ +using MesWorkMqtt; +using MQTTnet.Client.Connecting; +using MQTTnet.Client.Disconnecting; +using MQTTnet.Client.Receiving; + +using bizFacade; +using MesWorkMqtt; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Configuration; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; +using MQTTnet; +using System.Threading; +using DoWhatPlc; +using MesServerWork; + +namespace SyUpLoad +{ + public partial class PartLoad + { + private void SetChekcBox(int tagValue, object checkBox) + { + + CheckBox cb = (CheckBox)checkBox; + cb.Invoke(new Action(() => { + if (tagValue == 1) + { + cb.Checked = true; + cb.BackColor = Color.LightGreen; + } + else + { + cb.Checked = false; + cb.BackColor = Color.Gray; + } + })); + + } + private void SetTextBox(string text, object controlBox) + { + TextBox cb = (TextBox)controlBox; + cb.Invoke(new Action(() => { + cb.Text = text; + })); + } + } +} diff --git a/SyUpLoad/SyUpLoad/PartLoad.cs b/SyUpLoad/SyUpLoad/PartLoad.cs new file mode 100644 index 0000000..0532e10 --- /dev/null +++ b/SyUpLoad/SyUpLoad/PartLoad.cs @@ -0,0 +1,184 @@ +using MesWorkMqtt; +using MQTTnet.Client.Connecting; +using MQTTnet.Client.Disconnecting; +using MQTTnet.Client.Receiving; + +using bizFacade; +using MesWorkMqtt; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Configuration; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; +using MQTTnet; +using System.Threading; +using DoWhatPlc; +using MesServerWork; +using System.Collections; + +namespace SyUpLoad +{ + public partial class PartLoad : Form + { + + public static string MqttUrl = ConfigurationManager.AppSettings["MqttUrl"]; + public static string MqttTargetTopic = ConfigurationManager.AppSettings["MqttTargetTopic"]; + public static string Url_WebApi = ConfigurationManager.AppSettings["Url_WebApi"]; + public static string ConnectionString_MES = ConfigurationManager.AppSettings["ConnectionString_MES"]; + public static string OPName01Fun = ConfigurationManager.AppSettings["OPName01"]; + public static string OPName02Fun = ConfigurationManager.AppSettings["OPName02"]; + //public static string OPName03Fun = ConfigurationManager.AppSettings["OPName03"]; + //第一个库房工位号 + public static string OPName01; + //第二个库房工位号 + public static string OPName02; + public static byte warehouseLocation = 112; + Hashtable ht_OpnameFun; + + DataTable dt_OPName01; + DataTable dt_OPName02; + + public PartLoad() + { + InitializeComponent(); + InitHashTable(); + + BaseDataSystemMES.GetUpLoadBarCode(OPName01, out DataTable dt_OPName01); + BaseDataSystemMES.GetUpLoadBarCode(OPName02, out DataTable dt_OPName02); + + dataGridView_OPA1001.DataSource = dt_OPName01; + dataGridView_OPA1002.DataSource = dt_OPName02; + } + + private void InitHashTable() + { + ht_OpnameFun = new Hashtable(); + var op = OPName01Fun.Split('|'); + ht_OpnameFun.Add(op[0], op[1]); + OPName01 = op[0]; + op = OPName02Fun.Split('|'); + ht_OpnameFun.Add(op[0], op[1]); + OPName02 = op[0]; + + //op = OPName03Fun.Split('|'); + //ht_OpnameFun.Add(op[0], op[1]); + } + + + + private void PartLoad_Load(object sender, EventArgs e) + { + SetCOM(); + + Mqtt.StartAsync(); + Mqtt.mqttClient.ConnectedHandler = new MqttClientConnectedHandlerDelegate(OnSubscriberConnected); + Mqtt.mqttClient.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(OnSubscriberDisconnected); + Mqtt.mqttClient.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(OnSubscriberMessageReceived); + + ////MesServerCode哈希表创建 + //MesServerWork.MIS_BASE.InitHashtable_MesServerCode(); + } + + private void OnSubscriberConnected(MqttClientConnectedEventArgs x) + { + //var rec = x.AuthenticateResult.ResultCode.ToString(); + //label_State.Text = rec; + } + + private void OnSubscriberDisconnected(MqttClientDisconnectedEventArgs x) + { + //var rec = x.AuthenticateResult.ResultCode.ToString(); + //label_State.Text = rec; + } + + private void OnSubscriberMessageReceived(MqttApplicationMessageReceivedEventArgs x) + { + var rec = x.ApplicationMessage.ConvertPayloadToString(); + + //保存数据 + //ThreadPool.QueueUserWorkItem(MIS_Funtion, rec); + + //处理MES业务 + ThreadPool.QueueUserWorkItem(TransferInfToMES, rec); + } + + private void TransferInfToMES(object text) + { + try + { + string recData = text.ToString(); + string[] dataArray = recData.Split('|'); + if (dataArray.Length != 4) + return; + //消息来源 + string m_Source = dataArray[0].ToString(); + //消息类型 Barcode + string m_Command = dataArray[1].ToString(); + //工位号 + string m_OpName = dataArray[2].ToString(); + //消息参数 + string m_Value = dataArray[3].ToString(); + + //if (!m_WorkStart_OpName.ContainsKey(m_OpName)) return; //当前系统是否存在该工位 + + switch (m_Source) + { + case "BarCode": + //处理条码逻辑 + if (m_Command == "Bar") + { + //MesServerFunction(m_OpName, m_Value, "fun_Barcode"); + } + break; + case "WEB": + if (m_Command == "Barcode") + { + //MesServerFunction(m_OpName, m_Value, "fun_Barcode"); + + } + else + { + string Content = m_Command + "|" + m_Value; + //MesServerFunction(m_OpName, Content, "fun_WebSubmit"); + + } + break; + case "PLC": + if (!ht_OpnameFun.ContainsKey(m_OpName)) return; + string funID = ht_OpnameFun[m_OpName].ToString(); + switch(funID) + { + case "1": + SyUpLoadFun1.MesServerFunction(m_Value); + break; + case "2": + //SyUpLoadFun2.MesServerFunction(m_Value); + break; + case "3": + //SyUpLoadFun3.MesServerFunction(m_Value); + break; + //case "3": + // MesServerFunction(m_Value); + // break; + } + break; + } + + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "TransferInf"); + } + } + + private void button_ManualPartLoad2_Click(object sender, EventArgs e) + { + //fun_PartLoadManual2(OPName02); + } + } +} diff --git a/SyUpLoad/SyUpLoad/PartLoad.resx b/SyUpLoad/SyUpLoad/PartLoad.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/SyUpLoad/SyUpLoad/PartLoad.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/SyUpLoad/SyUpLoad/Program.cs b/SyUpLoad/SyUpLoad/Program.cs new file mode 100644 index 0000000..a69689c --- /dev/null +++ b/SyUpLoad/SyUpLoad/Program.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace SyUpLoad +{ + static class Program + { + /// + /// 应用程序的主入口点。 + /// + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + Application.Run(new PartLoad()); + } + } +} diff --git a/SyUpLoad/SyUpLoad/Properties/AssemblyInfo.cs b/SyUpLoad/SyUpLoad/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..c254d32 --- /dev/null +++ b/SyUpLoad/SyUpLoad/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// 有关程序集的一般信息由以下 +// 控制。更改这些特性值可修改 +// 与程序集关联的信息。 +[assembly: AssemblyTitle("SyUpLoad")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("SyUpLoad")] +[assembly: AssemblyCopyright("Copyright © 2022")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// 将 ComVisible 设置为 false 会使此程序集中的类型 +//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型 +//请将此类型的 ComVisible 特性设置为 true。 +[assembly: ComVisible(false)] + +// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID +[assembly: Guid("81604748-73c5-43fa-8e27-be0ab28618c3")] + +// 程序集的版本信息由下列四个值组成: +// +// 主版本 +// 次版本 +// 生成号 +// 修订号 +// +//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值 +//通过使用 "*",如下所示: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/SyUpLoad/SyUpLoad/Properties/Resources.Designer.cs b/SyUpLoad/SyUpLoad/Properties/Resources.Designer.cs new file mode 100644 index 0000000..a8192d6 --- /dev/null +++ b/SyUpLoad/SyUpLoad/Properties/Resources.Designer.cs @@ -0,0 +1,63 @@ +//------------------------------------------------------------------------------ +// +// 此代码由工具生成。 +// 运行时版本:4.0.30319.42000 +// +// 对此文件的更改可能会导致不正确的行为,并且如果 +// 重新生成代码,这些更改将会丢失。 +// +//------------------------------------------------------------------------------ + +namespace SyUpLoad.Properties { + using System; + + + /// + /// 一个强类型的资源类,用于查找本地化的字符串等。 + /// + // 此类是由 StronglyTypedResourceBuilder + // 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。 + // 若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen + // (以 /str 作为命令选项),或重新生成 VS 项目。 + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.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 (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("SyUpLoad.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/SyUpLoad/SyUpLoad/Properties/Resources.resx b/SyUpLoad/SyUpLoad/Properties/Resources.resx new file mode 100644 index 0000000..af7dbeb --- /dev/null +++ b/SyUpLoad/SyUpLoad/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/SyUpLoad/SyUpLoad/Properties/Settings.Designer.cs b/SyUpLoad/SyUpLoad/Properties/Settings.Designer.cs new file mode 100644 index 0000000..dc7a791 --- /dev/null +++ b/SyUpLoad/SyUpLoad/Properties/Settings.Designer.cs @@ -0,0 +1,26 @@ +//------------------------------------------------------------------------------ +// +// 此代码由工具生成。 +// 运行时版本:4.0.30319.42000 +// +// 对此文件的更改可能会导致不正确的行为,并且如果 +// 重新生成代码,这些更改将会丢失。 +// +//------------------------------------------------------------------------------ + +namespace SyUpLoad.Properties { + + + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "17.0.3.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/SyUpLoad/SyUpLoad/Properties/Settings.settings b/SyUpLoad/SyUpLoad/Properties/Settings.settings new file mode 100644 index 0000000..3964565 --- /dev/null +++ b/SyUpLoad/SyUpLoad/Properties/Settings.settings @@ -0,0 +1,7 @@ + + + + + + + diff --git a/SyUpLoad/SyUpLoad/SyUpLoad.csproj b/SyUpLoad/SyUpLoad/SyUpLoad.csproj new file mode 100644 index 0000000..c665f36 --- /dev/null +++ b/SyUpLoad/SyUpLoad/SyUpLoad.csproj @@ -0,0 +1,205 @@ + + + + + Debug + AnyCPU + {81604748-73C5-43FA-8E27-BE0AB28618C3} + WinExe + SyUpLoad + SyUpLoad + v4.8 + 512 + true + true + + + + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + False + ..\dll\MQTTnet.dll + + + False + ..\dll\MQTTnet.Extensions.ManagedClient.dll + + + + + ..\packages\System.Configuration.ConfigurationManager.6.0.1\lib\net461\System.Configuration.ConfigurationManager.dll + + + + + + ..\packages\System.Net.Security.4.3.2\lib\net46\System.Net.Security.dll + + + ..\packages\System.Net.WebSockets.4.3.0\lib\net46\System.Net.WebSockets.dll + + + ..\packages\System.Net.WebSockets.Client.4.3.2\lib\net46\System.Net.WebSockets.Client.dll + + + + ..\packages\System.Security.AccessControl.6.0.0\lib\net461\System.Security.AccessControl.dll + + + ..\packages\System.Security.Cryptography.Algorithms.4.3.0\lib\net461\System.Security.Cryptography.Algorithms.dll + + + ..\packages\System.Security.Cryptography.Encoding.4.3.0\lib\net46\System.Security.Cryptography.Encoding.dll + + + ..\packages\System.Security.Cryptography.Primitives.4.3.0\lib\net46\System.Security.Cryptography.Primitives.dll + + + ..\packages\System.Security.Cryptography.X509Certificates.4.3.0\lib\net461\System.Security.Cryptography.X509Certificates.dll + + + ..\packages\System.Security.Permissions.6.0.0\lib\net461\System.Security.Permissions.dll + + + ..\packages\System.Security.Principal.Windows.5.0.0\lib\net461\System.Security.Principal.Windows.dll + + + + + + + + + + + + + + + + + Form + + + Form + + + + + Form + + + + Form + + + Form + + + Form + + + Form + + + PartLoad.cs + + + Form + + + Form + + + + + PartLoad.cs + + + ResXFileCodeGenerator + Resources.Designer.cs + Designer + + + True + Resources.resx + True + + + + + SettingsSingleFileGenerator + Settings.Designer.cs + + + True + Settings.settings + True + + + + + + + + {1a10fdb2-1a6a-44a8-ab4d-33387563247e} + 00-0Json8.3.1 + + + {f55da1a0-a982-4479-8c47-0d9a5aaf3e18} + 00MesWorkMqtt + + + {0d1af432-439a-4920-8692-43ae139f5530} + 01_01DoWhatPlc + + + {3e6d1dd5-01c9-435f-9941-61f906ce35bb} + 02_02WebApiCallPLC + + + {f434e066-4c59-47c8-aa82-6f48cc84501a} + 04-DataBaseAccess + + + {f0a0c525-03fd-428a-9b17-7f54aa0e4475} + 07BusinessFacade + + + {d98be764-adeb-488d-9714-61e308aa8201} + 08-WebFun_base + + + {90e76fb4-646d-45e2-95db-0b8ab4e465d6} + 09-MesDataFunction + + + + + + + 这台计算机上缺少此项目引用的 NuGet 程序包。使用“NuGet 程序包还原”可下载这些程序包。有关更多信息,请参见 http://go.microsoft.com/fwlink/?LinkID=322105。缺少的文件是 {0}。 + + + + \ No newline at end of file diff --git a/SyUpLoad/SyUpLoad/packages.config b/SyUpLoad/SyUpLoad/packages.config new file mode 100644 index 0000000..4c595d5 --- /dev/null +++ b/SyUpLoad/SyUpLoad/packages.config @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/SyUpLoad/dll/00.1Newtonsoft.Json.dll b/SyUpLoad/dll/00.1Newtonsoft.Json.dll new file mode 100644 index 0000000..85a14c9 Binary files /dev/null and b/SyUpLoad/dll/00.1Newtonsoft.Json.dll differ diff --git a/SyUpLoad/dll/00.1Newtonsoft.Json.pdb b/SyUpLoad/dll/00.1Newtonsoft.Json.pdb new file mode 100644 index 0000000..a01b35b Binary files /dev/null and b/SyUpLoad/dll/00.1Newtonsoft.Json.pdb differ diff --git a/SyUpLoad/dll/00MesWorkMqtt.dll b/SyUpLoad/dll/00MesWorkMqtt.dll new file mode 100644 index 0000000..15cb845 Binary files /dev/null and b/SyUpLoad/dll/00MesWorkMqtt.dll differ diff --git a/SyUpLoad/dll/00MesWorkMqtt.pdb b/SyUpLoad/dll/00MesWorkMqtt.pdb new file mode 100644 index 0000000..5dc65cb Binary files /dev/null and b/SyUpLoad/dll/00MesWorkMqtt.pdb differ diff --git a/SyUpLoad/dll/01DoWhatPlc.dll b/SyUpLoad/dll/01DoWhatPlc.dll new file mode 100644 index 0000000..25c33ee Binary files /dev/null and b/SyUpLoad/dll/01DoWhatPlc.dll differ diff --git a/SyUpLoad/dll/01DoWhatPlc.pdb b/SyUpLoad/dll/01DoWhatPlc.pdb new file mode 100644 index 0000000..e75a71b Binary files /dev/null and b/SyUpLoad/dll/01DoWhatPlc.pdb differ diff --git a/SyUpLoad/dll/02WebApiCall.dll b/SyUpLoad/dll/02WebApiCall.dll new file mode 100644 index 0000000..9a3f5b0 Binary files /dev/null and b/SyUpLoad/dll/02WebApiCall.dll differ diff --git a/SyUpLoad/dll/02WebApiCall.dll.config b/SyUpLoad/dll/02WebApiCall.dll.config new file mode 100644 index 0000000..6035ea8 --- /dev/null +++ b/SyUpLoad/dll/02WebApiCall.dll.config @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/SyUpLoad/dll/02WebApiCall.pdb b/SyUpLoad/dll/02WebApiCall.pdb new file mode 100644 index 0000000..16b7902 Binary files /dev/null and b/SyUpLoad/dll/02WebApiCall.pdb differ diff --git a/SyUpLoad/dll/04DataBaseAccess.dll b/SyUpLoad/dll/04DataBaseAccess.dll new file mode 100644 index 0000000..1378ec9 Binary files /dev/null and b/SyUpLoad/dll/04DataBaseAccess.dll differ diff --git a/SyUpLoad/dll/04DataBaseAccess.pdb b/SyUpLoad/dll/04DataBaseAccess.pdb new file mode 100644 index 0000000..740cc80 Binary files /dev/null and b/SyUpLoad/dll/04DataBaseAccess.pdb differ diff --git a/SyUpLoad/dll/07BusinessFacade.dll b/SyUpLoad/dll/07BusinessFacade.dll new file mode 100644 index 0000000..02e2595 Binary files /dev/null and b/SyUpLoad/dll/07BusinessFacade.dll differ diff --git a/SyUpLoad/dll/07BusinessFacade.pdb b/SyUpLoad/dll/07BusinessFacade.pdb new file mode 100644 index 0000000..dcb0c1b Binary files /dev/null and b/SyUpLoad/dll/07BusinessFacade.pdb differ diff --git a/SyUpLoad/dll/08WebFun_base.dll b/SyUpLoad/dll/08WebFun_base.dll new file mode 100644 index 0000000..e088df4 Binary files /dev/null and b/SyUpLoad/dll/08WebFun_base.dll differ diff --git a/SyUpLoad/dll/08WebFun_base.pdb b/SyUpLoad/dll/08WebFun_base.pdb new file mode 100644 index 0000000..b4db747 Binary files /dev/null and b/SyUpLoad/dll/08WebFun_base.pdb differ diff --git a/SyUpLoad/dll/09MesDataFunction.dll b/SyUpLoad/dll/09MesDataFunction.dll new file mode 100644 index 0000000..e31947c Binary files /dev/null and b/SyUpLoad/dll/09MesDataFunction.dll differ diff --git a/SyUpLoad/dll/09MesDataFunction.pdb b/SyUpLoad/dll/09MesDataFunction.pdb new file mode 100644 index 0000000..8c336b4 Binary files /dev/null and b/SyUpLoad/dll/09MesDataFunction.pdb differ diff --git a/SyUpLoad/dll/BusinessFacade.pdb b/SyUpLoad/dll/BusinessFacade.pdb new file mode 100644 index 0000000..2e1bfcb Binary files /dev/null and b/SyUpLoad/dll/BusinessFacade.pdb differ diff --git a/SyUpLoad/dll/MQTTnet.Extensions.ManagedClient.dll b/SyUpLoad/dll/MQTTnet.Extensions.ManagedClient.dll new file mode 100644 index 0000000..99035f6 Binary files /dev/null and b/SyUpLoad/dll/MQTTnet.Extensions.ManagedClient.dll differ diff --git a/SyUpLoad/dll/MQTTnet.dll b/SyUpLoad/dll/MQTTnet.dll new file mode 100644 index 0000000..2951433 Binary files /dev/null and b/SyUpLoad/dll/MQTTnet.dll differ diff --git a/SyUpLoadBak/SyUpLoad.sln b/SyUpLoadBak/SyUpLoad.sln new file mode 100644 index 0000000..780d8ed --- /dev/null +++ b/SyUpLoadBak/SyUpLoad.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.32602.291 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SyUpLoad", "SyUpLoad\SyUpLoad.csproj", "{81604748-73C5-43FA-8E27-BE0AB28618C3}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {81604748-73C5-43FA-8E27-BE0AB28618C3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {81604748-73C5-43FA-8E27-BE0AB28618C3}.Debug|Any CPU.Build.0 = Debug|Any CPU + {81604748-73C5-43FA-8E27-BE0AB28618C3}.Release|Any CPU.ActiveCfg = Release|Any CPU + {81604748-73C5-43FA-8E27-BE0AB28618C3}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {AC76E79B-C576-4AF6-889E-57D1B50CC4F4} + EndGlobalSection +EndGlobal diff --git a/SyUpLoadBak/SyUpLoad/App.config b/SyUpLoadBak/SyUpLoad/App.config new file mode 100644 index 0000000..7b3c466 --- /dev/null +++ b/SyUpLoadBak/SyUpLoad/App.config @@ -0,0 +1,36 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/SyUpLoadBak/SyUpLoad/BarCode/MESPC.BarCode.Read.cs b/SyUpLoadBak/SyUpLoad/BarCode/MESPC.BarCode.Read.cs new file mode 100644 index 0000000..581926c --- /dev/null +++ b/SyUpLoadBak/SyUpLoad/BarCode/MESPC.BarCode.Read.cs @@ -0,0 +1,325 @@ +using System; +using System.Collections; +using System.Runtime.InteropServices; +using System.Drawing; +using System.ComponentModel; +using System.Windows.Forms; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Data; +using System.Net; +using System.IO; + +using System.IO.Ports; + +using System.Collections.Generic; +using System.Text; + +using System.Threading; + + +namespace SyUpLoad +{ + partial class PartLoad + { + /// + /// DataReceivedɨǹ뵽 + /// BarCode(string barCode) + /// + /// + public delegate void BarCodeInvoke(string barCode); + /// + /// BarCode(string barCode) + /// DataReceivedɨǹ뵽 + /// + BarCodeInvoke barCodeInvoke; + + + /// + /// ǰɨǹ + /// 1:ֳ֣2̶ + /// + string ScannerType_Current = "1"; + + //ֳɨǹ + private System.IO.Ports.SerialPort serialPort1 = new SerialPort(); + /// + /// ʼCOMͨѶ + /// + public void SetCOM() + { + try + { + //ѡɨǹ + barCodeInvoke = new BarCodeInvoke(BarCode); + SetCOM1(); + } + catch (Exception err) + { + // ApplicationLog.WriteLog(err, err.Message); + } + } + /// + /// ʼCOMͨѶ + /// + public void SetCOM1() + { + try + { + //if (ApplicationConfig.PortName.Length < 3) + //{ + // return; + //} + serialPort1.PortName = PortName; //˿ں + serialPort1.BaudRate = BaudRate; //ʣĬΪ9600 + serialPort1.Parity = Parity.None;//żУ + serialPort1.StopBits = StopBits.One;//ֹͣλ + serialPort1.ReadTimeout = ReadTimeout; //ʱ1000δݾʱ쳣 + serialPort1.DtrEnable = true; + serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived); + + OpenSerialPort(); + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, err.Message); + } + finally + { + + } + } + + /// + /// رɨǹ + /// + private void OpenSerialPortAll() + { + SetCOM1(); + } + /// + /// ɨǹ + /// + private bool OpenSerialPort() + { + try + { + //if (ApplicationConfig.PortName.Length < 4) + //{ + // return true; + //} + if (serialPort1 == null) return true; + if (!serialPort1.IsOpen) + { + serialPort1.Open(); + SerialPort_Closing = false; + } + return true; + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, err.Message); + return false; + } + } + /// + /// رɨǹ + /// + private bool CloseSerialPort() + { + try + { + //if (ApplicationConfig.PortName.Length < 4) + //{ + // return true; + //} + if (serialPort1 == null) return true; + + //ݵǰڶжϲ + if (serialPort1.IsOpen) + { + SerialPort_Closing = true; + while (SerialPort_Listening) Application.DoEvents(); + serialPort1.Close(); + } + return true; + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, "CloseSerialPort"); + return false; + } + } + /// + /// رɨǹ + /// + private void CloseSerialPortAll() + { + CloseSerialPort(); + } + /// + /// Ƿûִinvokeز + /// + private bool SerialPort_Listening = false; + /// + /// ǷڹرմڣִApplication.DoEvents + /// + private bool SerialPort_Closing = false; + /// + /// ֳɨǹ + /// ߸׸߹λɨǹǹ̶ɨǹF102 + /// + /// + /// + void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e) + { + //byte[] readBuf; + //int HowTime = ApplicationConfig.HowTime; + //int ByteTime = ApplicationConfig.ByteTime; + string barCode; + //ȡһֵֵڴͨŹն˾ (DTR) źš + //Ϊ trueն˾ (DTR)Ϊ falseĬΪ false + bool DtrEnable = serialPort1.DtrEnable; + //ѽþźŷ͵ö˿ڣΪ trueΪ false + bool DsrHolding = serialPort1.DsrHolding; + //˿ڴж״̬Ϊ trueΪ false + bool BreakState = serialPort1.BreakState; ; + + if (SerialPort_Closing) return; + //ڹرգԲֱӷأ ɴڼ̵߳һѭ + try + { + //ñǣ˵ѾʼݣһҪʹϵͳUIġ + SerialPort_Listening = true; + //20110225 zhangji + //ȡɨǹϢʱʱ޷ȫȡɨϢ + Thread.Sleep(200); + int n = serialPort1.BytesToRead; + byte[] buf = new byte[n]; + //һʱ洢ǰĴ + serialPort1.Read(buf, 0, n); + n = n - ScannerTrim; + barCode = Encoding.UTF8.GetString(buf, 0, n); + BeginInvoke(barCodeInvoke, new Object[] { barCode }); + } + catch (Exception err) + { + + barCode = ""; + //ApplicationLog.WriteLog(err, err.Message); + } + finally + { + //ɨǹ + serialPort1.DiscardInBuffer(); + SerialPort_Listening = false;//ˣuiԹرմˡ + + //ȹرմڣȻٴ򿪴 + CloseSerialPort(); + OpenSerialPort(); + } + } + + /// + /// ַתַ16 + /// + /// ֽ + /// "01 02 0F" + public static string ByteToString(byte[] InBytes) + { + string StringOut = ""; + foreach (byte InByte in InBytes) + { + StringOut = StringOut + String.Format("{0:X2}", InByte) + " "; + } + + return StringOut.Trim(); + } + /// + /// strhex תֽ + /// + /// "01 02 0F" ÿոֿ + /// + public static byte[] StringToByte_Int(string InString) + { + string[] ByteStrings; + ByteStrings = InString.Split("|".ToCharArray()); + byte[] ByteOut; + ByteOut = new byte[ByteStrings.Length]; + try + { + for (int i = 0; i <= ByteStrings.Length - 1; i++) + { + ByteOut[i] = byte.Parse(ByteStrings[i]); + } + } + catch (Exception err) + { + + //ApplicationLog.WriteLog(err, err.Message); + } + return ByteOut; + } + /// + /// strhex תֽ + /// + /// "01 02 0F" ÿոֿ + /// + public static byte[] StringToByte(string InString) + { + string[] ByteStrings; + ByteStrings = InString.Split(" ".ToCharArray()); + byte[] ByteOut; + ByteOut = new byte[ByteStrings.Length]; + for (int i = 0; i <= ByteStrings.Length - 1; i++) + { + ByteOut[i] = byte.Parse(ByteStrings[i], System.Globalization.NumberStyles.HexNumber); + } + return ByteOut; + } + + /// + /// strhex תֽ + /// + /// "01 02 0F" м޿ո + /// + public static byte[] StringToByte_2(string InString) + { + byte[] ByteOut; + InString = InString.Replace(" ", ""); + try + { + string[] ByteStrings = new string[InString.Length / 2]; + int j = 0; + for (int i = 0; i < ByteStrings.Length; i++) + { + + ByteStrings[i] = InString.Substring(j, 2); + j += 2; + } + + ByteOut = new byte[ByteStrings.Length]; + for (int i = 0; i <= ByteStrings.Length - 1; i++) + { + ByteOut[i] = byte.Parse(ByteStrings[i], System.Globalization.NumberStyles.HexNumber); + } + } + catch (Exception ex) + { + + throw new Exception(ex.Message); + } + + return ByteOut; + } + /// + /// ַ ת16ַ + /// + /// unico + /// ơ01 0f + public static string Str_To_0X(string InString) + { + return ByteToString(UnicodeEncoding.Default.GetBytes(InString)); + } + } +} diff --git a/SyUpLoadBak/SyUpLoad/BarCode/MESPC.BarCode.cs b/SyUpLoadBak/SyUpLoad/BarCode/MESPC.BarCode.cs new file mode 100644 index 0000000..27c2cc2 --- /dev/null +++ b/SyUpLoadBak/SyUpLoad/BarCode/MESPC.BarCode.cs @@ -0,0 +1,57 @@ +using System; +using System.Collections; +using System.Runtime.InteropServices; +using System.Drawing; +using System.ComponentModel; +using System.Windows.Forms; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Data; +using System.Net; +using System.IO; + +using System.IO.Ports; + +using System.Collections.Generic; +using System.Text; + +using System.Threading; +using System.Configuration; + +namespace SyUpLoad +{ + /// + /// 扫描枪 + /// + partial class PartLoad + { + string PortName = ConfigurationManager.AppSettings["PortName"]; + int ReadTimeout = Convert.ToInt32( ConfigurationManager.AppSettings["ReadTimeout"]); + int BaudRate = Convert.ToInt32(ConfigurationManager.AppSettings["BaudRate"]); + int ScannerTrim = Convert.ToInt32(ConfigurationManager.AppSettings["ScannerTrim"]); + + + /// + /// 处理条码信息 + /// + /// + private void BarCode(string barCode) + { + try + { + barCode = barCode.Replace("\r\n", ""); + textBox_barcode.Text = barCode; + + button_barcode_Click(null, null); + //string sendStr = "BarCode|Bar|" + ApplicationConfig.OpName + "|" + barCode; + //发送UDP到MES通讯服务器 + //ApplicationLog.WriteLog("11111111111111"); + //asySendMessage(sendStr); + } + catch (Exception err) + { + // ApplicationLog.WriteLog(err, "BarCode"); + } + } + } +} diff --git a/SyUpLoadBak/SyUpLoad/BarCode/_system~.ini b/SyUpLoadBak/SyUpLoad/BarCode/_system~.ini new file mode 100644 index 0000000..e69de29 diff --git a/SyUpLoadBak/SyUpLoad/Methods/EngineGetOverBaseWork.cs b/SyUpLoadBak/SyUpLoad/Methods/EngineGetOverBaseWork.cs new file mode 100644 index 0000000..4587a89 --- /dev/null +++ b/SyUpLoadBak/SyUpLoad/Methods/EngineGetOverBaseWork.cs @@ -0,0 +1,134 @@ +using System; +using System.Data; +using bizFacade; +using MesServerWork; + +namespace SyUpLoad +{ + partial class PartLoad + { + /// + /// 正常逻辑工作(传递机型) + /// + /// + /// + /// + /// + /// + private void EngineTypeGetOver_PLC_Work(string OpName, int EngineTypeID, string EngineType, string EngineID, int PartPallet_Code) + { + int IsAllowWork; + int IsrepairBarcode = 0;//拆解返修标志 + int RepairPartStatusPLC = 0; + int MES_QualityMask = 1; + + string OrderForm = "";//订单号 + string EngineID_MES; + string repairBarcode = "";//拆解返修条码 + bool MesRead = false; + bool MesReadOver = false; + DataTable dt; + + MIS_BASE.Read_EngineID_MES(OpName, out EngineID_MES);//获取MES总成号 + MIS_BASE.Read_MesReadOver(OpName, out MesReadOver); //保存完成 + MIS_BASE.Read_QualityData_Read_CF(OpName, out MesRead); //允许保存 + MIS_BASE.Read_PalletInfo(OpName, out MES_QualityMask);//合格标志 + MIS_BASE.Read_RepairStatus_PLC(OpName, out RepairPartStatusPLC);//返修标志 + + BaseDataSystemMES.GetEngineID_Select(OpName, EngineID, out dt);//查询订单信息 + + if (dt != null&&dt.Rows.Count > 0) + { + OrderForm = Convert.ToString(dt.Rows[0]["订单号"]); + IsrepairBarcode = Convert.ToInt32(dt.Rows[0]["拆解标志"]); + repairBarcode = Convert.ToString(dt.Rows[0]["拆解返修条码"]); + } + + BaseDataSystemMES.OpName_MIS_MOBY_Insert(OpName, OrderForm, EngineTypeID, EngineType, EngineID, PartPallet_Code, 0, IsrepairBarcode, repairBarcode); + SaveMobyMessage(OpName, EngineTypeID, EngineType, EngineID, OrderForm); + Sendmessage("5", "1", OpName); + SendInfomation("QualityMask", Convert.ToString(MES_QualityMask), OpName); + SendInfomation("RepairPartStatusPLC", Convert.ToString(RepairPartStatusPLC), OpName); + + BaseDataSystemMES.MaterialPush_EngineIDStatus_Insert(OpName); + + if (EngineID_MES == EngineID) + { + string kuweiNum; + kuweiNum = DtWebApi.ReadWritePLC.ReadPLC(warehouseLocation.ToString(), OpName).ToString(); + BaseDataSystemMES.GetUpLoadBarCode_0utUpdate(OpName, kuweiNum); + MIS_BASE.Write_FixAllow(OpName, true); + InitOpname01(); + } + else + { + AsyncSendMessage_Notice(OpName, "PLC与MES不一致"); + } + } + private void InitOpname01() + { + BaseDataSystemMES.GetUpLoadBarCode(OPName01, out DataTable dt_OPName01); + + dataGridView_OPA1001.Invoke(new Action(() => { + dataGridView_OPA1001.DataSource = dt_OPName01; + })); + } + + + + /// + /// 保存MOBY信息 + /// + /// + /// + /// + /// + private void SaveMobyMessage(string OpName, int engineTypeID, string engineType, string engineID, string orderForm) + { + if (MIS_BASE.hashtable_EngineGetOver_EngineTypeID == null) + { + MIS_BASE.InitHashtable_MesServerCode(); + } + if (MIS_BASE.hashtable_EngineGetOver_EngineTypeID.ContainsKey(OpName)) + { + MIS_BASE.hashtable_EngineGetOver_EngineTypeID[OpName] = engineTypeID; + } + if (MIS_BASE.hashtable_EngineGetOver_EngineType.ContainsKey(OpName)) + { + MIS_BASE.hashtable_EngineGetOver_EngineType[OpName] = engineType; + } + if (MIS_BASE.hashtable_EngineGetOver_EngineID.ContainsKey(OpName)) + { + MIS_BASE.hashtable_EngineGetOver_EngineID[OpName] = engineID; + } + if (MIS_BASE.hashtable_EngineGetOver_OrderForm.ContainsKey(OpName)) + { + MIS_BASE.hashtable_EngineGetOver_OrderForm[OpName] = orderForm; + } + } + + /// + /// 返修件需要工作 + /// + /// 工位号 + private void IsNeedRepaire_OK(string OpName) + { + + int isRepair; + int engineTypeID; + + string engineType = ""; + string engineID = ""; + string palletCode = ""; + string orderForm = ""; + string repairCode = ""; + //从监控系统中查询出本工位信息 + BaseDataSystemMES.OpName_MIS_Moby_Select(OpName, + out orderForm, out engineTypeID, out engineType, + out engineID, out palletCode, out isRepair, out repairCode); + + EngineTypeGetOver_PLC_Work(OpName, engineTypeID, engineType, engineID, Convert.ToInt32(palletCode)); + } + + } +} diff --git a/SyUpLoadBak/SyUpLoad/Methods/SubmitToMisweb.cs b/SyUpLoadBak/SyUpLoad/Methods/SubmitToMisweb.cs new file mode 100644 index 0000000..c9beba1 --- /dev/null +++ b/SyUpLoadBak/SyUpLoad/Methods/SubmitToMisweb.cs @@ -0,0 +1,139 @@ +using System; +using bizFacade; +//using SystemFramework; + +namespace SyUpLoad +{ + + /// + /// 此类用于向WEB发送各种类型消息 + /// + partial class PartLoad + { + + /// + /// 批量发送WEB消息(Value为BOOL值) + /// + /// 消息编号组合 + /// 消息值组合 + /// 工位号 + void Sendmessage(string MessageNumm, string Value, string OpName) + { + for (int i = 0; i < MessageNumm.Length; i++) + { + Sendmessage(MessageNumm[i], Value[i].ToString(), OpName); + + } + } + + /// + /// 选择发送给WEB的消息 + /// + /// 消息类型 + /// 消息工位 + void Sendmessage(char Num, string Value, string OpName) + { + string SendMessage; + switch (Num) + { + case '1': + //1(直接在界面通过选择机型确认工序内容) + SendMessage = "MES|ProcessList|" + OpName + "|" + Value; + AsyncSendMessage(SendMessage); + break; + + case '2': + //2显示物料 + SendMessage = "MES|MaterialList|" + OpName + "|" + Value; + AsyncSendMessage(SendMessage); + break; + + case '3': + //3显示操作指导图片 + SendMessage = "MES|PicShow|" + OpName + "|" + Value; + AsyncSendMessage(SendMessage); + break; + case '4': + //4显示订单完工数量 + SendMessage = "MES|OrderFormList|" + OpName + "|" + Value; + AsyncSendMessage(SendMessage); + break; + + case '5': + SendMessage = "MES|ShowMoby|" + OpName + "|" + Value; + AsyncSendMessage(SendMessage); + break; + case '6': + SendMessage = "MES|MaterialCheckPosition|" + OpName + "|" + Value; + AsyncSendMessage(SendMessage); + break; + case '7': + SendMessage = "MES|WorkStart|" + OpName + "|" + Value; + AsyncSendMessage(SendMessage); + break; + case '8': + + break; + case '9': + SendMessage = "MES|ConfirmOkGo|" + OpName + "|" + Value; + AsyncSendMessage(SendMessage); + break; + case 'a': + SendMessage = "MES|FixAllow|" + OpName + "|" + Value; + AsyncSendMessage(SendMessage); + break; + } + } + + /// + /// 向WEB发送信息(value为字符串) + /// + /// 消息种类 + /// 消息内容 + /// 工位号 + void SendInfomation(string Command, string Value, string OpName) + { + + string SendMessage = "MES|" + Command + "|" + OpName + "|" + Value; + AsyncSendMessage(SendMessage); + } + + + /// + /// 发送在线产量、在线节拍 + /// + /// + /// + private void SendActuallyCount(string OpName, int tagValue) + { + //当工件离开时,更新在线产量、在线节拍 + if (tagValue == 0) + { + try + { + int opNameCount = 0;//在线产量 + int opNameCountTime = 0;//在线节拍 + //基本数据_工作日历_班次产量查询_New + BaseDataSystemMES.OpNameCount_New(OpName, out opNameCount, out opNameCountTime); + + string SendMessage; + SendMessage = "MES|ActuallyCount|" + OpName + "|" + opNameCount.ToString() + "&" + opNameCountTime.ToString(); + AsyncSendMessage(SendMessage); + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function03:SendActuallyCount"); + } + } + } + + + + + + + + + + } +} diff --git a/SyUpLoadBak/SyUpLoad/Methods/UDP.Send.cs b/SyUpLoadBak/SyUpLoad/Methods/UDP.Send.cs new file mode 100644 index 0000000..87b2f72 --- /dev/null +++ b/SyUpLoadBak/SyUpLoad/Methods/UDP.Send.cs @@ -0,0 +1,57 @@ +using bizFacade; +//using SystemFramework; +using MesServerWork; + +namespace SyUpLoad +{ + partial class PartLoad + { + /// + /// 发送信息到MES通讯服务器或者其他的 + /// + /// + private void AsyncSendMessage(string Message) + { + // asyncSendMessage(Message); + MIS_BASE.asyncSendMessage(Message); + //Thread t = new Thread(delegate() { asyncSendMessage(Message); }); + //t.Start(); + } + + /// + /// 发送提示消息 + /// + /// + private void AsyncSendMessage_Notice(string opname, string notice) + { + //通知Web界面 + BaseDataSystemMES.Web_Notice_Insert(opname, notice); + string SendMessage = "MES|Notice|" + opname + "|" + "1"; + MIS_BASE.asyncSendMessage(SendMessage); + } + + /// + /// 发送信息到打印机 + /// + /// + private void asyncSendMessageToMark(string Message) + { + //System.Threading.Thread.Sleep(10); + string messageSend = (string)Message; + //UDPClientSend.Send_ALL(ApplicationConfig.MES_MarkPortNum, messageSend); + } + + /// + /// 发送信息到LED + /// + /// + private void asyncSendMessageLED(string OpName) + { + + //发送到大屏幕显示 41104 + string strMessage = "MIS|" + OpName + "|" + "0" + "|" + "1"; + //UDPClientSend.Send_ALL(ApplicationConfig.Port_ShowLED_ProductCount, strMessage); + + } + } +} diff --git a/SyUpLoadBak/SyUpLoad/Methods/vssver2.scc b/SyUpLoadBak/SyUpLoad/Methods/vssver2.scc new file mode 100644 index 0000000..ab9ce10 Binary files /dev/null and b/SyUpLoadBak/SyUpLoad/Methods/vssver2.scc differ diff --git a/SyUpLoadBak/SyUpLoad/PartLoad.CreateEngineID.cs b/SyUpLoadBak/SyUpLoad/PartLoad.CreateEngineID.cs new file mode 100644 index 0000000..34def74 --- /dev/null +++ b/SyUpLoadBak/SyUpLoad/PartLoad.CreateEngineID.cs @@ -0,0 +1,180 @@ +using bizFacade; +using System; +using System.Collections.Generic; +using System.Data; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SyUpLoad +{ + public partial class PartLoad + { + /// + /// 获取自动或手动,并以对应的方式创建总成号 + /// + /// 工位号 + /// 产品型号 + /// 产品编号 + private void CreateEngineID(string OpName, out string engineType, out int engineTypeID, out string engineID, out string orderForm) + { + //string orderForm = "";//订单号 + string repairCode = "";//返修代码 + string engineID2 = ""; + string palletCode = "";//托盘编号 + + int palletCode_PLC = 0; + int isRepair = 0; + int engineNumber = 0; + int IsAutoOrManul = 0;//0为自动方式,1为手动方式 + + DataTable dt_EngineType = null; + DataTable dt_temp_isAutoOrManul;//查询创建总成编号的table + + engineType = ""; + engineID = ""; + + //获取订单号,发动机型号,发动机型号代码(在线首工位将选择的订单,机型等信息保存到监控表中) + BaseDataSystemMES.OpName_MIS_Moby_Select(OpName, out orderForm, out engineTypeID, out engineType, out engineID2, out palletCode, out isRepair, out repairCode); + //MIS_BASE.Read_PalletCode(OpName, out palletCode_PLC);//获取托盘编号 + + + + //以自动或手动方式创建发动机号 + CreateEngineID(OpName, IsAutoOrManul, orderForm, engineType, engineTypeID, palletCode_PLC.ToString(), engineNumber, out dt_EngineType, out engineID); + + } + + + /// + /// 以自动或手动方式创建工件编号 + /// + /// 工位号 + /// 自动手动 + /// 订单号 + /// 产品型号 + /// 产品型号代码 + /// 托盘编号 + /// 手动创建_年 + /// 手动创建_月 + /// 手动创建_日 + /// 流水号 + /// 返回信息 + /// 产品编号 + /// + /// + private void CreateEngineID(string opName, int IsAutoOrManul, string orderForm, string engineType, int engineTypeID, string palletCode, int engineNumber, out DataTable dt_EngineType, out string engineID) + { + string engineYear = ""; + string engineMoon = ""; + string engineDay = ""; + + DataTable dt_MaualPrint; + + dt_EngineType = null; + engineID = ""; + + //自动方式创建工件编号 + CreateEngineID_Auto(opName, orderForm, engineType, engineTypeID, palletCode, out dt_EngineType, out engineID); + + + if (!GetEngineID_Save(opName, IsAutoOrManul, orderForm, engineType, engineTypeID, engineID, palletCode.ToString(), dt_EngineType, engineYear, engineMoon, engineDay)) + { + engineID = ""; + engineTypeID = -1; + engineType = ""; + //AsyncSendMessage_Notice(opName, "保存工件信息出错..."); + return; + } + } + + /// + /// 自动方式创建工件编号 + /// + /// + /// + /// + /// + /// 托盘号 + /// + /// 发动机号 + private void CreateEngineID_Auto(string opName, string orderForm, string engineType, int engineTypeID, string palletCode, out DataTable dt_EngineType, out string engineID) + { + dt_EngineType = null; + engineID = ""; + BaseDataSystemMES.GetEngineID_Auto_branch(opName, engineType, palletCode, out dt_EngineType); + + if (dt_EngineType != null && dt_EngineType.Rows.Count > 0) + { + engineID = dt_EngineType.Rows[0]["发动机号"].ToString(); + + } + } + + /// + /// 手动方式创建总成号 + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + private void CreateEngineID_Manul(string opName, string orderForm, string engineType, int engineTypeID, string palletCode, + string engineYear, string engineMoon, string engineDay, int engineNumber, out DataTable dt_EngineType, out string engineID) + { + dt_EngineType = null; + engineID = ""; + + //手动方式创建 + BaseDataSystemMES.GetEngineID_Manual_branch(opName, engineType, engineYear, engineMoon, engineDay, engineNumber, true, out dt_EngineType); + if (dt_EngineType != null) + { + if (dt_EngineType.Rows.Count > 0) + { + engineID = dt_EngineType.Rows[0]["发动机号"].ToString(); + } + } + } + + + /// + /// 电子看板_发动机号_线首工位_增加 + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + private bool GetEngineID_Save(string opName, int IsAutoOrManul, + string orderForm, string engineType, int engineTypeID, string engineID, string partPalletCode, DataTable dt_EngineType, + string year, string month, string day + ) + { + if (IsAutoOrManul == 1) + { + string EngineID_DateTime = year + "-" + month + "-" + day + " 00:00:00"; + return BaseDataSystemMES.GetEngineID_ManulEngine_Save(opName, orderForm, partPalletCode, engineType, EngineID_DateTime, dt_EngineType); + } + else + { + + return BaseDataSystemMES.GetEngineID_Save(opName, orderForm, partPalletCode, engineType, dt_EngineType); + + + } + } + } +} diff --git a/SyUpLoadBak/SyUpLoad/PartLoad.Designer.cs b/SyUpLoadBak/SyUpLoad/PartLoad.Designer.cs new file mode 100644 index 0000000..2a31748 --- /dev/null +++ b/SyUpLoadBak/SyUpLoad/PartLoad.Designer.cs @@ -0,0 +1,786 @@ + +namespace SyUpLoad +{ + partial class PartLoad + { + /// + /// 必需的设计器变量。 + /// + 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.button_barcode = new System.Windows.Forms.Button(); + this.textBox_barcode = new System.Windows.Forms.TextBox(); + this.dataGridView_OPA1001 = new System.Windows.Forms.DataGridView(); + this.dataGridView_OPA1002 = new System.Windows.Forms.DataGridView(); + this.groupBox1 = new System.Windows.Forms.GroupBox(); + this.button_ManualPartLoad3 = new System.Windows.Forms.Button(); + this.button_ManualPartLoad2 = new System.Windows.Forms.Button(); + this.textBox__PlcPosition3 = new System.Windows.Forms.TextBox(); + this.label12 = new System.Windows.Forms.Label(); + this.textBox__PlcPosition2 = new System.Windows.Forms.TextBox(); + this.textBox_PlcEngineID3 = new System.Windows.Forms.TextBox(); + this.label9 = new System.Windows.Forms.Label(); + this.textBox_PlcType3 = new System.Windows.Forms.TextBox(); + this.textBox_PlcEngineID2 = new System.Windows.Forms.TextBox(); + this.label11 = new System.Windows.Forms.Label(); + this.textBox_PlcType2 = new System.Windows.Forms.TextBox(); + this.label10 = new System.Windows.Forms.Label(); + this.label7 = new System.Windows.Forms.Label(); + this.label8 = new System.Windows.Forms.Label(); + this.groupBox5 = new System.Windows.Forms.GroupBox(); + this.checkBox_MesReadOver3 = new System.Windows.Forms.CheckBox(); + this.checkBox_WorkStart3 = new System.Windows.Forms.CheckBox(); + this.checkBox_MesRead3 = new System.Windows.Forms.CheckBox(); + this.checkBox_MesGoOver3 = new System.Windows.Forms.CheckBox(); + this.checkBox_PlcEngineTypeGetOver3 = new System.Windows.Forms.CheckBox(); + this.groupBox4 = new System.Windows.Forms.GroupBox(); + this.checkBox_WorkStart2 = new System.Windows.Forms.CheckBox(); + this.checkBox_MesReadOver2 = new System.Windows.Forms.CheckBox(); + this.checkBox_MesRead2 = new System.Windows.Forms.CheckBox(); + this.checkBox_MesGoOver2 = new System.Windows.Forms.CheckBox(); + this.checkBox_PlcEngineTypeGetOver2 = new System.Windows.Forms.CheckBox(); + this.groupBox2 = new System.Windows.Forms.GroupBox(); + this.button_ManualPartLoad = new System.Windows.Forms.Button(); + this.textBox__PlcPosition = new System.Windows.Forms.TextBox(); + this.textBox_PlcEngineID = new System.Windows.Forms.TextBox(); + this.textBox_MesPosition = new System.Windows.Forms.TextBox(); + this.label6 = new System.Windows.Forms.Label(); + this.textBox_MesEngineID = new System.Windows.Forms.TextBox(); + this.textBox_PlcType = new System.Windows.Forms.TextBox(); + this.label3 = new System.Windows.Forms.Label(); + this.label5 = new System.Windows.Forms.Label(); + this.textBox_MesType = new System.Windows.Forms.TextBox(); + this.label4 = new System.Windows.Forms.Label(); + this.label2 = new System.Windows.Forms.Label(); + this.label1 = new System.Windows.Forms.Label(); + this.groupBox3 = new System.Windows.Forms.GroupBox(); + this.checkBox_WorkStart = new System.Windows.Forms.CheckBox(); + this.checkBox_MesGoOver = new System.Windows.Forms.CheckBox(); + this.checkBox_PlcEngineTypeGetOver = new System.Windows.Forms.CheckBox(); + this.checkBox_MesEngineTypeGetOver = new System.Windows.Forms.CheckBox(); + this.checkBox_PartLoad = new System.Windows.Forms.CheckBox(); + this.button_OrderForm = new System.Windows.Forms.Button(); + this.radioButton6 = new System.Windows.Forms.RadioButton(); + this.radioButton5 = new System.Windows.Forms.RadioButton(); + this.radioButton4 = new System.Windows.Forms.RadioButton(); + this.radioButton3 = new System.Windows.Forms.RadioButton(); + this.radioButton2 = new System.Windows.Forms.RadioButton(); + this.radioButton1 = new System.Windows.Forms.RadioButton(); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView_OPA1001)).BeginInit(); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView_OPA1002)).BeginInit(); + this.groupBox1.SuspendLayout(); + this.groupBox5.SuspendLayout(); + this.groupBox4.SuspendLayout(); + this.groupBox2.SuspendLayout(); + this.groupBox3.SuspendLayout(); + this.SuspendLayout(); + // + // button_barcode + // + this.button_barcode.Location = new System.Drawing.Point(677, 59); + this.button_barcode.Name = "button_barcode"; + this.button_barcode.Size = new System.Drawing.Size(61, 23); + this.button_barcode.TabIndex = 4; + this.button_barcode.Text = "扫描条码"; + this.button_barcode.UseVisualStyleBackColor = true; + this.button_barcode.Click += new System.EventHandler(this.button_barcode_Click); + // + // textBox_barcode + // + this.textBox_barcode.Location = new System.Drawing.Point(530, 20); + this.textBox_barcode.Name = "textBox_barcode"; + this.textBox_barcode.Size = new System.Drawing.Size(208, 21); + this.textBox_barcode.TabIndex = 3; + // + // dataGridView_OPA1001 + // + this.dataGridView_OPA1001.AllowUserToAddRows = false; + this.dataGridView_OPA1001.AllowUserToDeleteRows = false; + this.dataGridView_OPA1001.AllowUserToResizeColumns = false; + this.dataGridView_OPA1001.AllowUserToResizeRows = false; + this.dataGridView_OPA1001.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; + this.dataGridView_OPA1001.Location = new System.Drawing.Point(6, 107); + this.dataGridView_OPA1001.MultiSelect = false; + this.dataGridView_OPA1001.Name = "dataGridView_OPA1001"; + this.dataGridView_OPA1001.RowTemplate.Height = 23; + this.dataGridView_OPA1001.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect; + this.dataGridView_OPA1001.Size = new System.Drawing.Size(384, 201); + this.dataGridView_OPA1001.TabIndex = 5; + // + // dataGridView_OPA1002 + // + this.dataGridView_OPA1002.AllowUserToAddRows = false; + this.dataGridView_OPA1002.AllowUserToDeleteRows = false; + this.dataGridView_OPA1002.AllowUserToResizeColumns = false; + this.dataGridView_OPA1002.AllowUserToResizeRows = false; + this.dataGridView_OPA1002.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; + this.dataGridView_OPA1002.Location = new System.Drawing.Point(6, 20); + this.dataGridView_OPA1002.MultiSelect = false; + this.dataGridView_OPA1002.Name = "dataGridView_OPA1002"; + this.dataGridView_OPA1002.RowTemplate.Height = 23; + this.dataGridView_OPA1002.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect; + this.dataGridView_OPA1002.Size = new System.Drawing.Size(384, 193); + this.dataGridView_OPA1002.TabIndex = 5; + // + // groupBox1 + // + this.groupBox1.Controls.Add(this.button_ManualPartLoad3); + this.groupBox1.Controls.Add(this.button_ManualPartLoad2); + this.groupBox1.Controls.Add(this.textBox__PlcPosition3); + this.groupBox1.Controls.Add(this.label12); + this.groupBox1.Controls.Add(this.textBox__PlcPosition2); + this.groupBox1.Controls.Add(this.textBox_PlcEngineID3); + this.groupBox1.Controls.Add(this.label9); + this.groupBox1.Controls.Add(this.textBox_PlcType3); + this.groupBox1.Controls.Add(this.textBox_PlcEngineID2); + this.groupBox1.Controls.Add(this.label11); + this.groupBox1.Controls.Add(this.textBox_PlcType2); + this.groupBox1.Controls.Add(this.label10); + this.groupBox1.Controls.Add(this.label7); + this.groupBox1.Controls.Add(this.label8); + this.groupBox1.Controls.Add(this.groupBox5); + this.groupBox1.Controls.Add(this.groupBox4); + this.groupBox1.Controls.Add(this.dataGridView_OPA1002); + this.groupBox1.Location = new System.Drawing.Point(12, 332); + this.groupBox1.Name = "groupBox1"; + this.groupBox1.Size = new System.Drawing.Size(776, 309); + this.groupBox1.TabIndex = 8; + this.groupBox1.TabStop = false; + this.groupBox1.Text = "分线上线"; + // + // button_ManualPartLoad3 + // + this.button_ManualPartLoad3.Location = new System.Drawing.Point(315, 253); + this.button_ManualPartLoad3.Name = "button_ManualPartLoad3"; + this.button_ManualPartLoad3.Size = new System.Drawing.Size(75, 40); + this.button_ManualPartLoad3.TabIndex = 19; + this.button_ManualPartLoad3.Text = "手动转线"; + this.button_ManualPartLoad3.UseVisualStyleBackColor = true; + // + // button_ManualPartLoad2 + // + this.button_ManualPartLoad2.Enabled = false; + this.button_ManualPartLoad2.Location = new System.Drawing.Point(633, 200); + this.button_ManualPartLoad2.Name = "button_ManualPartLoad2"; + this.button_ManualPartLoad2.Size = new System.Drawing.Size(124, 36); + this.button_ManualPartLoad2.TabIndex = 18; + this.button_ManualPartLoad2.Text = "手动入库"; + this.button_ManualPartLoad2.UseVisualStyleBackColor = true; + this.button_ManualPartLoad2.Click += new System.EventHandler(this.button_ManualPartLoad2_Click); + // + // textBox__PlcPosition3 + // + this.textBox__PlcPosition3.Location = new System.Drawing.Point(167, 282); + this.textBox__PlcPosition3.Name = "textBox__PlcPosition3"; + this.textBox__PlcPosition3.Size = new System.Drawing.Size(141, 21); + this.textBox__PlcPosition3.TabIndex = 17; + // + // label12 + // + this.label12.AutoSize = true; + this.label12.Location = new System.Drawing.Point(100, 285); + this.label12.Name = "label12"; + this.label12.Size = new System.Drawing.Size(47, 12); + this.label12.TabIndex = 16; + this.label12.Text = "PLC库位"; + // + // textBox__PlcPosition2 + // + this.textBox__PlcPosition2.Location = new System.Drawing.Point(475, 89); + this.textBox__PlcPosition2.Name = "textBox__PlcPosition2"; + this.textBox__PlcPosition2.Size = new System.Drawing.Size(141, 21); + this.textBox__PlcPosition2.TabIndex = 17; + // + // textBox_PlcEngineID3 + // + this.textBox_PlcEngineID3.Location = new System.Drawing.Point(167, 255); + this.textBox_PlcEngineID3.Name = "textBox_PlcEngineID3"; + this.textBox_PlcEngineID3.Size = new System.Drawing.Size(141, 21); + this.textBox_PlcEngineID3.TabIndex = 14; + // + // label9 + // + this.label9.AutoSize = true; + this.label9.Location = new System.Drawing.Point(408, 92); + this.label9.Name = "label9"; + this.label9.Size = new System.Drawing.Size(47, 12); + this.label9.TabIndex = 16; + this.label9.Text = "PLC库位"; + // + // textBox_PlcType3 + // + this.textBox_PlcType3.Location = new System.Drawing.Point(167, 228); + this.textBox_PlcType3.Name = "textBox_PlcType3"; + this.textBox_PlcType3.Size = new System.Drawing.Size(141, 21); + this.textBox_PlcType3.TabIndex = 15; + // + // textBox_PlcEngineID2 + // + this.textBox_PlcEngineID2.Location = new System.Drawing.Point(475, 62); + this.textBox_PlcEngineID2.Name = "textBox_PlcEngineID2"; + this.textBox_PlcEngineID2.Size = new System.Drawing.Size(141, 21); + this.textBox_PlcEngineID2.TabIndex = 14; + // + // label11 + // + this.label11.AutoSize = true; + this.label11.Location = new System.Drawing.Point(100, 258); + this.label11.Name = "label11"; + this.label11.Size = new System.Drawing.Size(59, 12); + this.label11.TabIndex = 12; + this.label11.Text = "PLC流水号"; + // + // textBox_PlcType2 + // + this.textBox_PlcType2.Location = new System.Drawing.Point(475, 35); + this.textBox_PlcType2.Name = "textBox_PlcType2"; + this.textBox_PlcType2.Size = new System.Drawing.Size(141, 21); + this.textBox_PlcType2.TabIndex = 15; + // + // label10 + // + this.label10.AutoSize = true; + this.label10.Location = new System.Drawing.Point(100, 231); + this.label10.Name = "label10"; + this.label10.Size = new System.Drawing.Size(47, 12); + this.label10.TabIndex = 13; + this.label10.Text = "PLC机型"; + // + // label7 + // + this.label7.AutoSize = true; + this.label7.Location = new System.Drawing.Point(408, 65); + this.label7.Name = "label7"; + this.label7.Size = new System.Drawing.Size(59, 12); + this.label7.TabIndex = 12; + this.label7.Text = "PLC流水号"; + // + // label8 + // + this.label8.AutoSize = true; + this.label8.Location = new System.Drawing.Point(408, 38); + this.label8.Name = "label8"; + this.label8.Size = new System.Drawing.Size(47, 12); + this.label8.TabIndex = 13; + this.label8.Text = "PLC机型"; + // + // groupBox5 + // + this.groupBox5.Controls.Add(this.checkBox_MesReadOver3); + this.groupBox5.Controls.Add(this.checkBox_WorkStart3); + this.groupBox5.Controls.Add(this.checkBox_MesRead3); + this.groupBox5.Controls.Add(this.checkBox_MesGoOver3); + this.groupBox5.Controls.Add(this.checkBox_PlcEngineTypeGetOver3); + this.groupBox5.Location = new System.Drawing.Point(410, 155); + this.groupBox5.Name = "groupBox5"; + this.groupBox5.Size = new System.Drawing.Size(124, 144); + this.groupBox5.TabIndex = 10; + this.groupBox5.TabStop = false; + this.groupBox5.Text = "PLC通讯"; + // + // checkBox_MesReadOver3 + // + this.checkBox_MesReadOver3.AutoSize = true; + this.checkBox_MesReadOver3.Location = new System.Drawing.Point(20, 122); + this.checkBox_MesReadOver3.Name = "checkBox_MesReadOver3"; + this.checkBox_MesReadOver3.Size = new System.Drawing.Size(72, 16); + this.checkBox_MesReadOver3.TabIndex = 19; + this.checkBox_MesReadOver3.Text = "保存完成"; + this.checkBox_MesReadOver3.UseVisualStyleBackColor = true; + // + // checkBox_WorkStart3 + // + this.checkBox_WorkStart3.AutoSize = true; + this.checkBox_WorkStart3.Location = new System.Drawing.Point(20, 20); + this.checkBox_WorkStart3.Name = "checkBox_WorkStart3"; + this.checkBox_WorkStart3.Size = new System.Drawing.Size(72, 16); + this.checkBox_WorkStart3.TabIndex = 8; + this.checkBox_WorkStart3.Text = "工件到位"; + this.checkBox_WorkStart3.UseVisualStyleBackColor = true; + // + // checkBox_MesRead3 + // + this.checkBox_MesRead3.AutoSize = true; + this.checkBox_MesRead3.Location = new System.Drawing.Point(20, 89); + this.checkBox_MesRead3.Name = "checkBox_MesRead3"; + this.checkBox_MesRead3.Size = new System.Drawing.Size(72, 16); + this.checkBox_MesRead3.TabIndex = 20; + this.checkBox_MesRead3.Text = "允许保存"; + this.checkBox_MesRead3.UseVisualStyleBackColor = true; + // + // checkBox_MesGoOver3 + // + this.checkBox_MesGoOver3.AutoSize = true; + this.checkBox_MesGoOver3.Location = new System.Drawing.Point(20, 67); + this.checkBox_MesGoOver3.Name = "checkBox_MesGoOver3"; + this.checkBox_MesGoOver3.Size = new System.Drawing.Size(90, 16); + this.checkBox_MesGoOver3.TabIndex = 8; + this.checkBox_MesGoOver3.Text = "MES工作完成"; + this.checkBox_MesGoOver3.UseVisualStyleBackColor = true; + // + // checkBox_PlcEngineTypeGetOver3 + // + this.checkBox_PlcEngineTypeGetOver3.AutoSize = true; + this.checkBox_PlcEngineTypeGetOver3.Location = new System.Drawing.Point(20, 45); + this.checkBox_PlcEngineTypeGetOver3.Name = "checkBox_PlcEngineTypeGetOver3"; + this.checkBox_PlcEngineTypeGetOver3.Size = new System.Drawing.Size(90, 16); + this.checkBox_PlcEngineTypeGetOver3.TabIndex = 8; + this.checkBox_PlcEngineTypeGetOver3.Text = "PLC传递机型"; + this.checkBox_PlcEngineTypeGetOver3.UseVisualStyleBackColor = true; + // + // groupBox4 + // + this.groupBox4.Controls.Add(this.checkBox_WorkStart2); + this.groupBox4.Controls.Add(this.checkBox_MesReadOver2); + this.groupBox4.Controls.Add(this.checkBox_MesRead2); + this.groupBox4.Controls.Add(this.checkBox_MesGoOver2); + this.groupBox4.Controls.Add(this.checkBox_PlcEngineTypeGetOver2); + this.groupBox4.Location = new System.Drawing.Point(633, 20); + this.groupBox4.Name = "groupBox4"; + this.groupBox4.Size = new System.Drawing.Size(124, 169); + this.groupBox4.TabIndex = 10; + this.groupBox4.TabStop = false; + this.groupBox4.Text = "PLC通讯"; + // + // checkBox_WorkStart2 + // + this.checkBox_WorkStart2.AutoSize = true; + this.checkBox_WorkStart2.Location = new System.Drawing.Point(20, 20); + this.checkBox_WorkStart2.Name = "checkBox_WorkStart2"; + this.checkBox_WorkStart2.Size = new System.Drawing.Size(72, 16); + this.checkBox_WorkStart2.TabIndex = 8; + this.checkBox_WorkStart2.Text = "工件到位"; + this.checkBox_WorkStart2.UseVisualStyleBackColor = true; + // + // checkBox_MesReadOver2 + // + this.checkBox_MesReadOver2.AutoSize = true; + this.checkBox_MesReadOver2.Location = new System.Drawing.Point(20, 135); + this.checkBox_MesReadOver2.Name = "checkBox_MesReadOver2"; + this.checkBox_MesReadOver2.Size = new System.Drawing.Size(72, 16); + this.checkBox_MesReadOver2.TabIndex = 8; + this.checkBox_MesReadOver2.Text = "保存完成"; + this.checkBox_MesReadOver2.UseVisualStyleBackColor = true; + // + // checkBox_MesRead2 + // + this.checkBox_MesRead2.AutoSize = true; + this.checkBox_MesRead2.Location = new System.Drawing.Point(20, 96); + this.checkBox_MesRead2.Name = "checkBox_MesRead2"; + this.checkBox_MesRead2.Size = new System.Drawing.Size(72, 16); + this.checkBox_MesRead2.TabIndex = 8; + this.checkBox_MesRead2.Text = "允许保存"; + this.checkBox_MesRead2.UseVisualStyleBackColor = true; + // + // checkBox_MesGoOver2 + // + this.checkBox_MesGoOver2.AutoSize = true; + this.checkBox_MesGoOver2.Location = new System.Drawing.Point(20, 74); + this.checkBox_MesGoOver2.Name = "checkBox_MesGoOver2"; + this.checkBox_MesGoOver2.Size = new System.Drawing.Size(90, 16); + this.checkBox_MesGoOver2.TabIndex = 8; + this.checkBox_MesGoOver2.Text = "MES工作完成"; + this.checkBox_MesGoOver2.UseVisualStyleBackColor = true; + // + // checkBox_PlcEngineTypeGetOver2 + // + this.checkBox_PlcEngineTypeGetOver2.AutoSize = true; + this.checkBox_PlcEngineTypeGetOver2.Location = new System.Drawing.Point(20, 47); + this.checkBox_PlcEngineTypeGetOver2.Name = "checkBox_PlcEngineTypeGetOver2"; + this.checkBox_PlcEngineTypeGetOver2.Size = new System.Drawing.Size(90, 16); + this.checkBox_PlcEngineTypeGetOver2.TabIndex = 8; + this.checkBox_PlcEngineTypeGetOver2.Text = "PLC传递机型"; + this.checkBox_PlcEngineTypeGetOver2.UseVisualStyleBackColor = true; + // + // groupBox2 + // + this.groupBox2.Controls.Add(this.button_ManualPartLoad); + this.groupBox2.Controls.Add(this.textBox__PlcPosition); + this.groupBox2.Controls.Add(this.textBox_PlcEngineID); + this.groupBox2.Controls.Add(this.textBox_MesPosition); + this.groupBox2.Controls.Add(this.label6); + this.groupBox2.Controls.Add(this.textBox_MesEngineID); + this.groupBox2.Controls.Add(this.textBox_PlcType); + this.groupBox2.Controls.Add(this.label3); + this.groupBox2.Controls.Add(this.label5); + this.groupBox2.Controls.Add(this.textBox_MesType); + this.groupBox2.Controls.Add(this.label4); + this.groupBox2.Controls.Add(this.label2); + this.groupBox2.Controls.Add(this.label1); + this.groupBox2.Controls.Add(this.groupBox3); + this.groupBox2.Controls.Add(this.button_OrderForm); + this.groupBox2.Controls.Add(this.radioButton6); + this.groupBox2.Controls.Add(this.radioButton5); + this.groupBox2.Controls.Add(this.radioButton4); + this.groupBox2.Controls.Add(this.radioButton3); + this.groupBox2.Controls.Add(this.radioButton2); + this.groupBox2.Controls.Add(this.radioButton1); + this.groupBox2.Controls.Add(this.dataGridView_OPA1001); + this.groupBox2.Controls.Add(this.textBox_barcode); + this.groupBox2.Controls.Add(this.button_barcode); + this.groupBox2.Location = new System.Drawing.Point(12, 12); + this.groupBox2.Name = "groupBox2"; + this.groupBox2.Size = new System.Drawing.Size(776, 314); + this.groupBox2.TabIndex = 9; + this.groupBox2.TabStop = false; + this.groupBox2.Text = "分线上线"; + // + // button_ManualPartLoad + // + this.button_ManualPartLoad.Enabled = false; + this.button_ManualPartLoad.Location = new System.Drawing.Point(633, 262); + this.button_ManualPartLoad.Name = "button_ManualPartLoad"; + this.button_ManualPartLoad.Size = new System.Drawing.Size(124, 36); + this.button_ManualPartLoad.TabIndex = 12; + this.button_ManualPartLoad.Text = "手动上线"; + this.button_ManualPartLoad.UseVisualStyleBackColor = true; + this.button_ManualPartLoad.Click += new System.EventHandler(this.button_ManualPartLoad_Click); + // + // textBox__PlcPosition + // + this.textBox__PlcPosition.Location = new System.Drawing.Point(475, 259); + this.textBox__PlcPosition.Name = "textBox__PlcPosition"; + this.textBox__PlcPosition.Size = new System.Drawing.Size(141, 21); + this.textBox__PlcPosition.TabIndex = 11; + // + // textBox_PlcEngineID + // + this.textBox_PlcEngineID.Location = new System.Drawing.Point(475, 232); + this.textBox_PlcEngineID.Name = "textBox_PlcEngineID"; + this.textBox_PlcEngineID.Size = new System.Drawing.Size(141, 21); + this.textBox_PlcEngineID.TabIndex = 11; + // + // textBox_MesPosition + // + this.textBox_MesPosition.Location = new System.Drawing.Point(475, 169); + this.textBox_MesPosition.Name = "textBox_MesPosition"; + this.textBox_MesPosition.Size = new System.Drawing.Size(141, 21); + this.textBox_MesPosition.TabIndex = 11; + // + // label6 + // + this.label6.AutoSize = true; + this.label6.Location = new System.Drawing.Point(408, 262); + this.label6.Name = "label6"; + this.label6.Size = new System.Drawing.Size(47, 12); + this.label6.TabIndex = 10; + this.label6.Text = "PLC库位"; + // + // textBox_MesEngineID + // + this.textBox_MesEngineID.Location = new System.Drawing.Point(475, 142); + this.textBox_MesEngineID.Name = "textBox_MesEngineID"; + this.textBox_MesEngineID.Size = new System.Drawing.Size(141, 21); + this.textBox_MesEngineID.TabIndex = 11; + // + // textBox_PlcType + // + this.textBox_PlcType.Location = new System.Drawing.Point(475, 205); + this.textBox_PlcType.Name = "textBox_PlcType"; + this.textBox_PlcType.Size = new System.Drawing.Size(141, 21); + this.textBox_PlcType.TabIndex = 11; + // + // label3 + // + this.label3.AutoSize = true; + this.label3.Location = new System.Drawing.Point(408, 172); + this.label3.Name = "label3"; + this.label3.Size = new System.Drawing.Size(47, 12); + this.label3.TabIndex = 10; + this.label3.Text = "MES库位"; + // + // label5 + // + this.label5.AutoSize = true; + this.label5.Location = new System.Drawing.Point(408, 235); + this.label5.Name = "label5"; + this.label5.Size = new System.Drawing.Size(59, 12); + this.label5.TabIndex = 10; + this.label5.Text = "PLC流水号"; + // + // textBox_MesType + // + this.textBox_MesType.Location = new System.Drawing.Point(475, 115); + this.textBox_MesType.Name = "textBox_MesType"; + this.textBox_MesType.Size = new System.Drawing.Size(141, 21); + this.textBox_MesType.TabIndex = 11; + // + // label4 + // + this.label4.AutoSize = true; + this.label4.Location = new System.Drawing.Point(408, 208); + this.label4.Name = "label4"; + this.label4.Size = new System.Drawing.Size(47, 12); + this.label4.TabIndex = 10; + this.label4.Text = "PLC机型"; + // + // label2 + // + this.label2.AutoSize = true; + this.label2.Location = new System.Drawing.Point(408, 145); + this.label2.Name = "label2"; + this.label2.Size = new System.Drawing.Size(59, 12); + this.label2.TabIndex = 10; + this.label2.Text = "MES流水号"; + // + // label1 + // + this.label1.AutoSize = true; + this.label1.Location = new System.Drawing.Point(408, 118); + this.label1.Name = "label1"; + this.label1.Size = new System.Drawing.Size(47, 12); + this.label1.TabIndex = 10; + this.label1.Text = "MES机型"; + // + // groupBox3 + // + this.groupBox3.Controls.Add(this.checkBox_WorkStart); + this.groupBox3.Controls.Add(this.checkBox_MesGoOver); + this.groupBox3.Controls.Add(this.checkBox_PlcEngineTypeGetOver); + this.groupBox3.Controls.Add(this.checkBox_MesEngineTypeGetOver); + this.groupBox3.Controls.Add(this.checkBox_PartLoad); + this.groupBox3.Location = new System.Drawing.Point(633, 107); + this.groupBox3.Name = "groupBox3"; + this.groupBox3.Size = new System.Drawing.Size(124, 146); + this.groupBox3.TabIndex = 9; + this.groupBox3.TabStop = false; + this.groupBox3.Text = "PLC通讯"; + // + // checkBox_WorkStart + // + this.checkBox_WorkStart.AutoSize = true; + this.checkBox_WorkStart.Location = new System.Drawing.Point(20, 20); + this.checkBox_WorkStart.Name = "checkBox_WorkStart"; + this.checkBox_WorkStart.Size = new System.Drawing.Size(72, 16); + this.checkBox_WorkStart.TabIndex = 8; + this.checkBox_WorkStart.Text = "工件到位"; + this.checkBox_WorkStart.UseVisualStyleBackColor = true; + // + // checkBox_MesGoOver + // + this.checkBox_MesGoOver.AutoSize = true; + this.checkBox_MesGoOver.Location = new System.Drawing.Point(20, 111); + this.checkBox_MesGoOver.Name = "checkBox_MesGoOver"; + this.checkBox_MesGoOver.Size = new System.Drawing.Size(90, 16); + this.checkBox_MesGoOver.TabIndex = 8; + this.checkBox_MesGoOver.Text = "MES工作完成"; + this.checkBox_MesGoOver.UseVisualStyleBackColor = true; + // + // checkBox_PlcEngineTypeGetOver + // + this.checkBox_PlcEngineTypeGetOver.AutoSize = true; + this.checkBox_PlcEngineTypeGetOver.Location = new System.Drawing.Point(20, 89); + this.checkBox_PlcEngineTypeGetOver.Name = "checkBox_PlcEngineTypeGetOver"; + this.checkBox_PlcEngineTypeGetOver.Size = new System.Drawing.Size(90, 16); + this.checkBox_PlcEngineTypeGetOver.TabIndex = 8; + this.checkBox_PlcEngineTypeGetOver.Text = "PLC传递机型"; + this.checkBox_PlcEngineTypeGetOver.UseVisualStyleBackColor = true; + // + // checkBox_MesEngineTypeGetOver + // + this.checkBox_MesEngineTypeGetOver.AutoSize = true; + this.checkBox_MesEngineTypeGetOver.Location = new System.Drawing.Point(20, 67); + this.checkBox_MesEngineTypeGetOver.Name = "checkBox_MesEngineTypeGetOver"; + this.checkBox_MesEngineTypeGetOver.Size = new System.Drawing.Size(90, 16); + this.checkBox_MesEngineTypeGetOver.TabIndex = 8; + this.checkBox_MesEngineTypeGetOver.Text = "MES传递机型"; + this.checkBox_MesEngineTypeGetOver.UseVisualStyleBackColor = true; + // + // checkBox_PartLoad + // + this.checkBox_PartLoad.AutoSize = true; + this.checkBox_PartLoad.Location = new System.Drawing.Point(20, 42); + this.checkBox_PartLoad.Name = "checkBox_PartLoad"; + this.checkBox_PartLoad.Size = new System.Drawing.Size(72, 16); + this.checkBox_PartLoad.TabIndex = 8; + this.checkBox_PartLoad.Text = "申请上线"; + this.checkBox_PartLoad.UseVisualStyleBackColor = true; + // + // button_OrderForm + // + this.button_OrderForm.Location = new System.Drawing.Point(530, 59); + this.button_OrderForm.Name = "button_OrderForm"; + this.button_OrderForm.Size = new System.Drawing.Size(75, 23); + this.button_OrderForm.TabIndex = 7; + this.button_OrderForm.Text = "下订单"; + this.button_OrderForm.UseVisualStyleBackColor = true; + // + // radioButton6 + // + this.radioButton6.AutoSize = true; + this.radioButton6.Font = new System.Drawing.Font("宋体", 21.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.radioButton6.Location = new System.Drawing.Point(304, 68); + this.radioButton6.Name = "radioButton6"; + this.radioButton6.Size = new System.Drawing.Size(104, 33); + this.radioButton6.TabIndex = 6; + this.radioButton6.Text = "库位6"; + this.radioButton6.UseVisualStyleBackColor = true; + // + // radioButton5 + // + this.radioButton5.AutoSize = true; + this.radioButton5.Font = new System.Drawing.Font("宋体", 21.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.radioButton5.Location = new System.Drawing.Point(304, 29); + this.radioButton5.Name = "radioButton5"; + this.radioButton5.Size = new System.Drawing.Size(104, 33); + this.radioButton5.TabIndex = 6; + this.radioButton5.Text = "库位5"; + this.radioButton5.UseVisualStyleBackColor = true; + // + // radioButton4 + // + this.radioButton4.AutoSize = true; + this.radioButton4.Font = new System.Drawing.Font("宋体", 21.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.radioButton4.Location = new System.Drawing.Point(158, 68); + this.radioButton4.Name = "radioButton4"; + this.radioButton4.Size = new System.Drawing.Size(104, 33); + this.radioButton4.TabIndex = 6; + this.radioButton4.Text = "库位4"; + this.radioButton4.UseVisualStyleBackColor = true; + // + // radioButton3 + // + this.radioButton3.AutoSize = true; + this.radioButton3.Font = new System.Drawing.Font("宋体", 21.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.radioButton3.Location = new System.Drawing.Point(158, 29); + this.radioButton3.Name = "radioButton3"; + this.radioButton3.Size = new System.Drawing.Size(104, 33); + this.radioButton3.TabIndex = 6; + this.radioButton3.Text = "库位3"; + this.radioButton3.UseVisualStyleBackColor = true; + // + // radioButton2 + // + this.radioButton2.AutoSize = true; + this.radioButton2.Font = new System.Drawing.Font("宋体", 21.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.radioButton2.Location = new System.Drawing.Point(19, 68); + this.radioButton2.Name = "radioButton2"; + this.radioButton2.Size = new System.Drawing.Size(104, 33); + this.radioButton2.TabIndex = 6; + this.radioButton2.Text = "库位2"; + this.radioButton2.UseVisualStyleBackColor = true; + // + // radioButton1 + // + this.radioButton1.AutoSize = true; + this.radioButton1.Checked = true; + this.radioButton1.Font = new System.Drawing.Font("宋体", 21.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.radioButton1.Location = new System.Drawing.Point(19, 29); + this.radioButton1.Name = "radioButton1"; + this.radioButton1.Size = new System.Drawing.Size(104, 33); + this.radioButton1.TabIndex = 6; + this.radioButton1.TabStop = true; + this.radioButton1.Text = "库位1"; + this.radioButton1.UseVisualStyleBackColor = true; + // + // PartLoad + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(800, 653); + this.Controls.Add(this.groupBox2); + this.Controls.Add(this.groupBox1); + this.DoubleBuffered = true; + this.Name = "PartLoad"; + this.Text = "Form1"; + this.Load += new System.EventHandler(this.PartLoad_Load); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView_OPA1001)).EndInit(); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView_OPA1002)).EndInit(); + this.groupBox1.ResumeLayout(false); + this.groupBox1.PerformLayout(); + this.groupBox5.ResumeLayout(false); + this.groupBox5.PerformLayout(); + this.groupBox4.ResumeLayout(false); + this.groupBox4.PerformLayout(); + this.groupBox2.ResumeLayout(false); + this.groupBox2.PerformLayout(); + this.groupBox3.ResumeLayout(false); + this.groupBox3.PerformLayout(); + this.ResumeLayout(false); + + } + + #endregion + + private System.Windows.Forms.Button button_barcode; + private System.Windows.Forms.TextBox textBox_barcode; + private System.Windows.Forms.DataGridView dataGridView_OPA1001; + private System.Windows.Forms.DataGridView dataGridView_OPA1002; + private System.Windows.Forms.GroupBox groupBox1; + private System.Windows.Forms.GroupBox groupBox2; + private System.Windows.Forms.RadioButton radioButton6; + private System.Windows.Forms.RadioButton radioButton5; + private System.Windows.Forms.RadioButton radioButton4; + private System.Windows.Forms.RadioButton radioButton3; + private System.Windows.Forms.RadioButton radioButton2; + private System.Windows.Forms.RadioButton radioButton1; + private System.Windows.Forms.Button button_OrderForm; + private System.Windows.Forms.CheckBox checkBox_PartLoad; + private System.Windows.Forms.GroupBox groupBox3; + private System.Windows.Forms.CheckBox checkBox_WorkStart; + private System.Windows.Forms.CheckBox checkBox_MesGoOver; + private System.Windows.Forms.CheckBox checkBox_PlcEngineTypeGetOver; + private System.Windows.Forms.CheckBox checkBox_MesEngineTypeGetOver; + private System.Windows.Forms.TextBox textBox__PlcPosition; + private System.Windows.Forms.TextBox textBox_PlcEngineID; + private System.Windows.Forms.TextBox textBox_MesPosition; + private System.Windows.Forms.Label label6; + private System.Windows.Forms.TextBox textBox_MesEngineID; + private System.Windows.Forms.TextBox textBox_PlcType; + private System.Windows.Forms.Label label3; + private System.Windows.Forms.Label label5; + private System.Windows.Forms.TextBox textBox_MesType; + private System.Windows.Forms.Label label4; + private System.Windows.Forms.Label label2; + private System.Windows.Forms.Label label1; + private System.Windows.Forms.Button button_ManualPartLoad; + private System.Windows.Forms.TextBox textBox_PlcEngineID2; + private System.Windows.Forms.TextBox textBox_PlcType2; + private System.Windows.Forms.Label label7; + private System.Windows.Forms.Label label8; + private System.Windows.Forms.GroupBox groupBox4; + private System.Windows.Forms.CheckBox checkBox_WorkStart2; + private System.Windows.Forms.CheckBox checkBox_MesGoOver2; + private System.Windows.Forms.CheckBox checkBox_PlcEngineTypeGetOver2; + private System.Windows.Forms.GroupBox groupBox5; + private System.Windows.Forms.CheckBox checkBox_WorkStart3; + private System.Windows.Forms.CheckBox checkBox_MesGoOver3; + private System.Windows.Forms.CheckBox checkBox_PlcEngineTypeGetOver3; + private System.Windows.Forms.TextBox textBox__PlcPosition2; + private System.Windows.Forms.Label label9; + private System.Windows.Forms.CheckBox checkBox_MesReadOver2; + private System.Windows.Forms.CheckBox checkBox_MesRead2; + private System.Windows.Forms.Button button_ManualPartLoad2; + private System.Windows.Forms.TextBox textBox__PlcPosition3; + private System.Windows.Forms.Label label12; + private System.Windows.Forms.TextBox textBox_PlcEngineID3; + private System.Windows.Forms.TextBox textBox_PlcType3; + private System.Windows.Forms.Label label11; + private System.Windows.Forms.Label label10; + private System.Windows.Forms.CheckBox checkBox_MesReadOver3; + private System.Windows.Forms.CheckBox checkBox_MesRead3; + private System.Windows.Forms.Button button_ManualPartLoad3; + } +} + diff --git a/SyUpLoadBak/SyUpLoad/PartLoad.Fun0.BarCode.cs b/SyUpLoadBak/SyUpLoad/PartLoad.Fun0.BarCode.cs new file mode 100644 index 0000000..c7bebf7 --- /dev/null +++ b/SyUpLoadBak/SyUpLoad/PartLoad.Fun0.BarCode.cs @@ -0,0 +1,93 @@ +using MesWorkMqtt; +using MQTTnet.Client.Connecting; +using MQTTnet.Client.Disconnecting; +using MQTTnet.Client.Receiving; + +using bizFacade; +using MesWorkMqtt; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Configuration; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; +using MQTTnet; +using System.Threading; +using DoWhatPlc; +using MesServerWork; + +namespace SyUpLoad +{ + public partial class PartLoad + { + private void button_barcode_Click(object sender, EventArgs e) + { + string opName; + string kuweiNum; + string barCode; + string orderForm; + string engineID; + string engineType; + int engineTypeID; + opName = OPName01; + barCode = textBox_barcode.Text.Replace("\r\n", ""); + kuweiNum = Get_kuweiNum(); + if (kuweiNum == "0") return; + + CreateEngineID(opName, out engineType, out engineTypeID, out engineID, out orderForm); + if(engineID.Length<1) + { + MessageBox.Show("入库失败"); + return; + } + BaseDataSystemMES.GetUpLoadBarCode_Update(opName, kuweiNum, barCode, orderForm, + engineID, engineType, engineTypeID); + + BaseDataSystemMES.GetUpLoadBarCode(OPName01, out DataTable dt_OPName01); + dataGridView_OPA1001.DataSource = dt_OPName01; + + } + + private string Get_kuweiNum() + { + string kuweiNum = "0"; + + if (radioButton1.Checked) + { + kuweiNum = "1"; + } + else if (radioButton2.Checked) + { + kuweiNum = "2"; + + } + else if (radioButton3.Checked) + { + kuweiNum = "3"; + + } + else if (radioButton4.Checked) + { + kuweiNum = "4"; + + } + else if (radioButton5.Checked) + { + kuweiNum = "5"; + + } + else if (radioButton6.Checked) + { + kuweiNum = "6"; + + } + + return kuweiNum; + } + + } +} diff --git a/SyUpLoadBak/SyUpLoad/PartLoad.Fun1.PartLoad.cs b/SyUpLoadBak/SyUpLoad/PartLoad.Fun1.PartLoad.cs new file mode 100644 index 0000000..b40ae43 --- /dev/null +++ b/SyUpLoadBak/SyUpLoad/PartLoad.Fun1.PartLoad.cs @@ -0,0 +1,223 @@ +using MesWorkMqtt; +using MQTTnet.Client.Connecting; +using MQTTnet.Client.Disconnecting; +using MQTTnet.Client.Receiving; + +using bizFacade; +using MesWorkMqtt; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Configuration; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; +using MQTTnet; +using System.Threading; +using DoWhatPlc; +using MesServerWork; + +namespace SyUpLoad +{ + public partial class PartLoad + { + /// + /// 申请上线 + /// + /// + /// + private void fun_PartLoad(object e) + { + try + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + + SetChekcBox(tagValue, checkBox_PartLoad); + + + int engineTypeID; + string engineID; + string engineType; + byte kuweiNum; + if (tagValue == 1) + { + // BaseDataSystemMES.MesServer_Process_EngineTypeOver(OpName); + DataTable dt; + BaseDataSystemMES.GetUpLoadBarCodeEngineID(OpName, out dt); + if (dt.Rows.Count < 1) + { + + button_ManualPartLoad.Invoke(new Action(() => { + button_ManualPartLoad.Enabled = true; + })); + MessageBox.Show("虚拟库存无件,请扫描上线工位小车上的工件条码"); + return; + } + engineTypeID = Convert.ToInt32(dt.Rows[0]["机型代码"]); + engineID = dt.Rows[0]["发动机号"].ToString(); + engineType = dt.Rows[0]["发动机型号"].ToString(); + kuweiNum = Convert.ToByte(dt.Rows[0]["库位号"]); + + + + + ////将产品信息写入PLC + MIS_BASE.Write_EngineTypeID_MES(OpName, engineTypeID); + MIS_BASE.Write_EngineType_MES(OpName, engineType); + MIS_BASE.Write_EngineID_MES(OpName, engineID); + DtWebApi.ReadWritePLC.WritePLC(warehouseLocation.ToString(), OpName, kuweiNum); + + MIS_BASE.Write_EngineTypeGetOver_MES(OpName, true); + + ////将产品信息写入PLC + MIS_BASE.Read_EngineTypeID_MES(OpName, out engineTypeID); + MIS_BASE.Read_EngineType_MES(OpName, out engineType); + MIS_BASE.Read_EngineID_MES(OpName, out engineID); + + kuweiNum = Convert.ToByte(DtWebApi.ReadWritePLC.ReadPLC(warehouseLocation.ToString(), OpName)); + + SetTextBox(engineType, textBox_MesType); + SetTextBox(engineID, textBox_MesEngineID); + SetTextBox(kuweiNum.ToString(), textBox_MesPosition); + + } + + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function03:PartLoad"); + } + } + /// + /// 申请上线 + /// + /// + /// + private void fun_PartLoadManual(string OpName) + { + try + { + bool engineTypeGetOver_MES; + bool partLoad; + MIS_BASE.Read_EngineTypeGetOver_MES(OpName, out engineTypeGetOver_MES); + + MIS_BASE.Read_PartLoad(OpName, out partLoad); + + if(partLoad == false || engineTypeGetOver_MES==true) + { + MessageBox.Show("检查申请上线信号"); + return; + } + + //DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + //string OpName = OPName01; + //int tagValue = Convert.ToInt32(msgEvent.TagValue); + + //SetChekcBox(tagValue, checkBox_PartLoad); + + + int engineTypeID; + string engineID; + string engineType; + byte kuweiNum; + //if (tagValue == 1) + { + // BaseDataSystemMES.MesServer_Process_EngineTypeOver(OpName); + DataTable dt; + BaseDataSystemMES.GetUpLoadBarCodeEngineID(OpName, out dt); + if (dt.Rows.Count < 1) + { + + button_ManualPartLoad.Invoke(new Action(() => { + button_ManualPartLoad.Enabled = true; + })); + MessageBox.Show("虚拟库存无件,请扫描上线工位小车上的工件条码"); + return; + } + engineTypeID = Convert.ToInt32(dt.Rows[0]["机型代码"]); + engineID = dt.Rows[0]["发动机号"].ToString(); + engineType = dt.Rows[0]["发动机型号"].ToString(); + kuweiNum = Convert.ToByte(dt.Rows[0]["库位号"]); + + + + + ////将产品信息写入PLC + MIS_BASE.Write_EngineTypeID_MES(OpName, engineTypeID); + MIS_BASE.Write_EngineType_MES(OpName, engineType); + MIS_BASE.Write_EngineID_MES(OpName, engineID); + DtWebApi.ReadWritePLC.WritePLC(warehouseLocation.ToString(), OpName, kuweiNum); + + MIS_BASE.Write_EngineTypeGetOver_MES(OpName, true); + + ////将产品信息写入PLC + MIS_BASE.Read_EngineTypeID_MES(OpName, out engineTypeID); + MIS_BASE.Read_EngineType_MES(OpName, out engineType); + MIS_BASE.Read_EngineID_MES(OpName, out engineID); + + kuweiNum = Convert.ToByte(DtWebApi.ReadWritePLC.ReadPLC(warehouseLocation.ToString(), OpName)); + + SetTextBox(engineType, textBox_MesType); + SetTextBox(engineID, textBox_MesEngineID); + SetTextBox(kuweiNum.ToString(), textBox_MesPosition); + + } + + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function03:PartLoad"); + } + } + + private void fun_PartLoadManual2(string OpName) + { + try + { + bool engineTypeGetOver; + bool partLoad; + + int engineTypeID; + string engineID; + string engineType; + byte kuweiNum; + + MIS_BASE.Read_EngineGetOver_PLC(OpName, out engineTypeGetOver); + + + if (engineTypeGetOver == false) + { + MessageBox.Show("检查传递机型信号"); + return; + } + + DataTable dt; + BaseDataSystemMES.GetUnLoadWarehouseNo(OpName, out dt); + if (dt.Rows.Count == 0) + { + MessageBox.Show("下线库位已满"); + button_ManualPartLoad2.Invoke(new Action(() => { + button_ManualPartLoad2.Enabled = true; + })); + return; + } + else + { + kuweiNum = Convert.ToByte(dt.Rows[0]["库位号"]); + DtWebApi.ReadWritePLC.WritePLC(warehouseLocation.ToString(), OpName, kuweiNum); + MIS_BASE.Write_FixAllow(OpName, true); + } + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function03:PartLoad"); + } + } + + } +} diff --git a/SyUpLoadBak/SyUpLoad/PartLoad.Fun1.cs b/SyUpLoadBak/SyUpLoad/PartLoad.Fun1.cs new file mode 100644 index 0000000..d490c8f --- /dev/null +++ b/SyUpLoadBak/SyUpLoad/PartLoad.Fun1.cs @@ -0,0 +1,215 @@ +using MesWorkMqtt; +using MQTTnet.Client.Connecting; +using MQTTnet.Client.Disconnecting; +using MQTTnet.Client.Receiving; + +using bizFacade; +using MesWorkMqtt; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Configuration; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; +using MQTTnet; +using System.Threading; +using DoWhatPlc; +using MesServerWork; + +namespace SyUpLoad +{ + public partial class PartLoad + { + /// + /// MesServerFunction + /// + /// + /// + /// + private void MesServerFunction(string msgValue) + { + try + { + DoWhatPlc.ReturnValueString rv = Newtonsoft.Json.JsonConvert.DeserializeObject(msgValue); + + string OpName; + string tagValue; + string fun; + string mesServerCode; + string mesServerdllName; + + OpName = rv.OpName; + switch (rv.TagValue.ToLower()) + { + case "false": + tagValue = "0"; + break; + case "true": + tagValue = "1"; + break; + default: + tagValue = rv.TagValue; + break; + } + fun = rv.FunCmd; + mesServerCode = rv.MesServerCode; + mesServerdllName = rv.FunName; + CustomeEvetnArgs e = new CustomeEvetnArgs(); + e.OpName = OpName; + e.TagValue = tagValue; + switch (fun) + { + + // + case "fun_MesReadOver": + fun_MesReadOver(e); + break; + case "fun_MesRead": + fun_MesRead(e); + break; + case "fun_EngineTypeGetOverMES": + fun_EngineTypeGetOverMES(e); + break; + case "fun_WorkStart": + fun_WorkStart(e); + break; + case "fun_PartLoad": + + fun_PartLoad(e); + break; + case "fun_EngineTypeGetOverPLC": + fun_EngineTypeGetOver_PLC(e); + break; + case "fun_FixAllow": + fun_FixAllow(e); + break; + + } + + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "MesServerFunction"); + } + } + + private void fun_EngineTypeGetOverMES(object e) + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + var cb = button_ManualPartLoad; + cb.Invoke(new Action(() => { + if (tagValue == 1) + { + cb.Enabled = false; + } + else + { + cb.Enabled = true; + } + })); + SetChekcBox(tagValue, checkBox_MesEngineTypeGetOver); + + } + private void fun_FixAllow(object e) + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + + + string funID = ht_OpnameFun[OpName].ToString(); + switch (funID) + { + case "1": + SetChekcBox(tagValue, checkBox_MesGoOver); + break; + case "2": + SetChekcBox(tagValue, checkBox_MesGoOver2); + break; + case "3": + SetChekcBox(tagValue, checkBox_MesGoOver3); + break; + } + + } + + private void fun_EngineTypeGetOver_PLC(object e) + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + + string funID = ht_OpnameFun[OpName].ToString(); + switch (funID) + { + case "1": + fun_EngineTypeGetOver_PLC1(e); + break; + case "2": + fun_EngineTypeGetOver_PLC2(e); + break; + case "3": + fun_EngineTypeGetOver_PLC3(e); + break; + } + } + private void fun_EngineTypeGetOver_PLC1(object e) + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + + SetChekcBox(tagValue, checkBox_PlcEngineTypeGetOver); + try + { + if (tagValue == 1) + { + int EngineTypeID;//机型代码 + int PartPallet_Code;//托盘编号 + string EngineType;//机型 + string EngineID;//工件编号 + + MIS_BASE.GetEngineTypeFromPLC(OpName, out EngineTypeID, out EngineType, out EngineID, out PartPallet_Code); + SetTextBox(EngineType, textBox_PlcType); + SetTextBox(EngineID, textBox_PlcEngineID); + EngineTypeGetOver_PLC_Work(OpName, EngineTypeID, EngineType, EngineID, PartPallet_Code); + } + + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function03:EngineTypeGetOver_PLC"); + } + } + private void fun_WorkStart(object e) + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + string funID = ht_OpnameFun[OpName].ToString(); + switch(funID) + { + case "1": + SetChekcBox(tagValue, checkBox_WorkStart); + break; + case "2": + SetChekcBox(tagValue, checkBox_WorkStart2); + break; + case "3": + SetChekcBox(tagValue, checkBox_WorkStart3); + break; + } + } + + private void button_ManualPartLoad_Click(object sender, EventArgs e) + { + fun_PartLoadManual(OPName01); + } + } +} diff --git a/SyUpLoadBak/SyUpLoad/PartLoad.Fun2.cs b/SyUpLoadBak/SyUpLoad/PartLoad.Fun2.cs new file mode 100644 index 0000000..ca6e554 --- /dev/null +++ b/SyUpLoadBak/SyUpLoad/PartLoad.Fun2.cs @@ -0,0 +1,209 @@ +using MesWorkMqtt; +using MQTTnet.Client.Connecting; +using MQTTnet.Client.Disconnecting; +using MQTTnet.Client.Receiving; + +using bizFacade; +using MesWorkMqtt; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Configuration; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; +using MQTTnet; +using System.Threading; +using DoWhatPlc; +using MesServerWork; + +namespace SyUpLoad +{ + public partial class PartLoad + { + // + private void fun_MesReadOver(object e) + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + string funID = ht_OpnameFun[OpName].ToString(); + + switch (funID) + { + case "1": + break; + case "2": + fun_MesReadOver2( e); + break; + case "3": + fun_MesReadOver3(e); + + break; + } + + } + private void fun_MesReadOver2(object e) + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + + SetChekcBox(tagValue, checkBox_MesReadOver2); + + } + private void fun_MesReadOver3(object e) + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + + SetChekcBox(tagValue, checkBox_MesReadOver3); + + } + private void fun_MesRead(object e) + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + string funID = ht_OpnameFun[OpName].ToString(); + + switch (funID) + { + case "1": + break; + case "2": + fun_MesRead2(e); + break; + case "3": + fun_MesRead3(e); + + break; + } + } + private void fun_MesRead2(object e) + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + //var cb = button_ManualPartLoad; + //cb.Invoke(new Action(() => { + // if (tagValue == 1) + // { + // cb.Enabled = false; + // } + // else + // { + // cb.Enabled = true; + // } + //})); + SetChekcBox(tagValue, checkBox_MesRead2); + + if(tagValue==1) + { + + //保存库数据 + int EngineTypeID;//机型代码 + int PartPallet_Code;//托盘编号 + string EngineType;//机型 + string EngineID;//工件编号 + + MIS_BASE.GetEngineTypeFromPLC(OpName, out EngineTypeID, out EngineType, out EngineID, out PartPallet_Code); + object kuweiNum=""; + //从库房拿 库位号 + //判断是否有库位 如果有 + + DataTable dt; + BaseDataSystemMES.GetUnLoadWarehouseNo(OPName02, out dt); + if (dt.Rows.Count >= 1) + { + kuweiNum = Convert.ToByte(dt.Rows[0]["库位号"]); + DtWebApi.ReadWritePLC.WritePLC(warehouseLocation.ToString(), OpName, kuweiNum); + MIS_BASE.Write_EngineTypeGetOver_MES(OpName, true); + + } + else + { + //button_ManualPartLoad.Invoke(new Action(() => + //{ + // button_ManualPartLoad.Enabled = true; + //})); + MessageBox.Show("虚拟库存无位置"); + return; + } + //engineTypeID = Convert.ToInt32(dt.Rows[0]["机型代码"]); + //engineID = dt.Rows[0]["发动机号"].ToString(); + //engineType = dt.Rows[0]["发动机型号"].ToString(); + //kuweiNum = Convert.ToByte(dt.Rows[0]["库位号"]); + + + + //kuweiNum =DtWebApi.ReadWritePLC.ReadPLC(warehouseLocation.ToString(), OpName); + +// BaseDataSystemMES.GetUpLoadBarCode_Update(OpName, kuweiNum.ToString(), "", "", +//EngineID, EngineType, EngineTypeID); +// BaseDataSystemMES.GetUpLoadBarCode(OPName02, out DataTable dt_OPName02); +// dataGridView_OPA1002.Invoke(new Action(() => { +// dataGridView_OPA1002.DataSource = dt_OPName02; +// })); + + + + MIS_BASE.Write_MesReadOver(OpName, true); + } + else + { + MIS_BASE.Write_MesReadOver(OpName, false); + } + + } + private void fun_EngineTypeGetOver_PLC2(object e) + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + + SetChekcBox(tagValue, checkBox_PlcEngineTypeGetOver2); + try + { + if (tagValue == 1) + { + int EngineTypeID;//机型代码 + int PartPallet_Code;//托盘编号 + string EngineType;//机型 + string EngineID;//工件编号 + + MIS_BASE.GetEngineTypeFromPLC(OpName, out EngineTypeID, out EngineType, out EngineID, out PartPallet_Code); + SetTextBox(EngineType, textBox_PlcType2); + SetTextBox(EngineID, textBox_PlcEngineID2); + DataTable dt; + BaseDataSystemMES.GetUnLoadWarehouseNo(OpName, out dt); + if(dt.Rows.Count==0) + { + MessageBox.Show("下线库位已满"); + button_ManualPartLoad2.Invoke(new Action(() => { + button_ManualPartLoad2.Enabled = true; + })); + } + else + { + byte kuweiNum = Convert.ToByte(dt.Rows[0]["库位号"]); + DtWebApi.ReadWritePLC.WritePLC(warehouseLocation.ToString(), OpName, kuweiNum); + + + MIS_BASE.Write_FixAllow(OpName, true); + + + } + //EngineTypeGetOver_PLC_Work(OpName, EngineTypeID, EngineType, EngineID, PartPallet_Code); + } + + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function03:EngineTypeGetOver_PLC"); + } + } + } +} diff --git a/SyUpLoadBak/SyUpLoad/PartLoad.Fun3.cs b/SyUpLoadBak/SyUpLoad/PartLoad.Fun3.cs new file mode 100644 index 0000000..6865048 --- /dev/null +++ b/SyUpLoadBak/SyUpLoad/PartLoad.Fun3.cs @@ -0,0 +1,138 @@ +using MesWorkMqtt; +using MQTTnet.Client.Connecting; +using MQTTnet.Client.Disconnecting; +using MQTTnet.Client.Receiving; + +using bizFacade; +using MesWorkMqtt; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Configuration; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; +using MQTTnet; +using System.Threading; +using DoWhatPlc; +using MesServerWork; + +namespace SyUpLoad +{ + public partial class PartLoad + { + private void fun_EngineTypeGetOver_PLC3(object e) + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + + SetChekcBox(tagValue, checkBox_PlcEngineTypeGetOver3); + try + { + if (tagValue == 1) + { + int EngineTypeID;//机型代码 + int PartPallet_Code;//托盘编号 + string EngineType;//机型 + string EngineID;//工件编号 + //GetUpLoadWarehouseNoOpName02(string opName, string EngineIDType, out DataTable dt) + + + MIS_BASE.GetEngineTypeFromPLC(OPName02, out EngineTypeID, out EngineType, out EngineID, out PartPallet_Code); + + + + SetTextBox(EngineType, textBox_PlcType3); + SetTextBox(EngineID, textBox_PlcEngineID3); + + DataTable dt; + BaseDataSystemMES.GetUpLoadWarehouseNoOpName02(OPName02, EngineType, out dt); + if (dt.Rows.Count < 1) + { + + button_ManualPartLoad.Invoke(new Action(() => { + button_ManualPartLoad.Enabled = true; + })); + MessageBox.Show("下线库存无匹配的工件!"); + return; + } + int engineTypeID_MES = Convert.ToInt32(dt.Rows[0]["机型代码"]); + string engineID_MES = dt.Rows[0]["发动机号"].ToString(); + string engineType_MES = dt.Rows[0]["发动机型号"].ToString(); + byte kuweiNum_MES = Convert.ToByte(dt.Rows[0]["库位号"]); + DtWebApi.ReadWritePLC.WritePLC(warehouseLocation.ToString(), OpName, kuweiNum_MES); + + + MIS_BASE.Write_FixAllow(OpName, true); + + // EngineTypeGetOver_PLC_Work(OpName, EngineTypeID, EngineType, EngineID, PartPallet_Code); + } + else + { + MIS_BASE.Write_FixAllow(OpName, false); + + } + + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "Function03:EngineTypeGetOver_PLC"); + } + } + + private void fun_MesRead3(object e) + { + DoWhatPlc.CustomeEvetnArgs msgEvent = (DoWhatPlc.CustomeEvetnArgs)e; + string OpName = Convert.ToString(msgEvent.OpName); + int tagValue = Convert.ToInt32(msgEvent.TagValue); + //var cb = button_ManualPartLoad; + //cb.Invoke(new Action(() => { + // if (tagValue == 1) + // { + // cb.Enabled = false; + // } + // else + // { + // cb.Enabled = true; + // } + //})); + SetChekcBox(tagValue, checkBox_MesRead3); + + if (tagValue == 1) + { + + //保存库数据 + int EngineTypeID;//机型代码 + int PartPallet_Code;//托盘编号 + string EngineType;//机型 + string EngineID;//工件编号 + + MIS_BASE.GetEngineTypeFromPLC(OpName, out EngineTypeID, out EngineType, out EngineID, out PartPallet_Code); + object kuweiNum; + kuweiNum = DtWebApi.ReadWritePLC.ReadPLC(warehouseLocation.ToString(), OpName); + + //1转移数据到总线 + + //2转移数据到总线 + BaseDataSystemMES.GetUpLoadBarCode_0utUpdate(OPName02, kuweiNum.ToString()); + BaseDataSystemMES.GetUpLoadBarCode(OPName02, out DataTable dt_OPName02); + + + dataGridView_OPA1002.Invoke(new Action(() => { + dataGridView_OPA1002.DataSource = dt_OPName02; + })); + + MIS_BASE.Write_MesReadOver(OpName, true); + } + else + { + MIS_BASE.Write_MesReadOver(OpName, false); + } + + } + } +} diff --git a/SyUpLoadBak/SyUpLoad/PartLoad.SetControl.cs b/SyUpLoadBak/SyUpLoad/PartLoad.SetControl.cs new file mode 100644 index 0000000..380647b --- /dev/null +++ b/SyUpLoadBak/SyUpLoad/PartLoad.SetControl.cs @@ -0,0 +1,53 @@ +using MesWorkMqtt; +using MQTTnet.Client.Connecting; +using MQTTnet.Client.Disconnecting; +using MQTTnet.Client.Receiving; + +using bizFacade; +using MesWorkMqtt; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Configuration; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; +using MQTTnet; +using System.Threading; +using DoWhatPlc; +using MesServerWork; + +namespace SyUpLoad +{ + public partial class PartLoad + { + private void SetChekcBox(int tagValue, object checkBox) + { + + CheckBox cb = (CheckBox)checkBox; + cb.Invoke(new Action(() => { + if (tagValue == 1) + { + cb.Checked = true; + cb.BackColor = Color.LightGreen; + } + else + { + cb.Checked = false; + cb.BackColor = Color.Gray; + } + })); + + } + private void SetTextBox(string text, object controlBox) + { + TextBox cb = (TextBox)controlBox; + cb.Invoke(new Action(() => { + cb.Text = text; + })); + } + } +} diff --git a/SyUpLoadBak/SyUpLoad/PartLoad.cs b/SyUpLoadBak/SyUpLoad/PartLoad.cs new file mode 100644 index 0000000..5861a10 --- /dev/null +++ b/SyUpLoadBak/SyUpLoad/PartLoad.cs @@ -0,0 +1,180 @@ +using MesWorkMqtt; +using MQTTnet.Client.Connecting; +using MQTTnet.Client.Disconnecting; +using MQTTnet.Client.Receiving; + +using bizFacade; +using MesWorkMqtt; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Configuration; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; +using MQTTnet; +using System.Threading; +using DoWhatPlc; +using MesServerWork; +using System.Collections; + +namespace SyUpLoad +{ + public partial class PartLoad : Form + { + + public static string MqttUrl = ConfigurationManager.AppSettings["MqttUrl"]; + public static string MqttTargetTopic = ConfigurationManager.AppSettings["MqttTargetTopic"]; + public static string Url_WebApi = ConfigurationManager.AppSettings["Url_WebApi"]; + public static string ConnectionString_MES = ConfigurationManager.AppSettings["ConnectionString_MES"]; + public static string OPName01Fun = ConfigurationManager.AppSettings["OPName01"]; + public static string OPName02Fun = ConfigurationManager.AppSettings["OPName02"]; + public static string OPName03Fun = ConfigurationManager.AppSettings["OPName03"]; + //第一个库房工位号 + public static string OPName01; + //第二个库房工位号 + public static string OPName02; + public static byte warehouseLocation = 112; + Hashtable ht_OpnameFun; + + DataTable dt_OPName01; + DataTable dt_OPName02; + + public PartLoad() + { + InitializeComponent(); + InitHashTable(); + + BaseDataSystemMES.GetUpLoadBarCode(OPName01, out DataTable dt_OPName01); + BaseDataSystemMES.GetUpLoadBarCode(OPName02, out DataTable dt_OPName02); + + dataGridView_OPA1001.DataSource = dt_OPName01; + dataGridView_OPA1002.DataSource = dt_OPName02; + } + + private void InitHashTable() + { + ht_OpnameFun = new Hashtable(); + var op = OPName01Fun.Split('|'); + ht_OpnameFun.Add(op[0], op[1]); + OPName01 = op[0]; + op = OPName02Fun.Split('|'); + ht_OpnameFun.Add(op[0], op[1]); + OPName02 = op[0]; + + op = OPName03Fun.Split('|'); + ht_OpnameFun.Add(op[0], op[1]); + } + + + + private void PartLoad_Load(object sender, EventArgs e) + { + SetCOM(); + + Mqtt.StartAsync(); + Mqtt.mqttClient.ConnectedHandler = new MqttClientConnectedHandlerDelegate(OnSubscriberConnected); + Mqtt.mqttClient.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(OnSubscriberDisconnected); + Mqtt.mqttClient.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(OnSubscriberMessageReceived); + + ////MesServerCode哈希表创建 + //MesServerWork.MIS_BASE.InitHashtable_MesServerCode(); + } + + private void OnSubscriberConnected(MqttClientConnectedEventArgs x) + { + var rec = x.AuthenticateResult.ResultCode.ToString(); + //label_State.Text = rec; + } + + private void OnSubscriberDisconnected(MqttClientDisconnectedEventArgs x) + { + var rec = x.AuthenticateResult.ResultCode.ToString(); + //label_State.Text = rec; + } + + private void OnSubscriberMessageReceived(MqttApplicationMessageReceivedEventArgs x) + { + var rec = x.ApplicationMessage.ConvertPayloadToString(); + + //保存数据 + //ThreadPool.QueueUserWorkItem(MIS_Funtion, rec); + + //处理MES业务 + ThreadPool.QueueUserWorkItem(TransferInfToMES, rec); + } + + private void TransferInfToMES(object text) + { + try + { + string recData = text.ToString(); + string[] dataArray = recData.Split('|'); + if (dataArray.Length != 4) + return; + //消息来源 + string m_Source = dataArray[0].ToString(); + //消息类型 Barcode + string m_Command = dataArray[1].ToString(); + //工位号 + string m_OpName = dataArray[2].ToString(); + //消息参数 + string m_Value = dataArray[3].ToString(); + + //if (!m_WorkStart_OpName.ContainsKey(m_OpName)) return; //当前系统是否存在该工位 + + switch (m_Source) + { + case "BarCode": + //处理条码逻辑 + if (m_Command == "Bar") + { + //MesServerFunction(m_OpName, m_Value, "fun_Barcode"); + } + break; + case "WEB": + if (m_Command == "Barcode") + { + //MesServerFunction(m_OpName, m_Value, "fun_Barcode"); + + } + else + { + string Content = m_Command + "|" + m_Value; + //MesServerFunction(m_OpName, Content, "fun_WebSubmit"); + + } + break; + case "PLC": + string funID = ht_OpnameFun[m_OpName].ToString(); + switch(funID) + { + case "1": + MesServerFunction(m_Value); + break; + case "2": + MesServerFunction(m_Value); + break; + case "3": + MesServerFunction(m_Value); + break; + } + break; + } + + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, "TransferInf"); + } + } + + private void button_ManualPartLoad2_Click(object sender, EventArgs e) + { + fun_PartLoadManual2(OPName02); + } + } +} diff --git a/SyUpLoadBak/SyUpLoad/PartLoad.resx b/SyUpLoadBak/SyUpLoad/PartLoad.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/SyUpLoadBak/SyUpLoad/PartLoad.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/SyUpLoadBak/SyUpLoad/Program.cs b/SyUpLoadBak/SyUpLoad/Program.cs new file mode 100644 index 0000000..a69689c --- /dev/null +++ b/SyUpLoadBak/SyUpLoad/Program.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace SyUpLoad +{ + static class Program + { + /// + /// 应用程序的主入口点。 + /// + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + Application.Run(new PartLoad()); + } + } +} diff --git a/SyUpLoadBak/SyUpLoad/Properties/AssemblyInfo.cs b/SyUpLoadBak/SyUpLoad/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..c254d32 --- /dev/null +++ b/SyUpLoadBak/SyUpLoad/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// 有关程序集的一般信息由以下 +// 控制。更改这些特性值可修改 +// 与程序集关联的信息。 +[assembly: AssemblyTitle("SyUpLoad")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("SyUpLoad")] +[assembly: AssemblyCopyright("Copyright © 2022")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// 将 ComVisible 设置为 false 会使此程序集中的类型 +//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型 +//请将此类型的 ComVisible 特性设置为 true。 +[assembly: ComVisible(false)] + +// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID +[assembly: Guid("81604748-73c5-43fa-8e27-be0ab28618c3")] + +// 程序集的版本信息由下列四个值组成: +// +// 主版本 +// 次版本 +// 生成号 +// 修订号 +// +//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值 +//通过使用 "*",如下所示: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/SyUpLoadBak/SyUpLoad/Properties/Resources.Designer.cs b/SyUpLoadBak/SyUpLoad/Properties/Resources.Designer.cs new file mode 100644 index 0000000..515da15 --- /dev/null +++ b/SyUpLoadBak/SyUpLoad/Properties/Resources.Designer.cs @@ -0,0 +1,70 @@ +//------------------------------------------------------------------------------ +// +// 此代码由工具生成。 +// 运行时版本: 4.0.30319.42000 +// +// 对此文件的更改可能导致不正确的行为,如果 +// 重新生成代码,则所做更改将丢失。 +// +//------------------------------------------------------------------------------ + + +namespace SyUpLoad.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("SyUpLoad.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/SyUpLoadBak/SyUpLoad/Properties/Resources.resx b/SyUpLoadBak/SyUpLoad/Properties/Resources.resx new file mode 100644 index 0000000..af7dbeb --- /dev/null +++ b/SyUpLoadBak/SyUpLoad/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/SyUpLoadBak/SyUpLoad/Properties/Settings.Designer.cs b/SyUpLoadBak/SyUpLoad/Properties/Settings.Designer.cs new file mode 100644 index 0000000..e27ee1d --- /dev/null +++ b/SyUpLoadBak/SyUpLoad/Properties/Settings.Designer.cs @@ -0,0 +1,29 @@ +//------------------------------------------------------------------------------ +// +// 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 SyUpLoad.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/SyUpLoadBak/SyUpLoad/Properties/Settings.settings b/SyUpLoadBak/SyUpLoad/Properties/Settings.settings new file mode 100644 index 0000000..3964565 --- /dev/null +++ b/SyUpLoadBak/SyUpLoad/Properties/Settings.settings @@ -0,0 +1,7 @@ + + + + + + + diff --git a/SyUpLoadBak/SyUpLoad/SyUpLoad.csproj b/SyUpLoadBak/SyUpLoad/SyUpLoad.csproj new file mode 100644 index 0000000..b5d15b4 --- /dev/null +++ b/SyUpLoadBak/SyUpLoad/SyUpLoad.csproj @@ -0,0 +1,212 @@ + + + + + Debug + AnyCPU + {81604748-73C5-43FA-8E27-BE0AB28618C3} + WinExe + SyUpLoad + SyUpLoad + v4.6.1 + 512 + true + true + + + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + False + ..\dll\MQTTnet.dll + + + False + ..\dll\MQTTnet.Extensions.ManagedClient.dll + + + + + ..\packages\System.Configuration.ConfigurationManager.6.0.1\lib\net461\System.Configuration.ConfigurationManager.dll + + + + + + ..\packages\System.Net.Security.4.3.2\lib\net46\System.Net.Security.dll + + + ..\packages\System.Net.WebSockets.4.3.0\lib\net46\System.Net.WebSockets.dll + + + ..\packages\System.Net.WebSockets.Client.4.3.2\lib\net46\System.Net.WebSockets.Client.dll + + + + ..\packages\System.Security.AccessControl.6.0.0\lib\net461\System.Security.AccessControl.dll + + + ..\packages\System.Security.Cryptography.Algorithms.4.3.0\lib\net461\System.Security.Cryptography.Algorithms.dll + + + ..\packages\System.Security.Cryptography.Encoding.4.3.0\lib\net46\System.Security.Cryptography.Encoding.dll + + + ..\packages\System.Security.Cryptography.Primitives.4.3.0\lib\net46\System.Security.Cryptography.Primitives.dll + + + ..\packages\System.Security.Cryptography.X509Certificates.4.3.0\lib\net461\System.Security.Cryptography.X509Certificates.dll + + + ..\packages\System.Security.Permissions.6.0.0\lib\net461\System.Security.Permissions.dll + + + ..\packages\System.Security.Principal.Windows.5.0.0\lib\net461\System.Security.Principal.Windows.dll + + + + + + + + + + + + + + + + + Form + + + Form + + + Form + + + Form + + + Form + + + Form + + + Form + + + Form + + + Form + + + Form + + + Form + + + Form + + + Form + + + PartLoad.cs + + + + + PartLoad.cs + + + ResXFileCodeGenerator + Resources.Designer.cs + Designer + + + True + Resources.resx + + + + + SettingsSingleFileGenerator + Settings.Designer.cs + + + True + Settings.settings + True + + + + + + + + {1a10fdb2-1a6a-44a8-ab4d-33387563247e} + 00-0Json8.3.1 + + + {f55da1a0-a982-4479-8c47-0d9a5aaf3e18} + 00MesWorkMqtt + + + {0d1af432-439a-4920-8692-43ae139f5530} + 01_01DoWhatPlc + + + {3e6d1dd5-01c9-435f-9941-61f906ce35bb} + 02_02WebApiCallPLC + + + {f434e066-4c59-47c8-aa82-6f48cc84501a} + 04-DataBaseAccess + + + {f0a0c525-03fd-428a-9b17-7f54aa0e4475} + 07BusinessFacade + + + {d98be764-adeb-488d-9714-61e308aa8201} + 08-WebFun_base + + + {90e76fb4-646d-45e2-95db-0b8ab4e465d6} + 09-MesDataFunction + + + + + + + 这台计算机上缺少此项目引用的 NuGet 程序包。使用“NuGet 程序包还原”可下载这些程序包。有关更多信息,请参见 http://go.microsoft.com/fwlink/?LinkID=322105。缺少的文件是 {0}。 + + + + \ No newline at end of file diff --git a/SyUpLoadBak/SyUpLoad/packages.config b/SyUpLoadBak/SyUpLoad/packages.config new file mode 100644 index 0000000..40d6006 --- /dev/null +++ b/SyUpLoadBak/SyUpLoad/packages.config @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/SyUpLoadBak/dll/00.1Newtonsoft.Json.dll b/SyUpLoadBak/dll/00.1Newtonsoft.Json.dll new file mode 100644 index 0000000..85a14c9 Binary files /dev/null and b/SyUpLoadBak/dll/00.1Newtonsoft.Json.dll differ diff --git a/SyUpLoadBak/dll/00.1Newtonsoft.Json.pdb b/SyUpLoadBak/dll/00.1Newtonsoft.Json.pdb new file mode 100644 index 0000000..a01b35b Binary files /dev/null and b/SyUpLoadBak/dll/00.1Newtonsoft.Json.pdb differ diff --git a/SyUpLoadBak/dll/00MesWorkMqtt.dll b/SyUpLoadBak/dll/00MesWorkMqtt.dll new file mode 100644 index 0000000..15cb845 Binary files /dev/null and b/SyUpLoadBak/dll/00MesWorkMqtt.dll differ diff --git a/SyUpLoadBak/dll/00MesWorkMqtt.pdb b/SyUpLoadBak/dll/00MesWorkMqtt.pdb new file mode 100644 index 0000000..5dc65cb Binary files /dev/null and b/SyUpLoadBak/dll/00MesWorkMqtt.pdb differ diff --git a/SyUpLoadBak/dll/01DoWhatPlc.dll b/SyUpLoadBak/dll/01DoWhatPlc.dll new file mode 100644 index 0000000..25c33ee Binary files /dev/null and b/SyUpLoadBak/dll/01DoWhatPlc.dll differ diff --git a/SyUpLoadBak/dll/01DoWhatPlc.pdb b/SyUpLoadBak/dll/01DoWhatPlc.pdb new file mode 100644 index 0000000..e75a71b Binary files /dev/null and b/SyUpLoadBak/dll/01DoWhatPlc.pdb differ diff --git a/SyUpLoadBak/dll/02WebApiCall.dll b/SyUpLoadBak/dll/02WebApiCall.dll new file mode 100644 index 0000000..9a3f5b0 Binary files /dev/null and b/SyUpLoadBak/dll/02WebApiCall.dll differ diff --git a/SyUpLoadBak/dll/02WebApiCall.dll.config b/SyUpLoadBak/dll/02WebApiCall.dll.config new file mode 100644 index 0000000..6035ea8 --- /dev/null +++ b/SyUpLoadBak/dll/02WebApiCall.dll.config @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/SyUpLoadBak/dll/02WebApiCall.pdb b/SyUpLoadBak/dll/02WebApiCall.pdb new file mode 100644 index 0000000..16b7902 Binary files /dev/null and b/SyUpLoadBak/dll/02WebApiCall.pdb differ diff --git a/SyUpLoadBak/dll/04DataBaseAccess.dll b/SyUpLoadBak/dll/04DataBaseAccess.dll new file mode 100644 index 0000000..1378ec9 Binary files /dev/null and b/SyUpLoadBak/dll/04DataBaseAccess.dll differ diff --git a/SyUpLoadBak/dll/04DataBaseAccess.pdb b/SyUpLoadBak/dll/04DataBaseAccess.pdb new file mode 100644 index 0000000..740cc80 Binary files /dev/null and b/SyUpLoadBak/dll/04DataBaseAccess.pdb differ diff --git a/SyUpLoadBak/dll/07BusinessFacade.dll b/SyUpLoadBak/dll/07BusinessFacade.dll new file mode 100644 index 0000000..02e2595 Binary files /dev/null and b/SyUpLoadBak/dll/07BusinessFacade.dll differ diff --git a/SyUpLoadBak/dll/07BusinessFacade.pdb b/SyUpLoadBak/dll/07BusinessFacade.pdb new file mode 100644 index 0000000..dcb0c1b Binary files /dev/null and b/SyUpLoadBak/dll/07BusinessFacade.pdb differ diff --git a/SyUpLoadBak/dll/08WebFun_base.dll b/SyUpLoadBak/dll/08WebFun_base.dll new file mode 100644 index 0000000..e088df4 Binary files /dev/null and b/SyUpLoadBak/dll/08WebFun_base.dll differ diff --git a/SyUpLoadBak/dll/08WebFun_base.pdb b/SyUpLoadBak/dll/08WebFun_base.pdb new file mode 100644 index 0000000..b4db747 Binary files /dev/null and b/SyUpLoadBak/dll/08WebFun_base.pdb differ diff --git a/SyUpLoadBak/dll/09MesDataFunction.dll b/SyUpLoadBak/dll/09MesDataFunction.dll new file mode 100644 index 0000000..e31947c Binary files /dev/null and b/SyUpLoadBak/dll/09MesDataFunction.dll differ diff --git a/SyUpLoadBak/dll/09MesDataFunction.pdb b/SyUpLoadBak/dll/09MesDataFunction.pdb new file mode 100644 index 0000000..8c336b4 Binary files /dev/null and b/SyUpLoadBak/dll/09MesDataFunction.pdb differ diff --git a/SyUpLoadBak/dll/BusinessFacade.pdb b/SyUpLoadBak/dll/BusinessFacade.pdb new file mode 100644 index 0000000..2e1bfcb Binary files /dev/null and b/SyUpLoadBak/dll/BusinessFacade.pdb differ diff --git a/SyUpLoadBak/dll/MQTTnet.Extensions.ManagedClient.dll b/SyUpLoadBak/dll/MQTTnet.Extensions.ManagedClient.dll new file mode 100644 index 0000000..99035f6 Binary files /dev/null and b/SyUpLoadBak/dll/MQTTnet.Extensions.ManagedClient.dll differ diff --git a/SyUpLoadBak/dll/MQTTnet.dll b/SyUpLoadBak/dll/MQTTnet.dll new file mode 100644 index 0000000..2951433 Binary files /dev/null and b/SyUpLoadBak/dll/MQTTnet.dll differ diff --git a/SystemConfig.xml b/SystemConfig.xml new file mode 100644 index 0000000..7a272ef --- /dev/null +++ b/SystemConfig.xml @@ -0,0 +1,261 @@ + + + + + + + + True + 10000 + true + 1000 + BreakPLC + + + + + PLC通讯 + 14 + PLC通讯 + 1 + true + PLC心跳信号 + + + PLC工件到位 + 2 + 工件到位 + 2 + true + PLC工件到位信号 + + + PLC申请上线 + 43 + 申请上线 + 3 + true + PLC向MES申请工件编号 + + + PLC传递机型 + 44 + 传递机型 + 4 + true + PLC向MES传递机型信息 + + + PLC拧紧完成 + 59 + 拧紧完成 + 5 + true + PLC当前螺栓拧紧完成 + + + PLC允许保存 + 19 + 允许保存 + 6 + true + PLC允许MES保存质量数据 + + + PLC申请下线 + 50 + 申请下线 + 7 + false + PLC申请下线 + + + PLC循环开始 + 1001 + 循环开始 + 8 + false + PLC循环开始 + + + PLC机床上电 + 1000 + 机床上电 + 9 + false + PLC设备上电 + + + PLC机床故障 + 1002 + 机床故障 + 10 + false + PLC设备故障 + + + PLC托盘到位 + 13 + 托盘到位 + 11 + false + PLC托盘到位 + + + PLC上料无件 + 1003 + 上料无件 + 12 + false + PLC当前工位无件 + + + PLC下料堵塞 + 1004 + 下料堵塞 + 13 + false + PLC放行工件拥堵 + + + PLC允许读节拍 + 16 + 节拍可读 + 14 + false + PLC允许MES都工位节拍 + + + + + MES通讯 + 15 + MES通讯 + 15 + false + MES心跳 + + + MES传递机型 + 5 + 传递编号 + 16 + true + MES向PLC传递机型信息 + + + MES允许工作 + 66 + 允许工作 + 17 + true + MES允许设备工作 + + + MES拧紧完成确认 + 67 + 完成确认 + 18 + true + MES保存拧紧数据完成 + + + MES保存完成 + 20 + 保存完成 + 19 + true + MES保存质量数据完成 + + + MES工作完成 + 7 + 工作完成 + 20 + true + MES工作完成 + + + MES合格放行 + 51 + 合格放行 + 21 + true + MES允许工件合格放行 + + + MES返修放行 + 8 + 返修放行 + 22 + true + MES允许工件不合格放行 + + + MES下线完成 + 53 + 下线完成 + 23 + false + MES允许工件下线 + + + MES空托盘放行 + 6 + 无件放行 + 24 + false + MES允许空托盘放行 + + + MES匹配完成 + 68 + 匹配完成 + 25 + false + MES匹配工件完成 + + + MES匹配结果 + 69 + 匹配结果 + 26 + false + MES匹配工件的结果 + + + MES自动手动 + 71 + 自动手动 + 27 + false + MES设备工作方式 + + + MES清空Moby + 72 + 清空Moby + 28 + false + MES清空RFID信息 + + + MES读节拍完成 + 54 + 节拍读完 + 29 + false + MES保存工位节拍完成 + + + MES复位设备 + 52 + 复位设备 + 30 + false + MES申请PLC复位 + + + + + \ No newline at end of file diff --git a/TagTypeCodeID/TagTypeCodeID.sln b/TagTypeCodeID/TagTypeCodeID.sln new file mode 100644 index 0000000..8cf00a2 --- /dev/null +++ b/TagTypeCodeID/TagTypeCodeID.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.32901.82 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TagTypeCodeID", "TagTypeCodeID\TagTypeCodeID.csproj", "{807FCC00-D1D5-45DF-A60D-E295640EB6AA}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {807FCC00-D1D5-45DF-A60D-E295640EB6AA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {807FCC00-D1D5-45DF-A60D-E295640EB6AA}.Debug|Any CPU.Build.0 = Debug|Any CPU + {807FCC00-D1D5-45DF-A60D-E295640EB6AA}.Release|Any CPU.ActiveCfg = Release|Any CPU + {807FCC00-D1D5-45DF-A60D-E295640EB6AA}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {C04EAAD0-63A0-4891-9833-DC9BADB2224A} + EndGlobalSection +EndGlobal diff --git a/TagTypeCodeID/TagTypeCodeID/13.2TagTypeCodeID.csproj b/TagTypeCodeID/TagTypeCodeID/13.2TagTypeCodeID.csproj new file mode 100644 index 0000000..e1ba6cf --- /dev/null +++ b/TagTypeCodeID/TagTypeCodeID/13.2TagTypeCodeID.csproj @@ -0,0 +1,73 @@ + + + + + Debug + AnyCPU + {807FCC00-D1D5-45DF-A60D-E295640EB6AA} + Library + Properties + TagTypeCodeID + TagTypeCodeID + v4.8 + 512 + true + + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + ..\..\Common\dll\MQTTnet.dll + + + ..\..\Common\dll\MQTTnet.Extensions.ManagedClient.dll + + + + + + + + + + + + + + + + + {1a10fdb2-1a6a-44a8-ab4d-33387563247e} + 00-0Json8.3.1 + + + {f55da1a0-a982-4479-8c47-0d9a5aaf3e18} + 00MesWorkMqtt + + + {0d1af432-439a-4920-8692-43ae139f5530} + 01_01DoWhatPlc + + + {f434e066-4c59-47c8-aa82-6f48cc84501a} + 04-DataBaseAccess + + + + \ No newline at end of file diff --git a/TagTypeCodeID/TagTypeCodeID/InitMqtt2TagTypeCodeID.cs b/TagTypeCodeID/TagTypeCodeID/InitMqtt2TagTypeCodeID.cs new file mode 100644 index 0000000..b079963 --- /dev/null +++ b/TagTypeCodeID/TagTypeCodeID/InitMqtt2TagTypeCodeID.cs @@ -0,0 +1,132 @@ +using DataLinkMesWork; +using MesWorkMqtt; +using MQTTnet; +using MQTTnet.Client.Connecting; +using MQTTnet.Client.Disconnecting; +using MQTTnet.Client.Receiving; +using System; +using System.Collections.Generic; +using System.Data.SqlClient; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +namespace MisDataSaveDate +{ + public class InitMqtt2 + { + //public Mqtt2 mqtt2; + //public InitMqtt2(string url,string topic) + //{ + // mqtt2 = new Mqtt2(); + // mqtt2.MqttUrl = url; + // mqtt2.topic = topic; + // mqtt2.StartAsync(); + // mqtt2.mqttClient.ConnectedHandler = new MqttClientConnectedHandlerDelegate(OnSubscriberConnected); + // mqtt2.mqttClient.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(OnSubscriberDisconnected); + // mqtt2.mqttClient.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(OnSubscriberMessageReceived); + + + + //} + //private void OnSubscriberConnected(MqttClientConnectedEventArgs x) + //{ + // var rec = x.AuthenticateResult.ResultCode.ToString(); + // //label_State.Text = rec; + //} + + //private void OnSubscriberDisconnected(MqttClientDisconnectedEventArgs x) + //{ + // //var rec = x.AuthenticateResult.ResultCode.ToString(); + // //label_State.Text = rec; + //} + + //private void OnSubscriberMessageReceived(MqttApplicationMessageReceivedEventArgs x) + //{ + // var rec = x.ApplicationMessage.ConvertPayloadToString(); + // ThreadPool.QueueUserWorkItem(MIS_Funtion, rec); + //} + + public static void MIS_Funtion(object e) + { + try + { + + string recData = e.ToString(); + + + var msgEvent = Newtonsoft.Json.JsonConvert.DeserializeObject(recData); + //Console.WriteLine($"【【{rv.TagID}【【【【{ rv.TagKeepTime}"); + if (msgEvent == null) return; + int tagType; + string tagValue; + int tagid; + + if (msgEvent.TagValue == null) return; + + + switch (msgEvent.TagValue.ToString().ToLower()) + { + case "1": + case "true": + tagValue = "1"; + break; + default: + tagValue = "0"; + break; + } + + tagType = Convert.ToInt32(msgEvent.TagTypeID); + tagid = Convert.ToInt32(msgEvent.TagID); + + string opName; + string TagTypeID; + string TagTypeCodeID; + string TagID; + string TagValue; + DateTime arrivedTime; + DateTime leavedTime; + int TimeDiff; + + opName = msgEvent.OpName.ToString(); + TagValue = tagValue; + TagTypeCodeID = msgEvent.TagTypeCodeID.ToString(); + TagTypeID = msgEvent.TagTypeID.ToString(); + TagID = msgEvent.TagID.ToString(); + leavedTime = Convert.ToDateTime(msgEvent.TimeStamp); + arrivedTime = Convert.ToDateTime(msgEvent.TimeStampBefore); + TimeDiff = Convert.ToInt32(msgEvent.TagKeepTime); + + TagTypeCodeID_Insert(opName, TagTypeCodeID, TagID, TagValue, arrivedTime, leavedTime, TimeDiff); + } + catch (Exception err) + { + ////ApplicationLog.WriteLog(err, err.Message); + } + } +// ALTER PROCEDURE[dbo].[测量数据设备状态日志_增加数据] +// @工位号 nvarchar(50)=null, +//@信号类型代码 nvarchar(50)=null, +//@TagID nvarchar(50)=null, +//@TagValue nvarchar(50)=null, +//@到达时间 datetime = null, +//@离开时间 datetime=null, +//@在线时间 int = null +//AS + static public void TagTypeCodeID_Insert(string opName, string TagTypeCodeID, string TagID,string TagValue, DateTime arrivedTime, DateTime leavedTime, int TimeDiff) + { + string procedureName; + procedureName = "测量数据设备状态日志_增加数据"; + SqlParameter[] thisParms = new SqlParameter[7]; + thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName); + thisParms[1] = new System.Data.SqlClient.SqlParameter("@信号类型代码", TagTypeCodeID); + thisParms[2] = new System.Data.SqlClient.SqlParameter("@TagID", TagID); + thisParms[3] = new System.Data.SqlClient.SqlParameter("@TagValue", TagValue); + thisParms[4] = new System.Data.SqlClient.SqlParameter("@到达时间", arrivedTime); + thisParms[5] = new System.Data.SqlClient.SqlParameter("@离开时间", leavedTime); + thisParms[6] = new System.Data.SqlClient.SqlParameter("@在线时间", TimeDiff); + DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms); + } + } +} diff --git a/TagTypeCodeID/TagTypeCodeID/Properties/AssemblyInfo.cs b/TagTypeCodeID/TagTypeCodeID/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..05e0451 --- /dev/null +++ b/TagTypeCodeID/TagTypeCodeID/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// 有关程序集的一般信息由以下 +// 控制。更改这些特性值可修改 +// 与程序集关联的信息。 +[assembly: AssemblyTitle("TagTypeCodeID")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("TagTypeCodeID")] +[assembly: AssemblyCopyright("Copyright © 2022")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// 将 ComVisible 设置为 false 会使此程序集中的类型 +//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型 +//请将此类型的 ComVisible 特性设置为 true。 +[assembly: ComVisible(false)] + +// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID +[assembly: Guid("807fcc00-d1d5-45df-a60d-e295640eb6aa")] + +// 程序集的版本信息由下列四个值组成: +// +// 主版本 +// 次版本 +// 生成号 +// 修订号 +// +//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值 +//通过使用 "*",如下所示: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Test/ManualSimulateSignal.cs b/Test/ManualSimulateSignal.cs new file mode 100644 index 0000000..eb20855 --- /dev/null +++ b/Test/ManualSimulateSignal.cs @@ -0,0 +1,522 @@ +//using BasicData; + +using DoWhatPlc; +using MesServerWork; +using MisDataFunction; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading; +using System.Windows.Forms; +//using SystemFramework; + +namespace MisDataSaveDate +{ + public partial class MisData + { + public void InitFormBtnColor() + { + try + { + if (!Cbx_StatusDisplay.Checked) return; + string OpName = WorkStationNum_Now; + foreach (Control GroupBox in this.groupBox_SignialSimulator.Controls) + { + foreach (Control Btn in GroupBox.Controls) + { + if (Btn.Name.Length < 8) continue; + if (Btn.Name.Substring(0, 8) == "Btn_PLC_" || Btn.Name.Substring(0, 8) == "Btn_MES_") + { + ControlData Ctrl1 = new ControlData(Btn, OpName); + Thread t=new Thread(new ParameterizedThreadStart(InitFormBtn_Thread)); + t.Start(Ctrl1); + } + } + } + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, err.Message); + + } + + + } + + static object test; + static void InitFormBtn_Thread(Object obj) + { + try + { + ControlData Btn = (ControlData)obj; + + test = DtWebApi.ReadWritePLC.ReadPLC(Btn.TagType.ToString(), Btn.opName); + + bool Result = Convert.ToBoolean(test); + if (Btn.btn.InvokeRequired) + { + Action actionDelegate = (x) => { Btn.btn.BackColor = x; }; + if (Result) + { + Btn.btn.BeginInvoke(actionDelegate, System.Drawing.Color.Green); + } + else + { + Btn.btn.BeginInvoke(actionDelegate, System.Drawing.Color.SlateGray); + } + } + else + { + if (Result) + { + Btn.btn.BackColor = System.Drawing.Color.Green; + } + else + { + Btn.btn.BackColor = System.Drawing.Color.SlateGray; + } + } + } + catch (Exception err) + { + ControlData Btn = (ControlData)obj; + //ApplicationLog.WriteLog(err, err.Message+"采集数据值:"+ ";按钮名称:"+test+ Btn.btn .Name +"工位号"+ WorkStationNum_Now); + } + } + + + + + + + /// + /// 通过点击界面按钮写入Bool信号 + /// + /// + /// + private void WriteBoolSignalByFormBtn(Object Sender) + { + try + { + string BtnName = ((System.Windows.Forms.Control)Sender).Name; + string[] Array_BtnNameSplit = BtnName.Split('_'); + int tagType = Convert.ToInt32(Array_BtnNameSplit[2]); + string OpName = WorkStationNum_Now; + + QualityDataQueryStruct QualityQueryStruct = new QualityDataQueryStruct(OpName, tagType); + Thread t = new Thread(new ParameterizedThreadStart(WriteBoolSignal_Thread)); + t.Start(QualityQueryStruct); + + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, err.Message); + + } + } + + void WriteBoolSignal_Thread(object obj) + { + try + { + QualityDataQueryStruct QDQ = (QualityDataQueryStruct)obj; + if (IsDemoMesServer==1) + { + string tagValueStr = ""; + MIS_BASE.Read_TagTypeID(QDQ.tagType, QDQ.OpName, out tagValueStr); + + if (tagValueStr=="1") + { + tagValueStr = "True"; + } + else if (tagValueStr == "0") + { + tagValueStr = "False"; + } + + bool ReadResult = Convert.ToBoolean(tagValueStr); + if (ReadResult) + { + MIS_BASE.Write_TagTypeID(QDQ.tagType, QDQ.OpName, false); + } + else + { + MIS_BASE.Write_TagTypeID(QDQ.tagType, QDQ.OpName, true); + } + } + else + { + bool ReadResult = Convert.ToBoolean(DtWebApi.ReadWritePLC.ReadPLC(QDQ.tagType.ToString(), QDQ.OpName)); + if (ReadResult) + { + DtWebApi.ReadWritePLC.WritePLC(QDQ.tagType.ToString(), QDQ.OpName, false); + } + else + { + DtWebApi.ReadWritePLC.WritePLC(QDQ.tagType.ToString(), QDQ.OpName, true); + } + } + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, err.Message); + + } + + } + + + + /// + /// 写入机型 + /// + /// + private void WriteNormalDataBygroupBox_SignialSimulatorWriteBtn(object Sender) + { + try + { + string BtnName = ((System.Windows.Forms.Control)Sender).Name; + string OpName = WorkStationNum_Now; + if (BtnName == "Btn_Write_PLC") + { + foreach (Control Tbx in this.groupBox_PLC.Controls) + { + if (Tbx.Name.Length < 12) continue; + if (Tbx.Name.Substring(0, 8) != "Tbx_PLC_") continue; + + string[] TbxName_Split = Tbx.Name.Split('_'); + int TagType = Convert.ToInt32(TbxName_Split[2]); + + HashtableList htList = DtWebApi.OpcDemo.GetHashtableList(); + int tagDataType = Convert.ToInt32(htList.hashtable_TagTypeDataType[TagType.ToString()]); + + string tagValue = Tbx.Text.Trim(); + short tagValue_int; + string tagValue_str; + byte tagValue_byte; + bool tagValue_bool; + + switch (tagDataType) + { + case 2: + if (!Regex.IsMatch(tagValue, @"^[-]?\d*$")) + { + MessageBox.Show("文本框\"" + Tbx.Name + "\"输入不是整数!"); + return; + } + if (tagValue == "") return; + tagValue_int = Convert.ToInt16(tagValue); + WriteAnyData_Thread(TagType, OpName, tagValue_int); + break; + case 8: + tagValue_str = tagValue.ToString(); + WriteAnyData_Thread(TagType, OpName, tagValue_str); + break; + case 17: + if (!Regex.IsMatch(tagValue, @"^[-]?\d*$")) + { + MessageBox.Show("文本框\"" + Tbx.Name + "\"输入不是整数!"); + return; + } + if (Convert.ToInt32(tagValue) > 255) + { + MessageBox.Show("文本框\"" + Tbx.Name + "\"输入数据不在范围内"); + return; + } + if (tagValue == "") return; + tagValue_byte = Convert.ToByte(tagValue); + WriteAnyData_Thread(TagType, OpName, tagValue_byte); + break; + case 11: + tagValue_bool = Convert.ToBoolean(Convert.ToInt32(tagValue)); + WriteAnyData_Thread(TagType, OpName, tagValue_bool); + break; + default: + tagValue_str = tagValue.ToString(); + WriteAnyData_Thread(TagType, OpName, tagValue_str); + break; + } + } + } + else if (BtnName == "Btn_Write_MES") + { + foreach (Control Tbx in this.groupBox_MES.Controls) + { + if (Tbx.Name.Length < 12) continue; + if (Tbx.Name.Substring(0, 8) != "Tbx_MES_") continue; + + string[] TbxName_Split = Tbx.Name.Split('_'); + int TagType = Convert.ToInt32(TbxName_Split[2]); + HashtableList htList = DtWebApi.OpcDemo.GetHashtableList(); + int tagDataType = Convert.ToInt32(htList.hashtable_TagTypeDataType[TagType.ToString()]); + //int tagDataType = Convert.ToInt32(MesDataFunction.OpcOperation.hashtable_TagTypeDataType[TagType.ToString()]); + + string tagValue = Tbx.Text.Trim(); + short tagValue_int; + string tagValue_str; + byte tagValue_byte; + bool tagValue_bool; + + switch (tagDataType) + { + case 2: + if (!Regex.IsMatch(tagValue, @"^[-]?\d*$")) + { + MessageBox.Show("文本框\"" + Tbx.Name + "\"输入不是整数!"); + return; + } + tagValue_int = Convert.ToInt16(tagValue); + WriteAnyData_Thread(TagType, OpName, tagValue_int); + break; + case 8: + tagValue_str = tagValue.ToString(); + WriteAnyData_Thread(TagType, OpName, tagValue_str); + break; + case 17: + if (!Regex.IsMatch(tagValue, @"^[-]?\d*$")) + { + MessageBox.Show("文本框\"" + Tbx.Name + "\"输入不是整数!"); + return; + } + if (Convert.ToInt32(tagValue) > 255) + { + MessageBox.Show("文本框\"" + Tbx.Name + "\"输入数据不在范围内"); + return; + } + tagValue_byte = Convert.ToByte(tagValue); + WriteAnyData_Thread(TagType, OpName, tagValue_byte); + break; + case 11: + tagValue_bool = Convert.ToBoolean(Convert.ToInt32(tagValue)); + WriteAnyData_Thread(TagType, OpName, tagValue_bool); + break; + default: + tagValue_str = tagValue.ToString(); + WriteAnyData_Thread(TagType, OpName, tagValue_str); + break; + } + } + } + + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, err.Message); + } + } + + + void WriteAnyData_Thread(int tagType, string opName, object tagValue) + { + try + { + QualityDataQueryStruct QualityStruct = new QualityDataQueryStruct(opName, tagType, tagValue); + + Thread t = new Thread(new ParameterizedThreadStart(WriteNormalDataBygroupBox_SignialSimulatorWriteBtn_Thread)); + t.Start(QualityStruct); + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, err.Message); + } + } + + void WriteNormalDataBygroupBox_SignialSimulatorWriteBtn_Thread(object obj) + { + try + { + QualityDataQueryStruct QualityStruct = (QualityDataQueryStruct)obj; + + MIS_BASE.WritePLC(QualityStruct.tagType, QualityStruct. OpName, QualityStruct.tagValue); + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, err.Message); + } + } + + + + /// + /// 根据工位号查询质量数据,返回质量数据列表 + /// + /// + /// + QualityDataType[] ReadPLC_ValueListForQualityDataTypeArray(string opName) + { + try + { + int i1 = 0; + Hashtable valueList; + valueList = Function.ReadPLC_Sync_DataList_MesRead(opName); + if (valueList != null) + { + QualityDataType[] QualityValue = new QualityDataType[valueList.Count]; + foreach (DictionaryEntry de in valueList) + { + try + { + QualityValue[i1] = (QualityDataType)de.Value; + i1++; + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, err.Message); + } + } + //ThisWorkStationData = QualityValue; + return QualityValue; + } + return null; + } + catch (Exception err) + { + + //ApplicationLog.WriteLog(err, err.Message); + return null; + } + + + } + + + //public QualityDataType[] ThisWorkStationData + //{ get; set; } + + //object QueryThisWorkStationDataByTagTypeFromThisWorkStationDataProperty(int TagType) + //{ + //try + //{ + // foreach (QualityDataType Data in ThisWorkStationData) + // { + // if (Data.tagValueType == TagType) + // { + // return Data.tagValue; + + // } + + // } + // return null; + //} + //catch (Exception err) + //{ + // ApplicationLog.WriteLog(err, err.Message); + // return null; + //} + + //} + + void RefreshBtnColor(object obj) + { + try + { + ControlChangeByTagType ControlValue = (ControlChangeByTagType)obj; + + if (!Cbx_StatusDisplay.Checked) return; + string OpName = WorkStationNum_Now; + + foreach (Control GroupBox in this.groupBox_SignialSimulator.Controls) + { + foreach (Control Btn in GroupBox.Controls) + { + if (Btn.Name.Length < 8) continue; + if (Btn.Name.Substring(0, 8) == "Btn_PLC_" || Btn.Name.Substring(0, 8) == "Btn_MES_") + { + string BtnName = Btn.Name; + string[] BtnName_SplitArray = BtnName.Split('_'); + if (Btn.InvokeRequired) + { + Action ActionDelegate = (x) => { Btn.BackColor = x; }; + if (Convert.ToInt32(BtnName_SplitArray[2]) == ControlValue.TagType) + { + if (ControlValue.Value == "1") + { + Btn.BeginInvoke(ActionDelegate, System.Drawing.Color.Green); + + } + else + { + Btn.BeginInvoke(ActionDelegate, System.Drawing.Color.LightGray); + } + } + + + } + else + { + if (Convert.ToInt32(BtnName_SplitArray[2]) == ControlValue.TagType) + { + if (ControlValue.Value == "1") + { + Btn.BackColor = System.Drawing.Color.Green; + } + else + { + + Btn.BackColor = System.Drawing.Color.LightGray; + } + } + } + } + + } + } + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, err.Message); + + } + + } + void RefreshBtnColor_Thread(int TagType, string Value) + { + ControlChangeByTagType ControlValue = new ControlChangeByTagType(TagType, Value); + Thread t = new Thread(new ParameterizedThreadStart(RefreshBtnColor)); + t.Start(ControlValue); + } + + + /// + /// 按钮颜色还原 + /// + void RefreshBtnColorWriteNull() + { + try + { + string OpName = WorkStationNum_Now; + + foreach (Control GroupBox in this.groupBox_SignialSimulator.Controls) + { + foreach (Control Btn in GroupBox.Controls) + { + if (Btn.Name.Length < 8) continue; + if (Btn.Name.Substring(0, 8) == "Btn_PLC_" || Btn.Name.Substring(0, 8) == "Btn_MES_") + { + if (Btn.InvokeRequired) + { + Action ActionDelegate = (x) => { Btn.BackColor = x; }; + Btn.BeginInvoke(ActionDelegate, System.Drawing.Color.LightGray); + } + else + { + Btn.BackColor = System.Drawing.Color.LightGray; + } + + } + } + } + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, err.Message); + + } + + } + + } +} diff --git a/Test/MisDataWebFun.Designer.cs b/Test/MisDataWebFun.Designer.cs new file mode 100644 index 0000000..d1d568f --- /dev/null +++ b/Test/MisDataWebFun.Designer.cs @@ -0,0 +1,1741 @@ +namespace MisDataSaveDate +{ + partial class MisData + { + /// + /// 必需的设计器变量。 + /// + 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.components = new System.ComponentModel.Container(); + System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MisData)); + this.comboBox_OpName = new System.Windows.Forms.ComboBox(); + this.label_OpNameList = new System.Windows.Forms.Label(); + this.textBox_tagValue_Read = new System.Windows.Forms.TextBox(); + this.textBox_tagValue = new System.Windows.Forms.TextBox(); + this.textBox_Cmd = new System.Windows.Forms.TextBox(); + this.button_Read = new System.Windows.Forms.Button(); + this.button_Write = new System.Windows.Forms.Button(); + this.listBox1 = new System.Windows.Forms.ListBox(); + this.checkBox_WorkStart = new System.Windows.Forms.CheckBox(); + this.numericUpDown1 = new System.Windows.Forms.NumericUpDown(); + this.listView_ShowQualityData = new System.Windows.Forms.ListView(); + this.columnHeader4 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); + this.columnHeader2 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); + this.columnHeader3 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); + this.columnHeader1 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); + this.button_ReadData = new System.Windows.Forms.Button(); + this.groupBox_SignialSimulator = new System.Windows.Forms.GroupBox(); + this.groupBox_WorkStationStatus = new System.Windows.Forms.GroupBox(); + this.Cbx_StatusDisplay = new System.Windows.Forms.CheckBox(); + this.Tbx_Status_11_EngineType = new System.Windows.Forms.TextBox(); + this.Tbx_Status_9_EngineTypeID = new System.Windows.Forms.TextBox(); + this.label2 = new System.Windows.Forms.Label(); + this.Tbx_Status_10_EngineID = new System.Windows.Forms.TextBox(); + this.label20 = new System.Windows.Forms.Label(); + this.Tbx_Status_80_Pallet = new System.Windows.Forms.TextBox(); + this.label21 = new System.Windows.Forms.Label(); + this.label22 = new System.Windows.Forms.Label(); + this.groupBox_PLC = new System.Windows.Forms.GroupBox(); + this.checkBox_PLCData_Display = new System.Windows.Forms.CheckBox(); + this.Btn_Read_PLC = new System.Windows.Forms.Button(); + this.Tbx_PLC_23_RepairMark = new System.Windows.Forms.TextBox(); + this.Tbx_PLC_22_PalletStatus = new System.Windows.Forms.TextBox(); + this.Tbx_PLC_21_ResultMark = new System.Windows.Forms.TextBox(); + this.Tbx_PLC_80_PalletNum = new System.Windows.Forms.TextBox(); + this.Tbx_PLC_10_EngineID = new System.Windows.Forms.TextBox(); + this.Tbx_PLC_18_Actual = new System.Windows.Forms.TextBox(); + this.Tbx_PLC_9_EngineTypeID = new System.Windows.Forms.TextBox(); + this.Tbx_PLC_17_TargetTime = new System.Windows.Forms.TextBox(); + this.Tbx_PLC_11_Enginetype = new System.Windows.Forms.TextBox(); + this.label3 = new System.Windows.Forms.Label(); + this.label4 = 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.label18 = new System.Windows.Forms.Label(); + this.label17 = new System.Windows.Forms.Label(); + this.label9 = new System.Windows.Forms.Label(); + this.groupBox3 = new System.Windows.Forms.GroupBox(); + this.Btn_PLC_1003_ShortFall = new System.Windows.Forms.Button(); + this.Btn_PLC_19_MesRead = new System.Windows.Forms.Button(); + this.Btn_PLC_1002_MachaineBreak = new System.Windows.Forms.Button(); + this.Btn_PLC_59_FixOK = new System.Windows.Forms.Button(); + this.Btn_PLC_1001_CycleStart = new System.Windows.Forms.Button(); + this.Btn_PLC_1000_MachinePowerOn = new System.Windows.Forms.Button(); + this.Btn_PLC_44_EngineTypeGetOver = new System.Windows.Forms.Button(); + this.Btn_PLC_13_PalletIn = new System.Windows.Forms.Button(); + this.Btn_PLC_50_ApplyOffline = new System.Windows.Forms.Button(); + this.Btn_PLC_43_PartLoad = new System.Windows.Forms.Button(); + this.Btn_Write_PLC = new System.Windows.Forms.Button(); + this.Btn_PLC_16_AllowReadCycleTime = new System.Windows.Forms.Button(); + this.Btn_PLC_1004_Jam = new System.Windows.Forms.Button(); + this.Btn_PLC_14_HeartBeat = new System.Windows.Forms.Button(); + this.Btn_PLC_2_WorkStart = new System.Windows.Forms.Button(); + this.groupBox_MES = new System.Windows.Forms.GroupBox(); + this.checkBox_MESData_Display = new System.Windows.Forms.CheckBox(); + this.Btn_Read_MES = new System.Windows.Forms.Button(); + this.Tbx_MES_88_SocketNum = new System.Windows.Forms.TextBox(); + this.Tbx_MES_77_FixOrder = new System.Windows.Forms.TextBox(); + this.Tbx_MES_74_EngineID = new System.Windows.Forms.TextBox(); + this.Tbx_MES_79_OnlineStatus = new System.Windows.Forms.TextBox(); + this.Tbx_MES_4_WorkStationRepairStr = new System.Windows.Forms.TextBox(); + this.Tbx_MES_93_RepairMark = new System.Windows.Forms.TextBox(); + this.label19 = new System.Windows.Forms.Label(); + this.Tbx_MES_73_EngineTypeID = new System.Windows.Forms.TextBox(); + this.Tbx_MES_75_Enginetype = new System.Windows.Forms.TextBox(); + this.label10 = new System.Windows.Forms.Label(); + this.label11 = new System.Windows.Forms.Label(); + this.label12 = new System.Windows.Forms.Label(); + this.label13 = new System.Windows.Forms.Label(); + this.label14 = new System.Windows.Forms.Label(); + this.label15 = new System.Windows.Forms.Label(); + this.label16 = new System.Windows.Forms.Label(); + this.groupBox5 = new System.Windows.Forms.GroupBox(); + this.Btn_MES_69_MachResult = new System.Windows.Forms.Button(); + this.Btn_MES_8_FalseGo = new System.Windows.Forms.Button(); + this.Btn_MES_67_FixOver = new System.Windows.Forms.Button(); + this.Btn_MES_7_WorkComplete = new System.Windows.Forms.Button(); + this.Btn_MES_53_OffLineOK = new System.Windows.Forms.Button(); + this.Btn_MES_66_AllowWork = new System.Windows.Forms.Button(); + this.Btn_MES_5_EngineTypeGetOver = new System.Windows.Forms.Button(); + this.Btn_MES_72_MobyClear = new System.Windows.Forms.Button(); + this.Btn_MES_54_ReadCycleTimeOK = new System.Windows.Forms.Button(); + this.Btn_MES_68_MachComplete = new System.Windows.Forms.Button(); + this.Btn_MES_52_ResetEquipment = new System.Windows.Forms.Button(); + this.Btn_MES_6_PalletGo = new System.Windows.Forms.Button(); + this.Btn_Write_MES = new System.Windows.Forms.Button(); + this.Btn_MES_20_MesReadOver = new System.Windows.Forms.Button(); + this.Btn_MES_71_IsAuto = new System.Windows.Forms.Button(); + this.Btn_MES_51_ConfirmOkGo = new System.Windows.Forms.Button(); + this.Btn_MES_15_HeartBeat = new System.Windows.Forms.Button(); + this.groupBox_WorkStationQuality = new System.Windows.Forms.GroupBox(); + this.cb_QdData = new System.Windows.Forms.CheckBox(); + this.cb_MonitorData = new System.Windows.Forms.CheckBox(); + this.contextMenuStrip_MIS = new System.Windows.Forms.ContextMenuStrip(this.components); + this.toolStripMenuItem_Show = new System.Windows.Forms.ToolStripMenuItem(); + this.toolStripMenuItem_Hide = new System.Windows.Forms.ToolStripMenuItem(); + this.toolStripMenuItem_Exit = new System.Windows.Forms.ToolStripMenuItem(); + this.menuStrip_Main = new System.Windows.Forms.MenuStrip(); + this.ToolStripMenuItem_Start = new System.Windows.Forms.ToolStripMenuItem(); + this.ToolStripMenuItem_PrintScreen = new System.Windows.Forms.ToolStripMenuItem(); + this.ToolStripMenuItem_SaveLog = new System.Windows.Forms.ToolStripMenuItem(); + this.ToolStripMenuItem_LockForm = new System.Windows.Forms.ToolStripMenuItem(); + this.ToolStripMenuItem_Quit = new System.Windows.Forms.ToolStripMenuItem(); + this.ToolStripMenuItem_Visual = new System.Windows.Forms.ToolStripMenuItem(); + this.ToolStripMenuItem_VWSStatus = new System.Windows.Forms.ToolStripMenuItem(); + this.EToolStripMenuItem_EquipAlarm = new System.Windows.Forms.ToolStripMenuItem(); + this.ToolStripMenuItem_Assembly = new System.Windows.Forms.ToolStripMenuItem(); + this.TSM_DebugPage = new System.Windows.Forms.ToolStripMenuItem(); + this.ToolStripMenuItem_Help = new System.Windows.Forms.ToolStripMenuItem(); + this.ToolStripMenuItem_HHelp = new System.Windows.Forms.ToolStripMenuItem(); + this.toolStripMenuItem_HVersion = new System.Windows.Forms.ToolStripMenuItem(); + this.MToolStripMenuItem_AboutMacroinf = new System.Windows.Forms.ToolStripMenuItem(); + this.groupBox_Depart = new System.Windows.Forms.GroupBox(); + this.statusStrip1 = new System.Windows.Forms.StatusStrip(); + this.toolStripStatusLabel_RunningStatu = new System.Windows.Forms.ToolStripStatusLabel(); + this.toolStripStatusLabel_RunningStatus = new System.Windows.Forms.ToolStripStatusLabel(); + this.toolStripStatusLabel2 = new System.Windows.Forms.ToolStripStatusLabel(); + this.toolStripStatusLabel_StartTime = new System.Windows.Forms.ToolStripStatusLabel(); + this.toolStripStatusLabel3 = new System.Windows.Forms.ToolStripStatusLabel(); + this.toolStripStatusLabel_RunTime = new System.Windows.Forms.ToolStripStatusLabel(); + this.toolStripStatusLabel1 = new System.Windows.Forms.ToolStripStatusLabel(); + this.toolStripStatusLabel_WorkStationNum = new System.Windows.Forms.ToolStripStatusLabel(); + this.toolStripStatusLabel6 = new System.Windows.Forms.ToolStripStatusLabel(); + this.toolStripStatusLabel_OnlineNum = new System.Windows.Forms.ToolStripStatusLabel(); + this.toolStripStatusLabel8 = new System.Windows.Forms.ToolStripStatusLabel(); + this.toolStripStatusLabel_DownLine = new System.Windows.Forms.ToolStripStatusLabel(); + this.toolStripStatusLabel4 = new System.Windows.Forms.ToolStripStatusLabel(); + this.toolStripStatusLabel_Version = new System.Windows.Forms.ToolStripStatusLabel(); + this.groupBox_Alarm = new System.Windows.Forms.GroupBox(); + ((System.ComponentModel.ISupportInitialize)(this.numericUpDown1)).BeginInit(); + this.groupBox_SignialSimulator.SuspendLayout(); + this.groupBox_WorkStationStatus.SuspendLayout(); + this.groupBox_PLC.SuspendLayout(); + this.groupBox_MES.SuspendLayout(); + this.groupBox_WorkStationQuality.SuspendLayout(); + this.contextMenuStrip_MIS.SuspendLayout(); + this.menuStrip_Main.SuspendLayout(); + this.statusStrip1.SuspendLayout(); + this.SuspendLayout(); + // + // comboBox_OpName + // + this.comboBox_OpName.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; + this.comboBox_OpName.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.comboBox_OpName.FormattingEnabled = true; + this.comboBox_OpName.Location = new System.Drawing.Point(72, 15); + this.comboBox_OpName.Name = "comboBox_OpName"; + this.comboBox_OpName.Size = new System.Drawing.Size(76, 20); + this.comboBox_OpName.TabIndex = 1425; + this.comboBox_OpName.SelectedIndexChanged += new System.EventHandler(this.comboBox_OpName_SelectedIndexChanged); + // + // label_OpNameList + // + this.label_OpNameList.AutoSize = true; + this.label_OpNameList.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.label_OpNameList.Location = new System.Drawing.Point(6, 19); + this.label_OpNameList.Name = "label_OpNameList"; + this.label_OpNameList.Size = new System.Drawing.Size(65, 12); + this.label_OpNameList.TabIndex = 1424; + this.label_OpNameList.Text = "工位编号:"; + this.label_OpNameList.DoubleClick += new System.EventHandler(this.label_OpNameList_DoubleClick); + // + // textBox_tagValue_Read + // + this.textBox_tagValue_Read.Location = new System.Drawing.Point(84, 91); + this.textBox_tagValue_Read.Margin = new System.Windows.Forms.Padding(2); + this.textBox_tagValue_Read.Name = "textBox_tagValue_Read"; + this.textBox_tagValue_Read.ReadOnly = true; + this.textBox_tagValue_Read.Size = new System.Drawing.Size(119, 21); + this.textBox_tagValue_Read.TabIndex = 1464; + // + // textBox_tagValue + // + this.textBox_tagValue.Location = new System.Drawing.Point(84, 124); + this.textBox_tagValue.Margin = new System.Windows.Forms.Padding(2); + this.textBox_tagValue.Name = "textBox_tagValue"; + this.textBox_tagValue.Size = new System.Drawing.Size(119, 21); + this.textBox_tagValue.TabIndex = 1458; + // + // textBox_Cmd + // + this.textBox_Cmd.Location = new System.Drawing.Point(123, 151); + this.textBox_Cmd.Margin = new System.Windows.Forms.Padding(2); + this.textBox_Cmd.Name = "textBox_Cmd"; + this.textBox_Cmd.Size = new System.Drawing.Size(80, 21); + this.textBox_Cmd.TabIndex = 1460; + // + // button_Read + // + this.button_Read.Location = new System.Drawing.Point(17, 89); + this.button_Read.Margin = new System.Windows.Forms.Padding(2); + this.button_Read.Name = "button_Read"; + this.button_Read.Size = new System.Drawing.Size(56, 25); + this.button_Read.TabIndex = 1454; + this.button_Read.Text = "读取"; + this.button_Read.UseVisualStyleBackColor = true; + this.button_Read.Click += new System.EventHandler(this.button_Read_Click); + // + // button_Write + // + this.button_Write.Location = new System.Drawing.Point(17, 122); + this.button_Write.Margin = new System.Windows.Forms.Padding(2); + this.button_Write.Name = "button_Write"; + this.button_Write.Size = new System.Drawing.Size(56, 25); + this.button_Write.TabIndex = 1455; + this.button_Write.Text = "写入"; + this.button_Write.UseVisualStyleBackColor = true; + this.button_Write.Click += new System.EventHandler(this.button_Write_Click); + // + // listBox1 + // + this.listBox1.FormattingEnabled = true; + this.listBox1.ItemHeight = 12; + this.listBox1.Location = new System.Drawing.Point(210, 86); + this.listBox1.Margin = new System.Windows.Forms.Padding(2); + this.listBox1.Name = "listBox1"; + this.listBox1.Size = new System.Drawing.Size(225, 88); + this.listBox1.TabIndex = 1453; + this.listBox1.SelectedValueChanged += new System.EventHandler(this.listBox1_SelectedValueChanged); + // + // checkBox_WorkStart + // + this.checkBox_WorkStart.AutoSize = true; + this.checkBox_WorkStart.Location = new System.Drawing.Point(18, 156); + this.checkBox_WorkStart.Margin = new System.Windows.Forms.Padding(2); + this.checkBox_WorkStart.Name = "checkBox_WorkStart"; + this.checkBox_WorkStart.Size = new System.Drawing.Size(48, 16); + this.checkBox_WorkStart.TabIndex = 1466; + this.checkBox_WorkStart.Text = "模拟"; + this.checkBox_WorkStart.UseVisualStyleBackColor = true; + this.checkBox_WorkStart.CheckedChanged += new System.EventHandler(this.checkBox_WorkStart_CheckedChanged); + // + // numericUpDown1 + // + this.numericUpDown1.Location = new System.Drawing.Point(84, 151); + this.numericUpDown1.Margin = new System.Windows.Forms.Padding(2); + this.numericUpDown1.Name = "numericUpDown1"; + this.numericUpDown1.Size = new System.Drawing.Size(35, 21); + this.numericUpDown1.TabIndex = 1467; + this.numericUpDown1.Value = new decimal(new int[] { + 5, + 0, + 0, + 0}); + this.numericUpDown1.ValueChanged += new System.EventHandler(this.numericUpDown1_ValueChanged); + // + // listView_ShowQualityData + // + this.listView_ShowQualityData.AllowColumnReorder = true; + this.listView_ShowQualityData.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { + this.columnHeader4, + this.columnHeader2, + this.columnHeader3, + this.columnHeader1}); + this.listView_ShowQualityData.FullRowSelect = true; + this.listView_ShowQualityData.GridLines = true; + this.listView_ShowQualityData.HideSelection = false; + this.listView_ShowQualityData.Location = new System.Drawing.Point(6, 61); + this.listView_ShowQualityData.Margin = new System.Windows.Forms.Padding(2); + this.listView_ShowQualityData.MultiSelect = false; + this.listView_ShowQualityData.Name = "listView_ShowQualityData"; + this.listView_ShowQualityData.ShowItemToolTips = true; + this.listView_ShowQualityData.Size = new System.Drawing.Size(484, 527); + this.listView_ShowQualityData.TabIndex = 1469; + this.listView_ShowQualityData.UseCompatibleStateImageBehavior = false; + this.listView_ShowQualityData.View = System.Windows.Forms.View.Details; + this.listView_ShowQualityData.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(this.listView_ShowQualityData_MouseDoubleClick); + // + // columnHeader4 + // + this.columnHeader4.DisplayIndex = 3; + this.columnHeader4.Text = "工位号"; + this.columnHeader4.Width = 70; + // + // columnHeader2 + // + this.columnHeader2.Text = "测量项目"; + this.columnHeader2.Width = 150; + // + // columnHeader3 + // + this.columnHeader3.Text = "值"; + this.columnHeader3.Width = 180; + // + // columnHeader1 + // + this.columnHeader1.DisplayIndex = 0; + this.columnHeader1.Text = "TagID"; + this.columnHeader1.Width = 70; + // + // button_ReadData + // + this.button_ReadData.Location = new System.Drawing.Point(114, 20); + this.button_ReadData.Name = "button_ReadData"; + this.button_ReadData.Size = new System.Drawing.Size(62, 23); + this.button_ReadData.TabIndex = 1470; + this.button_ReadData.Text = "读取数据"; + this.button_ReadData.UseVisualStyleBackColor = true; + this.button_ReadData.Click += new System.EventHandler(this.button_ReadData_Click); + // + // groupBox_SignialSimulator + // + this.groupBox_SignialSimulator.Controls.Add(this.groupBox_WorkStationStatus); + this.groupBox_SignialSimulator.Controls.Add(this.groupBox_PLC); + this.groupBox_SignialSimulator.Controls.Add(this.textBox_Cmd); + this.groupBox_SignialSimulator.Controls.Add(this.button_Write); + this.groupBox_SignialSimulator.Controls.Add(this.groupBox_MES); + this.groupBox_SignialSimulator.Controls.Add(this.button_Read); + this.groupBox_SignialSimulator.Controls.Add(this.numericUpDown1); + this.groupBox_SignialSimulator.Controls.Add(this.listBox1); + this.groupBox_SignialSimulator.Controls.Add(this.checkBox_WorkStart); + this.groupBox_SignialSimulator.Controls.Add(this.textBox_tagValue_Read); + this.groupBox_SignialSimulator.Controls.Add(this.textBox_tagValue); + this.groupBox_SignialSimulator.Location = new System.Drawing.Point(549, 29); + this.groupBox_SignialSimulator.Name = "groupBox_SignialSimulator"; + this.groupBox_SignialSimulator.Size = new System.Drawing.Size(447, 642); + this.groupBox_SignialSimulator.TabIndex = 1471; + this.groupBox_SignialSimulator.TabStop = false; + this.groupBox_SignialSimulator.Text = "信号模拟"; + // + // groupBox_WorkStationStatus + // + this.groupBox_WorkStationStatus.Controls.Add(this.Cbx_StatusDisplay); + this.groupBox_WorkStationStatus.Controls.Add(this.label_OpNameList); + this.groupBox_WorkStationStatus.Controls.Add(this.Tbx_Status_11_EngineType); + this.groupBox_WorkStationStatus.Controls.Add(this.Tbx_Status_9_EngineTypeID); + this.groupBox_WorkStationStatus.Controls.Add(this.comboBox_OpName); + this.groupBox_WorkStationStatus.Controls.Add(this.label2); + this.groupBox_WorkStationStatus.Controls.Add(this.Tbx_Status_10_EngineID); + this.groupBox_WorkStationStatus.Controls.Add(this.label20); + this.groupBox_WorkStationStatus.Controls.Add(this.Tbx_Status_80_Pallet); + this.groupBox_WorkStationStatus.Controls.Add(this.label21); + this.groupBox_WorkStationStatus.Controls.Add(this.label22); + this.groupBox_WorkStationStatus.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.groupBox_WorkStationStatus.Location = new System.Drawing.Point(12, 14); + this.groupBox_WorkStationStatus.Name = "groupBox_WorkStationStatus"; + this.groupBox_WorkStationStatus.Size = new System.Drawing.Size(423, 69); + this.groupBox_WorkStationStatus.TabIndex = 1468; + this.groupBox_WorkStationStatus.TabStop = false; + this.groupBox_WorkStationStatus.Text = "WorkStationStatus"; + // + // Cbx_StatusDisplay + // + this.Cbx_StatusDisplay.AutoSize = true; + this.Cbx_StatusDisplay.Enabled = false; + this.Cbx_StatusDisplay.Location = new System.Drawing.Point(355, 17); + this.Cbx_StatusDisplay.Name = "Cbx_StatusDisplay"; + this.Cbx_StatusDisplay.Size = new System.Drawing.Size(48, 16); + this.Cbx_StatusDisplay.TabIndex = 1426; + this.Cbx_StatusDisplay.Text = "同步"; + this.Cbx_StatusDisplay.UseVisualStyleBackColor = true; + // + // Tbx_Status_11_EngineType + // + this.Tbx_Status_11_EngineType.Location = new System.Drawing.Point(309, 41); + this.Tbx_Status_11_EngineType.Name = "Tbx_Status_11_EngineType"; + this.Tbx_Status_11_EngineType.ReadOnly = true; + this.Tbx_Status_11_EngineType.Size = new System.Drawing.Size(94, 21); + this.Tbx_Status_11_EngineType.TabIndex = 3; + this.Tbx_Status_11_EngineType.Text = "加载中..."; + // + // Tbx_Status_9_EngineTypeID + // + this.Tbx_Status_9_EngineTypeID.Location = new System.Drawing.Point(210, 15); + this.Tbx_Status_9_EngineTypeID.Name = "Tbx_Status_9_EngineTypeID"; + this.Tbx_Status_9_EngineTypeID.ReadOnly = true; + this.Tbx_Status_9_EngineTypeID.Size = new System.Drawing.Size(29, 21); + this.Tbx_Status_9_EngineTypeID.TabIndex = 3; + this.Tbx_Status_9_EngineTypeID.Text = "..."; + // + // label2 + // + this.label2.AutoSize = true; + this.label2.Location = new System.Drawing.Point(6, 45); + this.label2.Name = "label2"; + this.label2.Size = new System.Drawing.Size(65, 12); + this.label2.TabIndex = 2; + this.label2.Text = "产品编号:"; + // + // Tbx_Status_10_EngineID + // + this.Tbx_Status_10_EngineID.Location = new System.Drawing.Point(72, 41); + this.Tbx_Status_10_EngineID.Name = "Tbx_Status_10_EngineID"; + this.Tbx_Status_10_EngineID.ReadOnly = true; + this.Tbx_Status_10_EngineID.Size = new System.Drawing.Size(167, 21); + this.Tbx_Status_10_EngineID.TabIndex = 3; + this.Tbx_Status_10_EngineID.Text = "加载中..."; + // + // label20 + // + this.label20.AutoSize = true; + this.label20.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.label20.Location = new System.Drawing.Point(245, 45); + this.label20.Name = "label20"; + this.label20.Size = new System.Drawing.Size(65, 12); + this.label20.TabIndex = 2; + this.label20.Text = "产品型号:"; + // + // Tbx_Status_80_Pallet + // + this.Tbx_Status_80_Pallet.Location = new System.Drawing.Point(309, 15); + this.Tbx_Status_80_Pallet.Name = "Tbx_Status_80_Pallet"; + this.Tbx_Status_80_Pallet.ReadOnly = true; + this.Tbx_Status_80_Pallet.Size = new System.Drawing.Size(31, 21); + this.Tbx_Status_80_Pallet.TabIndex = 5; + this.Tbx_Status_80_Pallet.Text = "..."; + // + // label21 + // + this.label21.AutoSize = true; + this.label21.Location = new System.Drawing.Point(150, 19); + this.label21.Name = "label21"; + this.label21.Size = new System.Drawing.Size(65, 12); + this.label21.TabIndex = 2; + this.label21.Text = "机型代码:"; + // + // label22 + // + this.label22.AutoSize = true; + this.label22.Location = new System.Drawing.Point(245, 19); + this.label22.Name = "label22"; + this.label22.Size = new System.Drawing.Size(65, 12); + this.label22.TabIndex = 2; + this.label22.Text = "托盘编号:"; + // + // groupBox_PLC + // + this.groupBox_PLC.Controls.Add(this.checkBox_PLCData_Display); + this.groupBox_PLC.Controls.Add(this.Btn_Read_PLC); + this.groupBox_PLC.Controls.Add(this.Tbx_PLC_23_RepairMark); + this.groupBox_PLC.Controls.Add(this.Tbx_PLC_22_PalletStatus); + this.groupBox_PLC.Controls.Add(this.Tbx_PLC_21_ResultMark); + this.groupBox_PLC.Controls.Add(this.Tbx_PLC_80_PalletNum); + this.groupBox_PLC.Controls.Add(this.Tbx_PLC_10_EngineID); + this.groupBox_PLC.Controls.Add(this.Tbx_PLC_18_Actual); + this.groupBox_PLC.Controls.Add(this.Tbx_PLC_9_EngineTypeID); + this.groupBox_PLC.Controls.Add(this.Tbx_PLC_17_TargetTime); + this.groupBox_PLC.Controls.Add(this.Tbx_PLC_11_Enginetype); + this.groupBox_PLC.Controls.Add(this.label3); + this.groupBox_PLC.Controls.Add(this.label4); + this.groupBox_PLC.Controls.Add(this.label5); + this.groupBox_PLC.Controls.Add(this.label6); + this.groupBox_PLC.Controls.Add(this.label7); + this.groupBox_PLC.Controls.Add(this.label8); + this.groupBox_PLC.Controls.Add(this.label18); + this.groupBox_PLC.Controls.Add(this.label17); + this.groupBox_PLC.Controls.Add(this.label9); + this.groupBox_PLC.Controls.Add(this.groupBox3); + this.groupBox_PLC.Controls.Add(this.Btn_PLC_1003_ShortFall); + this.groupBox_PLC.Controls.Add(this.Btn_PLC_19_MesRead); + this.groupBox_PLC.Controls.Add(this.Btn_PLC_1002_MachaineBreak); + this.groupBox_PLC.Controls.Add(this.Btn_PLC_59_FixOK); + this.groupBox_PLC.Controls.Add(this.Btn_PLC_1001_CycleStart); + this.groupBox_PLC.Controls.Add(this.Btn_PLC_1000_MachinePowerOn); + this.groupBox_PLC.Controls.Add(this.Btn_PLC_44_EngineTypeGetOver); + this.groupBox_PLC.Controls.Add(this.Btn_PLC_13_PalletIn); + this.groupBox_PLC.Controls.Add(this.Btn_PLC_50_ApplyOffline); + this.groupBox_PLC.Controls.Add(this.Btn_PLC_43_PartLoad); + this.groupBox_PLC.Controls.Add(this.Btn_Write_PLC); + this.groupBox_PLC.Controls.Add(this.Btn_PLC_16_AllowReadCycleTime); + this.groupBox_PLC.Controls.Add(this.Btn_PLC_1004_Jam); + this.groupBox_PLC.Controls.Add(this.Btn_PLC_14_HeartBeat); + this.groupBox_PLC.Controls.Add(this.Btn_PLC_2_WorkStart); + this.groupBox_PLC.Location = new System.Drawing.Point(12, 174); + this.groupBox_PLC.Name = "groupBox_PLC"; + this.groupBox_PLC.Size = new System.Drawing.Size(423, 212); + this.groupBox_PLC.TabIndex = 0; + this.groupBox_PLC.TabStop = false; + this.groupBox_PLC.Text = "PLC"; + // + // checkBox_PLCData_Display + // + this.checkBox_PLCData_Display.AutoSize = true; + this.checkBox_PLCData_Display.Checked = true; + this.checkBox_PLCData_Display.CheckState = System.Windows.Forms.CheckState.Checked; + this.checkBox_PLCData_Display.Location = new System.Drawing.Point(192, 188); + this.checkBox_PLCData_Display.Name = "checkBox_PLCData_Display"; + this.checkBox_PLCData_Display.Size = new System.Drawing.Size(48, 16); + this.checkBox_PLCData_Display.TabIndex = 7; + this.checkBox_PLCData_Display.Text = "同步"; + this.checkBox_PLCData_Display.UseVisualStyleBackColor = true; + // + // Btn_Read_PLC + // + this.Btn_Read_PLC.Location = new System.Drawing.Point(249, 185); + this.Btn_Read_PLC.Name = "Btn_Read_PLC"; + this.Btn_Read_PLC.Size = new System.Drawing.Size(75, 23); + this.Btn_Read_PLC.TabIndex = 6; + this.Btn_Read_PLC.Text = "读取 PLC"; + this.Btn_Read_PLC.UseVisualStyleBackColor = true; + this.Btn_Read_PLC.Click += new System.EventHandler(this.Btn_Read_PLC_Click); + // + // Tbx_PLC_23_RepairMark + // + this.Tbx_PLC_23_RepairMark.Location = new System.Drawing.Point(373, 160); + this.Tbx_PLC_23_RepairMark.Name = "Tbx_PLC_23_RepairMark"; + this.Tbx_PLC_23_RepairMark.Size = new System.Drawing.Size(33, 21); + this.Tbx_PLC_23_RepairMark.TabIndex = 5; + this.Tbx_PLC_23_RepairMark.Text = "0"; + // + // Tbx_PLC_22_PalletStatus + // + this.Tbx_PLC_22_PalletStatus.Location = new System.Drawing.Point(373, 133); + this.Tbx_PLC_22_PalletStatus.Name = "Tbx_PLC_22_PalletStatus"; + this.Tbx_PLC_22_PalletStatus.Size = new System.Drawing.Size(33, 21); + this.Tbx_PLC_22_PalletStatus.TabIndex = 5; + this.Tbx_PLC_22_PalletStatus.Text = "1"; + // + // Tbx_PLC_21_ResultMark + // + this.Tbx_PLC_21_ResultMark.Location = new System.Drawing.Point(259, 161); + this.Tbx_PLC_21_ResultMark.Name = "Tbx_PLC_21_ResultMark"; + this.Tbx_PLC_21_ResultMark.Size = new System.Drawing.Size(37, 21); + this.Tbx_PLC_21_ResultMark.TabIndex = 5; + this.Tbx_PLC_21_ResultMark.Text = "1"; + // + // Tbx_PLC_80_PalletNum + // + this.Tbx_PLC_80_PalletNum.Location = new System.Drawing.Point(259, 134); + this.Tbx_PLC_80_PalletNum.Name = "Tbx_PLC_80_PalletNum"; + this.Tbx_PLC_80_PalletNum.Size = new System.Drawing.Size(37, 21); + this.Tbx_PLC_80_PalletNum.TabIndex = 5; + this.Tbx_PLC_80_PalletNum.Text = "2"; + // + // Tbx_PLC_10_EngineID + // + this.Tbx_PLC_10_EngineID.Location = new System.Drawing.Point(259, 108); + this.Tbx_PLC_10_EngineID.Name = "Tbx_PLC_10_EngineID"; + this.Tbx_PLC_10_EngineID.Size = new System.Drawing.Size(146, 21); + this.Tbx_PLC_10_EngineID.TabIndex = 3; + this.Tbx_PLC_10_EngineID.Text = "H12C3-00001001"; + // + // Tbx_PLC_18_Actual + // + this.Tbx_PLC_18_Actual.Location = new System.Drawing.Point(101, 186); + this.Tbx_PLC_18_Actual.Name = "Tbx_PLC_18_Actual"; + this.Tbx_PLC_18_Actual.Size = new System.Drawing.Size(61, 21); + this.Tbx_PLC_18_Actual.TabIndex = 3; + this.Tbx_PLC_18_Actual.Text = "50"; + // + // Tbx_PLC_9_EngineTypeID + // + this.Tbx_PLC_9_EngineTypeID.Location = new System.Drawing.Point(77, 133); + this.Tbx_PLC_9_EngineTypeID.Name = "Tbx_PLC_9_EngineTypeID"; + this.Tbx_PLC_9_EngineTypeID.Size = new System.Drawing.Size(85, 21); + this.Tbx_PLC_9_EngineTypeID.TabIndex = 3; + this.Tbx_PLC_9_EngineTypeID.Text = "1"; + // + // Tbx_PLC_17_TargetTime + // + this.Tbx_PLC_17_TargetTime.Location = new System.Drawing.Point(101, 160); + this.Tbx_PLC_17_TargetTime.Name = "Tbx_PLC_17_TargetTime"; + this.Tbx_PLC_17_TargetTime.Size = new System.Drawing.Size(61, 21); + this.Tbx_PLC_17_TargetTime.TabIndex = 3; + this.Tbx_PLC_17_TargetTime.Text = "50"; + // + // Tbx_PLC_11_Enginetype + // + this.Tbx_PLC_11_Enginetype.Location = new System.Drawing.Point(77, 108); + this.Tbx_PLC_11_Enginetype.Name = "Tbx_PLC_11_Enginetype"; + this.Tbx_PLC_11_Enginetype.Size = new System.Drawing.Size(85, 21); + this.Tbx_PLC_11_Enginetype.TabIndex = 3; + this.Tbx_PLC_11_Enginetype.Text = "H12C3-00001"; + // + // label3 + // + this.label3.AutoSize = true; + this.label3.Location = new System.Drawing.Point(192, 112); + this.label3.Name = "label3"; + this.label3.Size = new System.Drawing.Size(65, 12); + this.label3.TabIndex = 2; + this.label3.Text = "产品编号:"; + // + // label4 + // + this.label4.AutoSize = true; + this.label4.Location = new System.Drawing.Point(306, 138); + this.label4.Name = "label4"; + this.label4.Size = new System.Drawing.Size(65, 12); + this.label4.TabIndex = 2; + this.label4.Text = "托盘状态:"; + // + // label5 + // + this.label5.AutoSize = true; + this.label5.Location = new System.Drawing.Point(192, 138); + this.label5.Name = "label5"; + this.label5.Size = new System.Drawing.Size(65, 12); + this.label5.TabIndex = 2; + this.label5.Text = "托盘编号:"; + // + // label6 + // + this.label6.AutoSize = true; + this.label6.Location = new System.Drawing.Point(306, 164); + this.label6.Name = "label6"; + this.label6.Size = new System.Drawing.Size(65, 12); + this.label6.TabIndex = 2; + this.label6.Text = "返修标志:"; + // + // label7 + // + this.label7.AutoSize = true; + this.label7.Location = new System.Drawing.Point(192, 164); + this.label7.Name = "label7"; + this.label7.Size = new System.Drawing.Size(65, 12); + this.label7.TabIndex = 2; + this.label7.Text = "合格标志:"; + // + // label8 + // + this.label8.AutoSize = true; + this.label8.Location = new System.Drawing.Point(6, 138); + this.label8.Name = "label8"; + this.label8.Size = new System.Drawing.Size(65, 12); + this.label8.TabIndex = 2; + this.label8.Text = "机型代码:"; + // + // label18 + // + this.label18.AutoSize = true; + this.label18.Location = new System.Drawing.Point(6, 190); + this.label18.Name = "label18"; + this.label18.Size = new System.Drawing.Size(89, 12); + this.label18.TabIndex = 2; + this.label18.Text = "实际运行时间:"; + // + // label17 + // + this.label17.AutoSize = true; + this.label17.Location = new System.Drawing.Point(6, 164); + this.label17.Name = "label17"; + this.label17.Size = new System.Drawing.Size(89, 12); + this.label17.TabIndex = 2; + this.label17.Text = "目标运行时间:"; + // + // label9 + // + this.label9.AutoSize = true; + this.label9.Location = new System.Drawing.Point(6, 112); + this.label9.Name = "label9"; + this.label9.Size = new System.Drawing.Size(65, 12); + this.label9.TabIndex = 2; + this.label9.Text = "产品型号:"; + // + // groupBox3 + // + this.groupBox3.Location = new System.Drawing.Point(3, 100); + this.groupBox3.Name = "groupBox3"; + this.groupBox3.Size = new System.Drawing.Size(415, 1); + this.groupBox3.TabIndex = 1; + this.groupBox3.TabStop = false; + // + // Btn_PLC_1003_ShortFall + // + this.Btn_PLC_1003_ShortFall.Location = new System.Drawing.Point(87, 73); + this.Btn_PLC_1003_ShortFall.Name = "Btn_PLC_1003_ShortFall"; + this.Btn_PLC_1003_ShortFall.Size = new System.Drawing.Size(75, 23); + this.Btn_PLC_1003_ShortFall.TabIndex = 0; + this.Btn_PLC_1003_ShortFall.Text = "上料无件"; + this.Btn_PLC_1003_ShortFall.UseVisualStyleBackColor = true; + this.Btn_PLC_1003_ShortFall.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_PLC_19_MesRead + // + this.Btn_PLC_19_MesRead.Location = new System.Drawing.Point(330, 15); + this.Btn_PLC_19_MesRead.Name = "Btn_PLC_19_MesRead"; + this.Btn_PLC_19_MesRead.Size = new System.Drawing.Size(75, 23); + this.Btn_PLC_19_MesRead.TabIndex = 0; + this.Btn_PLC_19_MesRead.Text = "允许保存"; + this.Btn_PLC_19_MesRead.UseVisualStyleBackColor = true; + this.Btn_PLC_19_MesRead.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_PLC_1002_MachaineBreak + // + this.Btn_PLC_1002_MachaineBreak.Location = new System.Drawing.Point(330, 44); + this.Btn_PLC_1002_MachaineBreak.Name = "Btn_PLC_1002_MachaineBreak"; + this.Btn_PLC_1002_MachaineBreak.Size = new System.Drawing.Size(75, 23); + this.Btn_PLC_1002_MachaineBreak.TabIndex = 0; + this.Btn_PLC_1002_MachaineBreak.Text = "机床故障"; + this.Btn_PLC_1002_MachaineBreak.UseVisualStyleBackColor = true; + this.Btn_PLC_1002_MachaineBreak.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_PLC_59_FixOK + // + this.Btn_PLC_59_FixOK.Location = new System.Drawing.Point(249, 15); + this.Btn_PLC_59_FixOK.Name = "Btn_PLC_59_FixOK"; + this.Btn_PLC_59_FixOK.Size = new System.Drawing.Size(75, 23); + this.Btn_PLC_59_FixOK.TabIndex = 0; + this.Btn_PLC_59_FixOK.Text = "拧紧完成"; + this.Btn_PLC_59_FixOK.UseVisualStyleBackColor = true; + this.Btn_PLC_59_FixOK.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_PLC_1001_CycleStart + // + this.Btn_PLC_1001_CycleStart.Location = new System.Drawing.Point(168, 45); + this.Btn_PLC_1001_CycleStart.Name = "Btn_PLC_1001_CycleStart"; + this.Btn_PLC_1001_CycleStart.Size = new System.Drawing.Size(75, 23); + this.Btn_PLC_1001_CycleStart.TabIndex = 0; + this.Btn_PLC_1001_CycleStart.Text = "循环开始"; + this.Btn_PLC_1001_CycleStart.UseVisualStyleBackColor = true; + this.Btn_PLC_1001_CycleStart.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_PLC_1000_MachinePowerOn + // + this.Btn_PLC_1000_MachinePowerOn.Location = new System.Drawing.Point(249, 45); + this.Btn_PLC_1000_MachinePowerOn.Name = "Btn_PLC_1000_MachinePowerOn"; + this.Btn_PLC_1000_MachinePowerOn.Size = new System.Drawing.Size(75, 23); + this.Btn_PLC_1000_MachinePowerOn.TabIndex = 0; + this.Btn_PLC_1000_MachinePowerOn.Text = "机床上电"; + this.Btn_PLC_1000_MachinePowerOn.UseVisualStyleBackColor = true; + this.Btn_PLC_1000_MachinePowerOn.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_PLC_44_EngineTypeGetOver + // + this.Btn_PLC_44_EngineTypeGetOver.Location = new System.Drawing.Point(168, 15); + this.Btn_PLC_44_EngineTypeGetOver.Name = "Btn_PLC_44_EngineTypeGetOver"; + this.Btn_PLC_44_EngineTypeGetOver.Size = new System.Drawing.Size(75, 23); + this.Btn_PLC_44_EngineTypeGetOver.TabIndex = 0; + this.Btn_PLC_44_EngineTypeGetOver.Text = "传递机型"; + this.Btn_PLC_44_EngineTypeGetOver.UseVisualStyleBackColor = true; + this.Btn_PLC_44_EngineTypeGetOver.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_PLC_13_PalletIn + // + this.Btn_PLC_13_PalletIn.Location = new System.Drawing.Point(6, 73); + this.Btn_PLC_13_PalletIn.Name = "Btn_PLC_13_PalletIn"; + this.Btn_PLC_13_PalletIn.Size = new System.Drawing.Size(75, 23); + this.Btn_PLC_13_PalletIn.TabIndex = 0; + this.Btn_PLC_13_PalletIn.Text = "托盘到位"; + this.Btn_PLC_13_PalletIn.UseVisualStyleBackColor = true; + this.Btn_PLC_13_PalletIn.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_PLC_50_ApplyOffline + // + this.Btn_PLC_50_ApplyOffline.Location = new System.Drawing.Point(87, 44); + this.Btn_PLC_50_ApplyOffline.Name = "Btn_PLC_50_ApplyOffline"; + this.Btn_PLC_50_ApplyOffline.Size = new System.Drawing.Size(75, 23); + this.Btn_PLC_50_ApplyOffline.TabIndex = 0; + this.Btn_PLC_50_ApplyOffline.Text = "申请下线"; + this.Btn_PLC_50_ApplyOffline.UseVisualStyleBackColor = true; + this.Btn_PLC_50_ApplyOffline.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_PLC_43_PartLoad + // + this.Btn_PLC_43_PartLoad.Location = new System.Drawing.Point(87, 15); + this.Btn_PLC_43_PartLoad.Name = "Btn_PLC_43_PartLoad"; + this.Btn_PLC_43_PartLoad.Size = new System.Drawing.Size(75, 23); + this.Btn_PLC_43_PartLoad.TabIndex = 0; + this.Btn_PLC_43_PartLoad.Text = "申请上线"; + this.Btn_PLC_43_PartLoad.UseVisualStyleBackColor = true; + this.Btn_PLC_43_PartLoad.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_Write_PLC + // + this.Btn_Write_PLC.Location = new System.Drawing.Point(331, 185); + this.Btn_Write_PLC.Name = "Btn_Write_PLC"; + this.Btn_Write_PLC.Size = new System.Drawing.Size(75, 23); + this.Btn_Write_PLC.TabIndex = 0; + this.Btn_Write_PLC.Text = "写入 PLC"; + this.Btn_Write_PLC.UseVisualStyleBackColor = true; + this.Btn_Write_PLC.Click += new System.EventHandler(this.Btn_Write_PLC_Click); + // + // Btn_PLC_16_AllowReadCycleTime + // + this.Btn_PLC_16_AllowReadCycleTime.Location = new System.Drawing.Point(249, 74); + this.Btn_PLC_16_AllowReadCycleTime.Name = "Btn_PLC_16_AllowReadCycleTime"; + this.Btn_PLC_16_AllowReadCycleTime.Size = new System.Drawing.Size(75, 23); + this.Btn_PLC_16_AllowReadCycleTime.TabIndex = 0; + this.Btn_PLC_16_AllowReadCycleTime.Text = "允许读节拍"; + this.Btn_PLC_16_AllowReadCycleTime.UseVisualStyleBackColor = true; + this.Btn_PLC_16_AllowReadCycleTime.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_PLC_1004_Jam + // + this.Btn_PLC_1004_Jam.Location = new System.Drawing.Point(168, 73); + this.Btn_PLC_1004_Jam.Name = "Btn_PLC_1004_Jam"; + this.Btn_PLC_1004_Jam.Size = new System.Drawing.Size(75, 23); + this.Btn_PLC_1004_Jam.TabIndex = 0; + this.Btn_PLC_1004_Jam.Text = "下料堵塞"; + this.Btn_PLC_1004_Jam.UseVisualStyleBackColor = true; + this.Btn_PLC_1004_Jam.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_PLC_14_HeartBeat + // + this.Btn_PLC_14_HeartBeat.Location = new System.Drawing.Point(6, 44); + this.Btn_PLC_14_HeartBeat.Name = "Btn_PLC_14_HeartBeat"; + this.Btn_PLC_14_HeartBeat.Size = new System.Drawing.Size(75, 23); + this.Btn_PLC_14_HeartBeat.TabIndex = 0; + this.Btn_PLC_14_HeartBeat.Text = "心跳信号"; + this.Btn_PLC_14_HeartBeat.UseVisualStyleBackColor = true; + this.Btn_PLC_14_HeartBeat.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_PLC_2_WorkStart + // + this.Btn_PLC_2_WorkStart.Location = new System.Drawing.Point(6, 15); + this.Btn_PLC_2_WorkStart.Name = "Btn_PLC_2_WorkStart"; + this.Btn_PLC_2_WorkStart.Size = new System.Drawing.Size(75, 23); + this.Btn_PLC_2_WorkStart.TabIndex = 0; + this.Btn_PLC_2_WorkStart.Text = "工件到位"; + this.Btn_PLC_2_WorkStart.UseVisualStyleBackColor = true; + this.Btn_PLC_2_WorkStart.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // groupBox_MES + // + this.groupBox_MES.Controls.Add(this.checkBox_MESData_Display); + this.groupBox_MES.Controls.Add(this.Btn_Read_MES); + this.groupBox_MES.Controls.Add(this.Tbx_MES_88_SocketNum); + this.groupBox_MES.Controls.Add(this.Tbx_MES_77_FixOrder); + this.groupBox_MES.Controls.Add(this.Tbx_MES_74_EngineID); + this.groupBox_MES.Controls.Add(this.Tbx_MES_79_OnlineStatus); + this.groupBox_MES.Controls.Add(this.Tbx_MES_4_WorkStationRepairStr); + this.groupBox_MES.Controls.Add(this.Tbx_MES_93_RepairMark); + this.groupBox_MES.Controls.Add(this.label19); + this.groupBox_MES.Controls.Add(this.Tbx_MES_73_EngineTypeID); + this.groupBox_MES.Controls.Add(this.Tbx_MES_75_Enginetype); + this.groupBox_MES.Controls.Add(this.label10); + this.groupBox_MES.Controls.Add(this.label11); + this.groupBox_MES.Controls.Add(this.label12); + this.groupBox_MES.Controls.Add(this.label13); + this.groupBox_MES.Controls.Add(this.label14); + this.groupBox_MES.Controls.Add(this.label15); + this.groupBox_MES.Controls.Add(this.label16); + this.groupBox_MES.Controls.Add(this.groupBox5); + this.groupBox_MES.Controls.Add(this.Btn_MES_69_MachResult); + this.groupBox_MES.Controls.Add(this.Btn_MES_8_FalseGo); + this.groupBox_MES.Controls.Add(this.Btn_MES_67_FixOver); + this.groupBox_MES.Controls.Add(this.Btn_MES_7_WorkComplete); + this.groupBox_MES.Controls.Add(this.Btn_MES_53_OffLineOK); + this.groupBox_MES.Controls.Add(this.Btn_MES_66_AllowWork); + this.groupBox_MES.Controls.Add(this.Btn_MES_5_EngineTypeGetOver); + this.groupBox_MES.Controls.Add(this.Btn_MES_72_MobyClear); + this.groupBox_MES.Controls.Add(this.Btn_MES_54_ReadCycleTimeOK); + this.groupBox_MES.Controls.Add(this.Btn_MES_68_MachComplete); + this.groupBox_MES.Controls.Add(this.Btn_MES_52_ResetEquipment); + this.groupBox_MES.Controls.Add(this.Btn_MES_6_PalletGo); + this.groupBox_MES.Controls.Add(this.Btn_Write_MES); + this.groupBox_MES.Controls.Add(this.Btn_MES_20_MesReadOver); + this.groupBox_MES.Controls.Add(this.Btn_MES_71_IsAuto); + this.groupBox_MES.Controls.Add(this.Btn_MES_51_ConfirmOkGo); + this.groupBox_MES.Controls.Add(this.Btn_MES_15_HeartBeat); + this.groupBox_MES.Location = new System.Drawing.Point(12, 388); + this.groupBox_MES.Name = "groupBox_MES"; + this.groupBox_MES.Size = new System.Drawing.Size(423, 245); + this.groupBox_MES.TabIndex = 0; + this.groupBox_MES.TabStop = false; + this.groupBox_MES.Text = "MES"; + // + // checkBox_MESData_Display + // + this.checkBox_MESData_Display.AutoSize = true; + this.checkBox_MESData_Display.Checked = true; + this.checkBox_MESData_Display.CheckState = System.Windows.Forms.CheckState.Checked; + this.checkBox_MESData_Display.Location = new System.Drawing.Point(192, 217); + this.checkBox_MESData_Display.Name = "checkBox_MESData_Display"; + this.checkBox_MESData_Display.Size = new System.Drawing.Size(48, 16); + this.checkBox_MESData_Display.TabIndex = 7; + this.checkBox_MESData_Display.Text = "同步"; + this.checkBox_MESData_Display.UseVisualStyleBackColor = true; + // + // Btn_Read_MES + // + this.Btn_Read_MES.Location = new System.Drawing.Point(249, 214); + this.Btn_Read_MES.Name = "Btn_Read_MES"; + this.Btn_Read_MES.Size = new System.Drawing.Size(75, 23); + this.Btn_Read_MES.TabIndex = 6; + this.Btn_Read_MES.Text = "读取 MES"; + this.Btn_Read_MES.UseVisualStyleBackColor = true; + this.Btn_Read_MES.Click += new System.EventHandler(this.Btn_Read_MES_Click); + // + // Tbx_MES_88_SocketNum + // + this.Tbx_MES_88_SocketNum.Location = new System.Drawing.Point(373, 189); + this.Tbx_MES_88_SocketNum.Name = "Tbx_MES_88_SocketNum"; + this.Tbx_MES_88_SocketNum.Size = new System.Drawing.Size(33, 21); + this.Tbx_MES_88_SocketNum.TabIndex = 3; + this.Tbx_MES_88_SocketNum.Text = "1"; + // + // Tbx_MES_77_FixOrder + // + this.Tbx_MES_77_FixOrder.Location = new System.Drawing.Point(259, 189); + this.Tbx_MES_77_FixOrder.Name = "Tbx_MES_77_FixOrder"; + this.Tbx_MES_77_FixOrder.Size = new System.Drawing.Size(29, 21); + this.Tbx_MES_77_FixOrder.TabIndex = 3; + this.Tbx_MES_77_FixOrder.Text = "1"; + // + // Tbx_MES_74_EngineID + // + this.Tbx_MES_74_EngineID.Location = new System.Drawing.Point(259, 163); + this.Tbx_MES_74_EngineID.Name = "Tbx_MES_74_EngineID"; + this.Tbx_MES_74_EngineID.Size = new System.Drawing.Size(147, 21); + this.Tbx_MES_74_EngineID.TabIndex = 3; + this.Tbx_MES_74_EngineID.Text = "H12C3-00001001"; + // + // Tbx_MES_79_OnlineStatus + // + this.Tbx_MES_79_OnlineStatus.Location = new System.Drawing.Point(373, 136); + this.Tbx_MES_79_OnlineStatus.Name = "Tbx_MES_79_OnlineStatus"; + this.Tbx_MES_79_OnlineStatus.Size = new System.Drawing.Size(33, 21); + this.Tbx_MES_79_OnlineStatus.TabIndex = 3; + this.Tbx_MES_79_OnlineStatus.Text = "1"; + // + // Tbx_MES_4_WorkStationRepairStr + // + this.Tbx_MES_4_WorkStationRepairStr.Location = new System.Drawing.Point(77, 137); + this.Tbx_MES_4_WorkStationRepairStr.Name = "Tbx_MES_4_WorkStationRepairStr"; + this.Tbx_MES_4_WorkStationRepairStr.Size = new System.Drawing.Size(223, 21); + this.Tbx_MES_4_WorkStationRepairStr.TabIndex = 3; + this.Tbx_MES_4_WorkStationRepairStr.Text = "1111111111111111111"; + // + // Tbx_MES_93_RepairMark + // + this.Tbx_MES_93_RepairMark.Location = new System.Drawing.Point(77, 215); + this.Tbx_MES_93_RepairMark.Name = "Tbx_MES_93_RepairMark"; + this.Tbx_MES_93_RepairMark.Size = new System.Drawing.Size(85, 21); + this.Tbx_MES_93_RepairMark.TabIndex = 3; + this.Tbx_MES_93_RepairMark.Text = "0"; + // + // label19 + // + this.label19.AutoSize = true; + this.label19.Location = new System.Drawing.Point(6, 141); + this.label19.Name = "label19"; + this.label19.Size = new System.Drawing.Size(65, 12); + this.label19.TabIndex = 2; + this.label19.Text = "返修工位:"; + // + // Tbx_MES_73_EngineTypeID + // + this.Tbx_MES_73_EngineTypeID.Location = new System.Drawing.Point(77, 189); + this.Tbx_MES_73_EngineTypeID.Name = "Tbx_MES_73_EngineTypeID"; + this.Tbx_MES_73_EngineTypeID.Size = new System.Drawing.Size(85, 21); + this.Tbx_MES_73_EngineTypeID.TabIndex = 3; + this.Tbx_MES_73_EngineTypeID.Text = "1"; + // + // Tbx_MES_75_Enginetype + // + this.Tbx_MES_75_Enginetype.Location = new System.Drawing.Point(77, 163); + this.Tbx_MES_75_Enginetype.Name = "Tbx_MES_75_Enginetype"; + this.Tbx_MES_75_Enginetype.Size = new System.Drawing.Size(85, 21); + this.Tbx_MES_75_Enginetype.TabIndex = 3; + this.Tbx_MES_75_Enginetype.Text = "H12C3-00001"; + // + // label10 + // + this.label10.AutoSize = true; + this.label10.Location = new System.Drawing.Point(192, 167); + this.label10.Name = "label10"; + this.label10.Size = new System.Drawing.Size(65, 12); + this.label10.TabIndex = 2; + this.label10.Text = "产品编号:"; + // + // label11 + // + this.label11.AutoSize = true; + this.label11.Location = new System.Drawing.Point(306, 193); + this.label11.Name = "label11"; + this.label11.Size = new System.Drawing.Size(65, 12); + this.label11.TabIndex = 2; + this.label11.Text = "套筒编号:"; + // + // label12 + // + this.label12.AutoSize = true; + this.label12.Location = new System.Drawing.Point(192, 193); + this.label12.Name = "label12"; + this.label12.Size = new System.Drawing.Size(65, 12); + this.label12.TabIndex = 2; + this.label12.Text = "拧紧序号:"; + // + // label13 + // + this.label13.AutoSize = true; + this.label13.Location = new System.Drawing.Point(306, 140); + this.label13.Name = "label13"; + this.label13.Size = new System.Drawing.Size(65, 12); + this.label13.TabIndex = 2; + this.label13.Text = "工位状态:"; + // + // label14 + // + this.label14.AutoSize = true; + this.label14.Location = new System.Drawing.Point(6, 219); + this.label14.Name = "label14"; + this.label14.Size = new System.Drawing.Size(65, 12); + this.label14.TabIndex = 2; + this.label14.Text = "返修标志:"; + // + // label15 + // + this.label15.AutoSize = true; + this.label15.Location = new System.Drawing.Point(6, 193); + this.label15.Name = "label15"; + this.label15.Size = new System.Drawing.Size(65, 12); + this.label15.TabIndex = 2; + this.label15.Text = "机型代码:"; + // + // label16 + // + this.label16.AutoSize = true; + this.label16.Location = new System.Drawing.Point(6, 167); + this.label16.Name = "label16"; + this.label16.Size = new System.Drawing.Size(65, 12); + this.label16.TabIndex = 2; + this.label16.Text = "产品型号:"; + // + // groupBox5 + // + this.groupBox5.Location = new System.Drawing.Point(3, 128); + this.groupBox5.Name = "groupBox5"; + this.groupBox5.Size = new System.Drawing.Size(415, 1); + this.groupBox5.TabIndex = 1; + this.groupBox5.TabStop = false; + // + // Btn_MES_69_MachResult + // + this.Btn_MES_69_MachResult.Location = new System.Drawing.Point(87, 73); + this.Btn_MES_69_MachResult.Name = "Btn_MES_69_MachResult"; + this.Btn_MES_69_MachResult.Size = new System.Drawing.Size(75, 23); + this.Btn_MES_69_MachResult.TabIndex = 0; + this.Btn_MES_69_MachResult.Text = "匹配结果"; + this.Btn_MES_69_MachResult.UseVisualStyleBackColor = true; + this.Btn_MES_69_MachResult.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_MES_8_FalseGo + // + this.Btn_MES_8_FalseGo.Location = new System.Drawing.Point(168, 44); + this.Btn_MES_8_FalseGo.Name = "Btn_MES_8_FalseGo"; + this.Btn_MES_8_FalseGo.Size = new System.Drawing.Size(75, 23); + this.Btn_MES_8_FalseGo.TabIndex = 0; + this.Btn_MES_8_FalseGo.Text = "不合格放行"; + this.Btn_MES_8_FalseGo.UseVisualStyleBackColor = true; + this.Btn_MES_8_FalseGo.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_MES_67_FixOver + // + this.Btn_MES_67_FixOver.Location = new System.Drawing.Point(168, 15); + this.Btn_MES_67_FixOver.Name = "Btn_MES_67_FixOver"; + this.Btn_MES_67_FixOver.Size = new System.Drawing.Size(75, 23); + this.Btn_MES_67_FixOver.TabIndex = 0; + this.Btn_MES_67_FixOver.Text = "完成确认"; + this.Btn_MES_67_FixOver.UseVisualStyleBackColor = true; + this.Btn_MES_67_FixOver.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_MES_7_WorkComplete + // + this.Btn_MES_7_WorkComplete.Location = new System.Drawing.Point(330, 15); + this.Btn_MES_7_WorkComplete.Name = "Btn_MES_7_WorkComplete"; + this.Btn_MES_7_WorkComplete.Size = new System.Drawing.Size(75, 23); + this.Btn_MES_7_WorkComplete.TabIndex = 0; + this.Btn_MES_7_WorkComplete.Text = "工作完成"; + this.Btn_MES_7_WorkComplete.UseVisualStyleBackColor = true; + this.Btn_MES_7_WorkComplete.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_MES_53_OffLineOK + // + this.Btn_MES_53_OffLineOK.Location = new System.Drawing.Point(249, 44); + this.Btn_MES_53_OffLineOK.Name = "Btn_MES_53_OffLineOK"; + this.Btn_MES_53_OffLineOK.Size = new System.Drawing.Size(75, 23); + this.Btn_MES_53_OffLineOK.TabIndex = 0; + this.Btn_MES_53_OffLineOK.Text = "下线完成"; + this.Btn_MES_53_OffLineOK.UseVisualStyleBackColor = true; + this.Btn_MES_53_OffLineOK.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_MES_66_AllowWork + // + this.Btn_MES_66_AllowWork.Location = new System.Drawing.Point(87, 15); + this.Btn_MES_66_AllowWork.Name = "Btn_MES_66_AllowWork"; + this.Btn_MES_66_AllowWork.Size = new System.Drawing.Size(75, 23); + this.Btn_MES_66_AllowWork.TabIndex = 0; + this.Btn_MES_66_AllowWork.Text = "允许工作"; + this.Btn_MES_66_AllowWork.UseVisualStyleBackColor = true; + this.Btn_MES_66_AllowWork.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_MES_5_EngineTypeGetOver + // + this.Btn_MES_5_EngineTypeGetOver.Location = new System.Drawing.Point(6, 15); + this.Btn_MES_5_EngineTypeGetOver.Name = "Btn_MES_5_EngineTypeGetOver"; + this.Btn_MES_5_EngineTypeGetOver.Size = new System.Drawing.Size(75, 23); + this.Btn_MES_5_EngineTypeGetOver.TabIndex = 0; + this.Btn_MES_5_EngineTypeGetOver.Text = "传递机型"; + this.Btn_MES_5_EngineTypeGetOver.UseVisualStyleBackColor = true; + this.Btn_MES_5_EngineTypeGetOver.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_MES_72_MobyClear + // + this.Btn_MES_72_MobyClear.Location = new System.Drawing.Point(249, 73); + this.Btn_MES_72_MobyClear.Name = "Btn_MES_72_MobyClear"; + this.Btn_MES_72_MobyClear.Size = new System.Drawing.Size(75, 23); + this.Btn_MES_72_MobyClear.TabIndex = 0; + this.Btn_MES_72_MobyClear.Text = "清空Moby"; + this.Btn_MES_72_MobyClear.UseVisualStyleBackColor = true; + this.Btn_MES_72_MobyClear.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_MES_54_ReadCycleTimeOK + // + this.Btn_MES_54_ReadCycleTimeOK.Location = new System.Drawing.Point(330, 73); + this.Btn_MES_54_ReadCycleTimeOK.Name = "Btn_MES_54_ReadCycleTimeOK"; + this.Btn_MES_54_ReadCycleTimeOK.Size = new System.Drawing.Size(75, 23); + this.Btn_MES_54_ReadCycleTimeOK.TabIndex = 0; + this.Btn_MES_54_ReadCycleTimeOK.Text = "读节拍完成"; + this.Btn_MES_54_ReadCycleTimeOK.UseVisualStyleBackColor = true; + this.Btn_MES_54_ReadCycleTimeOK.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_MES_68_MachComplete + // + this.Btn_MES_68_MachComplete.Location = new System.Drawing.Point(6, 73); + this.Btn_MES_68_MachComplete.Name = "Btn_MES_68_MachComplete"; + this.Btn_MES_68_MachComplete.Size = new System.Drawing.Size(75, 23); + this.Btn_MES_68_MachComplete.TabIndex = 0; + this.Btn_MES_68_MachComplete.Text = "匹配完成"; + this.Btn_MES_68_MachComplete.UseVisualStyleBackColor = true; + this.Btn_MES_68_MachComplete.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_MES_52_ResetEquipment + // + this.Btn_MES_52_ResetEquipment.Location = new System.Drawing.Point(6, 102); + this.Btn_MES_52_ResetEquipment.Name = "Btn_MES_52_ResetEquipment"; + this.Btn_MES_52_ResetEquipment.Size = new System.Drawing.Size(75, 23); + this.Btn_MES_52_ResetEquipment.TabIndex = 0; + this.Btn_MES_52_ResetEquipment.Text = "复位设备"; + this.Btn_MES_52_ResetEquipment.UseVisualStyleBackColor = true; + this.Btn_MES_52_ResetEquipment.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_MES_6_PalletGo + // + this.Btn_MES_6_PalletGo.Location = new System.Drawing.Point(330, 44); + this.Btn_MES_6_PalletGo.Name = "Btn_MES_6_PalletGo"; + this.Btn_MES_6_PalletGo.Size = new System.Drawing.Size(75, 23); + this.Btn_MES_6_PalletGo.TabIndex = 0; + this.Btn_MES_6_PalletGo.Text = "空托盘放行"; + this.Btn_MES_6_PalletGo.UseVisualStyleBackColor = true; + this.Btn_MES_6_PalletGo.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_Write_MES + // + this.Btn_Write_MES.Location = new System.Drawing.Point(331, 214); + this.Btn_Write_MES.Name = "Btn_Write_MES"; + this.Btn_Write_MES.Size = new System.Drawing.Size(75, 23); + this.Btn_Write_MES.TabIndex = 0; + this.Btn_Write_MES.Text = "写入 MES"; + this.Btn_Write_MES.UseVisualStyleBackColor = true; + this.Btn_Write_MES.Click += new System.EventHandler(this.Btn_Write_MES_Click); + // + // Btn_MES_20_MesReadOver + // + this.Btn_MES_20_MesReadOver.Location = new System.Drawing.Point(249, 15); + this.Btn_MES_20_MesReadOver.Name = "Btn_MES_20_MesReadOver"; + this.Btn_MES_20_MesReadOver.Size = new System.Drawing.Size(75, 23); + this.Btn_MES_20_MesReadOver.TabIndex = 0; + this.Btn_MES_20_MesReadOver.Text = "保存完成"; + this.Btn_MES_20_MesReadOver.UseVisualStyleBackColor = true; + this.Btn_MES_20_MesReadOver.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_MES_71_IsAuto + // + this.Btn_MES_71_IsAuto.Location = new System.Drawing.Point(168, 73); + this.Btn_MES_71_IsAuto.Name = "Btn_MES_71_IsAuto"; + this.Btn_MES_71_IsAuto.Size = new System.Drawing.Size(75, 23); + this.Btn_MES_71_IsAuto.TabIndex = 0; + this.Btn_MES_71_IsAuto.Text = "自动手动"; + this.Btn_MES_71_IsAuto.UseVisualStyleBackColor = true; + this.Btn_MES_71_IsAuto.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_MES_51_ConfirmOkGo + // + this.Btn_MES_51_ConfirmOkGo.Location = new System.Drawing.Point(87, 44); + this.Btn_MES_51_ConfirmOkGo.Name = "Btn_MES_51_ConfirmOkGo"; + this.Btn_MES_51_ConfirmOkGo.Size = new System.Drawing.Size(75, 23); + this.Btn_MES_51_ConfirmOkGo.TabIndex = 0; + this.Btn_MES_51_ConfirmOkGo.Text = "合格放行"; + this.Btn_MES_51_ConfirmOkGo.UseVisualStyleBackColor = true; + this.Btn_MES_51_ConfirmOkGo.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // Btn_MES_15_HeartBeat + // + this.Btn_MES_15_HeartBeat.Location = new System.Drawing.Point(6, 44); + this.Btn_MES_15_HeartBeat.Name = "Btn_MES_15_HeartBeat"; + this.Btn_MES_15_HeartBeat.Size = new System.Drawing.Size(75, 23); + this.Btn_MES_15_HeartBeat.TabIndex = 0; + this.Btn_MES_15_HeartBeat.Text = "心跳信号"; + this.Btn_MES_15_HeartBeat.UseVisualStyleBackColor = true; + this.Btn_MES_15_HeartBeat.Click += new System.EventHandler(this.groupBox_SignialSimulatorBtn_Click); + // + // groupBox_WorkStationQuality + // + this.groupBox_WorkStationQuality.Controls.Add(this.cb_QdData); + this.groupBox_WorkStationQuality.Controls.Add(this.cb_MonitorData); + this.groupBox_WorkStationQuality.Controls.Add(this.listView_ShowQualityData); + this.groupBox_WorkStationQuality.Controls.Add(this.button_ReadData); + this.groupBox_WorkStationQuality.Location = new System.Drawing.Point(8, 29); + this.groupBox_WorkStationQuality.Name = "groupBox_WorkStationQuality"; + this.groupBox_WorkStationQuality.Size = new System.Drawing.Size(535, 593); + this.groupBox_WorkStationQuality.TabIndex = 1472; + this.groupBox_WorkStationQuality.TabStop = false; + this.groupBox_WorkStationQuality.Text = "质量数据"; + // + // cb_QdData + // + this.cb_QdData.AutoSize = true; + this.cb_QdData.Location = new System.Drawing.Point(10, 40); + this.cb_QdData.Name = "cb_QdData"; + this.cb_QdData.Size = new System.Drawing.Size(72, 16); + this.cb_QdData.TabIndex = 1472; + this.cb_QdData.Text = "质量数据"; + this.cb_QdData.UseVisualStyleBackColor = true; + // + // cb_MonitorData + // + this.cb_MonitorData.AutoSize = true; + this.cb_MonitorData.Location = new System.Drawing.Point(10, 20); + this.cb_MonitorData.Name = "cb_MonitorData"; + this.cb_MonitorData.Size = new System.Drawing.Size(72, 16); + this.cb_MonitorData.TabIndex = 1472; + this.cb_MonitorData.Text = "监控数据"; + this.cb_MonitorData.UseVisualStyleBackColor = true; + // + // contextMenuStrip_MIS + // + this.contextMenuStrip_MIS.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { + this.toolStripMenuItem_Show, + this.toolStripMenuItem_Hide, + this.toolStripMenuItem_Exit}); + this.contextMenuStrip_MIS.Name = "contextMenuStrip_MIS"; + this.contextMenuStrip_MIS.Size = new System.Drawing.Size(101, 70); + // + // toolStripMenuItem_Show + // + this.toolStripMenuItem_Show.Name = "toolStripMenuItem_Show"; + this.toolStripMenuItem_Show.Size = new System.Drawing.Size(100, 22); + this.toolStripMenuItem_Show.Text = "显示"; + this.toolStripMenuItem_Show.Click += new System.EventHandler(this.toolStripMenuItem_Show_Click); + // + // toolStripMenuItem_Hide + // + this.toolStripMenuItem_Hide.Name = "toolStripMenuItem_Hide"; + this.toolStripMenuItem_Hide.Size = new System.Drawing.Size(100, 22); + this.toolStripMenuItem_Hide.Text = "隐藏"; + this.toolStripMenuItem_Hide.Click += new System.EventHandler(this.toolStripMenuItem_Hide_Click); + // + // toolStripMenuItem_Exit + // + this.toolStripMenuItem_Exit.Name = "toolStripMenuItem_Exit"; + this.toolStripMenuItem_Exit.Size = new System.Drawing.Size(100, 22); + this.toolStripMenuItem_Exit.Text = "退出"; + this.toolStripMenuItem_Exit.Click += new System.EventHandler(this.toolStripMenuItem_Exit_Click); + // + // menuStrip_Main + // + this.menuStrip_Main.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { + this.ToolStripMenuItem_Start, + this.ToolStripMenuItem_Visual, + this.ToolStripMenuItem_Help}); + this.menuStrip_Main.Location = new System.Drawing.Point(0, 0); + this.menuStrip_Main.Name = "menuStrip_Main"; + this.menuStrip_Main.Size = new System.Drawing.Size(1008, 25); + this.menuStrip_Main.TabIndex = 1474; + this.menuStrip_Main.Text = "开始"; + // + // ToolStripMenuItem_Start + // + this.ToolStripMenuItem_Start.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { + this.ToolStripMenuItem_PrintScreen, + this.ToolStripMenuItem_SaveLog, + this.ToolStripMenuItem_LockForm, + this.ToolStripMenuItem_Quit}); + this.ToolStripMenuItem_Start.Name = "ToolStripMenuItem_Start"; + this.ToolStripMenuItem_Start.Size = new System.Drawing.Size(59, 21); + this.ToolStripMenuItem_Start.Text = "开始(&S)"; + // + // ToolStripMenuItem_PrintScreen + // + this.ToolStripMenuItem_PrintScreen.Name = "ToolStripMenuItem_PrintScreen"; + this.ToolStripMenuItem_PrintScreen.Size = new System.Drawing.Size(157, 22); + this.ToolStripMenuItem_PrintScreen.Text = "屏幕快照(&C)"; + this.ToolStripMenuItem_PrintScreen.Click += new System.EventHandler(this.ToolStripMenuItem_PrintScreen_Click); + // + // ToolStripMenuItem_SaveLog + // + this.ToolStripMenuItem_SaveLog.Name = "ToolStripMenuItem_SaveLog"; + this.ToolStripMenuItem_SaveLog.Size = new System.Drawing.Size(157, 22); + this.ToolStripMenuItem_SaveLog.Text = "保存PLC消息(&I)"; + this.ToolStripMenuItem_SaveLog.Click += new System.EventHandler(this.ToolStripMenuItem_SaveLog_Click); + // + // ToolStripMenuItem_LockForm + // + this.ToolStripMenuItem_LockForm.Name = "ToolStripMenuItem_LockForm"; + this.ToolStripMenuItem_LockForm.Size = new System.Drawing.Size(157, 22); + this.ToolStripMenuItem_LockForm.Text = "锁定(&L)"; + this.ToolStripMenuItem_LockForm.Click += new System.EventHandler(this.ToolStripMenuItem_LockForm_Click); + // + // ToolStripMenuItem_Quit + // + this.ToolStripMenuItem_Quit.Name = "ToolStripMenuItem_Quit"; + this.ToolStripMenuItem_Quit.Size = new System.Drawing.Size(157, 22); + this.ToolStripMenuItem_Quit.Text = "退出(&X)"; + this.ToolStripMenuItem_Quit.Click += new System.EventHandler(this.ToolStripMenuItem_Quit_Click); + // + // ToolStripMenuItem_Visual + // + this.ToolStripMenuItem_Visual.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { + this.ToolStripMenuItem_VWSStatus, + this.EToolStripMenuItem_EquipAlarm, + this.ToolStripMenuItem_Assembly, + this.TSM_DebugPage}); + this.ToolStripMenuItem_Visual.Name = "ToolStripMenuItem_Visual"; + this.ToolStripMenuItem_Visual.Size = new System.Drawing.Size(60, 21); + this.ToolStripMenuItem_Visual.Text = "窗口(&V)"; + // + // ToolStripMenuItem_VWSStatus + // + this.ToolStripMenuItem_VWSStatus.Name = "ToolStripMenuItem_VWSStatus"; + this.ToolStripMenuItem_VWSStatus.Size = new System.Drawing.Size(152, 22); + this.ToolStripMenuItem_VWSStatus.Text = "工位状态(&T)"; + this.ToolStripMenuItem_VWSStatus.Click += new System.EventHandler(this.ToolStripMenuItem_VWSStatus_Click); + // + // EToolStripMenuItem_EquipAlarm + // + this.EToolStripMenuItem_EquipAlarm.Checked = true; + this.EToolStripMenuItem_EquipAlarm.CheckState = System.Windows.Forms.CheckState.Checked; + this.EToolStripMenuItem_EquipAlarm.Name = "EToolStripMenuItem_EquipAlarm"; + this.EToolStripMenuItem_EquipAlarm.Size = new System.Drawing.Size(152, 22); + this.EToolStripMenuItem_EquipAlarm.Text = "设备报警(&E)"; + this.EToolStripMenuItem_EquipAlarm.Click += new System.EventHandler(this.EToolStripMenuItem_EquipAlarm_Click); + // + // ToolStripMenuItem_Assembly + // + this.ToolStripMenuItem_Assembly.Name = "ToolStripMenuItem_Assembly"; + this.ToolStripMenuItem_Assembly.Size = new System.Drawing.Size(152, 22); + this.ToolStripMenuItem_Assembly.Text = "程序集管理(&A)"; + this.ToolStripMenuItem_Assembly.Click += new System.EventHandler(this.ToolStripMenuItem_Assembly_Click); + // + // TSM_DebugPage + // + this.TSM_DebugPage.Name = "TSM_DebugPage"; + this.TSM_DebugPage.Size = new System.Drawing.Size(152, 22); + this.TSM_DebugPage.Text = "调试界面"; + this.TSM_DebugPage.Click += new System.EventHandler(this.TSM_DebugPage_Click); + // + // ToolStripMenuItem_Help + // + this.ToolStripMenuItem_Help.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { + this.ToolStripMenuItem_HHelp, + this.toolStripMenuItem_HVersion, + this.MToolStripMenuItem_AboutMacroinf}); + this.ToolStripMenuItem_Help.Name = "ToolStripMenuItem_Help"; + this.ToolStripMenuItem_Help.Size = new System.Drawing.Size(61, 21); + this.ToolStripMenuItem_Help.Text = "帮助(&H)"; + // + // ToolStripMenuItem_HHelp + // + this.ToolStripMenuItem_HHelp.Name = "ToolStripMenuItem_HHelp"; + this.ToolStripMenuItem_HHelp.Size = new System.Drawing.Size(144, 22); + this.ToolStripMenuItem_HHelp.Text = "MIS手册(&G)"; + this.ToolStripMenuItem_HHelp.Click += new System.EventHandler(this.ToolStripMenuItem_HHelp_Click); + // + // toolStripMenuItem_HVersion + // + this.toolStripMenuItem_HVersion.Name = "toolStripMenuItem_HVersion"; + this.toolStripMenuItem_HVersion.Size = new System.Drawing.Size(144, 22); + this.toolStripMenuItem_HVersion.Text = "版本信息(&O)"; + this.toolStripMenuItem_HVersion.Click += new System.EventHandler(this.toolStripMenuItem_HVersion_Click); + // + // MToolStripMenuItem_AboutMacroinf + // + this.MToolStripMenuItem_AboutMacroinf.Name = "MToolStripMenuItem_AboutMacroinf"; + this.MToolStripMenuItem_AboutMacroinf.Size = new System.Drawing.Size(144, 22); + this.MToolStripMenuItem_AboutMacroinf.Text = "关于迈思(&M)"; + this.MToolStripMenuItem_AboutMacroinf.Click += new System.EventHandler(this.MToolStripMenuItem_AboutMacroinf_Click); + // + // groupBox_Depart + // + this.groupBox_Depart.Location = new System.Drawing.Point(0, 25); + this.groupBox_Depart.Name = "groupBox_Depart"; + this.groupBox_Depart.Size = new System.Drawing.Size(1014, 1); + this.groupBox_Depart.TabIndex = 1475; + this.groupBox_Depart.TabStop = false; + this.groupBox_Depart.Text = "groupBox1"; + // + // statusStrip1 + // + this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { + this.toolStripStatusLabel_RunningStatu, + this.toolStripStatusLabel_RunningStatus, + this.toolStripStatusLabel2, + this.toolStripStatusLabel_StartTime, + this.toolStripStatusLabel3, + this.toolStripStatusLabel_RunTime, + this.toolStripStatusLabel1, + this.toolStripStatusLabel_WorkStationNum, + this.toolStripStatusLabel6, + this.toolStripStatusLabel_OnlineNum, + this.toolStripStatusLabel8, + this.toolStripStatusLabel_DownLine, + this.toolStripStatusLabel4, + this.toolStripStatusLabel_Version}); + this.statusStrip1.Location = new System.Drawing.Point(0, 673); + this.statusStrip1.Name = "statusStrip1"; + this.statusStrip1.Size = new System.Drawing.Size(1008, 26); + this.statusStrip1.TabIndex = 1478; + this.statusStrip1.Text = "statusStrip1"; + // + // toolStripStatusLabel_RunningStatu + // + this.toolStripStatusLabel_RunningStatu.Name = "toolStripStatusLabel_RunningStatu"; + this.toolStripStatusLabel_RunningStatu.Size = new System.Drawing.Size(68, 21); + this.toolStripStatusLabel_RunningStatu.Text = "运行状态:"; + // + // toolStripStatusLabel_RunningStatus + // + this.toolStripStatusLabel_RunningStatus.ActiveLinkColor = System.Drawing.Color.Red; + this.toolStripStatusLabel_RunningStatus.AutoSize = false; + this.toolStripStatusLabel_RunningStatus.BackColor = System.Drawing.Color.Yellow; + this.toolStripStatusLabel_RunningStatus.Name = "toolStripStatusLabel_RunningStatus"; + this.toolStripStatusLabel_RunningStatus.Size = new System.Drawing.Size(62, 21); + this.toolStripStatusLabel_RunningStatus.Text = "变量模拟"; + // + // toolStripStatusLabel2 + // + this.toolStripStatusLabel2.BorderSides = System.Windows.Forms.ToolStripStatusLabelBorderSides.Left; + this.toolStripStatusLabel2.Name = "toolStripStatusLabel2"; + this.toolStripStatusLabel2.Size = new System.Drawing.Size(72, 21); + this.toolStripStatusLabel2.Text = "启动时间:"; + // + // toolStripStatusLabel_StartTime + // + this.toolStripStatusLabel_StartTime.AutoSize = false; + this.toolStripStatusLabel_StartTime.BorderSides = System.Windows.Forms.ToolStripStatusLabelBorderSides.Right; + this.toolStripStatusLabel_StartTime.Name = "toolStripStatusLabel_StartTime"; + this.toolStripStatusLabel_StartTime.Size = new System.Drawing.Size(130, 21); + this.toolStripStatusLabel_StartTime.Text = "2018/08/08 08:08:08"; + // + // toolStripStatusLabel3 + // + this.toolStripStatusLabel3.Name = "toolStripStatusLabel3"; + this.toolStripStatusLabel3.Size = new System.Drawing.Size(68, 21); + this.toolStripStatusLabel3.Text = "运行时长:"; + // + // toolStripStatusLabel_RunTime + // + this.toolStripStatusLabel_RunTime.AutoSize = false; + this.toolStripStatusLabel_RunTime.BorderSides = System.Windows.Forms.ToolStripStatusLabelBorderSides.Right; + this.toolStripStatusLabel_RunTime.Name = "toolStripStatusLabel_RunTime"; + this.toolStripStatusLabel_RunTime.Size = new System.Drawing.Size(145, 21); + this.toolStripStatusLabel_RunTime.Text = "0天0小时0分0秒"; + // + // toolStripStatusLabel1 + // + this.toolStripStatusLabel1.Name = "toolStripStatusLabel1"; + this.toolStripStatusLabel1.Size = new System.Drawing.Size(68, 21); + this.toolStripStatusLabel1.Text = "工位数量:"; + // + // toolStripStatusLabel_WorkStationNum + // + this.toolStripStatusLabel_WorkStationNum.AutoSize = false; + this.toolStripStatusLabel_WorkStationNum.BorderSides = System.Windows.Forms.ToolStripStatusLabelBorderSides.Right; + this.toolStripStatusLabel_WorkStationNum.Name = "toolStripStatusLabel_WorkStationNum"; + this.toolStripStatusLabel_WorkStationNum.Size = new System.Drawing.Size(35, 21); + this.toolStripStatusLabel_WorkStationNum.Text = "100"; + // + // toolStripStatusLabel6 + // + this.toolStripStatusLabel6.Name = "toolStripStatusLabel6"; + this.toolStripStatusLabel6.Size = new System.Drawing.Size(68, 21); + this.toolStripStatusLabel6.Text = "在线数量:"; + // + // toolStripStatusLabel_OnlineNum + // + this.toolStripStatusLabel_OnlineNum.AutoSize = false; + this.toolStripStatusLabel_OnlineNum.BorderSides = System.Windows.Forms.ToolStripStatusLabelBorderSides.Right; + this.toolStripStatusLabel_OnlineNum.Name = "toolStripStatusLabel_OnlineNum"; + this.toolStripStatusLabel_OnlineNum.Size = new System.Drawing.Size(35, 21); + this.toolStripStatusLabel_OnlineNum.Text = "0"; + // + // toolStripStatusLabel8 + // + this.toolStripStatusLabel8.Name = "toolStripStatusLabel8"; + this.toolStripStatusLabel8.Size = new System.Drawing.Size(68, 21); + this.toolStripStatusLabel8.Text = "离线数量:"; + // + // toolStripStatusLabel_DownLine + // + this.toolStripStatusLabel_DownLine.AutoSize = false; + this.toolStripStatusLabel_DownLine.BorderSides = System.Windows.Forms.ToolStripStatusLabelBorderSides.Right; + this.toolStripStatusLabel_DownLine.Name = "toolStripStatusLabel_DownLine"; + this.toolStripStatusLabel_DownLine.Size = new System.Drawing.Size(35, 21); + this.toolStripStatusLabel_DownLine.Text = "0"; + // + // toolStripStatusLabel4 + // + this.toolStripStatusLabel4.Name = "toolStripStatusLabel4"; + this.toolStripStatusLabel4.Size = new System.Drawing.Size(44, 21); + this.toolStripStatusLabel4.Text = "版本:"; + // + // toolStripStatusLabel_Version + // + this.toolStripStatusLabel_Version.Name = "toolStripStatusLabel_Version"; + this.toolStripStatusLabel_Version.Size = new System.Drawing.Size(42, 21); + this.toolStripStatusLabel_Version.Text = "8.6.12"; + // + // groupBox_Alarm + // + this.groupBox_Alarm.Location = new System.Drawing.Point(0, 0); + this.groupBox_Alarm.Name = "groupBox_Alarm"; + this.groupBox_Alarm.Size = new System.Drawing.Size(200, 100); + this.groupBox_Alarm.TabIndex = 1; + this.groupBox_Alarm.TabStop = false; + // + // MisData + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(1008, 699); + this.Controls.Add(this.statusStrip1); + this.Controls.Add(this.groupBox_Depart); + this.Controls.Add(this.menuStrip_Main); + this.Controls.Add(this.groupBox_WorkStationQuality); + this.Controls.Add(this.groupBox_SignialSimulator); + this.Controls.Add(this.groupBox_Alarm); + this.DoubleBuffered = true; + this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; + this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); + this.MainMenuStrip = this.menuStrip_Main; + this.Margin = new System.Windows.Forms.Padding(2); + this.MaximumSize = new System.Drawing.Size(1024, 738); + this.MinimumSize = new System.Drawing.Size(1024, 705); + this.Name = "MisData"; + this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; + this.Text = "Demo Mes Work System Function 2022.08.23.1616"; + this.TopMost = true; + this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.MisData_FormClosing); + this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.MisData_FormClosed); + this.Load += new System.EventHandler(this.MisData_Load); + ((System.ComponentModel.ISupportInitialize)(this.numericUpDown1)).EndInit(); + this.groupBox_SignialSimulator.ResumeLayout(false); + this.groupBox_SignialSimulator.PerformLayout(); + this.groupBox_WorkStationStatus.ResumeLayout(false); + this.groupBox_WorkStationStatus.PerformLayout(); + this.groupBox_PLC.ResumeLayout(false); + this.groupBox_PLC.PerformLayout(); + this.groupBox_MES.ResumeLayout(false); + this.groupBox_MES.PerformLayout(); + this.groupBox_WorkStationQuality.ResumeLayout(false); + this.groupBox_WorkStationQuality.PerformLayout(); + this.contextMenuStrip_MIS.ResumeLayout(false); + this.menuStrip_Main.ResumeLayout(false); + this.menuStrip_Main.PerformLayout(); + this.statusStrip1.ResumeLayout(false); + this.statusStrip1.PerformLayout(); + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + private System.Windows.Forms.ComboBox comboBox_OpName; + private System.Windows.Forms.Label label_OpNameList; + private System.Windows.Forms.TextBox textBox_tagValue_Read; + private System.Windows.Forms.TextBox textBox_tagValue; + private System.Windows.Forms.TextBox textBox_Cmd; + private System.Windows.Forms.Button button_Read; + private System.Windows.Forms.Button button_Write; + private System.Windows.Forms.ListBox listBox1; + private System.Windows.Forms.CheckBox checkBox_WorkStart; + private System.Windows.Forms.NumericUpDown numericUpDown1; + private System.Windows.Forms.ListView listView_ShowQualityData; + private System.Windows.Forms.ColumnHeader columnHeader1; + private System.Windows.Forms.ColumnHeader columnHeader2; + private System.Windows.Forms.ColumnHeader columnHeader3; + private System.Windows.Forms.ColumnHeader columnHeader4; + private System.Windows.Forms.Button button_ReadData; + private System.Windows.Forms.GroupBox groupBox_SignialSimulator; + private System.Windows.Forms.GroupBox groupBox_MES; + private System.Windows.Forms.TextBox Tbx_MES_74_EngineID; + private System.Windows.Forms.TextBox Tbx_MES_75_Enginetype; + private System.Windows.Forms.Label label10; + private System.Windows.Forms.Label label11; + private System.Windows.Forms.Label label12; + private System.Windows.Forms.Label label13; + private System.Windows.Forms.Label label14; + private System.Windows.Forms.Label label15; + private System.Windows.Forms.Label label16; + private System.Windows.Forms.GroupBox groupBox5; + private System.Windows.Forms.Button Btn_MES_69_MachResult; + private System.Windows.Forms.Button Btn_MES_8_FalseGo; + private System.Windows.Forms.Button Btn_MES_67_FixOver; + private System.Windows.Forms.Button Btn_MES_7_WorkComplete; + private System.Windows.Forms.Button Btn_MES_53_OffLineOK; + private System.Windows.Forms.Button Btn_MES_66_AllowWork; + private System.Windows.Forms.Button Btn_MES_5_EngineTypeGetOver; + private System.Windows.Forms.Button Btn_MES_68_MachComplete; + private System.Windows.Forms.Button Btn_MES_52_ResetEquipment; + private System.Windows.Forms.Button Btn_MES_6_PalletGo; + private System.Windows.Forms.Button Btn_Write_MES; + private System.Windows.Forms.Button Btn_MES_71_IsAuto; + private System.Windows.Forms.Button Btn_MES_51_ConfirmOkGo; + private System.Windows.Forms.Button Btn_MES_15_HeartBeat; + private System.Windows.Forms.GroupBox groupBox_PLC; + private System.Windows.Forms.TextBox Tbx_PLC_10_EngineID; + private System.Windows.Forms.TextBox Tbx_PLC_11_Enginetype; + private System.Windows.Forms.Label label3; + private System.Windows.Forms.Label label4; + 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.Label label9; + private System.Windows.Forms.GroupBox groupBox3; + private System.Windows.Forms.Button Btn_PLC_1003_ShortFall; + private System.Windows.Forms.Button Btn_PLC_19_MesRead; + private System.Windows.Forms.Button Btn_PLC_1002_MachaineBreak; + private System.Windows.Forms.Button Btn_PLC_59_FixOK; + private System.Windows.Forms.Button Btn_PLC_1001_CycleStart; + private System.Windows.Forms.Button Btn_PLC_1000_MachinePowerOn; + private System.Windows.Forms.Button Btn_PLC_44_EngineTypeGetOver; + private System.Windows.Forms.Button Btn_PLC_13_PalletIn; + private System.Windows.Forms.Button Btn_PLC_50_ApplyOffline; + private System.Windows.Forms.Button Btn_PLC_43_PartLoad; + private System.Windows.Forms.Button Btn_Write_PLC; + private System.Windows.Forms.Button Btn_PLC_1004_Jam; + private System.Windows.Forms.Button Btn_PLC_14_HeartBeat; + private System.Windows.Forms.Button Btn_PLC_2_WorkStart; + private System.Windows.Forms.Button Btn_MES_20_MesReadOver; + private System.Windows.Forms.Button Btn_MES_72_MobyClear; + private System.Windows.Forms.TextBox Tbx_PLC_18_Actual; + private System.Windows.Forms.TextBox Tbx_PLC_17_TargetTime; + private System.Windows.Forms.Label label18; + private System.Windows.Forms.Label label17; + private System.Windows.Forms.Button Btn_PLC_16_AllowReadCycleTime; + private System.Windows.Forms.Button Btn_MES_54_ReadCycleTimeOK; + private System.Windows.Forms.TextBox Tbx_MES_73_EngineTypeID; + private System.Windows.Forms.TextBox Tbx_MES_79_OnlineStatus; + private System.Windows.Forms.TextBox Tbx_MES_93_RepairMark; + private System.Windows.Forms.TextBox Tbx_MES_88_SocketNum; + private System.Windows.Forms.TextBox Tbx_MES_77_FixOrder; + private System.Windows.Forms.TextBox Tbx_MES_4_WorkStationRepairStr; + private System.Windows.Forms.Label label19; + private System.Windows.Forms.TextBox Tbx_PLC_9_EngineTypeID; + private System.Windows.Forms.TextBox Tbx_PLC_23_RepairMark; + private System.Windows.Forms.TextBox Tbx_PLC_22_PalletStatus; + private System.Windows.Forms.TextBox Tbx_PLC_21_ResultMark; + private System.Windows.Forms.TextBox Tbx_PLC_80_PalletNum; + private System.Windows.Forms.GroupBox groupBox_WorkStationStatus; + private System.Windows.Forms.TextBox Tbx_Status_11_EngineType; + private System.Windows.Forms.TextBox Tbx_Status_9_EngineTypeID; + private System.Windows.Forms.Label label2; + private System.Windows.Forms.Label label20; + private System.Windows.Forms.TextBox Tbx_Status_10_EngineID; + private System.Windows.Forms.TextBox Tbx_Status_80_Pallet; + private System.Windows.Forms.Label label21; + private System.Windows.Forms.Label label22; + private System.Windows.Forms.GroupBox groupBox_WorkStationQuality; + private System.Windows.Forms.CheckBox Cbx_StatusDisplay; + private System.Windows.Forms.Button Btn_Read_PLC; + private System.Windows.Forms.Button Btn_Read_MES; + private System.Windows.Forms.ContextMenuStrip contextMenuStrip_MIS; + private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem_Show; + private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem_Hide; + private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem_Exit; + private System.Windows.Forms.MenuStrip menuStrip_Main; + private System.Windows.Forms.ToolStripMenuItem ToolStripMenuItem_Start; + private System.Windows.Forms.ToolStripMenuItem ToolStripMenuItem_SaveLog; + private System.Windows.Forms.ToolStripMenuItem ToolStripMenuItem_LockForm; + private System.Windows.Forms.ToolStripMenuItem ToolStripMenuItem_Quit; + private System.Windows.Forms.ToolStripMenuItem ToolStripMenuItem_Visual; + private System.Windows.Forms.ToolStripMenuItem ToolStripMenuItem_VWSStatus; + private System.Windows.Forms.ToolStripMenuItem ToolStripMenuItem_Help; + private System.Windows.Forms.ToolStripMenuItem ToolStripMenuItem_HHelp; + private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem_HVersion; + private System.Windows.Forms.ToolStripMenuItem ToolStripMenuItem_PrintScreen; + private System.Windows.Forms.GroupBox groupBox_Depart; + private System.Windows.Forms.ToolStripMenuItem MToolStripMenuItem_AboutMacroinf; + private System.Windows.Forms.CheckBox checkBox_PLCData_Display; + private System.Windows.Forms.CheckBox checkBox_MESData_Display; + private System.Windows.Forms.ToolStripMenuItem EToolStripMenuItem_EquipAlarm; + private System.Windows.Forms.StatusStrip statusStrip1; + private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel_RunningStatu; + private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel_RunningStatus; + private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel2; + private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel_StartTime; + private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel3; + private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel_RunTime; + private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel1; + private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel_WorkStationNum; + private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel6; + private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel_OnlineNum; + private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel8; + private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel_DownLine; + private System.Windows.Forms.GroupBox groupBox_Alarm; + private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel4; + private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel_Version; + private System.Windows.Forms.ToolStripMenuItem ToolStripMenuItem_Assembly; + private System.Windows.Forms.ToolStripMenuItem TSM_DebugPage; + private System.Windows.Forms.CheckBox cb_QdData; + private System.Windows.Forms.CheckBox cb_MonitorData; + } +} + diff --git a/Test/MisDataWebFun.cs b/Test/MisDataWebFun.cs new file mode 100644 index 0000000..37fa577 --- /dev/null +++ b/Test/MisDataWebFun.cs @@ -0,0 +1,956 @@ +//using BasicData; +using bizFacade; +//using OpcData; +using System; +using System.Collections; +using System.Data; +using System.Threading; +using System.Windows.Forms; +//using SystemFramework; + +using System.Drawing; +//using MesServerWork; +using System.Configuration; +//using MisDataFunction; +using System.Collections.Generic; +using MQTTnet.Client.Connecting; +using MQTTnet.Client.Disconnecting; +using MQTTnet.Client.Receiving; +using System.Linq; +using DoWhatPlc; +/// +/// +/// +namespace MisDataSaveDate +{ + /// + /// + /// + /// + /// + public delegate void RefreshForm(object obj1, EventArgs obj2); + /// + /// + /// + public partial class MisData:Form + { + /// + /// + /// + public static string BasicDataTableFile = ConfigurationManager.AppSettings["BasicDataTableFile"]; + /// + /// + /// + public static int IsDemoMesServer = Convert.ToInt32(ConfigurationManager.AppSettings["IsDemoMesServer"]); + /// + /// + /// + public static string MqttUrl = ConfigurationManager.AppSettings["MqttUrl"]; + public static string MqttUrlPLC = ConfigurationManager.AppSettings["MqttUrlPLC"]; + /// + /// + /// + public static string MqttTargetTopic = ConfigurationManager.AppSettings["MqttTargetTopic"]; + public static string MqttTargetTopicPLC = ConfigurationManager.AppSettings["MqttTargetTopicPLC"]; + /// + /// + /// + public static int IsWriteMonitorLog = Convert.ToInt32(ConfigurationManager.AppSettings["IsWriteMonitorLog"]); + /// + /// + /// + public static string ConnectionString_MES = ConfigurationManager.AppSettings["ConnectionString_MES"]; + /// + /// + /// + public static int WebApiPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["WebApiPort"]); + /// + /// + /// + public static RefreshForm MainFormRefresh, TestPlcStatusDel; + /// + /// 允许使用附加功能的变量,只有在系统开始加载Tag时,才允许读取PLC数据 + /// + public static bool AllowLoad; + /// + /// + /// + public MisData() + { + InitializeComponent(); + // CheckForIllegalCrossThreadCalls = false; + // this.Cursor = Cursors.WaitCursor; + // TopMost = true; + // Never_Know.Hello_You_All_Never_Know = Hello_You_All_Never_Know; + // new ApplicationLog(); + // ThreadPool.SetMaxThreads(1000, 500); + // MIS_BASE.MqttTargetTopic = MqttTargetTopic; + // new DataLinkMesWork.ApplicationConfig(); + + // DataTable dt_Signal; + // DataTable dt_Device; + // DataTable dt_TagTypeDataType; + // dt_Signal = bizFacade.BaseDataSystemMES.dt_Signal(); + // dt_Device = bizFacade.BaseDataSystemMES.dt_Device(); + // dt_TagTypeDataType = bizFacade.BaseDataSystemMES.dt_TagTypeDataType(); + // //if (LoadOPCData(BasicDataTableFile, IsDemoMesServer, IsWriteMonitorLog, true)) + + // #region LoadOPCData + + // //if (LoadOPCData(dt_Signal, dt_Device, IsDemoMesServer, IsWriteMonitorLog, true)) + // //{ + + // // //MisData_SyncRawData(); + + // // MesDataFunction.LoadTagTypeCodeID.Load(dt_TagTypeDataType); + // // //MesDataFunction.LoadTagTypeCodeID.Load(BasicDataTableFile); + // // showMessagePLCInvoke = new ShowMessagePLCInvoke(ShowMessagePLC); + // // TestPlcConnectInit(); + // // MainFormRefresh = new RefreshForm(button_ReadData_Click); + // // QueryMainFormPosition = new QueryFormData(QueryFormPosition); + // // MainActived = new MainAct(this.Activate); + // // TestPlcStatusDel = new RefreshForm(RefreshPlcConnectStatus); + + // // AssemblyManagement.InitAssembly_Recycle(); + + // // new InitTagValueListData(); + + // // //设备保养通知计划:设备保养通知计划调度 + // // InitMachinePlan(new MachinePlan_Invoke(MachinePlan)); + + + // // if (IsDemoMesServer == 1) + // // { + // // toolStripStatusLabel_RunningStatus.Text = "变量模拟"; + // // toolStripStatusLabel_RunningStatus.BackColor = System.Drawing.Color.Yellow; + // // } + // // else + // // { + // // toolStripStatusLabel_RunningStatus.Text = "PLC"; + // // toolStripStatusLabel_RunningStatus.BackColor = System.Drawing.Color.Green; + // // } + + // // StartTime = Convert.ToDateTime(toolStripStatusLabel_StartTime.Text = DateTime.Now.ToString()); + // // Runtime_Thread(); + + + // // //查询出“全部原始基本数据列表” + // // BasicDataTagValue = MesWork.PlcLinkForm.dt_BasicData.Select($"是否启用 = 1 and 变量类型代码=101 or 变量类型代码 = 102 or 变量类型代码 = 105 and 监控属性代码 = '{DataLinkMesWork.ApplicationConfig.MES_Code.ToString()}'").CopyToDataTable(); + // // if (BasicDataTagValue.Columns.Contains("上限值")) + // // { + // // BasicDataTagValue.Columns["上限值"].ColumnName = "值上限"; + // // } + // // if (BasicDataTagValue.Columns.Contains("下限值")) + // // { + // // BasicDataTagValue.Columns["下限值"].ColumnName = "值下限"; + // // } + // // // BasicDataTagValue = MesWork.PlcLinkForm.dt_BasicData.Select($"是否启用 = 1 and 监控属性代码 = '{DataLinkMesWork.ApplicationConfig.MES_Code.ToString()}'").CopyToDataTable(); + // // //查询出“MES_基本数据_测量范围” + // // BasicDataTagValueUpDown = MesWork.PlcLinkForm.dt_BasicData; + // // if (BasicDataTagValueUpDown.Columns.Contains("上限值")) + // // { + // // BasicDataTagValueUpDown.Columns["上限值"].ColumnName = "值上限"; + // // } + // // if (BasicDataTagValueUpDown.Columns.Contains("下限值")) + // // { + // // BasicDataTagValueUpDown.Columns["下限值"].ColumnName = "值下限"; + // // } + // // // 模拟时,写入质量数据 + // // //InitBasicDataTagValue(); + // // // 变量代码与其他字段的对应关系 + // // InitHashtableTagID(); + + + // // this.Cursor = Cursors.Default; + // // Cbx_StatusDisplay_CheckedChanged(null, null); + + // // AllowLoad = true; + // // Cbx_StatusDisplay.Enabled = true; + // // button_ReadData_Click(null, null); + // // timer_TestPLC.Enabled = true; + // // EToolStripMenuItem_EquipAlarm_Click(null, null); + // // timer_LoadOver.Enabled = true; + // // TopMost = false; + + // // // Thread.Sleep(200); + // // //First_TagMonitor(); //开启发送监控变量第一次的值 + // // // Thread.Sleep(200); + // // // Init_TagMonitor(); //开启初始化监控变量 + // // Thread.Sleep(200); + // // var deviceState = StartServer(WebApiPort); //开启监控服务 + + // // loadFinish = true; + // // InitcomboBox_OpNameWebApi(); + // // //InitcomboBox_OpName(); + // // //初始化程序集列表 + // // InitProgramFunctionAssembly(); + // // // WorkStationNum_Now = comboBox_OpName.SelectedValue.ToString(); + + // // ListBox1_Item_Init(); + + // //} + + + + + // #endregion + + // //MisData_SyncRawData(); + + // MesDataFunction.LoadTagTypeCodeID.Load(dt_TagTypeDataType); + // showMessagePLCInvoke = new ShowMessagePLCInvoke(ShowMessagePLC); + // TestPlcConnectInit(); + // MainFormRefresh = new RefreshForm(button_ReadData_Click); + // QueryMainFormPosition = new QueryFormData(QueryFormPosition); + // MainActived = new MainAct(this.Activate); + // TestPlcStatusDel = new RefreshForm(RefreshPlcConnectStatus); + + // AssemblyManagement.InitAssembly_Recycle(); + + //// new InitTagValueListData(); + + // //设备保养通知计划:设备保养通知计划调度 + // InitMachinePlan(new MachinePlan_Invoke(MachinePlan)); + + + //if (IsDemoMesServer == 1) + //{ + // toolStripStatusLabel_RunningStatus.Text = "变量模拟"; + // toolStripStatusLabel_RunningStatus.BackColor = System.Drawing.Color.Yellow; + //} + //else + //{ + // toolStripStatusLabel_RunningStatus.Text = "PLC"; + // toolStripStatusLabel_RunningStatus.BackColor = System.Drawing.Color.Green; + //} + + //StartTime = Convert.ToDateTime(toolStripStatusLabel_StartTime.Text = DateTime.Now.ToString()); + //Runtime_Thread(); + + //// 变量代码与其他字段的对应关系 + //InitHashtableTagID(); + + //this.Cursor = Cursors.Default; + //Cbx_StatusDisplay_CheckedChanged(null, null); + + //AllowLoad = true; + //Cbx_StatusDisplay.Enabled = true; + //button_ReadData_Click(null, null); + //timer_TestPLC.Enabled = true; + //EToolStripMenuItem_EquipAlarm_Click(null, null); + //timer_LoadOver.Enabled = true; + //TopMost = false; + + //InitcomboBox_OpNameWebApi(); + ////InitcomboBox_OpName(); + ////初始化程序集列表 + //InitProgramFunctionAssembly(); + //// WorkStationNum_Now = comboBox_OpName.SelectedValue.ToString(); + + //ListBox1_Item_Init(); + + + + } + + /// + /// 模拟时,写入质量数据 + /// + private void InitBasicDataTagValue() + { + //if (IsDemoMesServer != 1) return; + //string tagID; + //double tagValue; + ////写工位总合格标志 变量类型代码=21 + //for (int i = 0; i < MesWork.PlcLinkForm.dt_BasicData.Rows.Count; i++) + //{ + // if (MesWork.PlcLinkForm.dt_BasicData.Rows[i]["变量类型代码"].ToString() == "21") + // { + // tagID = MesWork.PlcLinkForm.dt_BasicData.Rows[i]["TagID"].ToString(); + // WritePLC(tagID, 1); + // } + + //} + + //for (int i = 0; i < BasicDataTagValue.Rows.Count; i++) + //{ + + // try + // { + // switch (Convert.ToInt32(BasicDataTagValue.Rows[i]["变量特点"])) + // { + + // case 7: + // tagID = BasicDataTagValue.Rows[i]["TagID"].ToString(); + // WritePLC(tagID, 1); + // break; + // case 6: + // tagID = BasicDataTagValue.Rows[i]["TagID"].ToString(); + // tagValue = Convert.ToDouble(BasicDataTagValue.Rows[i]["列位置"]) * 100 + // + Convert.ToDouble(BasicDataTagValue.Rows[i]["变量排序"]) / 100; + // WritePLC(tagID, tagValue); + // break; + // } + // } + // catch { } + + //} + } + + + /// + /// 初始化Function对应的程序集 + /// + void InitProgramFunctionAssembly() + { + + //int mesServerCode = 0; + //string mesServerdllName = ""; + //System.Reflection.Assembly assembly = null; + //foreach (var opName in opNameList) + //{ + // try + // { + // mesServerCode = GetMesServerCodeByOpName(opName); + + // mesServerdllName = GetMesServeDllByOpName(opName); + + // assembly = System.Reflection.Assembly.Load(mesServerdllName); + // if (assembly == null) + // { + // // return; + // } + // if (!MesDataFunction.OpcOperation.Hashtable_assembly.ContainsKey(mesServerdllName)) + // { + // MesDataFunction.OpcOperation.Hashtable_assembly.Add(mesServerdllName, assembly); + // } + + // } + // catch (Exception err) + // { + // if (!MesDataFunction.OpcOperation.Hashtable_assembly.ContainsKey(mesServerdllName)) + // { + // MesDataFunction.OpcOperation.Hashtable_assembly.Add(mesServerdllName, null); + // } + // ApplicationLog.WriteLog(err, err.Message); + + // } + //} + + + } + //List opNameList; + /// + /// 初始化comboBox_OpName(工位号) + /// + private void InitcomboBox_OpName() + { + ////全部工位号 + //comboBox_OpName.DataSource = opNameList = MesWork.PlcLinkForm.opNameList; + //FunctionForm_HashiTable.OpName_Hash_Write("OpNameList", opNameList); + //toolStripStatusLabel_WorkStationNum.Text = MesWork.PlcLinkForm.opNameList.Count.ToString(); + //toolStripStatusLabel_DownLine.Text = toolStripStatusLabel_WorkStationNum.Text; + //WorkStationNum_Now = comboBox_OpName.SelectedValue.ToString(); + + } + + private void InitcomboBox_OpNameWebApi() + { + List opNameList; + //全部工位号 + comboBox_OpName.DataSource = opNameList = DtWebApi.OpcDemo.Get_opNameList(); + + + //FunctionForm_HashiTable.OpName_Hash_Write("OpNameList", opNameList); + toolStripStatusLabel_WorkStationNum.Text = opNameList.Count.ToString(); + toolStripStatusLabel_DownLine.Text = toolStripStatusLabel_WorkStationNum.Text; + if (comboBox_OpName.Items.Count > 0) + { + WorkStationNum_Now = comboBox_OpName.SelectedValue.ToString(); + } + + } + + private void listBox1_SelectedValueChanged(object sender, EventArgs e) + { + //try + //{ + // string cmd; + // string opName; + // string tagValue; + // string[] strList; + // if (listBox1.Text != null) + // { + // strList = listBox1.Text.Split('|'); + // if (strList.Length >= 4) + // { + // cmd = strList[1]; + // opName = strList[2]; + // tagValue = strList[3]; + // textBox_Cmd.Text = cmd; + // textBox_tagValue.Text = tagValue; + // } + // } + //} + //catch (Exception err) + //{ + // ApplicationLog.WriteLog(err, err.Message); + + //} + + } + + private void button_Write_Click(object sender, EventArgs e) + { + try + { + short tagValue_int; + string tagValue_str; + byte tagValue_byte; + bool tagValue_bool; + int tagType; + int tagDataType; + string cmd = textBox_Cmd.Text; + string opName = WorkStationNum_Now; + string tagValue = textBox_tagValue.Text; + HashtableList htList = DtWebApi.OpcDemo.GetHashtableList(); + + tagType = Convert.ToInt32(htList.hashtable_TagType[cmd]); + + tagDataType = Convert.ToInt32(htList.hashtable_TagTypeDataType[tagType.ToString()]); + switch (tagDataType) + { + case 2: + tagValue_int = Convert.ToInt16(tagValue); + WriteAnyData_Thread(tagType, opName, tagValue_int); + break; + case 8: + tagValue_str = tagValue.ToString(); + WriteAnyData_Thread(tagType, opName, tagValue_str); + break; + case 17: + tagValue_byte = Convert.ToByte(tagValue); + WriteAnyData_Thread(tagType, opName, tagValue_byte); + break; + case 11: + tagValue_bool = Convert.ToBoolean(Convert.ToInt32(tagValue)); + WriteAnyData_Thread(tagType, opName, tagValue_bool); + break; + } + + } + catch (Exception err) + { + MessageBox.Show("输入命令异常,请重新输入!"); + //ApplicationLog.WriteLog(err, err.Message); + + } + } + + private void button_Read_Click(object sender, EventArgs e) + { + try + { + int tagType; + string cmd = textBox_Cmd.Text; + string opName = WorkStationNum_Now; + string tagValue = textBox_tagValue.Text; + + HashtableList htList = DtWebApi.OpcDemo.GetHashtableList(); + + tagType = Convert.ToInt32(htList.hashtable_TagType[cmd]); + + QualityDataQueryStruct QualityStruct = new QualityDataQueryStruct(opName, tagType, textBox_tagValue_Read); + Thread t = new Thread(new ParameterizedThreadStart(ReadPLC_ByTagType_Thread)); + t.Start(QualityStruct); + } + catch (Exception err) + { + // ApplicationLog.WriteLog(err, err.Message); + + } + } + + void ReadPLC_ByTagType_Thread(object obj) + { + //try + //{ + // QualityDataQueryStruct QualityStruct = (QualityDataQueryStruct)obj; + // TextBox tbx = (TextBox)QualityStruct.Ctrl; + + // tbx.Text = ReadPLC(QualityStruct.tagType, QualityStruct.OpName).ToString(); + //} + //catch (Exception err) + //{ + // ApplicationLog.WriteLog(err, err.Message); + //} + } + + + bool isWorkStart; + private void timer_WorkStart_Tick(object sender, EventArgs e) + { + //if (isWorkStart) + // isWorkStart = false; + //else + // isWorkStart = true; + //if (isWorkStart) + //{ + // textBox_tagValue.Text = "1"; + // button_Write_Click(null, null); + //} + //else + //{ + // textBox_tagValue.Text = "0"; + // button_Write_Click(null, null); + //} + } + + private void checkBox_WorkStart_CheckedChanged(object sender, EventArgs e) + { + //if (textBox_Cmd.Text == "" && checkBox_WorkStart.Checked) + //{ + // MessageBox.Show("请选择命令"); + // checkBox_WorkStart.Checked = false; + // return; + //} + //if (checkBox_WorkStart.Checked) + //{ + // timer_WorkStart.Enabled = true; + // listBox1.Enabled = false; + // textBox_Cmd.ReadOnly = true; + //} + //else + //{ + // timer_WorkStart.Enabled = false; + // listBox1.Enabled = true; + // textBox_Cmd.ReadOnly = false; + //} + + } + + private void numericUpDown1_ValueChanged(object sender, EventArgs e) + { + //timer_WorkStart.Interval = Convert.ToInt32(numericUpDown1.Value) * 1000; + } + + static Thread ReadQuality_t = null; + private void ReadQualityData(string opName) + { + try + { + if (ReadQualityRunning) return; + ReadQualityRunning = true; + QualityDataQueryStruct QltyQueryStr = new QualityDataQueryStruct(opName, listView_ShowQualityData); + + ReadQuality_t = new Thread(new ParameterizedThreadStart(ReadQualityData_Thread)); + ReadQuality_t.Start(QltyQueryStr); + + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, err.Message); + + } + } + public QualityDataType[] ThisWorkStationData + { get; set; } + static bool ReadQualityRunning = false; + void ReadQualityData_Thread(object obj) + { + int fTime = 0; + try + { + + QualityDataQueryStruct QualityStruct = (QualityDataQueryStruct)obj; + + ListView listViewTemp = (ListView)QualityStruct.Ctrl; + ListViewItem listViewItem = null; + string[] listViewItemString = new string[4]; + if (listViewTemp.InvokeRequired) + { + Action ActionDelegate = () => { listViewTemp.Items.Clear(); }; + listViewTemp.Invoke(ActionDelegate); + } + else + { + listViewTemp.Items.Clear(); + } + + System.Collections.Concurrent.ConcurrentDictionary cd = new System.Collections.Concurrent.ConcurrentDictionary(); + List cdTagIDTagFormat = null; + if (cb_MonitorData.Checked) + { + + cdTagIDTagFormat = DtWebApi.OpcDemo.ReadPLC_GroupMonitor(QualityStruct.OpName); + //cd = MesWork.PlcLinkForm.ReadPLC_GroupMonitor(QualityStruct.OpName); + } + if (cb_QdData.Checked) + { + cdTagIDTagFormat = DtWebApi.OpcDemo.ReadPLC_GroupData_Qd(QualityStruct.OpName); + //cd = MesWork.PlcLinkForm.ReadPLC_GroupData_Qd(QualityStruct.OpName); + } + if (cb_MonitorData.Checked == false & cb_QdData.Checked == false) + { + cdTagIDTagFormat = DtWebApi.OpcDemo.ReadPLC_GroupData(QualityStruct.OpName); + //cd = MesWork.PlcLinkForm.ReadPLC_GroupData(QualityStruct.OpName); + } + if (cb_MonitorData.Checked == true & cb_QdData.Checked == true) + { + cdTagIDTagFormat = DtWebApi.OpcDemo.ReadPLC_GroupData(QualityStruct.OpName); + //cd = MesWork.PlcLinkForm.ReadPLC_GroupData(QualityStruct.OpName); + } + if (cdTagIDTagFormat == null) return; + foreach (var item in cdTagIDTagFormat) + { + if (!cd.ContainsKey(item.TagID)) + { + cd.TryAdd(item.TagID, item.TF); + } + } + //排序 + var result2 = from pair in cd orderby pair.Key select pair; + ThisWorkStationData = new QualityDataType[cd.Count]; + var sortResult2 = from pair in cd orderby pair.Key descending select pair; + //cd.o.OrderBy(p => p.Value.Speed); + //foreach (KeyValuePair _cd in cd) + foreach (KeyValuePair _cd in result2) + { + var tagID = _cd.Key; + var TF = (DoWhatPlc.TagFormat)_cd.Value; + + listViewItemString[0] = TF.OpName; + listViewItemString[3] = TF.TagID; + listViewItemString[1] = TF.ItemName; + listViewItemString[2] = TF.TagValue.ToString(); + + listViewItem = new ListViewItem(listViewItemString); + if (TF.IsMonitor == 1) + { + listViewItem.BackColor = Color.LimeGreen; + } + if (listViewTemp.InvokeRequired) + { + Action ActionDelegate = (x) => { listViewTemp.Items.Add(x); }; + listViewTemp.BeginInvoke(ActionDelegate, listViewItem); + } + else + { + listViewTemp.Items.Add(listViewItem); + } + + QualityDataType t00 = new QualityDataType(); + t00.opName = TF.OpName; + t00.tagID = TF.TagID; + t00.tagTypeID = TF.TagTypeID; + t00.tagValue = TF.TagValue; + ThisWorkStationData[fTime] = t00; + //ThisWorkStationData[fTime].opName = TF.OpName; + //ThisWorkStationData[fTime].tagID = TF.TagID; + //ThisWorkStationData[fTime].tagTypeID = TF.TagTypeID; + //ThisWorkStationData[fTime].tagValue = TF.TagValue; + + + fTime++; + + } + + ReadQualityRunning = false; + } + catch (Exception err) + { + ReadQualityRunning = false; + // ApplicationLog.WriteLog(err, err.Message); + + } + + + + } + + private void button_ReadData_Click(object sender, EventArgs e) + { + ReadQualityData(WorkStationNum_Now); + + } + + + private void comboBox_OpName_SelectedIndexChanged(object sender, EventArgs e) + { + WorkStationNum_Now = comboBox_OpName.SelectedValue.ToString(); + } + + + private void listView_ShowQualityData_MouseDoubleClick(object sender, MouseEventArgs e) + { + try + { + var items = listView_ShowQualityData.SelectedItems; + QualityDataType SelectData = new QualityDataType(); + ListView.SelectedIndexCollection index = new ListView.SelectedIndexCollection(listView_ShowQualityData); + SelectData = ThisWorkStationData[index[0]]; + WriteQualityValueForm WriteForm = new WriteQualityValueForm(SelectData, this); + WriteForm.ShowDialog(); + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, err.Message); + + } + } + + private void groupBox_SignialSimulatorBtn_Click(object sender, EventArgs e) + { + WriteBoolSignalByFormBtn(sender); + } + + private void Btn_Write_PLC_Click(object sender, EventArgs e) + { + WriteNormalDataBygroupBox_SignialSimulatorWriteBtn(sender); + } + + private void Btn_Write_MES_Click(object sender, EventArgs e) + { + WriteNormalDataBygroupBox_SignialSimulatorWriteBtn(sender); + } + + + + + private void Btn_Read_PLC_Click(object sender, EventArgs e) + { + ReadPLC_ProductInfo(); + + } + + private void Btn_Read_MES_Click(object sender, EventArgs e) + { + ReadMES_ProductInfo(); + } + + private void MisData_FormClosed(object sender, FormClosedEventArgs e) + { + //notifyIcon_MIS.Visible = false; + //this.Dispose(); + //Application.Exit(); + //System.Environment.Exit(0); + } + + private void toolStripMenuItem_Show_Click(object sender, EventArgs e) + { + //this.Show(); + //this.WindowState = FormWindowState.Normal; + //this.Activate(); + } + + private void toolStripMenuItem_Hide_Click(object sender, EventArgs e) + { + //this.Hide(); + //if (PlcChange != null) + //{ + + // Sencondform.Invoke(SecondFormClose); + // ToolStripMenuItem_VWSStatus.Checked = false; + + //} + + } + + private void toolStripMenuItem_Exit_Click(object sender, EventArgs e) + { + //this.Close(); + } + + + + public static string WorkStationNum_Now; + private void MisData_FormClosing(object sender, FormClosingEventArgs e) + { + //notifyIcon_MIS.Visible = false; + //if (MessageBox.Show("你确定要退出程序吗?", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.OK) + //{ + // notifyIcon_MIS.Visible = false; + // e.Cancel = false; + + // //判断SecondForm是否关闭 + // if (PlcChange != null) + // { + // Sencondform.BeginInvoke(SecondFormClose); + // } + + // StopServer(); + // MesWork.Mqtt.StopAsync(); + + //} + //else + //{ + // notifyIcon_MIS.Visible = true; + // e.Cancel = true; + + //} + } + + + private void ToolStripMenuItem_PrintScreen_Click(object sender, EventArgs e) + { + + //PrintMainForm_Thread(); + + } + + private void ToolStripMenuItem_Quit_Click(object sender, EventArgs e) + { + //this.Close(); + } + + private void ToolStripMenuItem_SaveLog_Click(object sender, EventArgs e) + { + //SavePLCMessage SavePlcMSG = new SavePLCMessage(); + //SavePlcMSG.SavePlcMessage_Thread(richTextBox_MessagePLC.Text); + } + + + private void ToolStripMenuItem_LockForm_Click(object sender, EventArgs e) + { + //MainFormLock = new MainAct(LockMainForm); + //MainFormUnlock = new MainAct(UnLockForm); + //MainLockConfirm LockConfirm = new MainLockConfirm(this, Sencondform); + //LockConfirm.ShowDialog(); + + + + } + + private void ToolStripMenuItem_VWSStatus_Click(object sender, EventArgs e) + { + //if (PlcChange == null) + //{ + // OpenSecondForm_Thread(); + + //} + //else + //{ + // Sencondform.BeginInvoke(SecondFormClose); + // ToolStripMenuItem_VWSStatus.Checked = false; + //} + + } + + + + + private void MToolStripMenuItem_AboutMacroinf_Click(object sender, EventArgs e) + { + //System.Diagnostics.Process.Start("https://www.meswork.com"); + } + + private void toolStripMenuItem_HVersion_Click(object sender, EventArgs e) + { + //VersionsInformation VersionForm = new VersionsInformation(); + //VersionForm.ShowDialog(); + } + + + private void MisData_Load(object sender, EventArgs e) + { + //MesWork.Mqtt.StartAsync(MqttUrl); + //MesWork.Mqtt.mqttClient.ConnectedHandler = new MqttClientConnectedHandlerDelegate(OnSubscriberConnected); + //MesWork.Mqtt.mqttClient.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(OnSubscriberDisconnected); + //MesWork.Mqtt.mqttClient.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(OnSubscriberMessageReceived); + } + + + + + + bool EToolStripMenuItem_EquipAlarm_Visiable = false; + + + + private void ToolStripMenuItem_HHelp_Click(object sender, EventArgs e) + { + //string file = Environment.CurrentDirectory + "\\MisData操作手册.pdf"; + //string str = file.Replace("\\bin\\Debug", "\\PDF\\MisData说明文档.pdf"); + //System.Diagnostics.Process.Start(file); + } + + /// + /// 程序集界面 + /// + /// + /// + private void ToolStripMenuItem_Assembly_Click(object sender, EventArgs e) + { + //AssemblyManagement AssemblyView = new AssemblyManagement(); + //AssemblyView.ShowDialog(); + } + //MesWork.OpcForm opcForm = null; + private void TSM_DebugPage_Click(object sender, EventArgs e) + { + //if (opcForm != null) + //{ + // opcForm.Close(); + // opcForm.Dispose(); + // opcForm = null; + //} + + //opcForm = new MesWork.OpcForm(IsDemoMesServer); + //opcForm.Show(); + + + } + + private void button1_Click(object sender, EventArgs e) + { + //WritePLC("71015001", 1); + //WritePLC("71015002", 1.1); + //WritePLC("71015003", 2.2); + + //WritePLC("71015004", 0); + //WritePLC("71015005", 3.3); + //WritePLC("71015006", 4.4); + + } + + private void label_OpNameList_DoubleClick(object sender, EventArgs e) + { + InitcomboBox_OpNameWebApi(); + } + + private void EToolStripMenuItem_EquipAlarm_Click(object sender, EventArgs e) + { + //try + //{ + // if (!EToolStripMenuItem_EquipAlarm.Checked) + // { + + // groupBox_WorkStationQuality.Width = 307; + // groupBox_WorkStationQuality.Height = 313; + // listView_ShowQualityData.Width = 294; + // listView_ShowQualityData.Height = 234; + // button_ReadData_Click(null, null); + // groupBox_Alarm.Visible = true; + // EToolStripMenuItem_EquipAlarm.Checked = true; + // EToolStripMenuItem_EquipAlarm_Visiable = true; + // } + // else + // { + // groupBox_Alarm.Visible = false; + + // groupBox_WorkStationQuality.Width = 307; + // groupBox_WorkStationQuality.Height = 642; + // listView_ShowQualityData.Width = 294; + // listView_ShowQualityData.Height = 572; + // button_ReadData_Click(null, null); + // EToolStripMenuItem_EquipAlarm.Checked = false; + // } + //} + //catch (Exception err) + //{ + // ApplicationLog.WriteLog(err, err.Message); + + //} + } + + } +} diff --git a/Test/MisDataWebFun.resx b/Test/MisDataWebFun.resx new file mode 100644 index 0000000..f5e0c74 --- /dev/null +++ b/Test/MisDataWebFun.resx @@ -0,0 +1,209 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 423, 5 + + + 608, 4 + + + 749, 3 + + + 37 + + + + + AAABAAEAICAAAAEAIACoEAAAFgAAACgAAAAgAAAAQAAAAAEAIAAAAAAAABAAABMLAAATCwAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMgChADIAoQIyAKEgMgChczIA + occyAKHqMgChmTIAoTwyAKEJMgChAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMgChADIAoQQyAKEvMgChdzIA + odYyAKH7MgCh/zIAof8yAKH/MgCh6jIAoacyAKFJMgChEjIAoQAyAKEAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAyAKEAMgChADIAoQoyAKE+MgChkTIA + oeoyAKH+MgCh+TIAoe0yAKH+MgCh/zIAofwyAKH3MgCh/jIAofgyAKHBMgChZDIAoR4yAKEBMgChAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAyAKEAMgChATIAoRUyAKFcMgChujIA + ofEyAKH/MgCh9DIAobcyAKFPMgChfjIAof8yAKH/MgCh5TIAoVUyAKGLMgCh4jIAofwyAKH9MgCh2TIA + oYcyAKEoMgChBTIAoQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAyAKEAMgChAjIAoSYyAKF2MgCh0DIA + ofcyAKH+MgCh8zIAof8yAKGjMgChDTIAoQAyAKFpMgCh/zIAof8yAKHhMgChHjIAoQIyAKEiMgChbjIA + ocoyAKH3MgCh/jIAoeUyAKGfMgChQTIAoQsyAKEAAAAAAAAAAAAAAAAAMgChCDIAoUEyAKGXMgCh4jIA + of4yAKH/MgChzzIAoW0yAKFoMgCh+zIAoZcyAKEAMgChADIAoWkyAKH/MgCh/zIAoeEyAKEeMgChADIA + oQAyAKEBMgChETIAoVAyAKGiMgCh8DIAof8yAKH0MgChuTIAoW0yAKEVMgChADIAoQAyAKG2MgCh7TIA + of8yAKHvMgCh7jIAofgyAKFLMgChADIAoTcyAKH1MgChlzIAoQAyAKEAMgChaTIAof8yAKH/MgCh4TIA + oR4yAKEAAAAAAAAAAAAAAAAAMgChADIAoQcyAKE4MgChijIAod8yAKH9MgCh+zIAoc4yAKFdMgChADIA + of8yAKHlMgChlDIAoToyAKGgMgCh7jIAoSwyAKEAMgChFzIAodgyAKGZMgChADIAoQAyAKFpMgCh/zIA + of8yAKHxMgChfDIAoSkyAKEBMgChAAAAAAAAAAAAAAAAADIAoQAyAKECMgChITIAoW8yAKG/MgCh/zIA + oZYyAKEAMgCh/zIAoZoyAKEBMgChADIAoZkyAKHSMgChEjIAoQAyAKEGMgChujIAoZoyAKEAMgChADIA + oWkyAKH/MgCh/zIAof0yAKH+MgCh4TIAoZIyAKFEMgChDjIAoQAyAKEAAAAAAAAAAAAAAAAAMgChADIA + oUIyAKH7MgChlzIAoQAyAKH/MgChlzIAoQAyAKEAMgChmjIAobMyAKEEMgChADIAoQAyAKGcMgChmzIA + oQAyAKEAMgChaTIAof8yAKH/MgCh4zIAoZYyAKHRMgCh+zIAofQyAKHDMgChZDIAoSIyAKEBMgChAAAA + AAAyAKEAMgChPzIAofsyAKGXMgChADIAof8yAKGXMgChADIAoQAyAKGaMgChiDIAoQAAAAAAMgChADIA + oYgyAKGaMgChADIAoQAyAKFpMgCh/zIAof8yAKHhMgChIDIAoRIyAKFeMgChqzIAoe0yAKH+MgCh3jIA + oYYyAKEqMgChADIAoQAyAKE/MgCh+zIAoZcyAKEAMgCh/zIAoZcyAKEAMgChADIAoZgyAKFtMgChAAAA + AAAyAKEAMgChXDIAoZQyAKEAMgChADIAoWkyAKH/MgCh/zIAoeEyAKEeMgChADIAoQAyAKEGMgChMDIA + oX8yAKHTMgCh+jIAoWkyAKEAMgChADIAoT8yAKH7MgChlzIAoQAyAKH/MgChlzIAoQAyAKEAMgChlTIA + oWMyAKEAAAAAADIAoQAyAKE2MgChhTIAoQAyAKEAMgChaTIAof8yAKH/MgCh4TIAoR4yAKEAAAAAAAAA + AAAyAKEAMgChATIAoRUyAKFYMgChQDIAoQAyAKEAMgChPzIAofsyAKGXMgChADIAof8yAKGXMgChADIA + oQAyAKGLMgChQTIAoQAyAKEFMgChADIAoSMyAKF4MgChADIAoQAyAKFpMgCh/zIAof8yAKHhMgChHjIA + oQAAAAAAAAAAAAAAAAAAAAAAMgChADIAoQAyAKEBMgChADIAoQAyAKE/MgCh+zIAoZcyAKEAMgCh/zIA + oZcyAKEAMgChADIAoXcyAKEkMgChBzIAoUIyAKEBMgChFjIAoWUyAKEBMgChADIAoWkyAKH/MgCh/zIA + oeEyAKEeMgChADIAoQAyAKE5MgChSTIAoQ8yAKEBMgChAAAAAAAAAAAAMgChADIAoT8yAKH7MgChlzIA + oQAyAKH/MgChlzIAoQAyAKECMgChWzIAoQ8yAKEVMgChhTIAoQoyAKEHMgChMzIAoQEyAKEAMgChaTIA + of8yAKH/MgCh4TIAoR4yAKEAMgChADIAoWkyAKH1MgChyzIAoX8yAKE4MgChBTIAoQAyAKEAMgChPzIA + ofsyAKGXMgChADIAof8yAKGXMgChADIAoQMyAKFZMgChCzIAoS4yAKHDMgChGjIAoQAAAAAAAAAAADIA + oQAyAKFpMgCh/zIAof8yAKHhMgChHjIAoQAyAKEAMgChLDIAoaEyAKHkMgCh/DIAoe8yAKGrMgChUzIA + oREyAKFBMgCh+zIAoZcyAKEAMgCh/zIAoZcyAKEAMgChBzIAoVAyAKEEMgChQTIAodoyAKEjMgChAAAA + AAAAAAAAMgChADIAoWkyAKH/MgCh/zIAoeEyAKEeMgChAAAAAAAyAKEAMgChBjIAoSAyAKFyMgChwjIA + ofMyAKH4MgCh0zIAobMyAKH9MgChljIAoQAyAKH/MgChlzIAoQAyAKEBMgChBDIAoQAyAKFKMgCh7jIA + oT0yAKEAAAAAADIAoQAyAKEAMgChbDIAof8yAKH/MgCh4TIAoR8yAKEAAAAAAAAAAAAAAAAAMgChADIA + oQEyAKELMgChRzIAoZYyAKHeMgCh/TIAof8yAKGWMgChADIAof8yAKGXMgChAAAAAAAAAAAAMgChADIA + oW0yAKH/MgChZDIAoQAyAKEEMgChHDIAoWAyAKHPMgCh/zIAof8yAKH3MgChkTIAoS8yAKELMgChADIA + oQAAAAAAAAAAAAAAAAAyAKEAMgChATIAoSAyAKF2MgCh/zIAoZYyAKEAMgCh/zIAoZcyAKEAAAAAADIA + oQAyAKEAMgChljIAof8yAKGeMgChOTIAoZEyAKHcMgCh+TIAof8yAKH/MgCh/zIAof8yAKH+MgCh6jIA + obgyAKFXMgChITIAoQEyAKEAAAAAAAAAAAAAAAAAMgChADIAoT8yAKH7MgChlzIAoQAyAKH/MgChlzIA + oQAAAAAAMgChADIAoQwyAKG9MgCh/zIAofMyAKHyMgCh/jIAof8yAKH/MgCh/zIAofoyAKH3MgCh/jIA + of8yAKH/MgCh/zIAofsyAKHbMgChmzIAoUwyAKENMgChATIAoQAyAKEAMgChPzIAofsyAKGXMgChADIA + of8yAKGXMgChATIAoRkyAKFbMgChsTIAofAyAKH/MgCh/zIAof8yAKH/MgCh/DIAoeYyAKGxMgChVTIA + oUIyAKGFMgCh1TIAofUyAKH/MgCh/zIAof8yAKH/MgCh9DIAocUyAKGDMgChMDIAoQYyAKE/MgCh+zIA + oZcyAKEAMgCh/zIAocEyAKGOMgCh2TIAofcyAKH/MgCh/zIAof8yAKH/MgCh7jIAobMyAKFwMgChJjIA + oQoyAKEAMgChADIAoQEyAKEXMgChTTIAoZsyAKHYMgCh/TIAof8yAKH/MgCh/zIAof4yAKHqMgChszIA + oZgyAKH+MgChljIAoQAyAKH/MgCh/zIAof8yAKH/MgCh/zIAof8yAKH0MgChyTIAoYEyAKE/MgChBzIA + oQAAAAAAMgChADIAoSIyAKF2MgChQjIAoRIyAKEAMgChATIAoR4yAKFjMgChrjIAoecyAKH9MgCh/zIA + of8yAKH/MgCh/zIAof8yAKGWMgChADIAof8yAKH/MgCh/zIAofkyAKHWMgChmjIAoUIyAKERMgChATIA + oQAyAKEGMgChFTIAoQMyAKEAMgChKDIAoZUyAKHHMgChxjIAoXcyAKE3MgChBzIAoQAyAKEGMgChKTIA + oXYyAKHDMgCh7jIAof4yAKH/MgCh/zIAoZYyAKEAMgChrjIAoeYyAKH+MgCh0zIAoVcyAKELMgChADIA + oQAyAKEAMgChADIAoVUyAKHAMgChkjIAoVYyAKEUMgChATIAoRYyAKFhMgChqzIAodUyAKGmMgChZTIA + oR8yAKEDMgChBDIAoS0yAKGiMgCh9DIAofUyAKHGMgChWTIAoQAyAKEGMgChKjIAoWsyAKHBMgCh3DIA + ocEyAKFwMgChJTIAoQYyAKEAMgChDDIAoTgyAKF/MgChyjIAocMyAKGUMgChMzIAoQsyAKEEMgChJjIA + oWUyAKG/MgCh0TIAoaYyAKGoMgCh1TIAodYyAKGNMgChQTIAoRAyAKEAMgChAAAAAAAyAKEAMgChADIA + oQ8yAKE8MgChkDIAoc8yAKHfMgChpDIAoVIyAKEcMgChADIAoQEyAKETMgChRzIAoZ8yAKHGMgChvzIA + oWQyAKEtMgChMzIAoY8yAKHvMgCh5zIAoa8yAKFcMgChHDIAoQMyAKEAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAADIAoQAyAKECMgChFTIAoVcyAKGaMgCh3DIAodEyAKGaMgChSDIAoQsyAKEAMgChATIA + oSUyAKGGMgCh6TIAofEyAKHhMgChtzIAoXAyAKErMgChBTIAoQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMgChADIAoQIyAKElMgChXTIAobgyAKHbMgChxTIA + oYUyAKFbMgChqzIAodEyAKHLMgChhDIAoTsyAKELMgChAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAyAKEAMgChCzIA + oTcyAKGTMgCh0zIAofAyAKG2MgChWjIAoRcyAKEBMgChAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAA/+Af//+AB//8AAD/8AAAP8AIAA8AGDABARg+AQEYD4ERGAPxMZgAcTOY + ADEzmDAxM5g8MTKIPzEgCDDxIAgwMSB4MAEgeDgBJHg+ATxAD8E8AAHxOAAAMQAAAAEAAwABABwgAQBE + BAEBwAABAEAAA+AAAA/4AAB//wAD///gD/8= + + + \ No newline at end of file diff --git a/Test/ReadThisStationProductInfo.cs b/Test/ReadThisStationProductInfo.cs new file mode 100644 index 0000000..204e766 --- /dev/null +++ b/Test/ReadThisStationProductInfo.cs @@ -0,0 +1,107 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading; +using System.Windows.Forms; +//using SystemFramework; + +namespace MisDataSaveDate +{ + public partial class MisData + { + + void ReadPLC_ProductInfo() + { + try + { + foreach (Control Tbx in this.groupBox_PLC.Controls) + { + + Thread t = new Thread(new ParameterizedThreadStart(ReadPLC_ProductInfo_Thread)); + t.Start(Tbx); + } + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, err.Message); + + } + } + + + + void ReadPLC_ProductInfo_Thread(object obj) + { + try + { + Control Tbx = (Control)obj; + if (Tbx.Name.Length < 12) return; + if (Tbx.Name.Substring(0, 8) != "Tbx_PLC_") return; + string[] TbxName_Split = Tbx.Name.Split('_'); + int TagType = Convert.ToInt32(TbxName_Split[2]); + if (Tbx.InvokeRequired ) + { + Action actionDelegate = (x) => { Tbx.Text = x; }; + Tbx.BeginInvoke(actionDelegate, DtWebApi.ReadWritePLC.ReadPLC(TagType.ToString(), WorkStationNum_Now).ToString()); + } + else + { + Tbx.Text = DtWebApi.ReadWritePLC.ReadPLC(TagType.ToString(), WorkStationNum_Now).ToString(); + } + + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, err.Message); + } + } + + + void ReadMES_ProductInfo() + { + try + { + foreach (Control Tbx in this.groupBox_MES.Controls) + { + Thread t = new Thread(new ParameterizedThreadStart(ReadMES_ProductInfo_Thread)); + t.Start(Tbx); + } + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, err.Message); + + } + } + void ReadMES_ProductInfo_Thread(object obj) + { + try + { + Control Tbx = (Control)obj; + + if (Tbx.Name.Length < 12) return; + if (Tbx.Name.Substring(0, 8) != "Tbx_MES_") return; + + string[] TbxName_Split = Tbx.Name.Split('_'); + int TagType = Convert.ToInt32(TbxName_Split[2]); + if (Tbx .InvokeRequired ) + { + Action ActionDelegate = (x) => { Tbx.Text = x; }; + Tbx.BeginInvoke(ActionDelegate, DtWebApi.ReadWritePLC.ReadPLC(TagType.ToString(), WorkStationNum_Now).ToString()); + } + else + { + Tbx.Text = DtWebApi.ReadWritePLC.ReadPLC(TagType.ToString(), WorkStationNum_Now).ToString(); + } + + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, err.Message); + } + } + + + } +} diff --git a/Test/WriteQualityValueForm.Designer.cs b/Test/WriteQualityValueForm.Designer.cs new file mode 100644 index 0000000..0c2fcb2 --- /dev/null +++ b/Test/WriteQualityValueForm.Designer.cs @@ -0,0 +1,114 @@ +namespace MisDataSaveDate +{ + partial class WriteQualityValueForm + { + /// + /// 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.label_Message = new System.Windows.Forms.Label(); + this.textBox_InputValue = new System.Windows.Forms.TextBox(); + this.button_OK = new System.Windows.Forms.Button(); + this.button_Cancle = new System.Windows.Forms.Button(); + this.comboBox_InputValue = new System.Windows.Forms.ComboBox(); + this.SuspendLayout(); + // + // label_Message + // + this.label_Message.AutoSize = true; + this.label_Message.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.label_Message.Location = new System.Drawing.Point(15, 10); + this.label_Message.Name = "label_Message"; + this.label_Message.Size = new System.Drawing.Size(41, 12); + this.label_Message.TabIndex = 0; + this.label_Message.Text = "label1"; + // + // textBox_InputValue + // + this.textBox_InputValue.Location = new System.Drawing.Point(10, 50); + this.textBox_InputValue.Name = "textBox_InputValue"; + this.textBox_InputValue.Size = new System.Drawing.Size(475, 21); + this.textBox_InputValue.TabIndex = 1; + // + // button_OK + // + this.button_OK.Location = new System.Drawing.Point(268, 81); + this.button_OK.Name = "button_OK"; + this.button_OK.Size = new System.Drawing.Size(95, 25); + this.button_OK.TabIndex = 2; + this.button_OK.Text = "OK"; + this.button_OK.UseVisualStyleBackColor = true; + this.button_OK.Click += new System.EventHandler(this.button_OK_Click); + // + // button_Cancle + // + this.button_Cancle.Location = new System.Drawing.Point(369, 81); + this.button_Cancle.Name = "button_Cancle"; + this.button_Cancle.Size = new System.Drawing.Size(95, 25); + this.button_Cancle.TabIndex = 2; + this.button_Cancle.Text = "Cancel"; + this.button_Cancle.UseVisualStyleBackColor = true; + this.button_Cancle.Click += new System.EventHandler(this.button_Cancle_Click); + // + // comboBox_InputValue + // + this.comboBox_InputValue.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; + this.comboBox_InputValue.FormattingEnabled = true; + this.comboBox_InputValue.Items.AddRange(new object[] { + "false", + "true"}); + this.comboBox_InputValue.Location = new System.Drawing.Point(10, 50); + this.comboBox_InputValue.Name = "comboBox_InputValue"; + this.comboBox_InputValue.Size = new System.Drawing.Size(475, 20); + this.comboBox_InputValue.TabIndex = 3; + // + // WriteQualityValueForm + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(494, 111); + this.Controls.Add(this.comboBox_InputValue); + this.Controls.Add(this.button_Cancle); + this.Controls.Add(this.button_OK); + this.Controls.Add(this.textBox_InputValue); + this.Controls.Add(this.label_Message); + this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow; + this.Name = "WriteQualityValueForm"; + this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; + this.Text = "Write value"; + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private System.Windows.Forms.Label label_Message; + private System.Windows.Forms.TextBox textBox_InputValue; + private System.Windows.Forms.Button button_OK; + private System.Windows.Forms.Button button_Cancle; + private System.Windows.Forms.ComboBox comboBox_InputValue; + } +} \ No newline at end of file diff --git a/Test/WriteQualityValueForm.cs b/Test/WriteQualityValueForm.cs new file mode 100644 index 0000000..25ba7f3 --- /dev/null +++ b/Test/WriteQualityValueForm.cs @@ -0,0 +1,266 @@ +using System; +using System.Windows.Forms; +//using BasicData; +using System.Text.RegularExpressions; +//using SystemFramework; +using System.Threading; +using DoWhatPlc; + +namespace MisDataSaveDate +{ + public partial class WriteQualityValueForm : Form + { + QualityDataType SelectListData; + Form MainForm; + public WriteQualityValueForm(QualityDataType SelectData,Form Mainform) + { + try + { + InitializeComponent(); + SelectListData = new QualityDataType(); + SelectListData = SelectData; + SetForm(SelectData.tagTypeID, SelectData.tagValue); + MainForm = Mainform; + + + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, err.Message); + } + } + + private void button_OK_Click(object sender, EventArgs e) + { + try + { + if (!TagTypeID_Confirm(SelectListData.tagTypeID)) return; + + this.Hide () ; + + QualityDataQueryStruct QualityStruct = new QualityDataQueryStruct(SelectListData.tagID , SelectListData.tagTypeID , comboBox_InputValue.SelectedIndex.ToString(), textBox_InputValue.Text,this); + Thread t = new Thread(new ParameterizedThreadStart(WriteQualityDataByTagID_Thread)); + t.Start(QualityStruct); + + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, err.Message); + + } + } + + + void WriteQualityDataByTagID_Thread(object obj) + { + try + { + QualityDataQueryStruct QualityStruct = (QualityDataQueryStruct)obj; + Form ThisForm = (Form)QualityStruct.tempForm; + + + if (QualityStruct.tagTypeID == 11) + { + DtWebApi.ReadWritePLC.WritePLC(QualityStruct.tagID, QualityStruct.tagValue.ToString()); + } + else + { + DtWebApi.ReadWritePLC.WritePLC(SelectListData.tagID, QualityStruct.tagValue2.ToString()); + } + MainForm.BeginInvoke (MisData.MainFormRefresh, null, null); + Action ActionDelete = () => { this.Close();this.Dispose(); }; + if(this.InvokeRequired ) + { + ThisForm.BeginInvoke(ActionDelete); + } + else + { + ActionDelete(); + } + + + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, err.Message); + + } + + } + + + + + private void button_Cancle_Click(object sender, EventArgs e) + { + this.Close(); + this.Dispose(); + } + + + + void SetForm( int TagTypeID,object TagValue) + { + try + { + switch (TagTypeID) + { + case 11://BOOL + comboBox_InputValue.Enabled = true; + comboBox_InputValue.Visible = true; + textBox_InputValue.Enabled = false; + textBox_InputValue.Visible = false; + label_Message.Text = "Data type: Boolean"; + if (Convert.ToBoolean(TagValue)) + { + comboBox_InputValue.SelectedIndex = 1; + } + else + { + comboBox_InputValue.SelectedIndex = 0; + } + + break; + + case 2://INT. + label_Message.Text = "Data type: Int16 Range from -32768 to 32767"; + comboBox_InputValue.Enabled = false; + comboBox_InputValue.Visible = false; + textBox_InputValue.Enabled = true; + textBox_InputValue.Visible = true; + textBox_InputValue.Text = TagValue.ToString(); + + break; + case 17://BYTE + label_Message.Text = "Data type: Byte Range from 0 to 255"; + comboBox_InputValue.Enabled = false; + comboBox_InputValue.Visible = false; + textBox_InputValue.Enabled = true; + textBox_InputValue.Visible = true; + textBox_InputValue.Text = TagValue.ToString(); + + break; + case 8://STRING + label_Message.Text = "Data type: String"; + comboBox_InputValue.Enabled = false; + comboBox_InputValue.Visible = false; + textBox_InputValue.Enabled = true; + textBox_InputValue.Visible = true; + textBox_InputValue.Text = TagValue.ToString(); + + break; + case 18://Word + label_Message.Text = "Data type: UInt16 Range from 0 to 65535"; + comboBox_InputValue.Enabled = false; + comboBox_InputValue.Visible = false; + textBox_InputValue.Enabled = true; + textBox_InputValue.Visible = true; + textBox_InputValue.Text = TagValue.ToString(); + + break; + case 4://real + label_Message.Text = "Data type: Single Range from -3.402823E+38 to 3.402823E+38"; + comboBox_InputValue.Enabled = false; + comboBox_InputValue.Visible = false; + textBox_InputValue.Enabled = true; + textBox_InputValue.Visible = true; + textBox_InputValue.Text = TagValue.ToString(); + + break; + default://Unknow + label_Message.Text = "Data type: Unknow"; + comboBox_InputValue.Enabled = false; + comboBox_InputValue.Visible = false; + textBox_InputValue.Enabled = true; + textBox_InputValue.Visible = true; + textBox_InputValue.Text = TagValue.ToString(); + + break; + + } + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, err.Message); + + } + + + } + + bool TagTypeID_Confirm( int TagTypeID) + { + try + { + switch (TagTypeID) + { + + + case 2://INT + //TextBox存在非数字字符 报错 + if (!Regex.IsMatch(textBox_InputValue.Text, @"^[-]?\d*$")) + { + MessageBox.Show("输入不是整数!"); + return false; + } + if (textBox_InputValue.Text.Length > 9) + { + MessageBox.Show("输入数据不在范围内"); + return false; + } + break; + case 17://BYTE + //TextBox存在非数字字符 报错 + if (!Regex.IsMatch(textBox_InputValue.Text, @"^[-]?\d*$")) + { + MessageBox.Show("输入不是整数!"); + return false; + } + if (Convert.ToInt32(textBox_InputValue.Text.Trim()) > 255) + { + MessageBox.Show("输入数据不在范围内"); + return false; + } + break; + case 8://STRING + + break; + case 18://Word + //TextBox存在非数字字符 报错 + if (!Regex.IsMatch(textBox_InputValue.Text, @"^[-]?\d*$")) + { + MessageBox.Show("输入不是整数!"); + return false; + } + if (textBox_InputValue.Text.Trim().Length > 4) + { + MessageBox.Show("输入数据不在范围内"); + return false; + } + break; + case 4://real + //TextBox存在非数字字符 报错 + //TextBox存在非数字字符 报错 + if (!Regex.IsMatch(textBox_InputValue.Text, @"^-?\d+\.?\d*$")) + { + MessageBox.Show("输入不是实数!"); + return false; + } + + break; + default: + break; + + } + + return true; + } + catch (Exception err) + { + //ApplicationLog.WriteLog(err, err.Message); + return true; + } + } + + } +} diff --git a/Test/WriteQualityValueForm.resx b/Test/WriteQualityValueForm.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/Test/WriteQualityValueForm.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/dll_common/AsyncIO.dll b/dll_common/AsyncIO.dll new file mode 100644 index 0000000..5bfd21b Binary files /dev/null and b/dll_common/AsyncIO.dll differ diff --git a/dll_common/BasicData.dll b/dll_common/BasicData.dll new file mode 100644 index 0000000..8dfe09b Binary files /dev/null and b/dll_common/BasicData.dll differ diff --git a/dll_common/BasicData.pdb b/dll_common/BasicData.pdb new file mode 100644 index 0000000..e432017 Binary files /dev/null and b/dll_common/BasicData.pdb differ diff --git a/dll_common/BouncyCastle.Crypto.dll b/dll_common/BouncyCastle.Crypto.dll new file mode 100644 index 0000000..0310983 Binary files /dev/null and b/dll_common/BouncyCastle.Crypto.dll differ diff --git a/dll_common/ConLink.dll b/dll_common/ConLink.dll new file mode 100644 index 0000000..6ccb558 Binary files /dev/null and b/dll_common/ConLink.dll differ diff --git a/dll_common/DataLinkMesWork.dll b/dll_common/DataLinkMesWork.dll new file mode 100644 index 0000000..57fcd25 Binary files /dev/null and b/dll_common/DataLinkMesWork.dll differ diff --git a/dll_common/ICSharpCode.SharpZipLib.dll b/dll_common/ICSharpCode.SharpZipLib.dll new file mode 100644 index 0000000..84e8c68 Binary files /dev/null and b/dll_common/ICSharpCode.SharpZipLib.dll differ diff --git a/dll_common/MQTT.dll b/dll_common/MQTT.dll new file mode 100644 index 0000000..c61c4f0 Binary files /dev/null and b/dll_common/MQTT.dll differ diff --git a/dll_common/MQTTnet.Extensions.ManagedClient.dll b/dll_common/MQTTnet.Extensions.ManagedClient.dll new file mode 100644 index 0000000..99035f6 Binary files /dev/null and b/dll_common/MQTTnet.Extensions.ManagedClient.dll differ diff --git a/dll_common/MQTTnet.dll b/dll_common/MQTTnet.dll new file mode 100644 index 0000000..2951433 Binary files /dev/null and b/dll_common/MQTTnet.dll differ diff --git a/dll_common/MesControl.dll b/dll_common/MesControl.dll new file mode 100644 index 0000000..cd3960b Binary files /dev/null and b/dll_common/MesControl.dll differ diff --git a/dll_common/MesControl.pdb b/dll_common/MesControl.pdb new file mode 100644 index 0000000..53210df Binary files /dev/null and b/dll_common/MesControl.pdb differ diff --git a/dll_common/MesWork.DeviceDriver.dll b/dll_common/MesWork.DeviceDriver.dll new file mode 100644 index 0000000..a6ec60f Binary files /dev/null and b/dll_common/MesWork.DeviceDriver.dll differ diff --git a/dll_common/MesWork.DeviceDriver.pdb b/dll_common/MesWork.DeviceDriver.pdb new file mode 100644 index 0000000..6ebff64 Binary files /dev/null and b/dll_common/MesWork.DeviceDriver.pdb differ diff --git a/dll_common/MesWork.PLC.dll b/dll_common/MesWork.PLC.dll new file mode 100644 index 0000000..3399040 Binary files /dev/null and b/dll_common/MesWork.PLC.dll differ diff --git a/dll_common/MesWork.PLC.pdb b/dll_common/MesWork.PLC.pdb new file mode 100644 index 0000000..af5273f Binary files /dev/null and b/dll_common/MesWork.PLC.pdb differ diff --git a/dll_common/MesWork.exe.config b/dll_common/MesWork.exe.config new file mode 100644 index 0000000..20f2007 --- /dev/null +++ b/dll_common/MesWork.exe.config @@ -0,0 +1,64 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/dll_common/MesWork.pdb b/dll_common/MesWork.pdb new file mode 100644 index 0000000..fa433ed Binary files /dev/null and b/dll_common/MesWork.pdb differ diff --git a/dll_common/Monitor.MesWork.dll b/dll_common/Monitor.MesWork.dll new file mode 100644 index 0000000..1874ca5 Binary files /dev/null and b/dll_common/Monitor.MesWork.dll differ diff --git a/dll_common/Monitor.MesWork.pdb b/dll_common/Monitor.MesWork.pdb new file mode 100644 index 0000000..a2c1b3f Binary files /dev/null and b/dll_common/Monitor.MesWork.pdb differ diff --git a/dll_common/Monitor.MesWork.xml b/dll_common/Monitor.MesWork.xml new file mode 100644 index 0000000..f978604 --- /dev/null +++ b/dll_common/Monitor.MesWork.xml @@ -0,0 +1,2860 @@ + + + + Monitor.MesWork + + + + + AlarmListView 的摘要说明。 + + + + + 从OnDataChange发送int tagID, int tagValue到处理程序 + private void OnDataChange(int tagID, int tagValue) + + + + + + + 从OnDataChange发送int tagID, int tagValue到处理程序 + private void OnDataChange(int tagID, int tagValue) + + + + + 必需的设计器变量。 + + + + + 当时发生的报警总行数 + + + + + + + + + + 清理所有正在使用的资源。 + + + + + 设计器支持所需的方法 - 不要使用代码编辑器 + 修改此方法的内容。 + + + + + 报警到达 + + + + + 报警到达 + + + + + 报警解除 + + + + + 报警解除 + + + + + 报警确认 + + + + + 报警确认 + + + + + 报警过滤条件 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 报警过滤条件 + + + + + 从系统获得 + =null 时,初始化时显示全部报警 + =AlarmItemSelect,初始化时显示AlarmItemSelect条件报警 + + + + + + + + + + 报警到达文字颜色 + + + + + 报警到达文本底色 + + + + + 报警解除文字颜色 + + + + + 报警解除文本底色 + + + + + 报警确认文字颜色 + + + + + 报警确认文本底色 + + + + + 初始化报警显示 + + + + + 报警控件,监控值变化时,图形重绘 + + + + + + 增加TagKey + + + + + =true,调Gif;false不调Gif + + + + + Gif图像 + + + + + Gif图像 + + + + + IsRotation =0不调用Gif;=1调用Gif TagValueType + + + + + IsRotation =0不调用Gif;=1调用Gif + + + + + Tag位置0时颜色 1 + + + + + Tag位置1时颜色 2 + + + + + Tag位置2时颜色 4 + + + + + Tag位置3时颜色 8 + + + + + Tag位置4时颜色 16 + + + + + Tag位置5时颜色 32 + + + + + Tag位置6时颜色 64 + + + + + Tag位置7时颜色 128 + + + + + 设置Tag位置0时颜色 + + + + + 设置Tag位置1时颜色 + + + + + 设置Tag位置2时颜色 + + + + + 设置Tag位置3时颜色 + + + + + 设置Tag位置4时颜色 + + + + + 设置Tag位置5时颜色 + + + + + 设置Tag位置6时颜色 + + + + + 设置Tag位置7时颜色 + + + + + TagKey 显示选项 + + + + + TagKey 显示选项 + + + + + OpName + 工位名称 + + + + + OpName + 工位名称 + + + + + 序号 + + + + + 序号 + + + + + 是否保存到数据库 + + + + + LineColor设置外园线颜色 + + + + + Tag位置1时颜色 + + + + + Tag位置0时颜色 + + + + + 变量值 + + + + + 变量值 + + + + + TagBit变量测试位 + + + + + Tag位置1时颜色 + + + + + Tag位置0时颜色 + + + + + TagBit变量测试位 + + + + + LineColor设置外园线颜色 + + + + + 是否保存到数据库 + + + + + + + + + + + + + + + 绘制图形 + + + + + + 正常绘制 + + + + + + 显示Gif + + + + + + 增加TagKey + + + + + =true,调Gif;false不调Gif + + + + + Gif图像 + + + + + IsRotation =0不调用Gif;=1调用Gif TagValueType + + + + + IsRotation =0不调用Gif;=1调用Gif + + + + + Tag位置0时颜色 1 + + + + + Tag位置1时颜色 2 + + + + + Tag位置2时颜色 4 + + + + + Tag位置3时颜色 8 + + + + + Tag位置4时颜色 16 + + + + + Tag位置5时颜色 32 + + + + + Tag位置6时颜色 64 + + + + + Tag位置7时颜色 128 + + + + + 设置Tag位置0时颜色 + + + + + 设置Tag位置1时颜色 + + + + + 设置Tag位置2时颜色 + + + + + 设置Tag位置3时颜色 + + + + + 设置Tag位置4时颜色 + + + + + 设置Tag位置5时颜色 + + + + + 设置Tag位置6时颜色 + + + + + 设置Tag位置7时颜色 + + + + + TagKey 显示选项 + + + + + TagKey 显示选项 + + + + + OpName + 工位名称 + + + + + OpName + 工位名称 + + + + + 序号 + + + + + 序号 + + + + + 是否保存到数据库 + + + + + LineColor设置外园线颜色 + + + + + Tag位置1时颜色 + + + + + Tag位置0时颜色 + + + + + 变量值 + + + + + 变量值 + + + + + TagBit变量测试位 + + + + + Tag位置1时颜色 + + + + + Tag位置0时颜色 + + + + + TagBit变量测试位 + + + + + LineColor设置外园线颜色 + + + + + 是否保存到数据库 + + + + + + + + + + + + + + + 绘制图形 + + + + + + 正常绘制 + + + + + + 显示Gif + + + + + + PlcLinkStatus 的摘要说明。 + + + + + 显示PLC连接状态 + + + + + + PLC连接正常时图形 + + + + + PLC连接正常时图形 + + + + + PLC连接不正常时图形 + + + + + PLC连接不正常时图形 + + + + + + + + + + 清理所有正在使用的资源。 + + + + + 设计器支持所需的方法 - 不要使用代码编辑器 + 修改此方法的内容。 + + + + + PlcLinkStatusWork 的摘要说明。 + + + + + OpName + 工位名称 + + + + + OpName + 工位名称 + + + + + + + + + + 根据变量是否正确,显示通讯状态 通讯数据交换 + + + + + + 通讯正常 + + + + + 通讯失败 + + + + + 清理所有正在使用的资源。 + + + + + 设计器支持所需的方法 - 不要使用代码编辑器 + 修改此方法的内容。 + + + + + PlcLinkStatusWork 的摘要说明。 + + + + + OpName + 工位名称 + + + + + OpName + 工位名称 + + + + + + + + + + 根据变量是否正确,显示通讯状态 通讯数据交换 + + + + + + 通讯正常 + + + + + 通讯失败 + + + + + 清理所有正在使用的资源。 + + + + + 设计器支持所需的方法 - 不要使用代码编辑器 + 修改此方法的内容。 + + + + + Tag位置1时颜色 + + + + + OpName + 工位名称 + + + + + OpName + 工位名称 + + + + + 变量类型 + + + + + 变量类型 + + + + + 是否保存到数据库 + + + + + LineColor设置外园线颜色 + + + + + Tag位置1时颜色 + + + + + Tag位置0时颜色 + + + + + 变量值 + + + + + 变量值 + + + + + TagBit变量测试位 + + + + + Tag位置1时颜色 + + + + + Tag位置0时颜色 + + + + + TagBit变量测试位 + + + + + LineColor设置外园线颜色 + + + + + 是否保存到数据库 + + + + + + + + + + 显示机床状态 + + + + + + 绘制图形 + + + + + + Tag位置1时颜色 + + + + + OpName + 工位名称 + + + + + OpName + 工位名称 + + + + + 是否保存到数据库 + + + + + LineColor设置外园线颜色 + + + + + Tag位置1时颜色 + + + + + Tag位置0时颜色 + + + + + 变量值 + + + + + 变量值 + + + + + TagBit变量测试位 + + + + + Tag位置1时颜色 + + + + + Tag位置0时颜色 + + + + + TagBit变量测试位 + + + + + LineColor设置外园线颜色 + + + + + 是否保存到数据库 + + + + + + + + + + 显示机床状态 + + + + + + 绘制图形 + + + + + + 增加TagKey + + + + + TagKey 显示选项 + + + + + TagKey 显示选项 + + + + + OpName + 工位名称 + + + + + OpName + 工位名称 + + + + + 是否保存到数据库 + + + + + LineColor设置外园线颜色 + + + + + Tag位置1时颜色 + + + + + Tag位置0时颜色 + + + + + 变量值 + + + + + 变量值 + + + + + TagBit变量测试位 + + + + + Tag位置1时颜色 + + + + + Tag位置0时颜色 + + + + + TagBit变量测试位 + + + + + LineColor设置外园线颜色 + + + + + 是否保存到数据库 + + + + + + + + + + 显示到位信号 + + + + + + 绘制图形 + + + + + + 发动机工位在线显示 + + + + + OpName + 工位名称 + + + + + 是否保存到数据库 + + + + + LineColor设置外园线颜色 + + + + + Tag位置1时颜色 + + + + + Tag位置0时颜色 + + + + + + + + + + 显示托盘状态 + 1 有托盘(黄色) + 0 无托盘(灰色) + + + + + 显示托盘状态 + 1 有托盘(黄色) + 0 无托盘(灰色) + + + + + 发动机号 + + + + + 发动机号 + + + + + Tag位置1时颜色 + + + + + Tag位置0时颜色 + + + + + LineColor设置外园线颜色 + + + + + 是否保存到数据库 + + + + + OpName + 工位名称 + + + + + 是否进行具体发动机号追踪 + + + + + 是否进行具体发动机号追踪 + + + + + 具体发动机号追踪发动机号 + 发动机号 + + + + + 具体发动机号追踪 + 发动机号 + + + + + 具体发动机号追踪 + Tag位置0时颜色 + + + + + 具体发动机号追踪 + Tag位置1时颜色 + + + + + + + + + + 发动机号的变化,给本控件的发动机号赋值 + 确定被追踪的发动机号 + + + + + + + 发动机号动态追踪设定 + + + + + + + 显示被追踪的发动机 + + + + + 显示托盘状态 + 1 有托盘(黄色) + 0 无托盘(灰色) + + + + + + 显示托盘状态 + 1 有托盘(黄色) + 0 无托盘(灰色) + + + + + 托盘到位 + + + + + + + 绘制图形 + + + + + + 发动机工位在线显示 + + + + + 当鼠标在上方时出现工件编号 + + + + + Tag位置0时颜色 1 + + + + + Tag位置1时颜色 2 + + + + + Tag位置2时颜色 4 + + + + + Tag位置3时颜色 8 + + + + + Tag位置4时颜色 16 + + + + + Tag位置5时颜色 32 + + + + + Tag位置6时颜色 64 + + + + + Tag位置7时颜色 128 + + + + + 设置Tag位置0时颜色 + + + + + 设置Tag位置1时颜色 + + + + + 设置Tag位置2时颜色 + + + + + 设置Tag位置3时颜色 + + + + + 设置Tag位置4时颜色 + + + + + 设置Tag位置5时颜色 + + + + + 设置Tag位置6时颜色 + + + + + 设置Tag位置7时颜色 + + + + + 变量值 + + + + + 变量值 + + + + + OpName + 工位名称 + + + + + 是否保存到数据库 + + + + + LineColor设置外园线颜色 + + + + + Tag位置1时颜色 + + + + + Tag位置0时颜色 + + + + + + + + + + 显示托盘状态 + 1 有托盘(黄色) + 0 无托盘(灰色) + + + + + 显示托盘状态 + 1 有托盘(黄色) + 0 无托盘(灰色) + + + + + 发动机号 + + + + + 发动机号 + + + + + Tag位置1时颜色 + + + + + Tag位置0时颜色 + + + + + LineColor设置外园线颜色 + + + + + 是否保存到数据库 + + + + + OpName + 工位名称 + + + + + 是否进行具体发动机号追踪 + + + + + 是否进行具体发动机号追踪 + + + + + 具体发动机号追踪发动机号 + 发动机号 + + + + + 具体发动机号追踪 + 发动机号 + + + + + 具体发动机号追踪 + Tag位置0时颜色 + + + + + 具体发动机号追踪 + Tag位置1时颜色 + + + + + + + + + + 发动机号的变化,给本控件的发动机号赋值 + 确定被追踪的发动机号 + + + + + + + 发动机号动态追踪设定 + + + + + + + 显示被追踪的发动机 + + + + + 显示托盘状态 + 1 有托盘(黄色) + 0 无托盘(灰色) + + + + + + 显示托盘状态 + 1 有托盘(黄色) + 0 无托盘(灰色) + + + + + 托盘到位 + + + + + + + 绘制图形 + + + + + + UserControlButton 的摘要说明。 + + + + + 发动机号 + + + + + 发动机号 + + + + + 当鼠标在上方时出现发动机号 + + + + + + + + + + Button 文本 + + + + + Button 文本 + + + + + OpName + 工位名称 + + + + + OpName + 工位名称 + + + + + Button 文本 + + + + + Button 文本 + + + + + + + + + + 清理所有正在使用的资源。 + + + + + 设计器支持所需的方法 - 不要使用代码编辑器 + 修改此方法的内容。 + + + + + + + + + + + UserControlButton 的摘要说明。 + + + + + 机床状态 + + + + + 机床状态 + + + + + 工件编号 + + + + + 工件编号 + + + + + 当鼠标在上方时出现工件编号 + + + + + + + + + + Button 文本 + + + + + Button 文本 + + + + + OpName + 工位名称 + + + + + OpName + 工位名称 + + + + + Button 文本 + + + + + Button 文本 + + + + + + + + + + 机床状态 + + + + + + + 清理所有正在使用的资源。 + + + + + 设计器支持所需的方法 - 不要使用代码编辑器 + 修改此方法的内容。 + + + + + + + + + + + UserControlLable11 的摘要说明。 + + + + + 必需的设计器变量。 + + + + + 变量值 + + + + + 变量值 + + + + + 变量类型 + + + + + 变量类型 + + + + + LableText 变量值 + + + + + LableText 变量值 + + + + + + + + + + + + + + + 清理所有正在使用的资源。 + + + + + 设计器支持所需的方法 - 不要使用代码编辑器 + 修改此方法的内容。 + + + + + + + + + + + UserControlLable11 的摘要说明。 + + + + + 必需的设计器变量。 + + + + + TagNameID名称 + + + + + LableText 变量值 + + + + + LableText 变量值 + + + + + + + + + + + + + + + 清理所有正在使用的资源。 + + + + + 设计器支持所需的方法 - 不要使用代码编辑器 + 修改此方法的内容。 + + + + + + + + + + + UserControlButton 的摘要说明。 + + + + + 发动机号 + + + + + 发动机号 + + + + + 当鼠标在上方时出现发动机号 + + + + + + + + + + Button 文本 + + + + + Button 文本 + + + + + OpName + 工位名称 + + + + + OpName + 工位名称 + + + + + Button 文本 + + + + + Button 文本 + + + + + + + + + + 清理所有正在使用的资源。 + + + + + 设计器支持所需的方法 - 不要使用代码编辑器 + 修改此方法的内容。 + + + + + + + + + + + Tag位置1时颜色 + + + + + OpName + 工位名称 + + + + + OpName + 工位名称 + + + + + 是否保存到数据库 + + + + + LineColor设置外园线颜色 + + + + + Tag位置1时颜色 + + + + + Tag位置0时颜色 + + + + + 变量值 + + + + + 变量值 + + + + + TagBit变量测试位 + + + + + Tag位置1时颜色 + + + + + Tag位置0时颜色 + + + + + TagBit变量测试位 + + + + + LineColor设置外园线颜色 + + + + + 是否保存到数据库 + + + + + + + + + + 显示心跳控件 + + + + + + 绘制图形 + + + + + + 增加TagKey + + + + + Tag位置0时颜色 1 + + + + + Tag位置1时颜色 2 + + + + + Tag位置2时颜色 4 + + + + + Tag位置3时颜色 8 + + + + + Tag位置4时颜色 16 + + + + + Tag位置5时颜色 32 + + + + + Tag位置6时颜色 64 + + + + + Tag位置7时颜色 128 + + + + + 设置Tag位置0时颜色 + + + + + 设置Tag位置1时颜色 + + + + + 设置Tag位置2时颜色 + + + + + 设置Tag位置3时颜色 + + + + + 设置Tag位置4时颜色 + + + + + 设置Tag位置5时颜色 + + + + + 设置Tag位置6时颜色 + + + + + 设置Tag位置7时颜色 + + + + + TagKey 显示选项 + + + + + TagKey 显示选项 + + + + + OpName + 工位名称 + + + + + OpName + 工位名称 + + + + + 序号 + + + + + 序号 + + + + + 是否保存到数据库 + + + + + LineColor设置外园线颜色 + + + + + Tag位置1时颜色 + + + + + Tag位置0时颜色 + + + + + 变量值 + + + + + 变量值 + + + + + TagBit变量测试位 + + + + + Tag位置1时颜色 + + + + + Tag位置0时颜色 + + + + + TagBit变量测试位 + + + + + LineColor设置外园线颜色 + + + + + 是否保存到数据库 + + + + + + + + + + 绘制图形 + + + + + + 水平方式显示工件编号。 + + + + + 机床状态 + + + + + 机床状态 + + + + + 工件编号 + + + + + 工件编号 + + + + + 当鼠标在上方时出现工件编号 + + + + + + + + + + Button 文本 + + + + + Button 文本 + + + + + OpName + 工位名称 + + + + + OpName + 工位名称 + + + + + Button 文本 + + + + + Button 文本 + + + + + + + + + + + + + + + + 清理所有正在使用的资源。 + + + + + 设计器支持所需的方法 - 不要使用代码编辑器 + 修改此方法的内容。 + + + + + + + + + + + 垂直方式显示工件编号。 + + + + + Tag位置0时颜色 1 + + + + + Tag位置1时颜色 2 + + + + + Tag位置2时颜色 4 + + + + + Tag位置3时颜色 8 + + + + + Tag位置4时颜色 16 + + + + + Tag位置5时颜色 32 + + + + + Tag位置6时颜色 64 + + + + + Tag位置7时颜色 128 + + + + + 设置Tag位置0时颜色 + + + + + 设置Tag位置1时颜色 + + + + + 设置Tag位置2时颜色 + + + + + 设置Tag位置3时颜色 + + + + + 设置Tag位置4时颜色 + + + + + 设置Tag位置5时颜色 + + + + + 设置Tag位置6时颜色 + + + + + 设置Tag位置7时颜色 + + + + + TagKey 显示选项 + + + + + TagKey 显示选项 + + + + + 变量值 + + + + + 机床状态 + + + + + 机床状态 + + + + + 工件编号 + + + + + 工件编号 + + + + + 当鼠标在上方时出现工件编号 + + + + + + + + + + Button 文本 + + + + + Button 文本 + + + + + OpName + 工位名称 + + + + + OpName + 工位名称 + + + + + Button 文本 + + + + + Button 文本 + + + + + Button 文本颜色代码 + + + + + + + + + + 显示工件编号 + + + + + + 清理所有正在使用的资源。 + + + + + 设计器支持所需的方法 - 不要使用代码编辑器 + 修改此方法的内容。 + + + + + + + + + + + UserControlButton 的摘要说明。 + + + + + Tag位置0时颜色 1 + + + + + Tag位置1时颜色 2 + + + + + Tag位置2时颜色 4 + + + + + Tag位置3时颜色 8 + + + + + Tag位置4时颜色 16 + + + + + Tag位置5时颜色 32 + + + + + Tag位置6时颜色 64 + + + + + Tag位置7时颜色 128 + + + + + 设置Tag位置0时颜色 + + + + + 设置Tag位置1时颜色 + + + + + 设置Tag位置2时颜色 + + + + + 设置Tag位置3时颜色 + + + + + 设置Tag位置4时颜色 + + + + + 设置Tag位置5时颜色 + + + + + 设置Tag位置6时颜色 + + + + + 设置Tag位置7时颜色 + + + + + TagKey 显示选项 + + + + + TagKey 显示选项 + + + + + 变量值 + + + + + 机床状态 + + + + + 机床状态 + + + + + 工件编号 + + + + + 工件编号 + + + + + 当鼠标在上方时出现工件编号 + + + + + + + + + + Button 文本 + + + + + Button 文本 + + + + + OpName + 工位名称 + + + + + OpName + 工位名称 + + + + + Button 文本 + + + + + Button 文本 + + + + + Button 文本颜色代码 + + + + + + + + + + + + + + + + 清理所有正在使用的资源。 + + + + + 设计器支持所需的方法 - 不要使用代码编辑器 + 修改此方法的内容。 + + + + + + + + + + + UserControlLable11 的摘要说明。 + + + + + 必需的设计器变量。 + + + + + TagNameID名称 + + + + + TagNameID名称 + + + + + TagNameID名称 + + + + + TagNameID名称 + + + + + LableText 变量值 + + + + + LableText 变量值 + + + + + + + + + + + + + + + 清理所有正在使用的资源。 + + + + + 设计器支持所需的方法 - 不要使用代码编辑器 + 修改此方法的内容。 + + + + + + + + + + + 增加TagKey + + + + + TagKey 显示选项 + + + + + TagKey 显示选项 + + + + + OpName + 工位名称 + + + + + OpName + 工位名称 + + + + + 是否保存到数据库 + + + + + LineColor设置外园线颜色 + + + + + Tag位置1时颜色 + + + + + Tag位置0时颜色 + + + + + 变量值 + + + + + 变量值 + + + + + TagBit变量测试位 + + + + + Tag位置1时颜色 + + + + + Tag位置0时颜色 + + + + + TagBit变量测试位 + + + + + LineColor设置外园线颜色 + + + + + 是否保存到数据库 + + + + + + + + + + 绘制图形 + + + + + + 一个强类型的资源类,用于查找本地化的字符串等。 + + + + + 返回此类使用的缓存的 ResourceManager 实例。 + + + + + 重写当前线程的 CurrentUICulture 属性 + 重写当前线程的 CurrentUICulture 属性。 + + + + + 查找 System.Drawing.Bitmap 类型的本地化资源。 + + + + + 查找 System.Drawing.Bitmap 类型的本地化资源。 + + + + + 查找 System.Drawing.Bitmap 类型的本地化资源。 + + + + diff --git a/dll_common/NPOI.OOXML.dll b/dll_common/NPOI.OOXML.dll new file mode 100644 index 0000000..031d41d Binary files /dev/null and b/dll_common/NPOI.OOXML.dll differ diff --git a/dll_common/NPOI.OpenXml4Net.dll b/dll_common/NPOI.OpenXml4Net.dll new file mode 100644 index 0000000..8da4ac2 Binary files /dev/null and b/dll_common/NPOI.OpenXml4Net.dll differ diff --git a/dll_common/NPOI.OpenXmlFormats.dll b/dll_common/NPOI.OpenXmlFormats.dll new file mode 100644 index 0000000..4a8f87b Binary files /dev/null and b/dll_common/NPOI.OpenXmlFormats.dll differ diff --git a/dll_common/NPOI.dll b/dll_common/NPOI.dll new file mode 100644 index 0000000..1a500e9 Binary files /dev/null and b/dll_common/NPOI.dll differ diff --git a/dll_common/NetMQ.dll b/dll_common/NetMQ.dll new file mode 100644 index 0000000..e649c0e Binary files /dev/null and b/dll_common/NetMQ.dll differ diff --git a/dll_common/Newtonsoft.Json.7z b/dll_common/Newtonsoft.Json.7z new file mode 100644 index 0000000..ae3ba01 Binary files /dev/null and b/dll_common/Newtonsoft.Json.7z differ diff --git a/dll_common/Newtonsoft.Json.dll b/dll_common/Newtonsoft.Json.dll new file mode 100644 index 0000000..7af125a Binary files /dev/null and b/dll_common/Newtonsoft.Json.dll differ diff --git a/dll_common/Opc.Ua.Client.dll b/dll_common/Opc.Ua.Client.dll new file mode 100644 index 0000000..8874d8f Binary files /dev/null and b/dll_common/Opc.Ua.Client.dll differ diff --git a/dll_common/Opc.Ua.Configuration.dll b/dll_common/Opc.Ua.Configuration.dll new file mode 100644 index 0000000..b3f3970 Binary files /dev/null and b/dll_common/Opc.Ua.Configuration.dll differ diff --git a/dll_common/Opc.Ua.Core.dll b/dll_common/Opc.Ua.Core.dll new file mode 100644 index 0000000..ee01d0d Binary files /dev/null and b/dll_common/Opc.Ua.Core.dll differ diff --git a/dll_common/OpcUaHelper.dll b/dll_common/OpcUaHelper.dll new file mode 100644 index 0000000..e95e509 Binary files /dev/null and b/dll_common/OpcUaHelper.dll differ diff --git a/dll_common/OpcUaHelper.pdb b/dll_common/OpcUaHelper.pdb new file mode 100644 index 0000000..dee6394 Binary files /dev/null and b/dll_common/OpcUaHelper.pdb differ diff --git a/dll_common/OpcUaHelper.xml b/dll_common/OpcUaHelper.xml new file mode 100644 index 0000000..a7977ad --- /dev/null +++ b/dll_common/OpcUaHelper.xml @@ -0,0 +1,1281 @@ + + + + OpcUaHelper + + + + + Defines numerous re-useable utility functions. + + + + + Handles an exception. + + + + + Returns the application icon. + + + + + Gets the display text for the access level attribute. + + The access level. + The access level formatted as a string. + + + + Gets the display text for the event notifier attribute. + + The event notifier. + The event notifier formatted as a string. + + + + Gets the display text for the value rank attribute. + + The value rank. + The value rank formatted as a string. + + + + Gets the display text for the specified attribute. + + The currently active session. + The id of the attribute. + The value of the attribute. + The attribute formatted as a string. + + + + Browses the address space and returns the references found. + + The session. + The set of browse operations to perform. + if set to true a exception will be thrown on an error. + + The references found. Null if an error occurred. + + + + + Browses the address space and returns the references found. + + + + + Browses the address space and returns the references found. + + The session. + The NodeId for the starting node. + if set to true a exception will be thrown on an error. + + The references found. Null if an error occurred. + + + + + Browses the address space and returns the references found. + + + + + Browses the address space and returns all of the supertypes of the specified type node. + + The session. + The NodeId for a type node in the address space. + if set to true a exception will be thrown on an error. + + The references found. Null if an error occurred. + + + + + Returns the node ids for a set of relative paths. + + An open session with the server to use. + The starting node for the relative paths. + The namespace URIs referenced by the relative paths. + The relative paths. + A collection of local nodes. + + + + Finds the type of the event for the notification. + + The monitored item. + The notification. + The NodeId of the EventType. + + + + Constructs an event object from a notification. + + The session. + The monitored item that produced the notification. + The notification. + The known event types. + Mapping between event types and known event types. + + The event object. Null if the notification is not a valid event type. + + + + + Collects the instance declarations for a type. + + + + + Collects the instance declarations for a type. + + + + + Collects the fields for the instance node. + + + + + Finds the targets for the specified reference. + + + + + Finds the targets for the specified reference. + + + + + Collects the fields for the type. + + The session. + The type id. + The fields. + The node id for the declaration of the field. + + + + Collects the fields for the instance. + + The session. + The instance id. + The fields. + The node id for the declaration of the field. + + + + Collects the fields for the instance node. + + The session. + The node id. + The parent path. + The event fields. + The node id for the declaration of the field. + The table of found nodes. + + + + Determines whether the specified select clause contains the browse path. + + The select clause. + The browse path. + + true if the specified select clause contains path; otherwise, false. + + + + + Prompts the user to specify a host name and discovers the servers. + + + + + Creates an empty form. + + + + + Shows the dialog. + + The client applicatio configuration. + The selected endpoint url + + + + Shows the dialog. + + The client applicatio configuration. + The default host name. + The selected endpoint url + + + + Gets the endpoints for the host. + + Name of the host. + + + + Required designer variable. + + + + + Clean up any resources being used. + + true if managed resources should be disposed; otherwise, false. + + + + Required method for Designer support - do not modify + the contents of this method with the code editor. + + + + + 一个浏览OPC服务器节点的窗口类 + + + + + 允许自己输入服务器地址的实例化 + + + + + 固定地址且不允许更改的实例化 + + + + + Opc客户端的核心类 + + + + + 初始化 + + + + + 连接服务器结束后马上浏览根节点 + + + + + + + OPC 客户端的状态变化后的消息提醒 + + + + + + + 0:NodeClass 1:Value 2:AccessLevel 3:DisplayName 4:Description + + + + + + + 读取一个节点的指定属性 + + + + + + + + Populates the branch in the tree view. + + The NodeId of the Node to browse. + The node collect to populate. + + + + 点击了节点名称前的内容进行复制 + + + + + + + Required designer variable. + + + + + Clean up any resources being used. + + true if managed resources should be disposed; otherwise, false. + + + + Required method for Designer support - do not modify + the contents of this method with the code editor. + + + + + Required designer variable. + + + + + Clean up any resources being used. + + true if managed resources should be disposed; otherwise, false. + + + + Required method for Designer support - do not modify + the contents of this method with the code editor. + + + + + 无闪烁的树节点控件,结果还是没有实现 + + + + + 实例化一个新的控件 + + + + + 通知 + + + + + + A dialog that displays an exception trace in an HTML page. + + + + + Initializes a new instance of the class. + + + + + Replaces all special characters in the message. + + + + + Displays the exception in a dialog. + + + + + Display the exception in the dialog. + + + + + Required designer variable. + + + + + Clean up any resources being used. + + true if managed resources should be disposed; otherwise, false. + + + + Required method for Designer support - do not modify + the contents of this method with the code editor. + + + + + Stores a type declaration retrieved from a server. + + + + + The node if for the type. + + + + + The fully inhierited list of instance declarations for the type. + + + + + Stores an instance declaration fetched from the server. + + + + + The type that the declaration belongs to. + + + + + The browse path to the instance declaration. + + + + + The browse path to the instance declaration. + + + + + A localized path to the instance declaration. + + + + + The node id for the instance declaration. + + + + + The node class of the instance declaration. + + + + + The browse name for the instance declaration. + + + + + The display name for the instance declaration. + + + + + The description for the instance declaration. + + + + + The modelling rule for the instance declaration (i.e. Mandatory or Optional). + + + + + The data type for the instance declaration. + + + + + The value rank for the instance declaration. + + + + + The built-in type parent for the data type. + + + + + A localized name for the data type. + + + + + An instance declaration that has been overridden by the current instance. + + + + + A field in a filter declaration. + + + + + Creates a new instance of a FilterDeclarationField. + + + + + Creates a new instance of a FilterDeclarationField. + + + + + Creates a new instance of a FilterDeclarationField. + + + + + Whether the field is returned as part of the event notification. + + + + + Whether the field is displayed in the list view. + + + + + Whether the filter is enabled. + + + + + The filter operator to use in the where clause. + + + + + The filter value to use in the where clause. + + + + + The instance declaration associated with the field. + + + + + A declararion of an event filter. + + + + + Creates a new instance of a FilterDeclaration. + + + + + Creates a new instance of a FilterDeclaration. + + + + + Creates a new instance of a FilterDeclaration. + + + + + Returns the event filter defined by the filter declaration. + + + + + Adds a simple field to the declaration. + + + + + Adds a simple field to the declaration. + + + + + Adds a simple field to the declaration. + + + + + Adds a simple field to the declaration. + + + + + Returns the select clause defined by the filter declaration. + + + + + Returns the where clause defined by the filter declaration. + + + + + Returns the value for the specified browse name. + + + + + The type of event. + + + + + The list of declarations for the fields. + + + + + 用NodeId读取 + + + + + + + 关闭程序时候断开连接 + + + + + + + 异步回调执行函数 + + + + + + + + 多个节点的订阅 + + + + + + + 取消多个节点的订阅 + + + + + + + 打开监视 + + + + + + + 建立连接的按钮 + + + + + + + 建立连接 + + + + + + 必需的设计器变量。 + + + + + 清理所有正在使用的资源。 + + 如果应释放托管资源,为 true;否则为 false。 + + + + 设计器支持所需的方法 - 不要修改 + 使用代码编辑器修改此方法的内容。 + + + + + 一个二次封装了的OPC UA库,支持从opc ua服务器读写节点数据,批量读写,订阅,批量订阅,历史数据读取,方法调用操作。 + + + + + 默认的构造函数,实例化一个新的OPC UA类 + + + + + connect to server + + remote url + + + + Creates a new session. + + The new session object. + + + + Disconnects from the server. + + + + + Report the client status + + Whether the status represents an error. + The time associated with the status. + The status message. + Arguments used to format the status message. + + + + Handles a keep alive event from a session. + + + + + Handles a reconnect event complete from the reconnect handler. + + + + + 设置OPC客户端的日志输出 + + 完整的文件路径 + 是否删除原文件 + + + + a name of application name show on server + + + + + Whether to use security when connecting. + + + + + The user identity to use when creating the session. + + + + + The currently active session. + + + + + Indicate the connect status + + + + + The number of seconds between reconnect attempts (0 means reconnect is disabled). + + + + + Raised when a good keep alive from the server arrives. + + + + + Raised when a reconnect operation starts. + + + + + Raised when a reconnect operation completes. + + + + + Raised after successfully connecting to or disconnecing from a server. + + + + + Raised after the client status change + + + + + 配置信息 + + + + + Read a value node from server + + node id + DataValue + + + + Read a value node from server + + type of value + node id + 实际值 + + + + Read a tag asynchronously + + The type of tag to read + tag值 + The value retrieved from the OPC + + + + read several value nodes from server + + all NodeIds + all values + + + + read several value nodes from server + + 所以的节点数组信息 + all values + + + + write a note to server(you should use try catch) + + The type of tag to write on + 节点名称 + 值 + if success True,otherwise False + + + + Write a value on the specified opc tag asynchronously + + The type of tag to write on + The fully-qualified identifier of the tag. You can specify a subfolder by using a comma delimited name. E.g: the tag `foo.bar` writes on the tag `bar` on the folder `foo` + The value for the item to write + + + + 所有的节点都写入成功,返回True,否则返回False + + 节点名称数组 + 节点的值数据 + 所有的是否都写入成功 + + + + 删除一个节点的操作,除非服务器配置允许,否则引发异常,成功返回True,否则返回False + + 节点文本描述 + + + + + 新增一个节点数据 + + 父节点tag名称 + + + + 新增一批订阅,需要指定订阅的关键字,订阅的tag名数组,以及回调方法 + + 关键字 + 节点名称数组 + 回调方法 + + + + 移除订阅消息,如果该订阅消息是批量的,也直接移除 + + 订阅关键值 + + + + 移除所有的订阅消息 + + + + + read History data + + 节点的索引 + 开始时间 + 结束时间 + 读取的个数 + 是否包含边界 + 读取的数据列表 + + + + 读取一连串的历史数据,并将其转化成指定的类型 + + 节点的索引 + 开始时间 + 结束时间 + 读取的个数 + 是否包含边界 + 读取的数据列表 + + + + 浏览一个节点的引用 + + 节点值 + 引用节点描述 + + + + 读取一个节点的所有属性 + + 节点信息 + 节点的特性值 + + + + 读取一个节点的所有属性 + + 节点值 + 所有的数据 + + + + call a server method + + 方法的父节点tag + 方法的节点tag + 传递的参数 + 输出的结果值 + + + + Raises the connect complete event on the main GUI thread. + + + + + OPC UA的状态更新消息 + + + + + 是否异常 + + + + + 时间 + + + + + 文本 + + + + + 转化为字符串 + + + + + + 读取属性过程中用于描述的 + + + + + 属性的名称 + + + + + 属性的类型描述 + + + + + 操作结果状态描述 + + + + + 属性的值,如果读取错误,返回文本描述 + + + + + Gets the display text for the access level attribute. + + The access level. + The access level formatted as a string. + + + + Gets the display text for the event notifier attribute. + + The event notifier. + The event notifier formatted as a string. + + + + Gets the display text for the value rank attribute. + + The value rank. + The value rank formatted as a string. + + + + Gets the display text for the specified attribute. + + The currently active session. + The id of the attribute. + The value of the attribute. + The attribute formatted as a string. + + + + Discovers the servers on the local machine. + + The configuration. + A list of server urls. + + + + Finds the endpoint that best matches the current settings. + + The discovery URL. + if set to true select an endpoint that uses security. + The best available endpoint. + + + + Browses the address space and returns the references found. + + The session. + The set of browse operations to perform. + if set to true a exception will be thrown on an error. + + The references found. Null if an error occurred. + + + + + Finds the type of the event for the notification. + + The monitored item. + The notification. + The NodeId of the EventType. + + + + Browses the address space and returns the references found. + + The session. + The NodeId for the starting node. + if set to true a exception will be thrown on an error. + + The references found. Null if an error occurred. + + + + + Browses the address space and returns all of the supertypes of the specified type node. + + The session. + The NodeId for a type node in the address space. + if set to true a exception will be thrown on an error. + + The references found. Null if an error occurred. + + + + + Constructs an event object from a notification. + + The session. + The monitored item that produced the notification. + The notification. + The known event types. + Mapping between event types and known event types. + + The event object. Null if the notification is not a valid event type. + + + + + Returns the node ids for a set of relative paths. + + An open session with the server to use. + The starting node for the relative paths. + The namespace URIs referenced by the relative paths. + The relative paths. + A collection of local nodes. + + + + Collects the fields for the type. + + The session. + The type id. + The fields. + The node id for the declaration of the field. + + + + Collects the fields for the instance. + + The session. + The instance id. + The fields. + The node id for the declaration of the field. + + + + Collects the fields for the instance node. + + The session. + The node id. + The parent path. + The event fields. + The node id for the declaration of the field. + The table of found nodes. + + + + Determines whether the specified select clause contains the browse path. + + The select clause. + The browse path. + + true if the specified select clause contains path; otherwise, false. + + + + + 一个强类型的资源类,用于查找本地化的字符串等。 + + + + + 返回此类使用的缓存的 ResourceManager 实例。 + + + + + 重写当前线程的 CurrentUICulture 属性 + 重写当前线程的 CurrentUICulture 属性。 + + + + + 查找 System.Drawing.Bitmap 类型的本地化资源。 + + + + + 查找 System.Drawing.Bitmap 类型的本地化资源。 + + + + + 查找 System.Drawing.Bitmap 类型的本地化资源。 + + + + + 查找 System.Drawing.Bitmap 类型的本地化资源。 + + + + + 查找 System.Drawing.Bitmap 类型的本地化资源。 + + + + + 查找 System.Drawing.Bitmap 类型的本地化资源。 + + + + + 查找 System.Drawing.Bitmap 类型的本地化资源。 + + + + + 查找 System.Drawing.Bitmap 类型的本地化资源。 + + + + + 查找 System.Drawing.Bitmap 类型的本地化资源。 + + + + + 查找 System.Drawing.Bitmap 类型的本地化资源。 + + + + + 查找 System.Drawing.Bitmap 类型的本地化资源。 + + + + + 查找 System.Drawing.Bitmap 类型的本地化资源。 + + + + + 查找 System.Drawing.Bitmap 类型的本地化资源。 + + + + + 查找 System.Drawing.Bitmap 类型的本地化资源。 + + + + + 查找 System.Drawing.Bitmap 类型的本地化资源。 + + + + + 查找 System.Drawing.Bitmap 类型的本地化资源。 + + + + + 查找 System.Drawing.Bitmap 类型的本地化资源。 + + + + + 查找 System.Drawing.Bitmap 类型的本地化资源。 + + + + + 查找 System.Drawing.Bitmap 类型的本地化资源。 + + + + + 查找 System.Drawing.Bitmap 类型的本地化资源。 + + + + + 查找 System.Drawing.Bitmap 类型的本地化资源。 + + + + + 查找 System.Drawing.Bitmap 类型的本地化资源。 + + + + + 查找 System.Drawing.Bitmap 类型的本地化资源。 + + + + diff --git a/dll_common/SqlCmd.dll b/dll_common/SqlCmd.dll new file mode 100644 index 0000000..b6b25f9 Binary files /dev/null and b/dll_common/SqlCmd.dll differ diff --git a/dll_common/System.Net.Http.Formatting.dll b/dll_common/System.Net.Http.Formatting.dll new file mode 100644 index 0000000..e9e80be Binary files /dev/null and b/dll_common/System.Net.Http.Formatting.dll differ diff --git a/dll_common/System.Net.Http.dll b/dll_common/System.Net.Http.dll new file mode 100644 index 0000000..1c5c6fd Binary files /dev/null and b/dll_common/System.Net.Http.dll differ diff --git a/dll_common/System.Web.Cors.dll b/dll_common/System.Web.Cors.dll new file mode 100644 index 0000000..6f3da24 Binary files /dev/null and b/dll_common/System.Web.Cors.dll differ diff --git a/dll_common/System.Web.Http.Cors.dll b/dll_common/System.Web.Http.Cors.dll new file mode 100644 index 0000000..fd0b539 Binary files /dev/null and b/dll_common/System.Web.Http.Cors.dll differ diff --git a/dll_common/System.Web.Http.SelfHost.dll b/dll_common/System.Web.Http.SelfHost.dll new file mode 100644 index 0000000..852728e Binary files /dev/null and b/dll_common/System.Web.Http.SelfHost.dll differ diff --git a/dll_common/System.Web.Http.dll b/dll_common/System.Web.Http.dll new file mode 100644 index 0000000..7e3bd30 Binary files /dev/null and b/dll_common/System.Web.Http.dll differ diff --git a/dll_common/WC.xlsx b/dll_common/WC.xlsx new file mode 100644 index 0000000..25d71af Binary files /dev/null and b/dll_common/WC.xlsx differ diff --git a/dll_fun/00.1Newtonsoft.Json.dll b/dll_fun/00.1Newtonsoft.Json.dll new file mode 100644 index 0000000..fe004fd Binary files /dev/null and b/dll_fun/00.1Newtonsoft.Json.dll differ diff --git a/dll_fun/00.1Newtonsoft.Json.pdb b/dll_fun/00.1Newtonsoft.Json.pdb new file mode 100644 index 0000000..b9b7b33 Binary files /dev/null and b/dll_fun/00.1Newtonsoft.Json.pdb differ diff --git a/dll_fun/00MesWorkMqtt.dll b/dll_fun/00MesWorkMqtt.dll new file mode 100644 index 0000000..a480e9f Binary files /dev/null and b/dll_fun/00MesWorkMqtt.dll differ diff --git a/dll_fun/00MesWorkMqtt.pdb b/dll_fun/00MesWorkMqtt.pdb new file mode 100644 index 0000000..03a50bf Binary files /dev/null and b/dll_fun/00MesWorkMqtt.pdb differ diff --git a/dll_fun/02WebApiCall.dll b/dll_fun/02WebApiCall.dll new file mode 100644 index 0000000..c6c9aa8 Binary files /dev/null and b/dll_fun/02WebApiCall.dll differ diff --git a/dll_fun/02WebApiCall.dll.config b/dll_fun/02WebApiCall.dll.config new file mode 100644 index 0000000..b740b86 --- /dev/null +++ b/dll_fun/02WebApiCall.dll.config @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/dll_fun/02WebApiCall.pdb b/dll_fun/02WebApiCall.pdb new file mode 100644 index 0000000..ea8e015 Binary files /dev/null and b/dll_fun/02WebApiCall.pdb differ diff --git a/dll_fun/04DataBaseAccess.dll b/dll_fun/04DataBaseAccess.dll new file mode 100644 index 0000000..74ebd53 Binary files /dev/null and b/dll_fun/04DataBaseAccess.dll differ diff --git a/dll_fun/04DataBaseAccess.pdb b/dll_fun/04DataBaseAccess.pdb new file mode 100644 index 0000000..ccbde38 Binary files /dev/null and b/dll_fun/04DataBaseAccess.pdb differ diff --git a/dll_fun/07BusinessFacade.dll b/dll_fun/07BusinessFacade.dll new file mode 100644 index 0000000..a881932 Binary files /dev/null and b/dll_fun/07BusinessFacade.dll differ diff --git a/dll_fun/07BusinessFacade.pdb b/dll_fun/07BusinessFacade.pdb new file mode 100644 index 0000000..bec0dfb Binary files /dev/null and b/dll_fun/07BusinessFacade.pdb differ diff --git a/dll_fun/08WebFun_base.dll b/dll_fun/08WebFun_base.dll new file mode 100644 index 0000000..aa1cbe6 Binary files /dev/null and b/dll_fun/08WebFun_base.dll differ diff --git a/dll_fun/08WebFun_base.pdb b/dll_fun/08WebFun_base.pdb new file mode 100644 index 0000000..4c7e173 Binary files /dev/null and b/dll_fun/08WebFun_base.pdb differ diff --git a/dll_fun/09MesDataFunction.dll b/dll_fun/09MesDataFunction.dll new file mode 100644 index 0000000..0bc974a Binary files /dev/null and b/dll_fun/09MesDataFunction.dll differ diff --git a/dll_fun/09MesDataFunction.pdb b/dll_fun/09MesDataFunction.pdb new file mode 100644 index 0000000..716b2df Binary files /dev/null and b/dll_fun/09MesDataFunction.pdb differ diff --git a/dll_fun/BasicData.dll b/dll_fun/BasicData.dll new file mode 100644 index 0000000..8dfe09b Binary files /dev/null and b/dll_fun/BasicData.dll differ diff --git a/dll_fun/BasicData.pdb b/dll_fun/BasicData.pdb new file mode 100644 index 0000000..e432017 Binary files /dev/null and b/dll_fun/BasicData.pdb differ diff --git a/dll_fun/DataLinkMesWork.dll b/dll_fun/DataLinkMesWork.dll new file mode 100644 index 0000000..57fcd25 Binary files /dev/null and b/dll_fun/DataLinkMesWork.dll differ diff --git a/dll_fun/DoWhatPlc.dll b/dll_fun/DoWhatPlc.dll new file mode 100644 index 0000000..8f218b4 Binary files /dev/null and b/dll_fun/DoWhatPlc.dll differ diff --git a/dll_fun/DoWhatPlc.pdb b/dll_fun/DoWhatPlc.pdb new file mode 100644 index 0000000..5f70e79 Binary files /dev/null and b/dll_fun/DoWhatPlc.pdb differ diff --git a/dll_fun/Function1051.dll b/dll_fun/Function1051.dll new file mode 100644 index 0000000..60d9a31 Binary files /dev/null and b/dll_fun/Function1051.dll differ diff --git a/dll_fun/Function1051.dll.config b/dll_fun/Function1051.dll.config new file mode 100644 index 0000000..b4c4daf --- /dev/null +++ b/dll_fun/Function1051.dll.config @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + + + diff --git a/dll_fun/Function1051.pdb b/dll_fun/Function1051.pdb new file mode 100644 index 0000000..e0b8af2 Binary files /dev/null and b/dll_fun/Function1051.pdb differ diff --git a/dll_fun/Function1052.dll b/dll_fun/Function1052.dll new file mode 100644 index 0000000..f9b24a9 Binary files /dev/null and b/dll_fun/Function1052.dll differ diff --git a/dll_fun/Function1052.dll.config b/dll_fun/Function1052.dll.config new file mode 100644 index 0000000..b4c4daf --- /dev/null +++ b/dll_fun/Function1052.dll.config @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + + + diff --git a/dll_fun/Function1052.pdb b/dll_fun/Function1052.pdb new file mode 100644 index 0000000..2482140 Binary files /dev/null and b/dll_fun/Function1052.pdb differ diff --git a/dll_fun/Function1053.dll b/dll_fun/Function1053.dll new file mode 100644 index 0000000..90f1029 Binary files /dev/null and b/dll_fun/Function1053.dll differ diff --git a/dll_fun/Function1053.dll.config b/dll_fun/Function1053.dll.config new file mode 100644 index 0000000..b4c4daf --- /dev/null +++ b/dll_fun/Function1053.dll.config @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + + + diff --git a/dll_fun/Function1053.pdb b/dll_fun/Function1053.pdb new file mode 100644 index 0000000..fc59d63 Binary files /dev/null and b/dll_fun/Function1053.pdb differ diff --git a/dll_fun/Function1054.dll b/dll_fun/Function1054.dll new file mode 100644 index 0000000..6458a99 Binary files /dev/null and b/dll_fun/Function1054.dll differ diff --git a/dll_fun/Function1054.dll.config b/dll_fun/Function1054.dll.config new file mode 100644 index 0000000..b4c4daf --- /dev/null +++ b/dll_fun/Function1054.dll.config @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + + + diff --git a/dll_fun/Function1054.pdb b/dll_fun/Function1054.pdb new file mode 100644 index 0000000..94ba143 Binary files /dev/null and b/dll_fun/Function1054.pdb differ diff --git a/dll_fun/Function1055.dll b/dll_fun/Function1055.dll new file mode 100644 index 0000000..8284f98 Binary files /dev/null and b/dll_fun/Function1055.dll differ diff --git a/dll_fun/Function1055.dll.config b/dll_fun/Function1055.dll.config new file mode 100644 index 0000000..b4c4daf --- /dev/null +++ b/dll_fun/Function1055.dll.config @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + + + diff --git a/dll_fun/Function1055.pdb b/dll_fun/Function1055.pdb new file mode 100644 index 0000000..98280fe Binary files /dev/null and b/dll_fun/Function1055.pdb differ diff --git a/dll_fun/Function1056.dll b/dll_fun/Function1056.dll new file mode 100644 index 0000000..c05f882 Binary files /dev/null and b/dll_fun/Function1056.dll differ diff --git a/dll_fun/Function1056.dll.config b/dll_fun/Function1056.dll.config new file mode 100644 index 0000000..b4c4daf --- /dev/null +++ b/dll_fun/Function1056.dll.config @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + + + diff --git a/dll_fun/Function1056.pdb b/dll_fun/Function1056.pdb new file mode 100644 index 0000000..902a408 Binary files /dev/null and b/dll_fun/Function1056.pdb differ diff --git a/dll_fun/Function1057.dll b/dll_fun/Function1057.dll new file mode 100644 index 0000000..7b41a4e Binary files /dev/null and b/dll_fun/Function1057.dll differ diff --git a/dll_fun/Function1057.dll.config b/dll_fun/Function1057.dll.config new file mode 100644 index 0000000..b4c4daf --- /dev/null +++ b/dll_fun/Function1057.dll.config @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + + + diff --git a/dll_fun/Function1057.pdb b/dll_fun/Function1057.pdb new file mode 100644 index 0000000..e4b1a07 Binary files /dev/null and b/dll_fun/Function1057.pdb differ diff --git a/dll_fun/Function1058.dll b/dll_fun/Function1058.dll new file mode 100644 index 0000000..835068e Binary files /dev/null and b/dll_fun/Function1058.dll differ diff --git a/dll_fun/Function1058.dll.config b/dll_fun/Function1058.dll.config new file mode 100644 index 0000000..b4c4daf --- /dev/null +++ b/dll_fun/Function1058.dll.config @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + + + diff --git a/dll_fun/Function1058.pdb b/dll_fun/Function1058.pdb new file mode 100644 index 0000000..7a880a5 Binary files /dev/null and b/dll_fun/Function1058.pdb differ diff --git a/dll_fun/Function1059.dll b/dll_fun/Function1059.dll new file mode 100644 index 0000000..4693f92 Binary files /dev/null and b/dll_fun/Function1059.dll differ diff --git a/dll_fun/Function1059.dll.config b/dll_fun/Function1059.dll.config new file mode 100644 index 0000000..b4c4daf --- /dev/null +++ b/dll_fun/Function1059.dll.config @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + + + diff --git a/dll_fun/Function1059.pdb b/dll_fun/Function1059.pdb new file mode 100644 index 0000000..9019e55 Binary files /dev/null and b/dll_fun/Function1059.pdb differ diff --git a/dll_fun/Function1060.dll b/dll_fun/Function1060.dll new file mode 100644 index 0000000..e1c6cf3 Binary files /dev/null and b/dll_fun/Function1060.dll differ diff --git a/dll_fun/Function1060.dll.config b/dll_fun/Function1060.dll.config new file mode 100644 index 0000000..b4c4daf --- /dev/null +++ b/dll_fun/Function1060.dll.config @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + + + diff --git a/dll_fun/Function1060.pdb b/dll_fun/Function1060.pdb new file mode 100644 index 0000000..f347906 Binary files /dev/null and b/dll_fun/Function1060.pdb differ diff --git a/dll_fun/Function1061.dll b/dll_fun/Function1061.dll new file mode 100644 index 0000000..09da6bb Binary files /dev/null and b/dll_fun/Function1061.dll differ diff --git a/dll_fun/Function1061.dll.config b/dll_fun/Function1061.dll.config new file mode 100644 index 0000000..b4c4daf --- /dev/null +++ b/dll_fun/Function1061.dll.config @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + + + diff --git a/dll_fun/Function1061.pdb b/dll_fun/Function1061.pdb new file mode 100644 index 0000000..cd27c60 Binary files /dev/null and b/dll_fun/Function1061.pdb differ diff --git a/dll_fun/MIS_FuntionSaveData.dll b/dll_fun/MIS_FuntionSaveData.dll new file mode 100644 index 0000000..7ff9f2c Binary files /dev/null and b/dll_fun/MIS_FuntionSaveData.dll differ diff --git a/dll_fun/MIS_FuntionSaveData.pdb b/dll_fun/MIS_FuntionSaveData.pdb new file mode 100644 index 0000000..63e7153 Binary files /dev/null and b/dll_fun/MIS_FuntionSaveData.pdb differ diff --git a/dll_fun/MQTTnet.Extensions.ManagedClient.dll b/dll_fun/MQTTnet.Extensions.ManagedClient.dll new file mode 100644 index 0000000..99035f6 Binary files /dev/null and b/dll_fun/MQTTnet.Extensions.ManagedClient.dll differ diff --git a/dll_fun/MQTTnet.dll b/dll_fun/MQTTnet.dll new file mode 100644 index 0000000..2951433 Binary files /dev/null and b/dll_fun/MQTTnet.dll differ diff --git a/dll_fun/MesWork.DeviceDriver.dll b/dll_fun/MesWork.DeviceDriver.dll new file mode 100644 index 0000000..a6ec60f Binary files /dev/null and b/dll_fun/MesWork.DeviceDriver.dll differ diff --git a/dll_fun/MesWork.DeviceDriver.pdb b/dll_fun/MesWork.DeviceDriver.pdb new file mode 100644 index 0000000..6ebff64 Binary files /dev/null and b/dll_fun/MesWork.DeviceDriver.pdb differ diff --git a/dll_fun/MesWork.PLC.dll b/dll_fun/MesWork.PLC.dll new file mode 100644 index 0000000..3399040 Binary files /dev/null and b/dll_fun/MesWork.PLC.dll differ diff --git a/dll_fun/MesWork.PLC.pdb b/dll_fun/MesWork.PLC.pdb new file mode 100644 index 0000000..af5273f Binary files /dev/null and b/dll_fun/MesWork.PLC.pdb differ diff --git a/dll_fun/MyLog4Net.dll b/dll_fun/MyLog4Net.dll new file mode 100644 index 0000000..8751171 Binary files /dev/null and b/dll_fun/MyLog4Net.dll differ diff --git a/dll_fun/MyLog4Net.pdb b/dll_fun/MyLog4Net.pdb new file mode 100644 index 0000000..8368c86 Binary files /dev/null and b/dll_fun/MyLog4Net.pdb differ diff --git a/dll_fun/Newtonsoft.Json.dll b/dll_fun/Newtonsoft.Json.dll new file mode 100644 index 0000000..7af125a Binary files /dev/null and b/dll_fun/Newtonsoft.Json.dll differ diff --git a/dll_fun/SendMessageToWebMqtt.dll b/dll_fun/SendMessageToWebMqtt.dll new file mode 100644 index 0000000..95d0a18 Binary files /dev/null and b/dll_fun/SendMessageToWebMqtt.dll differ diff --git a/dll_fun/SendMessageToWebMqtt.pdb b/dll_fun/SendMessageToWebMqtt.pdb new file mode 100644 index 0000000..07db817 Binary files /dev/null and b/dll_fun/SendMessageToWebMqtt.pdb differ diff --git a/dll_fun/log4net.config b/dll_fun/log4net.config new file mode 100644 index 0000000..92f4d40 --- /dev/null +++ b/dll_fun/log4net.config @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/dll_fun/log4net.dll b/dll_fun/log4net.dll new file mode 100644 index 0000000..84bf5b6 Binary files /dev/null and b/dll_fun/log4net.dll differ diff --git a/基本变量.xlsx b/基本变量.xlsx new file mode 100644 index 0000000..1e9e080 Binary files /dev/null and b/基本变量.xlsx differ diff --git a/数据库结构.xlsx b/数据库结构.xlsx new file mode 100644 index 0000000..f83c0e9 Binary files /dev/null and b/数据库结构.xlsx differ