diff --git a/.editorconfig b/.editorconfig
index 4ebde410..eb1efe38 100644
--- a/.editorconfig
+++ b/.editorconfig
@@ -2,3 +2,6 @@
# CS8765: Nullability of type of parameter doesn't match overridden member (possibly because of nullability attributes).
dotnet_diagnostic.CS8765.severity = none
+
+# CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.
+dotnet_diagnostic.CS8632.severity = none
diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml
index ab1573d9..0f16cd57 100644
--- a/.gitlab-ci.yml
+++ b/.gitlab-ci.yml
@@ -82,6 +82,7 @@ stages:
- installer
- release
+# ----- Start BUILD -----
LAND:build:
stage: build
tags:
@@ -173,7 +174,21 @@ CONF:build:
script:
- dotnet build $env:APP_NAME/$env:APP_NAME.csproj
+IOC:build:
+ stage: build
+ tags:
+ - win
+ variables:
+ APP_NAME: MP.IOC
+ SOL_NAME: MP-IOC
+ before_script:
+ - *nuget-fix
+ - dotnet restore "$env:SOL_NAME.sln"
+ script:
+ - dotnet build $env:APP_NAME/$env:APP_NAME.csproj
+
+# ----- Start DEPLOY develop (IIS01) -----
LAND:IIS01:deploy:
stage: deploy
tags:
@@ -293,6 +308,24 @@ CONF:IIS01:deploy:
- dotnet build $env:APP_NAME/$env:APP_NAME.csproj
- dotnet publish -p:PublishProfile=IIS01.pubxml -p:RunCodeAnalysis=false -p:Configuration=Release -p:username=jenkins -p:Password=$IIS_PASSWD -p:AllowUntrustedCertificate=true -p:verbosity=quiet $env:APP_NAME/$env:APP_NAME.csproj
+IOC:IIS01:deploy:
+ stage: deploy
+ tags:
+ - win
+ variables:
+ APP_NAME: MP.IOC
+ SOL_NAME: MP-IOC
+ before_script:
+ - *nuget-fix
+ - dotnet restore "$env:SOL_NAME.sln"
+ only:
+ - develop
+ needs: ["IOC:build"]
+ script:
+ - dotnet build $env:APP_NAME/$env:APP_NAME.csproj
+ - dotnet publish -p:PublishProfile=IIS01.pubxml -p:RunCodeAnalysis=false -p:Configuration=Release -p:username=jenkins -p:Password=$IIS_PASSWD -p:AllowUntrustedCertificate=true -p:verbosity=quiet $env:APP_NAME/$env:APP_NAME.csproj
+
+# ----- Start DEPLOY master (IIS02/IIS04) -----
LAND:IIS02:deploy:
stage: deploy
tags:
@@ -309,7 +342,7 @@ LAND:IIS02:deploy:
script:
- dotnet build $env:APP_NAME/$env:APP_NAME.csproj
- dotnet publish -p:PublishProfile=IIS02.pubxml -p:RunCodeAnalysis=false -p:Configuration=Release -p:username=jenkins -p:Password=$IIS_PASSWD -p:AllowUntrustedCertificate=true -p:verbosity=quiet $env:APP_NAME/$env:APP_NAME.csproj
- - dotnet publish -p:PublishProfile=IIS03.pubxml -p:RunCodeAnalysis=false -p:Configuration=Release -p:username=jenkins -p:Password=$IIS_PASSWD -p:AllowUntrustedCertificate=true -p:verbosity=quiet $env:APP_NAME/$env:APP_NAME.csproj
+ - dotnet publish -p:PublishProfile=IIS04.pubxml -p:RunCodeAnalysis=false -p:Configuration=Release -p:username=jenkins -p:Password=$IIS_PASSWD -p:AllowUntrustedCertificate=true -p:verbosity=quiet $env:APP_NAME/$env:APP_NAME.csproj
PROG:IIS02:deploy:
stage: deploy
@@ -327,7 +360,7 @@ PROG:IIS02:deploy:
script:
- dotnet build $env:APP_NAME/$env:APP_NAME.csproj
- dotnet publish -p:PublishProfile=IIS02.pubxml -p:RunCodeAnalysis=false -p:Configuration=Release -p:username=jenkins -p:Password=$IIS_PASSWD -p:AllowUntrustedCertificate=true -p:verbosity=quiet $env:APP_NAME/$env:APP_NAME.csproj
- - dotnet publish -p:PublishProfile=IIS03.pubxml -p:RunCodeAnalysis=false -p:Configuration=Release -p:username=jenkins -p:Password=$IIS_PASSWD -p:AllowUntrustedCertificate=true -p:verbosity=quiet $env:APP_NAME/$env:APP_NAME.csproj
+ - dotnet publish -p:PublishProfile=IIS04.pubxml -p:RunCodeAnalysis=false -p:Configuration=Release -p:username=jenkins -p:Password=$IIS_PASSWD -p:AllowUntrustedCertificate=true -p:verbosity=quiet $env:APP_NAME/$env:APP_NAME.csproj
STAT:IIS02:deploy:
stage: deploy
@@ -345,7 +378,7 @@ STAT:IIS02:deploy:
script:
- dotnet build $env:APP_NAME/$env:APP_NAME.csproj
- dotnet publish -p:PublishProfile=IIS02.pubxml -p:RunCodeAnalysis=false -p:Configuration=Release -p:username=jenkins -p:Password=$IIS_PASSWD -p:AllowUntrustedCertificate=true -p:verbosity=quiet $env:APP_NAME/$env:APP_NAME.csproj
- - dotnet publish -p:PublishProfile=IIS03.pubxml -p:RunCodeAnalysis=false -p:Configuration=Release -p:username=jenkins -p:Password=$IIS_PASSWD -p:AllowUntrustedCertificate=true -p:verbosity=quiet $env:APP_NAME/$env:APP_NAME.csproj
+ - dotnet publish -p:PublishProfile=IIS04.pubxml -p:RunCodeAnalysis=false -p:Configuration=Release -p:username=jenkins -p:Password=$IIS_PASSWD -p:AllowUntrustedCertificate=true -p:verbosity=quiet $env:APP_NAME/$env:APP_NAME.csproj
MON:IIS02:deploy:
stage: deploy
@@ -363,7 +396,7 @@ MON:IIS02:deploy:
script:
- dotnet build $env:APP_NAME/$env:APP_NAME.csproj
- dotnet publish -p:PublishProfile=IIS02.pubxml -p:RunCodeAnalysis=false -p:Configuration=Release -p:username=jenkins -p:Password=$IIS_PASSWD -p:AllowUntrustedCertificate=true -p:verbosity=quiet $env:APP_NAME/$env:APP_NAME.csproj
- - dotnet publish -p:PublishProfile=IIS03.pubxml -p:RunCodeAnalysis=false -p:Configuration=Release -p:username=jenkins -p:Password=$IIS_PASSWD -p:AllowUntrustedCertificate=true -p:verbosity=quiet $env:APP_NAME/$env:APP_NAME.csproj
+ - dotnet publish -p:PublishProfile=IIS04.pubxml -p:RunCodeAnalysis=false -p:Configuration=Release -p:username=jenkins -p:Password=$IIS_PASSWD -p:AllowUntrustedCertificate=true -p:verbosity=quiet $env:APP_NAME/$env:APP_NAME.csproj
SPEC:IIS02:deploy:
stage: deploy
@@ -381,7 +414,7 @@ SPEC:IIS02:deploy:
script:
- dotnet build $env:APP_NAME/$env:APP_NAME.csproj
- dotnet publish -p:PublishProfile=IIS02.pubxml -p:RunCodeAnalysis=false -p:Configuration=Release -p:username=jenkins -p:Password=$IIS_PASSWD -p:AllowUntrustedCertificate=true -p:verbosity=quiet $env:APP_NAME/$env:APP_NAME.csproj
- - dotnet publish -p:PublishProfile=IIS03.pubxml -p:RunCodeAnalysis=false -p:Configuration=Release -p:username=jenkins -p:Password=$IIS_PASSWD -p:AllowUntrustedCertificate=true -p:verbosity=quiet $env:APP_NAME/$env:APP_NAME.csproj
+ - dotnet publish -p:PublishProfile=IIS04.pubxml -p:RunCodeAnalysis=false -p:Configuration=Release -p:username=jenkins -p:Password=$IIS_PASSWD -p:AllowUntrustedCertificate=true -p:verbosity=quiet $env:APP_NAME/$env:APP_NAME.csproj
INVE:IIS02:deploy:
stage: deploy
@@ -399,7 +432,7 @@ INVE:IIS02:deploy:
script:
- dotnet build $env:APP_NAME/$env:APP_NAME.csproj
- dotnet publish -p:PublishProfile=IIS02.pubxml -p:RunCodeAnalysis=false -p:Configuration=Release -p:username=jenkins -p:Password=$IIS_PASSWD -p:AllowUntrustedCertificate=true -p:verbosity=quiet $env:APP_NAME/$env:APP_NAME.csproj
- - dotnet publish -p:PublishProfile=IIS03.pubxml -p:RunCodeAnalysis=false -p:Configuration=Release -p:username=jenkins -p:Password=$IIS_PASSWD -p:AllowUntrustedCertificate=true -p:verbosity=quiet $env:APP_NAME/$env:APP_NAME.csproj
+ - dotnet publish -p:PublishProfile=IIS04.pubxml -p:RunCodeAnalysis=false -p:Configuration=Release -p:username=jenkins -p:Password=$IIS_PASSWD -p:AllowUntrustedCertificate=true -p:verbosity=quiet $env:APP_NAME/$env:APP_NAME.csproj
CONF:IIS02:deploy:
stage: deploy
@@ -417,8 +450,27 @@ CONF:IIS02:deploy:
script:
- dotnet build $env:APP_NAME/$env:APP_NAME.csproj
- dotnet publish -p:PublishProfile=IIS02.pubxml -p:RunCodeAnalysis=false -p:Configuration=Release -p:username=jenkins -p:Password=$IIS_PASSWD -p:AllowUntrustedCertificate=true -p:verbosity=quiet $env:APP_NAME/$env:APP_NAME.csproj
- - dotnet publish -p:PublishProfile=IIS03.pubxml -p:RunCodeAnalysis=false -p:Configuration=Release -p:username=jenkins -p:Password=$IIS_PASSWD -p:AllowUntrustedCertificate=true -p:verbosity=quiet $env:APP_NAME/$env:APP_NAME.csproj
+ - dotnet publish -p:PublishProfile=IIS04.pubxml -p:RunCodeAnalysis=false -p:Configuration=Release -p:username=jenkins -p:Password=$IIS_PASSWD -p:AllowUntrustedCertificate=true -p:verbosity=quiet $env:APP_NAME/$env:APP_NAME.csproj
+IOC:IIS02:deploy:
+ stage: deploy
+ tags:
+ - win
+ variables:
+ APP_NAME: MP.IOC
+ SOL_NAME: MP-IOC
+ before_script:
+ - *nuget-fix
+ - dotnet restore "$env:SOL_NAME.sln"
+ only:
+ - develop
+ needs: ["IOC:build"]
+ script:
+ - dotnet build $env:APP_NAME/$env:APP_NAME.csproj
+ - dotnet publish -p:PublishProfile=IIS02.pubxml -p:RunCodeAnalysis=false -p:Configuration=Release -p:username=jenkins -p:Password=$IIS_PASSWD -p:AllowUntrustedCertificate=true -p:verbosity=quiet $env:APP_NAME/$env:APP_NAME.csproj
+ - dotnet publish -p:PublishProfile=IIS04.pubxml -p:RunCodeAnalysis=false -p:Configuration=Release -p:username=jenkins -p:Password=$IIS_PASSWD -p:AllowUntrustedCertificate=true -p:verbosity=quiet $env:APP_NAME/$env:APP_NAME.csproj
+
+# ----- Start INSTALLER (develop/master) -----
LAND:installer:
stage: installer
tags:
@@ -573,6 +625,29 @@ INVE:installer:
# - *hashBuild
# - *nexusUpload
+IOC:installer:
+ stage: installer
+ tags:
+ - win
+ variables:
+ APP_NAME: MP.IOC
+ SOL_NAME: MP-IOC
+ NEXUS_PATH: MP-IOC
+ before_script:
+ - *nuget-fix
+ - dotnet restore "$env:SOL_NAME.sln"
+ only:
+ - develop
+ - master
+ needs: ["IOC:build"]
+ script:
+ - dotnet build $env:APP_NAME/$env:APP_NAME.csproj
+ - dotnet publish -p:PublishProfile=IISProfile.pubxml -p:RunCodeAnalysis=false -p:Configuration=Release $env:APP_NAME/$env:APP_NAME.csproj -o:publish -p:verbosity=quiet
+ # qui il deploy su nexus...
+ - *hashBuild
+ - *nexusUpload
+
+# ----- Start RELEASE (tags only) -----
LAND:release:
stage: release
tags:
@@ -585,8 +660,6 @@ LAND:release:
- *nuget-fix
- dotnet restore "$env:SOL_NAME.sln"
only:
- #- feature/Deploy_CI_CD
- # - master
- tags
except:
- branches
@@ -740,3 +813,26 @@ CONF:release:
- dotnet build $env:APP_NAME/$env:APP_NAME.csproj
- dotnet publish -c Release -o ./publish $env:APP_NAME/$env:APP_NAME.csproj -p:verbosity=quiet
+IOC:release:
+ stage: release
+ tags:
+ - win
+ variables:
+ APP_NAME: MP.IOC
+ SOL_NAME: MP-IOC
+ NEXUS_PATH: MP-IOC
+ before_script:
+ - *nuget-fix
+ - dotnet restore "$env:SOL_NAME.sln"
+ only:
+ - tags
+ except:
+ - branches
+ needs: ["IOC:build"]
+ artifacts:
+ paths:
+ - publish/
+ script:
+ - dotnet build $env:APP_NAME/$env:APP_NAME.csproj
+ - dotnet publish -c Release -o ./publish $env:APP_NAME/$env:APP_NAME.csproj -p:verbosity=quiet
+
diff --git a/Insomnia/MAPO-SPEC.json b/Insomnia/MAPO-SPEC.json
new file mode 100644
index 00000000..b14c98f9
--- /dev/null
+++ b/Insomnia/MAPO-SPEC.json
@@ -0,0 +1 @@
+{"_type":"export","__export_format":4,"__export_date":"2023-04-04T15:23:33.215Z","__export_source":"insomnia.desktop.app:v2023.1.0","resources":[{"_id":"req_cd57cb8728854cd5a7d026b9aba60047","parentId":"wrk_86debe1a96ca41cdbfb53ed71a9d6d84","modified":1680616613886,"created":1680616613017,"url":"https://localhost:7212/api/Recipe/GetRecipe?idxPODL=1656","name":"New Request","description":"","method":"GET","body":{},"parameters":[],"headers":[],"authentication":{},"metaSortKey":-1680616613017,"isPrivate":false,"settingStoreCookies":true,"settingSendCookies":true,"settingDisableRenderRequestBody":false,"settingEncodeUrl":true,"settingRebuildPath":true,"settingFollowRedirects":"global","_type":"request"},{"_id":"wrk_86debe1a96ca41cdbfb53ed71a9d6d84","parentId":null,"modified":1680615228636,"created":1680615228636,"name":"MAPO-SPEC","description":"","scope":"collection","_type":"workspace"},{"_id":"req_4d233d6fb970485ea929bdffdcfae05a","parentId":"wrk_86debe1a96ca41cdbfb53ed71a9d6d84","modified":1680621773464,"created":1680615246346,"url":"{{ _.BASE_URL }}/api/Recipe/GetRecipe?idxPODL=1656","name":"GET RECIPE (calc)","description":"","method":"GET","body":{},"parameters":[],"headers":[],"authentication":{},"metaSortKey":-1680615241541.5,"isPrivate":false,"settingStoreCookies":true,"settingSendCookies":true,"settingDisableRenderRequestBody":false,"settingEncodeUrl":true,"settingRebuildPath":true,"settingFollowRedirects":"global","_type":"request"},{"_id":"req_278d5f0a6555457e88ad2e58cfdaae23","parentId":"wrk_86debe1a96ca41cdbfb53ed71a9d6d84","modified":1680621754168,"created":1680615436433,"url":"{{ BASE_URL }}/api/RecipeArchive/GetFile?idxMacc=SIMUL_02&fileName=10002.xml","name":"GET FILE (from archive)","description":"","method":"GET","body":{},"parameters":[],"headers":[],"authentication":{},"metaSortKey":-1679846511868.4375,"isPrivate":false,"settingStoreCookies":true,"settingSendCookies":true,"settingDisableRenderRequestBody":false,"settingEncodeUrl":true,"settingRebuildPath":true,"settingFollowRedirects":"global","_type":"request"},{"_id":"env_ea1cd34b6839260f9a1edf3546f3c605bb6f3a2c","parentId":"wrk_86debe1a96ca41cdbfb53ed71a9d6d84","modified":1680615377532,"created":1680615228640,"name":"Base Environment","data":{},"dataPropertyOrder":{},"color":null,"isPrivate":false,"metaSortKey":1680615228640,"_type":"environment"},{"_id":"jar_ea1cd34b6839260f9a1edf3546f3c605bb6f3a2c","parentId":"wrk_86debe1a96ca41cdbfb53ed71a9d6d84","modified":1680615228642,"created":1680615228642,"name":"Default Jar","cookies":[],"_type":"cookie_jar"},{"_id":"spc_b61936e963e34a759001c6a22ad8da60","parentId":"wrk_86debe1a96ca41cdbfb53ed71a9d6d84","modified":1680615228637,"created":1680615228637,"fileName":"MAPO-SPEC","contents":"","contentType":"yaml","_type":"api_spec"},{"_id":"env_2757d8ba1b17435987847d0499e9369e","parentId":"env_ea1cd34b6839260f9a1edf3546f3c605bb6f3a2c","modified":1680616993850,"created":1680615301619,"name":"DEV","data":{"BASE_URL":"https://localhost:7212"},"dataPropertyOrder":{"&":["BASE_URL"]},"color":"#ff0000","isPrivate":false,"metaSortKey":1680615301619,"_type":"environment"},{"_id":"env_f5b6aef3c2b444aab04c9056404d63f9","parentId":"env_ea1cd34b6839260f9a1edf3546f3c605bb6f3a2c","modified":1680616996428,"created":1680615328099,"name":"IIS01","data":{"BASE_URL":"https://iis01.egalware.com/MP/SPEC"},"dataPropertyOrder":{"&":["BASE_URL"]},"color":"#6600ff","isPrivate":false,"metaSortKey":1680615328099,"_type":"environment"}]}
\ No newline at end of file
diff --git a/IobConf.Core/IniFile.cs b/IobConf.Core/IniFile.cs
index 1a0fc606..f02ee733 100644
--- a/IobConf.Core/IniFile.cs
+++ b/IobConf.Core/IniFile.cs
@@ -41,7 +41,7 @@ namespace IobConf.Core
///
public void IniDeleteKey(string Section, string Key)
{
- WritePrivateProfileString(Section, Key, null, FileName);
+ WritePrivateProfileString(Section, Key, "", FileName);
}
///
@@ -50,7 +50,7 @@ namespace IobConf.Core
///
public void IniDeleteSection(string Section)
{
- WritePrivateProfileSection(Section, null, FileName);
+ WritePrivateProfileSection(Section, "", FileName);
}
///
diff --git a/IobConf.Core/IobConf.Core.csproj b/IobConf.Core/IobConf.Core.csproj
index 7361855e..d36839cf 100644
--- a/IobConf.Core/IobConf.Core.csproj
+++ b/IobConf.Core/IobConf.Core.csproj
@@ -8,8 +8,8 @@
-
-
+
+
diff --git a/IobConf.Core/IobConfTree.cs b/IobConf.Core/IobConfTree.cs
index 7c76ca94..d169220a 100644
--- a/IobConf.Core/IobConfTree.cs
+++ b/IobConf.Core/IobConfTree.cs
@@ -19,7 +19,9 @@ namespace IobConf.Core
/// Init classe configurazione
///
public IobConfTree()
- { }
+ {
+ Log = LogManager.GetCurrentClassLogger();
+ }
///
/// Restituisce un oggetto di conf leggendo INI ed effettuando conversione
@@ -33,8 +35,8 @@ namespace IobConf.Core
{
// leggo file INI
IniFile fIni = new IniFile(iniFilePath);
- string codIob= Path.GetFileNameWithoutExtension(iniFilePath);
-
+ string codIob = Path.GetFileNameWithoutExtension(iniFilePath);
+
// effettuo conversione...
// Dati generali (vendor, modello...)
@@ -46,13 +48,13 @@ namespace IobConf.Core
// tipo adapter// verifico tipo adapter
try
{
- newConfObj.IobType = (AdapterType)Enum.Parse(typeof(AdapterType), fIni.ReadString("IOB", "CNCTYPE", "ND"));
+ newConfObj.IobType = (AdapterType)Enum.Parse(typeof(AdapterType), fIni.ReadString("IOB", "CNCTYPE", "ND"));
}
catch (Exception exc)
{
newConfObj.IobType = AdapterType.ND;
string rawVal = fIni.ReadString("IOB", "CNCTYPE", "DEMO");
- //newConfObj.lgError($"Eccezione in conversione tipo adapter: richiesto {rawVal} | tipo non codificato...{Environment.NewLine}{exc}");
+ newConfObj.lgError($"Eccezione in conversione tipo adapter: richiesto {rawVal} | tipo non codificato...{Environment.NewLine}{exc}");
}
newConfObj.GeneralCom = (ComLayer)Enum.Parse(typeof(ComLayer), fIni.ReadString("IOB", "CNCFAMILY", "ND"));
@@ -72,16 +74,15 @@ namespace IobConf.Core
newConfObj.TempoCiclo.MaxIncrPz = Convert.ToDouble(fIni.ReadString("OPTPAR", "TC_MAX_INCR", "5").Replace(".", ","));
// Server
- string MpIp=fIni.ReadString("SERVER", "MPIP", "::1");
+ string MpIp = fIni.ReadString("SERVER", "MPIP", "::1");
if (!string.IsNullOrEmpty(MpIp))
{
newConfObj.ServerMES.Transport = MpIp.StartsWith("https://") ? "https" : "http";
newConfObj.ServerMES.IpAddr = MpIp.Replace($"{newConfObj.ServerMES.Transport}://", ""); // tolgo http/https...
}
- //newConfObj.ServerMES.Commands.Alive
-
+
// Altro (versione, ...)
- newConfObj.ReleaseVers = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
+ newConfObj.ReleaseVers = $"{System.Reflection.Assembly.GetExecutingAssembly().GetName().Version}";
newConfObj.IobManConf.MinDeltaSec = fIni.ReadInteger("IOB", "MinDeltaSec", 6);
// OptPar
@@ -101,7 +102,7 @@ namespace IobConf.Core
}
catch (Exception exc)
{
- //newConfObj.lgError(string.Format("EXCEPTION in fase di lettura OPTPAR: {0}{1}", Environment.NewLine, exc));
+ newConfObj.lgError(string.Format("EXCEPTION in fase di lettura OPTPAR: {0}{1}", Environment.NewLine, exc));
}
}
// riordino alfabeticamente
diff --git a/IobConf.UI/IobConf.UI.csproj b/IobConf.UI/IobConf.UI.csproj
index 9e8176b4..e47e885a 100644
--- a/IobConf.UI/IobConf.UI.csproj
+++ b/IobConf.UI/IobConf.UI.csproj
@@ -9,7 +9,7 @@
<_WebToolingArtifacts Remove="Properties\PublishProfiles\IIS01.pubxml" />
<_WebToolingArtifacts Remove="Properties\PublishProfiles\IIS02.pubxml" />
- <_WebToolingArtifacts Remove="Properties\PublishProfiles\IIS03.pubxml" />
+ <_WebToolingArtifacts Remove="Properties\PublishProfiles\IIS04.pubxml" />
diff --git a/MP-IOC.sln b/MP-IOC.sln
new file mode 100644
index 00000000..a64b294c
--- /dev/null
+++ b/MP-IOC.sln
@@ -0,0 +1,31 @@
+
+Microsoft Visual Studio Solution File, Format Version 12.00
+# Visual Studio Version 17
+VisualStudioVersion = 17.4.33205.214
+MinimumVisualStudioVersion = 10.0.40219.1
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MP.Data", "MP.Data\MP.Data.csproj", "{A0C7A1E7-6E5F-41BA-8ED0-C4A6C581C1B3}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MP.IOC", "MP.IOC\MP.IOC.csproj", "{B9F508BF-8503-4C25-B9BA-0FAC411C44C5}"
+EndProject
+Global
+ GlobalSection(SolutionConfigurationPlatforms) = preSolution
+ Debug|Any CPU = Debug|Any CPU
+ Release|Any CPU = Release|Any CPU
+ EndGlobalSection
+ GlobalSection(ProjectConfigurationPlatforms) = postSolution
+ {A0C7A1E7-6E5F-41BA-8ED0-C4A6C581C1B3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {A0C7A1E7-6E5F-41BA-8ED0-C4A6C581C1B3}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {A0C7A1E7-6E5F-41BA-8ED0-C4A6C581C1B3}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {A0C7A1E7-6E5F-41BA-8ED0-C4A6C581C1B3}.Release|Any CPU.Build.0 = Release|Any CPU
+ {B9F508BF-8503-4C25-B9BA-0FAC411C44C5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {B9F508BF-8503-4C25-B9BA-0FAC411C44C5}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {B9F508BF-8503-4C25-B9BA-0FAC411C44C5}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {B9F508BF-8503-4C25-B9BA-0FAC411C44C5}.Release|Any CPU.Build.0 = Release|Any CPU
+ EndGlobalSection
+ GlobalSection(SolutionProperties) = preSolution
+ HideSolutionNode = FALSE
+ EndGlobalSection
+ GlobalSection(ExtensibilityGlobals) = postSolution
+ SolutionGuid = {8030DF52-992F-46A3-A9F1-5FF64A9D5D9D}
+ EndGlobalSection
+EndGlobal
diff --git a/MP.Data/Conf/RecipeBlockConfig.cs b/MP.Data/Conf/RecipeBlockConfig.cs
new file mode 100644
index 00000000..b960fabc
--- /dev/null
+++ b/MP.Data/Conf/RecipeBlockConfig.cs
@@ -0,0 +1,27 @@
+using System.Collections.Generic;
+
+namespace MP.Data.Conf
+{
+ ///
+ /// Configurazione blocco ricetta (Header / Rows)
+ ///
+ public class RecipeBlockConfig
+ {
+ #region Public Properties
+
+ ///
+ /// Dizionario degli enum permessi
+ ///
+ public Dictionary> EnumVal { get; set; } = new Dictionary>();
+
+ ///
+ /// Dizionario delle chiavi, differenziate dai primi caratteri:
+ /// C: --> Calcolato
+ /// E: --> Enum: modificabile ma da dizionario valori seguente
+ /// F: --> Fixed (NON modificabile) "" --> editabile
+ ///
+ public Dictionary ListKeys { get; set; } = new Dictionary();
+
+ #endregion Public Properties
+ }
+}
\ No newline at end of file
diff --git a/MP.Data/Conf/RecipeConfig.cs b/MP.Data/Conf/RecipeConfig.cs
new file mode 100644
index 00000000..c6744cbd
--- /dev/null
+++ b/MP.Data/Conf/RecipeConfig.cs
@@ -0,0 +1,32 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace MP.Data.Conf
+{
+ public class RecipeConfig
+ {
+ ///
+ /// File di configurazione template ricetta
+ ///
+ public string TemplateFile { get; set; } = "";
+
+ ///
+ /// Numero di righe da creare x ricetta
+ ///
+ public int NumRow { get; set; } = 1;
+
+ ///
+ /// Configurazione ricetta x header
+ ///
+ public RecipeBlockConfig HeadConf { get; set; } = new RecipeBlockConfig();
+
+ ///
+ /// Configurazione ricetta x rows
+ ///
+ public RecipeBlockConfig RowsConf { get; set; } = new RecipeBlockConfig();
+
+ }
+}
diff --git a/MP.Data/Controllers/MpIocController.cs b/MP.Data/Controllers/MpIocController.cs
new file mode 100644
index 00000000..9b52a93a
--- /dev/null
+++ b/MP.Data/Controllers/MpIocController.cs
@@ -0,0 +1,391 @@
+using Microsoft.Data.SqlClient;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.Extensions.Configuration;
+using MP.Data.DatabaseModels;
+using NLog;
+using System;
+using System.Collections.Generic;
+using System.Data;
+using System.Linq;
+using System.Threading.Tasks;
+
+namespace MP.Data.Controllers
+{
+ public class MpIocController : IDisposable
+ {
+ #region Public Constructors
+
+ public MpIocController(IConfiguration configuration)
+ {
+ _configuration = configuration;
+ Log.Info("Avviata classe MpIocController");
+ }
+
+ #endregion Public Constructors
+
+ #region Public Methods
+
+
+ ///
+ /// Elenco da tabella Config
+ ///
+ ///
+ public List ConfigGetAll()
+ {
+ List dbResult = new List();
+ using (var dbCtx = new MoonProContext(_configuration))
+ {
+ dbResult = dbCtx
+ .DbSetConfig
+ .AsNoTracking()
+ .OrderBy(x => x.Chiave)
+ .ToList();
+ }
+ return dbResult;
+ }
+
+ ///
+ /// Update record config
+ ///
+ ///
+ public bool ConfigUpdate(ConfigModel updRec)
+ {
+ bool fatto = false;
+ ConfigModel dbResult = new ConfigModel();
+ using (var dbCtx = new MoonProContext(_configuration))
+ {
+ dbResult = dbCtx
+ .DbSetConfig
+ .Where(x => x.Chiave == updRec.Chiave)
+ .FirstOrDefault();
+ if (dbResult != null)
+ {
+ dbResult.Valore = updRec.Valore;
+ dbCtx.SaveChanges();
+ fatto = true;
+ }
+ }
+ return fatto;
+ }
+
+ ///
+ /// Intera tab dati macchina
+ ///
+ ///
+ public List DatiMacchineGetAll()
+ {
+ List dbResult = new List();
+ using (var dbCtx = new MoonProContext(_configuration))
+ {
+ dbResult = dbCtx
+ .DbSetDatiMacchine
+ .AsNoTracking()
+ .OrderBy(x => x.IdxMacchina)
+ .ToList();
+ }
+ return dbResult;
+ }
+
+ public void Dispose()
+ {
+ _configuration = null;
+ }
+
+
+ ///
+ /// Aggiunta record EventList
+ ///
+ ///
+ ///
+ public async Task EvListInsert(EventListModel newRec)
+ {
+ bool fatto = false;
+ using (var dbCtx = new MoonProContext(_configuration))
+ {
+ try
+ {
+ var currRec = dbCtx
+ .DbSetEvList
+ .Add(newRec);
+ await dbCtx.SaveChangesAsync();
+ }
+ catch (Exception exc)
+ {
+ Log.Error($"Eccezione durante EvListInsert{Environment.NewLine}{exc}");
+ }
+ }
+ await Task.Delay(1);
+ return fatto;
+ }
+
+ ///
+ /// Elenco ultimi n record flux log dato macchina e flusso (ordinato x data registrazione)
+ ///
+ /// Data massima x eventi
+ /// Data minima x eventi
+ /// * = tutte, altrimenti solo x una data macchina
+ /// *=tutti, altrimenti solo selezionato
+ /// numero massimo record da restituire
+ ///
+ public List FluxLogGetLastFilt(DateTime DtMax, DateTime DtMin, string IdxMacchina, string CodFlux, int MaxRec)
+ {
+ List dbResult = new List();
+ using (var dbCtx = new MoonProContext(_configuration))
+ {
+ dbResult = dbCtx
+ .DbSetFluxLog
+ .AsNoTracking()
+ .Where(x => (x.dtEvento >= DtMin && x.dtEvento <= DtMax) && (IdxMacchina == "*" || x.IdxMacchina == IdxMacchina) && (CodFlux == "*" || x.CodFlux == CodFlux))
+ .OrderByDescending(x => x.dtEvento)
+ .Take(MaxRec)
+ .ToList();
+ }
+ return dbResult;
+ }
+
+ public bool KeepAliveUpsert(string IdxMacc, DateTime OraServer, DateTime OraMacc)
+ {
+ bool fatto = false;
+ using (var dbCtx = new MoonProContext(_configuration))
+ {
+ var currRec = dbCtx
+ .DbSetKeepAlive
+ .Where(x => x.IdxMacchina == IdxMacc)
+ .FirstOrDefault();
+ if (currRec != null)
+ {
+ currRec.DataOraServer = OraServer;
+ currRec.DataOraMacchina = OraMacc;
+ dbCtx.Entry(currRec).State = EntityState.Modified;
+ }
+ else
+ {
+ KeepAliveModel newRec = new KeepAliveModel()
+ {
+ IdxMacchina = IdxMacc,
+ DataOraMacchina = OraMacc,
+ DataOraServer = OraServer,
+ DataOraStart = DateTime.Now
+ };
+ dbCtx
+ .DbSetKeepAlive
+ .Add(newRec);
+ }
+ dbCtx.SaveChanges();
+ fatto = true;
+ }
+ return fatto;
+ }
+
+
+ public List ListLinkFilt(string tipoLink)
+ {
+ List dbResult = new List();
+ using (var dbCtx = new MoonProContext(_configuration))
+ {
+ dbResult = dbCtx
+ .DbSetLinkMenu
+ .Where(x => x.TipoLink == tipoLink)
+ .AsNoTracking()
+ .OrderBy(x => x.ordine)
+ .ToList();
+ }
+ return dbResult;
+ }
+
+ ///
+ /// Intera tabella relazione master/slave in machine (gestione setup master --> slave)
+ ///
+ ///
+ public List Macchine2Slave()
+ {
+ List dbResult = new List();
+ using (var dbCtx = new MoonProContext(_configuration))
+ {
+ dbResult = dbCtx
+ .DbSetM2S
+ .AsNoTracking()
+ .OrderBy(x => x.IdxMacchina)
+ .ToList();
+ }
+ return dbResult;
+ }
+
+ ///
+ /// Elenco da tabella Macchine
+ ///
+ ///
+ ///
+ public List MacchineGetFilt(string codGruppo)
+ {
+ List dbResult = new List();
+ try
+ {
+ using (var dbCtx = new MoonProContext(_configuration))
+ {
+ if (codGruppo == "*")
+ {
+ dbResult = dbCtx
+ .DbSetMacchine
+ .AsNoTracking()
+ .OrderBy(x => x.IdxMacchina)
+ .ToList();
+ }
+ else
+ {
+ dbResult = dbCtx
+ .DbSetGrp2Macc
+ .Where(g => g.CodGruppo == codGruppo)
+ .Join(dbCtx.DbSetMacchine,
+ g => g.IdxMacchina,
+ m => m.IdxMacchina,
+ (g, m) => m
+ )
+ .AsNoTracking()
+ .OrderBy(x => x.IdxMacchina)
+ .ToList();
+ }
+ }
+ }
+ catch (Exception exc)
+ {
+ Log.Error($"Eccezione in MacchineGetFilt{Environment.NewLine}{exc}");
+ }
+ return dbResult;
+ }
+
+ ///
+ /// Elenco da tabella MappaStatoExpl
+ ///
+ ///
+ public List MseGetAll(int maxAge = 2000)
+ {
+ List dbResult = new List();
+ using (var dbCtx = new MoonProContext(_configuration))
+ {
+ var maxAgeSec = new SqlParameter("@maxAgeSec", maxAge);
+
+ dbResult = dbCtx
+ .DbSetMSE
+ .FromSqlRaw("EXEC stp_MSE_getData @maxAgeSec", maxAgeSec)
+ .AsNoTracking()
+ .ToList();
+ }
+ return dbResult;
+ }
+
+ ///
+ /// Annulla modifiche su una specifica entity (cancel update)
+ ///
+ ///
+ ///
+ public bool RollBackEntity(object item)
+ {
+ bool answ = false;
+ using (var dbCtx = new MoonProContext(_configuration))
+ {
+ try
+ {
+ if (dbCtx.Entry(item).State == Microsoft.EntityFrameworkCore.EntityState.Deleted || dbCtx.Entry(item).State == Microsoft.EntityFrameworkCore.EntityState.Modified)
+ {
+ dbCtx.Entry(item).Reload();
+ }
+ }
+ catch (Exception exc)
+ {
+ Log.Error($"Eccezione in rollBackEntity{Environment.NewLine}{exc}");
+ }
+ }
+ return answ;
+ }
+
+ ///
+ /// Intera tabella relazione master/slave in machine (gestione setup master --> slave)
+ ///
+ ///
+ public List StateMachineIngressi(int idxFam)
+ {
+ List dbResult = new List();
+ using (var dbCtx = new MoonProContext(_configuration))
+ {
+ var IdxFamIn = new SqlParameter("@IdxFamigliaIngresso", idxFam);
+ dbResult = dbCtx
+ .DbSetSMI
+ .FromSqlRaw("exec dbo.stp_TRI_getByIdxFamIng @IdxFamigliaIngresso", IdxFamIn)
+ .AsNoTracking()
+ .AsEnumerable()
+ .ToList();
+ }
+ return dbResult;
+ }
+
+ ///
+ /// Stato prod macchina
+ ///
+ ///
+ ///
+ public StatoProdModel StatoProdMacchina(string idxMacchina)
+ {
+ StatoProdModel dbResult = new StatoProdModel();
+ using (var dbCtx = new MoonProContext(_configuration))
+ {
+ var IdxMacchina = new SqlParameter("@IdxMacchina", idxMacchina);
+ dbResult = dbCtx
+ .DbSetStatoProd
+ .FromSqlRaw("EXEC stp_PzProd_getByMacchina @IdxMacchina", IdxMacchina)
+ .AsNoTracking()
+ .FirstOrDefault();
+ }
+ return dbResult;
+ }
+
+ ///
+ /// Intera vista v_MSFD
+ ///
+ ///
+ public List VMSFDGetAll()
+ {
+ List dbResult = new List();
+ using (var dbCtx = new MoonProContext(_configuration))
+ {
+ dbResult = dbCtx
+ .DbSetMSFD
+ .AsNoTracking()
+ .OrderBy(x => x.IdxMacchina)
+ .ToList();
+ }
+ return dbResult;
+ }
+
+ ///
+ /// Vista v_MSFD CALCOALTA x singola macchina (da stored) - singolo record
+ ///
+ ///
+ public List VMSFDGetByMacc(string idxMacc)
+ {
+ List dbResult = new List();
+ using (var dbCtx = new MoonProContext(_configuration))
+ {
+ var IdxMacchina = new SqlParameter("@IdxMacchina", idxMacc);
+
+ dbResult = dbCtx
+ .DbSetMSFD
+ .FromSqlRaw("exec dbo.stp_MSFD_getMacc @IdxMacchina", IdxMacchina)
+ .AsNoTracking()
+ .AsEnumerable()
+ .ToList();
+ }
+ return dbResult;
+ }
+
+ #endregion Public Methods
+
+ #region Private Fields
+
+ private static IConfiguration _configuration;
+
+ private static NLog.Logger Log = LogManager.GetCurrentClassLogger();
+
+ #endregion Private Fields
+ }
+}
\ No newline at end of file
diff --git a/MP.Data/Controllers/MpMongoController.cs b/MP.Data/Controllers/MpMongoController.cs
new file mode 100644
index 00000000..939a5768
--- /dev/null
+++ b/MP.Data/Controllers/MpMongoController.cs
@@ -0,0 +1,209 @@
+using Microsoft.Extensions.Configuration;
+using NLog;
+using NLog.Fluent;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using MongoDB.Driver;
+using MongoDB.Bson;
+using MP.Data.MgModels;
+using System.IO;
+using MP.Data.Conf;
+using Newtonsoft.Json;
+using static MP.Data.MgModels.RecipeModel;
+
+namespace MP.Data.Controllers
+{
+ public class MpMongoController : IDisposable
+ {
+
+ public MpMongoController(IConfiguration configuration)
+ {
+ _configuration = configuration;
+ string mongoConf = _configuration.GetConnectionString("mdbConnString");
+ client = new MongoClient(mongoConf);
+ mongoDb = client.GetDatabase("MAPO");
+ Log.Info("Avviata classe MpMongoController");
+ }
+ ///
+ /// Database corrente MongoDB
+ ///
+ private IMongoDatabase mongoDb;
+
+ public void Dispose()
+ {
+ client = null;
+ _configuration = null;
+ }
+
+ ///
+ /// Ricerca ricetta su MongoDB dato PODL
+ ///
+ ///
+ ///
+ public async Task RecipeGetByPODL(int idxPODL)
+ {
+ await Task.Delay(1);
+ RecipeModel answ = new RecipeModel();
+ try
+ {
+ // definisco filtro
+ var filtBuilder = Builders.Filter;
+ var filter = filtBuilder.Eq("IdxPODL", idxPODL);
+ var collectionData = mongoDb.GetCollection("RecipeArchive");
+ // recupero
+ answ = collectionData.Find(filter).Project("{_id: 0}").FirstOrDefault();
+ }
+ catch
+ { }
+ return answ;
+ }
+
+ ///
+ /// Ricerca ricetta su MongoDB dato ID MongoDB
+ ///
+ ///
+ ///
+ public async Task RecipeGetByID(string mID)
+ {
+ await Task.Delay(1);
+ RecipeModel answ = new RecipeModel();
+ try
+ {
+ // definisco filtro
+ var filtBuilder = Builders.Filter;
+ var filter = filtBuilder.Eq("_id", mID);
+ var collectionData = mongoDb.GetCollection("RecipeArchive");
+ // recupero
+ answ = collectionData.Find(filter).Project("{_id: 0}").FirstOrDefault();
+ }
+ catch
+ { }
+ return answ;
+ }
+ ///
+ /// Salva ricetta su MongoDB
+ ///
+ ///
+ ///
+ public async Task RecipeSetByPODL(RecipeModel currRecord)
+ {
+ await Task.Delay(1);
+ bool answ = false;
+ try
+ {
+ // definisco filtro
+ var filtBuilder = Builders.Filter;
+ var filter = filtBuilder.Eq("IdxPODL", currRecord.IdxPODL);
+ var collectionData = mongoDb.GetCollection("RecipeArchive");
+ // elimino old
+ collectionData.DeleteMany(filter);
+ // aggiungo
+ collectionData.InsertOne(currRecord);
+ answ = true;
+ }
+ catch (Exception exc)
+ {
+ Log.Error($"Eccezione in RecipeSetByPODL{Environment.NewLine}{exc}");
+ }
+
+ return answ;
+ }
+
+ ///
+ /// Init ricetta dato PODL + conf
+ ///
+ ///
+ ///
+ ///
+ ///
+ public RecipeModel InitRecipe(string confPath, int idxPODL, Dictionary CalcArgs)
+ {
+ RecipeModel answ = new RecipeModel();
+ // per prima cosa leggo file di conf x inizializzare ricetta...
+ string fullPath = RecipePath(confPath);
+ bool fileOk = File.Exists(fullPath);
+ if (fileOk)
+ {
+ string rawData = File.ReadAllText(fullPath);
+ var currRecipe = JsonConvert.DeserializeObject(rawData);
+ // inizializzo dalla conf...
+ answ = new RecipeModel(idxPODL, currRecipe, CalcArgs);
+ }
+
+ return answ;
+ }
+
+
+ ///
+ /// Ricetta in formato calcolato (string)
+ ///
+ public string CalcRecipe(RecipeModel currRecipe)
+ {
+ string answ = "";
+ // per prima cosa leggo file di conf x inizializzare ricetta...
+ string fullPath = RecipePath(currRecipe.TemplateFile);
+ bool fileOk = File.Exists(fullPath);
+ if (fileOk)
+ {
+ // preparo dati header
+ var headStrings = currRecipe.HeadVal.Select(x => $"\"{x.Key}\": \"{x.Value}\"").ToList();
+ string headVals = string.Join(",", headStrings);
+
+
+ // leggo template
+ string rawData = File.ReadAllText(fullPath);
+ // recupero configurazione x inizio/fine righe
+ string[] righe = rawData.Split(Environment.NewLine);
+ List righeRed = new List();
+ string sRow = "";
+ string eRow = "";
+ foreach (var riga in righe)
+ {
+ if (riga.Trim().StartsWith("||SROW:"))
+ {
+ sRow = riga.Trim().Replace("||SROW:", "").Replace("||", "");
+ }
+ else if (riga.Trim().StartsWith("||EROW:"))
+ {
+ eRow = riga.Trim().Replace("||EROW:", "").Replace("||", "");
+ }
+ else
+ {
+ righeRed.Add(riga);
+ }
+ }
+ // rigenero righe senza le parti da ripetere...
+ rawData = string.Join(Environment.NewLine, righeRed);
+ // effettuo sostituzione...
+ answ = rawData.Replace("||PlaceholderHeader||", headVals);
+ // per le righe prima calcolo blocchi ripetuti
+ List rowComp = new List();
+ foreach (var item in currRecipe.RowsVal)
+ {
+ var rowsStrings = item.Value.Select(x => $"\"{x.Key}\": \"{x.Value}\"").ToList();
+ rowComp.Add($"{sRow}{string.Join(",", rowsStrings)}{eRow}");
+ }
+ string rowsVals = string.Join($",{Environment.NewLine}", rowComp);
+ //...poi sostituisco
+ answ = answ.Replace("||PlaceholderRows||", rowsVals);
+ }
+ return answ;
+ }
+
+
+ private MongoClient client = new MongoClient("mongodb://localhost:27017");
+
+ private static IConfiguration _configuration;
+
+ private static Logger Log = LogManager.GetCurrentClassLogger();
+
+ public static string RecipePath(string ruleName)
+ {
+ return string.Format($"Recipe/{ruleName}");
+ }
+
+ }
+}
diff --git a/MP.Data/Controllers/MpSpecController.cs b/MP.Data/Controllers/MpSpecController.cs
index 3f8b3c6d..a05153ba 100644
--- a/MP.Data/Controllers/MpSpecController.cs
+++ b/MP.Data/Controllers/MpSpecController.cs
@@ -294,6 +294,24 @@ namespace MP.Data.Controllers
return fatto;
}
+ ///
+ /// Intera tab dati macchina
+ ///
+ ///
+ public List DatiMacchineGetAll()
+ {
+ List dbResult = new List();
+ using (var dbCtx = new MoonProContext(_configuration))
+ {
+ dbResult = dbCtx
+ .DbSetDatiMacchine
+ .AsNoTracking()
+ .OrderBy(x => x.IdxMacchina)
+ .ToList();
+ }
+ return dbResult;
+ }
+
public void Dispose()
{
_configuration = null;
@@ -348,8 +366,8 @@ namespace MP.Data.Controllers
.AsNoTracking()
.Where(x => (IdxMacchina == "*" || x.IdxMacchina == IdxMacchina) && (CodArticolo == "*" || x.CodArticolo == CodArticolo) && (x.DtRif >= DtStart && x.DtRif <= DtEnd))
.Include(m => m.MachineNav)
- //.Include(o => o.OdlNav)
.Include(a => a.ArticoloNav)
+ ////.Include(o => o.OdlNav)
.OrderByDescending(x => x.DtRif)
.ToList();
}
@@ -571,7 +589,7 @@ namespace MP.Data.Controllers
/// Elenco TUTTI GLI ODL
///
///
- public List ListOdlAll()
+ public List OdlListAll()
{
List dbResult = new List();
using (var dbCtx = new MoonProContext(_configuration))
@@ -619,24 +637,8 @@ namespace MP.Data.Controllers
.DbSetODLExp
.FromSqlRaw("EXEC stp_ODL_getByFiltSpec @InCorso, @CodArt, @KeyRich, @CodGruppo, @IdxMacchina, @DataFrom, @DataTo", InCorso, CodArt, KeyRich, CodGruppo, IdxMacc, DataFrom, DataTo)
.AsNoTracking()
- //.AsEnumerable()
.ToList();
-#if false
- dbResult = dbCtx
- .DbSetODL
- .Where(x => ((inCorso && x.DataFine == null) || ((!inCorso && x.DataFine != null)
- && x.DataInizio >= startDate && x.DataInizio <= endDate))
- && (x.KeyRichiesta.Contains(keyRichPart) || keyRichPart == "*")
- //&& (x.MachineNav.Contains(IdxMacchina) || Reparto == "*")
- && (x.IdxMacchina.Contains(IdxMacchina) || IdxMacchina == "*")
- && (codArt == "*" || x.CodArticolo.Contains(codArt)))
- .AsNoTracking()
- .Include(m => m.MachineNav)
- .Include(a => a.ArticoloNav)
- .OrderByDescending(x => x.IdxOdl)
- .ToList();
-#endif
}
return dbResult;
}
@@ -656,14 +658,14 @@ namespace MP.Data.Controllers
{
var Lanc = new SqlParameter("@Lanciato", lanciato);
var KeyRich = new SqlParameter("@KeyRich", keyRichPart);
- var IdxMacc = new SqlParameter("@IdxMacchina", idxMacchina);
var CodGrp = new SqlParameter("@CodGruppo", codGruppo);
- var DateFrom = new SqlParameter("@DateFrom", startDate);
- var DateTo = new SqlParameter("@DateTo", endDate);
+ var IdxMacc = new SqlParameter("@IdxMacchina", idxMacchina);
+ var DateFrom = new SqlParameter("@DtInizio", startDate);
+ var DateTo = new SqlParameter("@DtFine", endDate);
dbResult = dbCtx
.DbSetPODLExp
- .FromSqlRaw("EXEC stp_PODL_getByFiltSpec @Lanciato, @KeyRich, @CodGruppo, @IdxMacchina, @DateFrom, @DateTo", Lanc, KeyRich, CodGrp, IdxMacc, DateFrom, DateTo)
+ .FromSqlRaw("EXEC stp_PODL_getByFiltSpec @Lanciato, @KeyRich, @CodGruppo, @IdxMacchina, @DtInizio, @DtFine", Lanc, KeyRich, CodGrp, IdxMacc, DateFrom, DateTo)
.AsNoTracking()
.ToList();
}
@@ -699,31 +701,38 @@ namespace MP.Data.Controllers
public List MacchineGetFilt(string codGruppo)
{
List dbResult = new List();
- using (var dbCtx = new MoonProContext(_configuration))
+ try
{
- if (codGruppo == "*")
+ using (var dbCtx = new MoonProContext(_configuration))
{
- dbResult = dbCtx
- .DbSetMacchine
- .AsNoTracking()
- .OrderBy(x => x.IdxMacchina)
- .ToList();
- }
- else
- {
- dbResult = dbCtx
- .DbSetGrp2Macc
- .Where(g => g.CodGruppo == codGruppo)
- .Join(dbCtx.DbSetMacchine,
- g => g.IdxMacchina,
- m => m.IdxMacchina,
- (g, m) => m
- )
- .AsNoTracking()
- .OrderBy(x => x.IdxMacchina)
- .ToList();
+ if (codGruppo == "*")
+ {
+ dbResult = dbCtx
+ .DbSetMacchine
+ .AsNoTracking()
+ .OrderBy(x => x.IdxMacchina)
+ .ToList();
+ }
+ else
+ {
+ dbResult = dbCtx
+ .DbSetGrp2Macc
+ .Where(g => g.CodGruppo == codGruppo)
+ .Join(dbCtx.DbSetMacchine,
+ g => g.IdxMacchina,
+ m => m.IdxMacchina,
+ (g, m) => m
+ )
+ .AsNoTracking()
+ .OrderBy(x => x.IdxMacchina)
+ .ToList();
+ }
}
}
+ catch (Exception exc)
+ {
+ Log.Error($"Eccezione in MacchineGetFilt{Environment.NewLine}{exc}");
+ }
return dbResult;
}
@@ -821,32 +830,6 @@ namespace MP.Data.Controllers
return dbResult;
}
-#if false
-
- ///
- /// Elenco PODL non avviati filtrati x articolo, KeyRich (che contiene stato)
- ///
- /// Cod articolo
- /// KeyRich (parziale) da cercare (es cod stato x yacht)
- ///
- public List ListPODLFiltNOOdl(string codArt, string keyRichPart)
- {
- List dbResult = new List();
- using (var dbCtx = new MoonProContext(_configuration))
- {
- dbResult = dbCtx
- .DbSetPODL
- .Where(x => (x.IdxOdl != 0) && (x.KeyRichiesta.Contains(keyRichPart) || keyRichPart == "*") && (codArt == "*" || x.CodArticolo.Contains(codArt)))
- .AsNoTracking()
- .Include(m => m.MachineNav)
- .Include(a => a.ArticoloNav)
- .OrderByDescending(x => x.InsertDate)
- .ToList();
- }
- return dbResult;
- }
-#endif
-
///
/// Chiusura ODL con eventuale conferma pezzi
///
@@ -1027,6 +1010,7 @@ namespace MP.Data.Controllers
.DbSetPODL
.AsNoTracking()
.Where(x => x.IdxPromessa == idxPODL)
+ .Include(a => a.ArticoloNav)
.FirstOrDefault();
}
catch (Exception exc)
@@ -1073,7 +1057,7 @@ namespace MP.Data.Controllers
///
///
///
- public async Task PODL_startSetup(PODLExpModel editRec, int matrOpr, double tcRich, int pzPallet, string note)
+ public async Task PODL_startSetup(PODLExpModel editRec, int matrOpr, double tcRich, int pzPallet, string note, DateTime dtEvent)
{
bool answ = false;
@@ -1115,9 +1099,10 @@ namespace MP.Data.Controllers
var TCRichAttr = new SqlParameter("@TCRichAttr", tcRich);
var PzPallet = new SqlParameter("@PzPallet", pzPallet);
var Note = new SqlParameter("@Note", note);
+ var DtEvento = new SqlParameter("@dtEvento", dtEvent);
var callResult = await dbCtx
.Database
- .ExecuteSqlRawAsync("EXEC stp_ODL_inizioSetupPromessa @idxPromessa, @MatrOpr, @IdxMacchina, @TCRichAttr, @PzPallet, @Note", IdxPromessa, MatrOpr, IdxMacchina, TCRichAttr, PzPallet, Note);
+ .ExecuteSqlRawAsync("EXEC stp_ODL_inizioSetupPromessa @idxPromessa, @MatrOpr, @IdxMacchina, @TCRichAttr, @PzPallet, @Note, @dtEvento", IdxPromessa, MatrOpr, IdxMacchina, TCRichAttr, PzPallet, Note, DtEvento);
answ = true;
}
@@ -1131,6 +1116,41 @@ namespace MP.Data.Controllers
return answ;
}
+ ///
+ /// Chiamata salvataggio ricetta su DB
+ ///
+ ///
+ ///
+ ///
+ public async Task PODL_updateRecipe(int idxPODL, string recipeName)
+ {
+ bool answ = false;
+ using (var dbCtx = new MoonProContext(_configuration))
+ {
+ try
+ {
+ var currRec = dbCtx
+ .DbSetPODL
+ .Where(x => x.IdxPromessa == idxPODL)
+ .FirstOrDefault();
+
+ if (currRec != null)
+ {
+ currRec.Recipe = recipeName;
+ dbCtx.Entry(currRec).State = EntityState.Modified;
+ await dbCtx.SaveChangesAsync();
+ answ = true;
+ }
+ }
+ catch (Exception exc)
+ {
+ Log.Error($"Eccezione durante PODL_updateRecipe{Environment.NewLine}{exc}");
+ }
+ }
+ await Task.Delay(1);
+ return answ;
+ }
+
///
/// Eliminazione Record
///
diff --git a/MP.Data/DatabaseModels/DatiMacchineModel.cs b/MP.Data/DatabaseModels/DatiMacchineModel.cs
new file mode 100644
index 00000000..329a6a1f
--- /dev/null
+++ b/MP.Data/DatabaseModels/DatiMacchineModel.cs
@@ -0,0 +1,33 @@
+using System;
+using System.Collections.Generic;
+
+namespace MP.Data.DatabaseModels
+{
+ public partial class DatiMacchineModel
+ {
+ public string IdxMacchina { get; set; }
+ public bool? PalletChange { get; set; }
+ public string CodArticoloA { get; set; }
+ public string CodArticoloB { get; set; }
+ public string SerialPort { get; set; }
+ public int? RefreshPeriod { get; set; }
+ public bool? Simulazione { get; set; }
+ public bool? SimplePallet { get; set; }
+ ///
+ /// definisce se l'INSERT sia abilitato per la macchina (disabilitato in fase di ricostruzione batch...)
+ ///
+ public bool? InsEnabled { get; set; }
+ ///
+ /// definisce se sia abilitata la registrazione di TUTTI gli invii di dati in ingresso da questa specifica macchina
+ ///
+ public bool SLogEnabled { get; set; }
+ ///
+ /// Abilita o meno il trigger su DiarioDiBordo x ricalcolo eventi
+ ///
+ public bool? IsTrigerDbon { get; set; }
+ ///
+ /// Indica se la macchina abbia un COUNTER (assoluto) o meno, tipicamente true x IOB-WIN, false per IOB-PI
+ ///
+ public bool HasCounter { get; set; }
+ }
+}
diff --git a/MP.Data/DatabaseModels/KeepAliveModel.cs b/MP.Data/DatabaseModels/KeepAliveModel.cs
new file mode 100644
index 00000000..a30ac535
--- /dev/null
+++ b/MP.Data/DatabaseModels/KeepAliveModel.cs
@@ -0,0 +1,13 @@
+using System;
+using System.Collections.Generic;
+
+namespace MP.Data.DatabaseModels
+{
+ public partial class KeepAliveModel
+ {
+ public string IdxMacchina { get; set; }
+ public DateTime? DataOraServer { get; set; }
+ public DateTime? DataOraMacchina { get; set; }
+ public DateTime? DataOraStart { get; set; }
+ }
+}
diff --git a/MP.Data/DatabaseModels/Macchine.cs b/MP.Data/DatabaseModels/Macchine.cs
index a2bbcc56..5cd3c9ac 100644
--- a/MP.Data/DatabaseModels/Macchine.cs
+++ b/MP.Data/DatabaseModels/Macchine.cs
@@ -17,9 +17,44 @@ namespace MP.Data.DatabaseModels
[Key]
public string IdxMacchina { get; set; }
+ ///
+ /// Cod macchina
+ ///
public string CodMacchina { get; set; } = "";
+ ///
+ /// Nome macchina
+ ///
public string Nome { get; set; } = "";
+ ///
+ /// Descrizione macchina
+ ///
public string Descrizione { get; set; } = "";
+ ///
+ /// Patch del file json di configurazione di una ricetta
+ ///
+ public string RecipePath { get; set; } = "";
+ ///
+ /// Path (assoluto!) dell'archivio ricette da impiegare
+ ///
+ public string RecipeArchivePath { get; set; } = "";
+
+ ///
+ /// Indica se abbia ricetta calcolata
+ ///
+ [NotMapped]
+ public bool hasRecipeCalc
+ {
+ get => !string.IsNullOrEmpty(RecipePath);
+ }
+ ///
+ /// Indica se abbia ricetta calcolata
+ ///
+ [NotMapped]
+ public bool hasRecipeArch
+ {
+ get => !string.IsNullOrEmpty(RecipeArchivePath);
+ }
+
//public string Note { get; set; } = "";
//public string url { get; set; } = "";
//public string locazione { get; set; } = "";
diff --git a/MP.Data/DatabaseModels/Macchine2SlaveModel.cs b/MP.Data/DatabaseModels/Macchine2SlaveModel.cs
new file mode 100644
index 00000000..6643c7d0
--- /dev/null
+++ b/MP.Data/DatabaseModels/Macchine2SlaveModel.cs
@@ -0,0 +1,11 @@
+using System;
+using System.Collections.Generic;
+
+namespace MP.Data.DatabaseModels
+{
+ public partial class Macchine2SlaveModel
+ {
+ public string IdxMacchina { get; set; }
+ public string IdxMacchinaSlave { get; set; }
+ }
+}
diff --git a/MP.Data/DatabaseModels/MappaStatoExpl.cs b/MP.Data/DatabaseModels/MappaStatoExpl.cs
index 09149dd4..34052fb4 100644
--- a/MP.Data/DatabaseModels/MappaStatoExpl.cs
+++ b/MP.Data/DatabaseModels/MappaStatoExpl.cs
@@ -15,7 +15,8 @@ namespace MP.Data.DatabaseModels
public string CodMacchina { get; set; }
public string Nome { get; set; }
public string Url { get; set; }
- public int? IdxOdl { get; set; }
+ public int? IdxOdl { get; set; } = 0;
+ public int? IdxPOdl { get; set; } = 0;
public string CodArticolo { get; set; }
public string Disegno { get; set; }
public int? NumPezzi { get; set; }
diff --git a/MP.Data/DatabaseModels/PODLExpModel.cs b/MP.Data/DatabaseModels/PODLExpModel.cs
index 849fb33d..ff1c3cfc 100644
--- a/MP.Data/DatabaseModels/PODLExpModel.cs
+++ b/MP.Data/DatabaseModels/PODLExpModel.cs
@@ -38,6 +38,8 @@ namespace MP.Data.DatabaseModels
[MaxLength(50)]
public string CodCli { get; set; } = "";
public DateTime InsertDate { get; set; } = DateTime.Now;
+ [MaxLength(500)]
+ public string Recipe { get; set; } = "";
[NotMapped]
public string CodFase
diff --git a/MP.Data/DatabaseModels/PODLModel.cs b/MP.Data/DatabaseModels/PODLModel.cs
index 2575e287..668fbb87 100644
--- a/MP.Data/DatabaseModels/PODLModel.cs
+++ b/MP.Data/DatabaseModels/PODLModel.cs
@@ -39,6 +39,8 @@ namespace MP.Data.DatabaseModels
[MaxLength(50)]
public string CodCli { get; set; } = "";
public DateTime InsertDate { get; set; } = DateTime.Now;
+ [MaxLength(500)]
+ public string Recipe { get; set; } = "";
[NotMapped]
public string CodFase
diff --git a/MP.Data/DatabaseModels/TransizioneIngressiModel.cs b/MP.Data/DatabaseModels/TransizioneIngressiModel.cs
new file mode 100644
index 00000000..72e3ad15
--- /dev/null
+++ b/MP.Data/DatabaseModels/TransizioneIngressiModel.cs
@@ -0,0 +1,14 @@
+using System;
+using System.Collections.Generic;
+
+namespace MP.Data.DatabaseModels
+{
+ public partial class TransizioneIngressiModel
+ {
+ public int IdxFamigliaIngresso { get; set; }
+ public int IdxMicroStato { get; set; }
+ public int ValoreIngresso { get; set; }
+ public int? IdxTipoEvento { get; set; }
+ public int NextIdxMicroStato { get; set; }
+ }
+}
diff --git a/MP.Data/DatabaseModels/VMSFDModel.cs b/MP.Data/DatabaseModels/VMSFDModel.cs
new file mode 100644
index 00000000..f9745bbf
--- /dev/null
+++ b/MP.Data/DatabaseModels/VMSFDModel.cs
@@ -0,0 +1,34 @@
+using System;
+using System.Collections.Generic;
+
+namespace MP.Data.DatabaseModels
+{
+ public partial class VMSFDModel
+ {
+ public string IdxMacchina { get; set; }
+ public string Codmacchina { get; set; }
+ public bool PalletChange { get; set; }
+ public string CodArticoloA { get; set; }
+ public string CodArticoloB { get; set; }
+ public bool SimplePallet { get; set; }
+ public bool InsEnabled { get; set; }
+ public bool SLogEnabled { get; set; }
+ public int IdxFamigliaIngresso { get; set; }
+ public int Multi { get; set; }
+ public int BitFilt { get; set; }
+ public int MaxVal { get; set; }
+ public int Bsr { get; set; }
+ public bool ExplodeBit { get; set; }
+ public int NumBit { get; set; }
+ public int IdxMicroStato { get; set; }
+ public int IdxFamiglia { get; set; }
+ public int IdxStato { get; set; }
+ public string LastVal { get; set; }
+ public string CodArticolo { get; set; }
+ public double TempoCicloBase { get; set; }
+ public int PzPalletProd { get; set; }
+ public int MatrOpr { get; set; }
+ public string Pallet { get; set; }
+ public string CodMaccArticolo { get; set; }
+ }
+}
diff --git a/MP.Data/MP.Data.csproj b/MP.Data/MP.Data.csproj
index 83d8498c..1086aa2d 100644
--- a/MP.Data/MP.Data.csproj
+++ b/MP.Data/MP.Data.csproj
@@ -26,6 +26,8 @@
runtime; build; native; contentfiles; analyzers; buildtransitive
+
+
\ No newline at end of file
diff --git a/MP.Data/MgModels/RecipeModel.cs b/MP.Data/MgModels/RecipeModel.cs
new file mode 100644
index 00000000..1e64f17d
--- /dev/null
+++ b/MP.Data/MgModels/RecipeModel.cs
@@ -0,0 +1,283 @@
+using MongoDB.Bson;
+using MongoDB.Bson.Serialization.Attributes;
+using MP.Data.Conf;
+using System.Collections.Generic;
+using System.ComponentModel.DataAnnotations.Schema;
+using System.Linq;
+
+namespace MP.Data.MgModels
+{
+ [BsonIgnoreExtraElements]
+ public class RecipeModel
+ {
+ #region Public Constructors
+
+ ///
+ /// Init vuoto
+ ///
+ public RecipeModel()
+ { }
+
+ ///
+ /// Init da configurazione di base
+ ///
+ /// idx PODL
+ ///
+ /// Dizionario argomenti x decodifica (es cod articolo, descrizione...)
+ public RecipeModel(int IdxPODL, RecipeConfig OrigConfig, Dictionary CalcArgs)
+ {
+ this.IdxPODL = IdxPODL;
+ this.TemplateFile = OrigConfig.TemplateFile;
+ this.HeadConf = OrigConfig.HeadConf;
+ this.RowsConf = OrigConfig.RowsConf;
+ // init oggetti tipizzati da valori conf ricevuti
+ this.HeadVal = ElementConverter(this.HeadConf.ListKeys, CalcArgs);
+ // aggiungo args x gestione contatori righe...
+ CalcArgs.Add("RowNum", $"0");
+ CalcArgs.Add("RowTot", $"{OrigConfig.NumRow}");
+ // aggiungo righe elementi..
+ for (int i = 1; i <= OrigConfig.NumRow; i++)
+ {
+ // valore calcolato numero riga gestito ad ogni iterazione
+ CalcArgs["RowNum"] = $"{i}";
+ this.RowsVal.Add($"{i}", ElementConverter(this.RowsConf.ListKeys, CalcArgs));
+ }
+ }
+ ///
+ /// Aggiunta righe
+ ///
+ ///
+ public List getNewRow(Dictionary CalcArgs)
+ {
+ List rowList = new List();
+ rowList = ElementConverter(this.RowsConf.ListKeys, CalcArgs);
+ return rowList;
+ }
+
+ #endregion Public Constructors
+
+ #region Public Properties
+
+#if false
+ ///
+ /// Ricetta in formato calcolato (string)
+ ///
+ public string CalcRecipe { get; set; } = "";
+#endif
+
+ ///
+ /// Configurazione ricetta x header
+ ///
+ public RecipeBlockConfig HeadConf { get; set; } = new RecipeBlockConfig();
+
+ ///
+ /// Lista element x testata ricetta
+ ///
+ public List HeadVal { get; set; } = new List();
+
+ [BsonId]
+ [BsonRepresentation(BsonType.ObjectId)]
+ public string? Id { get; set; }
+
+ ///
+ /// idx ODL di riferimento
+ ///
+ public int IdxODL { get; set; } = 0;
+
+ ///
+ /// Idx PODL di riferimento
+ ///
+ public int IdxPODL { get; set; } = 0;
+
+ ///
+ /// Configurazione ricetta x rows
+ ///
+ public RecipeBlockConfig RowsConf { get; set; } = new RecipeBlockConfig();
+
+ ///
+ /// Dizionario di righe, ognuna come Lista element
+ ///
+ public Dictionary> RowsVal { get; set; } = new Dictionary>();
+
+ ///
+ /// File di configurazione template ricetta
+ ///
+ public string TemplateFile { get; set; } = "";
+
+ #endregion Public Properties
+
+ #region Public Methods
+
+ ///
+ /// Converte il dizionario in List Element
+ ///
+ public static List ElementConverter(Dictionary ListKeys, Dictionary CalcArgs)
+ {
+ List ListObj = ListKeys
+ .Select(x => new Element(x.Key, x.Value, CalcArgs))
+ .ToList();
+ return ListObj;
+ }
+
+ #endregion Public Methods
+
+ #region Public Classes
+
+ ///
+ /// Elemento unitario con cui costruire la ricetta
+ ///
+ public class Element
+ {
+ #region Public Constructors
+
+ ///
+ /// Init classe da valore kvp
+ ///
+ /// Chiave item
+ /// Valore grezzo item
+ public Element(string rawKey, string rawVal, Dictionary CalcArgs)
+ {
+ this.Key = rawKey;
+ this.OrigVal = rawVal;
+ this.Value = rawVal;
+ // cerco se ho uno dei 3 caratteri (C/E/F/S):
+ if (rawVal.Length >= 2 && rawVal.Substring(1, 1) == ":")
+ {
+ string selTipo = rawVal.Substring(0, 2);
+ switch (selTipo)
+ {
+ case "C:":
+ this.Type = KeyType.Calc;
+ // recupero item x ricerca in dizionario...
+ string cKey = rawVal.Substring(2);
+ if (CalcArgs.ContainsKey(cKey))
+ {
+ this.Value = CalcArgs[cKey];
+ }
+ else
+ {
+ this.Value = cKey;
+ }
+ break;
+
+ case "E:":
+ this.Type = KeyType.Enum;
+ this.Value = "";
+ this.EnumType = rawVal.Substring(2);
+ break;
+
+ case "F:":
+ this.Type = KeyType.Fixed;
+ this.Value = rawVal.Substring(2);
+ break;
+
+ case "S:":
+ this.Type = KeyType.Calc;
+ // recupero item x ricerca in dizionario...
+ string sKey = rawVal.Substring(2);
+ if (CalcArgs.ContainsKey(sKey))
+ {
+ this.Value = CalcArgs[sKey];
+ }
+ else
+ {
+ this.Value = sKey;
+ }
+ break;
+
+ default:
+ this.Type = KeyType.None;
+ break;
+ }
+ }
+ else
+ {
+ this.Type = KeyType.Free;
+ }
+ }
+
+ #endregion Public Constructors
+
+
+ public override bool Equals(object obj)
+ {
+ if (!(obj is Element item))
+ return false;
+
+ if (Key != item.Key)
+ return false;
+
+ if (Value != item.Value)
+ return false;
+
+ if (OrigVal != item.OrigVal)
+ return false;
+
+ if (Type != item.Type)
+ return false;
+
+ if (EnumType != item.EnumType)
+ return false;
+
+ return true;
+ }
+
+ public override int GetHashCode()
+ {
+ return base.GetHashCode();
+ }
+
+ #region Public Enums
+
+ ///
+ /// Tipi di valore ammessi
+ ///
+ public enum KeyType
+ {
+ None = 0,
+ ///
+ /// Campo calcolato (NON modificabile)
+ ///
+ Calc,
+ ///
+ /// Valore da Enum
+ ///
+ Enum,
+ ///
+ /// Valore fisso
+ ///
+ Fixed,
+ ///
+ /// Valore libero
+ ///
+ Free,
+ ///
+ /// Campo suggerito (=calcolato modificabile)
+ ///
+ Suggested
+ }
+
+ #endregion Public Enums
+
+ #region Public Properties
+
+ [NotMapped]
+ public string EnumType { get; set; } = "";
+
+ [NotMapped]
+ public string Key { get; set; } = "";
+
+ public string OrigVal { get; set; } = "";
+
+ [NotMapped]
+ public KeyType Type { get; set; } = KeyType.None;
+
+ [NotMapped]
+ public string Value { get; set; } = "";
+
+ #endregion Public Properties
+ }
+
+ #endregion Public Classes
+ }
+}
\ No newline at end of file
diff --git a/MP.Data/MoonProContext.cs b/MP.Data/MoonProContext.cs
index c971d028..d25b9ddf 100644
--- a/MP.Data/MoonProContext.cs
+++ b/MP.Data/MoonProContext.cs
@@ -56,6 +56,11 @@ namespace MP.Data
public virtual DbSet DbSetVocabolario { get; set; }
public virtual DbSet DbOperatori { get; set; }
public virtual DbSet DbSetGrp2Macc { get; set; }
+ public virtual DbSet DbSetDatiMacchine { get; set; }
+ public virtual DbSet DbSetMSFD { get; set; }
+ public virtual DbSet DbSetM2S { get; set; }
+ public virtual DbSet DbSetSMI { get; set; }
+ public virtual DbSet DbSetKeepAlive { get; set; }
#endregion Public Properties
@@ -322,6 +327,146 @@ namespace MP.Data
});
+ modelBuilder.Entity(entity =>
+ {
+ entity.HasKey(e => e.IdxMacchina);
+
+ entity.ToTable("DatiMacchine");
+
+ entity.Property(e => e.IdxMacchina)
+ .HasMaxLength(50)
+ .HasColumnName("idxMacchina");
+
+ entity.Property(e => e.CodArticoloA)
+ .HasMaxLength(50)
+ .HasColumnName("CodArticolo_A");
+
+ entity.Property(e => e.CodArticoloB)
+ .HasMaxLength(50)
+ .HasColumnName("CodArticolo_B");
+
+ entity.Property(e => e.HasCounter)
+ .HasColumnName("hasCounter")
+ .HasComment("Indica se la macchina abbia un COUNTER (assoluto) o meno, tipicamente true x IOB-WIN, false per IOB-PI");
+
+ entity.Property(e => e.InsEnabled)
+ .HasColumnName("insEnabled")
+ .HasDefaultValueSql("((1))")
+ .HasComment("definisce se l'INSERT sia abilitato per la macchina (disabilitato in fase di ricostruzione batch...)");
+
+ entity.Property(e => e.IsTrigerDbon)
+ .IsRequired()
+ .HasColumnName("isTrigerDBOn")
+ .HasDefaultValueSql("((1))")
+ .HasComment("Abilita o meno il trigger su DiarioDiBordo x ricalcolo eventi");
+
+ entity.Property(e => e.PalletChange).HasColumnName("palletChange");
+
+ entity.Property(e => e.RefreshPeriod).HasColumnName("refreshPeriod");
+
+ entity.Property(e => e.SLogEnabled)
+ .HasColumnName("sLogEnabled")
+ .HasComment("definisce se sia abilitata la registrazione di TUTTI gli invii di dati in ingresso da questa specifica macchina");
+
+ entity.Property(e => e.SerialPort)
+ .HasMaxLength(50)
+ .HasColumnName("serialPort");
+
+ entity.Property(e => e.SimplePallet).HasColumnName("simplePallet");
+
+ entity.Property(e => e.Simulazione).HasColumnName("simulazione");
+ });
+
+
+ modelBuilder.Entity(entity =>
+ {
+ entity.HasNoKey();
+
+ entity.ToView("v_MSFD");
+
+ entity.Property(e => e.Bsr).HasColumnName("BSR");
+
+ entity.Property(e => e.CodArticolo)
+ .IsRequired()
+ .HasMaxLength(50);
+
+ entity.Property(e => e.CodArticoloA)
+ .IsRequired()
+ .HasMaxLength(50)
+ .HasColumnName("CodArticolo_A");
+
+ entity.Property(e => e.CodArticoloB)
+ .IsRequired()
+ .HasMaxLength(50)
+ .HasColumnName("CodArticolo_B");
+
+ entity.Property(e => e.CodMaccArticolo)
+ .IsRequired()
+ .HasMaxLength(103);
+
+ entity.Property(e => e.Codmacchina)
+ .IsRequired()
+ .HasMaxLength(50)
+ .HasColumnName("codmacchina");
+
+ entity.Property(e => e.IdxMacchina)
+ .IsRequired()
+ .HasMaxLength(50)
+ .HasColumnName("idxmacchina");
+
+ entity.Property(e => e.InsEnabled).HasColumnName("insEnabled");
+
+ entity.Property(e => e.LastVal)
+ .IsRequired()
+ .HasMaxLength(50)
+ .HasColumnName("lastVal");
+
+ entity.Property(e => e.Pallet)
+ .IsRequired()
+ .HasMaxLength(20)
+ .HasColumnName("pallet");
+
+ entity.Property(e => e.PalletChange).HasColumnName("palletChange");
+
+ entity.Property(e => e.SLogEnabled).HasColumnName("sLogEnabled");
+
+ entity.Property(e => e.SimplePallet).HasColumnName("simplePallet");
+ });
+
+ modelBuilder.Entity(entity =>
+ {
+ entity.HasKey(e => new { e.IdxMacchina, e.IdxMacchinaSlave })
+ .HasName("PK_Macc2Slave");
+
+ entity.ToTable("Macchine2Slave");
+
+ entity.Property(e => e.IdxMacchina).HasMaxLength(50);
+
+ entity.Property(e => e.IdxMacchinaSlave).HasMaxLength(50);
+ });
+
+ modelBuilder.Entity(entity =>
+ {
+ entity.HasKey(e => new { e.IdxFamigliaIngresso, e.IdxMicroStato, e.ValoreIngresso });
+
+ entity.ToTable("TransizioneIngressi");
+
+ entity.Property(e => e.NextIdxMicroStato).HasColumnName("next_IdxMicroStato");
+ });
+
+ modelBuilder.Entity(entity =>
+ {
+ entity.HasKey(e => e.IdxMacchina);
+
+ entity.ToTable("KeepAlive");
+
+ entity.Property(e => e.IdxMacchina).HasMaxLength(50);
+
+ entity.Property(e => e.DataOraMacchina).HasColumnType("datetime");
+
+ entity.Property(e => e.DataOraStart).HasColumnType("datetime");
+ });
+
OnModelCreatingPartial(modelBuilder);
}
diff --git a/MP.Data/Utils.cs b/MP.Data/Utils.cs
index 7a400db0..77f04a19 100644
--- a/MP.Data/Utils.cs
+++ b/MP.Data/Utils.cs
@@ -1,4 +1,5 @@
using MP.Data.DatabaseModels;
+using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.ComponentModel;
@@ -43,21 +44,89 @@ namespace MP.Data
}
///
- /// Nome della variabile HASH da utilizzare (dato CodModulo / Server / DB impiegato da
- /// funzionalita' DbConfig) + keyName richiesto...
+ /// Hash dati STATUS x la macchina specificata
///
- public static string RedHash(string keyName)
+ ///
+ ///
+ public static RedisKey dtMaccHash(string idxMacchina)
{
- string answ = keyName;
- try
+ return (RedisKey)$"{redisBaseAddr}DtMac:{idxMacchina}";
+ }
+
+ public static string FormDurata(double durataMinuti)
+ {
+ string answ = "";
+ TimeSpan tsDurata = TimeSpan.FromMinutes(durataMinuti);
+ if (tsDurata.TotalDays < 1)
{
- answ = $"MP:Data:{keyName}";
+ answ = $"{tsDurata.Hours:00}h {tsDurata.Minutes:00}'";
+ }
+ else
+ {
+ answ = $"{tsDurata.Days}gg {tsDurata.Hours:00}h";
}
- catch
- { }
return answ;
}
+ ///
+ /// RedisKey calcolata x tabella HSI
+ ///
+ ///
+ ///
+ public static RedisKey hSMI(int idxFamIn)
+ {
+ return (RedisKey)$"{redisBaseAddr}hSMI:{idxFamIn}";
+ }
+
+ ///
+ /// Inizializzazione con periodo e arrotondamento
+ ///
+ ///
+ ///
+ public static DateTime InitDatetime(DateTime dtRif, int minRound)
+ {
+ TimeSpan DayElapsed = dtRif.Subtract(dtRif.Date);
+ int minDay = (int)Math.Ceiling((double)(DayElapsed.TotalMinutes / minRound)) * minRound;
+ DateTime endRounded = DateTime.Today.AddMinutes(minDay);
+ return endRounded;
+ }
+
+ ///
+ /// Nome della variabile HASH da utilizzare (dato CodModulo / Server / DB impiegato
+ /// dafunzionalita' DbConfig) + idxMacchina richiesto...
+ ///
+ ///
+ ///
+ public static RedisKey OptParHash(string idxMacchina)
+ {
+ return (RedisKey)$"{redisBaseAddr}OpPar:{idxMacchina}";
+ }
+
+ ///
+ /// Nome della variabile HASH da utilizzare (dato CodModulo / Server / DB impiegato da
+ /// funzionalita' DbConfig) + idxMacchina richiesto...
+ ///
+ public static RedisKey RedHash(string keyName)
+ {
+ return (RedisKey)$"MP:Data:{keyName}";
+ }
+
+ ///
+ /// Formato RedisKey delal chaive richeista (completa)
+ ///
+ public static RedisKey RedKeyHash(string keyName)
+ {
+ return (RedisKey)$"{redisBaseAddr}{keyName}";
+ }
+
+ ///
+ /// Formato RedisValue delal chaive richeista (completa)
+ ///
+ public static RedisValue RedValue(string keyName)
+ {
+ return (RedisValue)$"{redisBaseAddr}{keyName}";
+ }
+
///
/// Effettua salvataggio in file di un generico oggetto in formato CSV
///
@@ -78,36 +147,45 @@ namespace MP.Data
await Task.Run(() => File.WriteAllLines(path, lines.ToArray()));
}
- ///
- /// Inizializzazione con periodo e arrotondamento
- ///
- ///
- ///
- public static DateTime InitDatetime(DateTime dtRif, int minRound)
- {
- TimeSpan DayElapsed = dtRif.Subtract(dtRif.Date);
- int minDay = (int)Math.Ceiling((double)(DayElapsed.TotalMinutes / minRound)) * minRound;
- DateTime endRounded = DateTime.Today.AddMinutes(minDay);
- return endRounded;
- }
+ #endregion Public Methods
- public static string FormDurata(double durataMinuti)
- {
- string answ = "";
- TimeSpan tsDurata = TimeSpan.FromMinutes(durataMinuti);
- if (tsDurata.TotalDays < 1)
- {
- answ = $"{tsDurata.Hours:00}h {tsDurata.Minutes:00}'";
- }
- else
- {
- answ = $"{tsDurata.Days}gg {tsDurata.Hours:00}h";
- }
- return answ;
- }
+ #region Public Classes
public class POdlExt
{
+ #region Public Methods
+
+ ///
+ /// Clona un POdleExt, tutti i valori (compreso idxOdl)
+ ///
+ ///
+ ///
+ public static PODLExpModel clone(PODLExpModel selRec, bool resetOdl)
+ {
+ // creo record duplicato...
+ PODLExpModel newRec = new PODLExpModel()
+ {
+ Attivabile = resetOdl ? false : selRec.Attivabile,
+ CodArticolo = selRec.CodArticolo,
+ CodCli = selRec.CodCli,
+ CodGruppo = selRec.CodGruppo,
+ DueDate = selRec.DueDate,
+ IdxMacchina = selRec.IdxMacchina,
+ IdxOdl = resetOdl ? 0 : selRec.IdxOdl,
+ IdxPromessa = 0,
+ InsertDate = selRec.InsertDate,
+ KeyBCode = selRec.KeyBCode,
+ KeyRichiesta = selRec.KeyRichiesta,
+ Note = $"DUPLICATED - {selRec.Note}",
+ NumPezzi = selRec.NumPezzi,
+ Priorita = selRec.Priorita,
+ PzPallet = selRec.PzPallet,
+ Tcassegnato = selRec.Tcassegnato,
+ Recipe = selRec.Recipe
+ };
+ return newRec;
+ }
+
///
/// Clona un POdleExt a POdl
///
@@ -133,42 +211,46 @@ namespace MP.Data
NumPezzi = selRec.NumPezzi,
Priorita = selRec.Priorita,
PzPallet = selRec.PzPallet,
- Tcassegnato = selRec.Tcassegnato
+ Tcassegnato = selRec.Tcassegnato,
+ Recipe = selRec.Recipe
};
return newRec;
}
- ///
- /// Clona un POdleExt, tutti i valori (compreso idxOdl)
- ///
- ///
- ///
- public static PODLExpModel clone(PODLExpModel selRec, bool resetOdl)
- {
- // creo record duplicato...
- PODLExpModel newRec = new PODLExpModel()
- {
- Attivabile = selRec.Attivabile,
- CodArticolo = selRec.CodArticolo,
- CodCli = selRec.CodCli,
- CodGruppo = selRec.CodGruppo,
- DueDate = selRec.DueDate,
- IdxMacchina = selRec.IdxMacchina,
- IdxOdl = resetOdl ? 0 : selRec.IdxOdl,
- IdxPromessa = 0,
- InsertDate = selRec.InsertDate,
- KeyBCode = selRec.KeyBCode,
- KeyRichiesta = selRec.KeyRichiesta,
- Note = $"DUPLICATED - {selRec.Note}",
- NumPezzi = selRec.NumPezzi,
- Priorita = selRec.Priorita,
- PzPallet = selRec.PzPallet,
- Tcassegnato = selRec.Tcassegnato
- };
- return newRec;
- }
+ #endregion Public Methods
}
- #endregion Public Methods
+ #endregion Public Classes
+
+ #region Private Fields
+
+ public const string redisActionReq = redisBaseAddr + "Action:Req";
+ public const string redisAnagGruppi = redisBaseAddr + "Cache:AnagGruppi";
+ public const string redisArtByDossier = redisBaseAddr + "Cache:ArtByDossier";
+ public const string redisArtList = redisBaseAddr + "Cache:ArtList";
+ public const string redisBaseAddr = "MP:";
+ public const string redisConfKey = redisBaseAddr + "Cache:Config";
+ public const string redisDossByMac = redisBaseAddr + "Cache:DossByMac";
+ public const string redisFluxByMac = redisBaseAddr + "Cache:FluxByMac";
+ public const string redisFluxLogFilt = redisBaseAddr + "Cache:FluxLogFilt";
+ public const string redisGiacenzaList = redisBaseAddr + "Cache:GiacenzaList";
+ public const string redisMacByFlux = redisBaseAddr + "Cache:MacByFlux";
+ public const string redisMacList = redisBaseAddr + "Cache:MacList";
+ public const string redisMacRecipeConf = redisBaseAddr + "Cache:RecipeConf";
+ public const string redisMacRecipePath = redisBaseAddr + "Cache:RecipePath";
+ public const string redisOdlByBatch = redisXdlData + "OdlByBatch";
+ public const string redisOdlCurrByMac = redisXdlData + "OdlByMac";
+ public const string redisOdlList = redisXdlData + "OdlList";
+ public const string redisParamPageExp = redisBaseAddr + "Cache:ParamPage";
+ public const string redisPOdlByOdl = redisXdlData + "POdlByOdl";
+ public const string redisPOdlByPOdl = redisXdlData + "POdlByPOdl";
+ public const string redisPOdlList = redisXdlData + "POdlList";
+ public const string redisRecipeConf = redisBaseAddr + "Cache:Recipe:Conf";
+ public const string redisStatoCom = redisBaseAddr + "Cache:StatoCom";
+ public const string redisTipoArt = redisBaseAddr + "Cache:TipoArt";
+ public const string redisVocabolario = redisBaseAddr + "Cache:Vocabolario";
+ public const string redisXdlData = redisBaseAddr + "Cache:XDL:";
+
+ #endregion Private Fields
}
}
\ No newline at end of file
diff --git a/MP.FileData/MP.FileData.csproj b/MP.FileData/MP.FileData.csproj
index 287fa655..529ef021 100644
--- a/MP.FileData/MP.FileData.csproj
+++ b/MP.FileData/MP.FileData.csproj
@@ -5,19 +5,21 @@
-
-
+
+
+
all
runtime; build; native; contentfiles; analyzers; buildtransitive
-
-
-
+
+
+
all
runtime; build; native; contentfiles; analyzers; buildtransitive
-
-
+
+
+
diff --git a/MP.INVE/MP.INVE.csproj b/MP.INVE/MP.INVE.csproj
index 3d658b8d..e0ed8811 100644
--- a/MP.INVE/MP.INVE.csproj
+++ b/MP.INVE/MP.INVE.csproj
@@ -5,7 +5,7 @@
enable
enable
MP.INVE
- 6.16.2302.2309
+ 6.16.2306.915
@@ -18,10 +18,10 @@
-
-
+
+
-
+
diff --git a/MP.INVE/Properties/PublishProfiles/IIS03.pubxml b/MP.INVE/Properties/PublishProfiles/IIS04.pubxml
similarity index 89%
rename from MP.INVE/Properties/PublishProfiles/IIS03.pubxml
rename to MP.INVE/Properties/PublishProfiles/IIS04.pubxml
index fd9d1a6e..b86cfa44 100644
--- a/MP.INVE/Properties/PublishProfiles/IIS03.pubxml
+++ b/MP.INVE/Properties/PublishProfiles/IIS04.pubxml
@@ -8,11 +8,11 @@ https://go.microsoft.com/fwlink/?LinkID=208121.
true
Release
Any CPU
- https://iis03.egalware.com/MP/INVE
+ https://iis04.egalware.com/MP/INVE
false
fd5b477e-96a4-42f6-b2e8-7fc221c9971c
false
- https://iis03.egalware.com:8172/MsDeploy.axd
+ https://iis04.egalware.com:8172/MsDeploy.axd
Default Web Site/MP/INVE
false
diff --git a/MP.INVE/Resources/ChangeLog.html b/MP.INVE/Resources/ChangeLog.html
index 000ed40f..18eec117 100644
--- a/MP.INVE/Resources/ChangeLog.html
+++ b/MP.INVE/Resources/ChangeLog.html
@@ -1,6 +1,6 @@
Modulo MAPOINVE
- Versione: 6.16.2302.2309
+ Versione: 6.16.2306.915
Note di rilascio:
-
diff --git a/MP.INVE/Resources/manifest.xml b/MP.INVE/Resources/manifest.xml
index 7158a0fb..602b67b1 100644
--- a/MP.INVE/Resources/manifest.xml
+++ b/MP.INVE/Resources/manifest.xml
@@ -1,6 +1,6 @@
-
- 6.16.2302.2309
+ 6.16.2306.915
https://nexus.steamware.net/repository/SWS/MP-INVE/stable/LAST/MP.INVE.zip
https://nexus.steamware.net/repository/SWS/MP-INVE/stable/LAST/ChangeLog.html
false
diff --git a/MP.IOC/.config/dotnet-tools.json b/MP.IOC/.config/dotnet-tools.json
new file mode 100644
index 00000000..b0e38abd
--- /dev/null
+++ b/MP.IOC/.config/dotnet-tools.json
@@ -0,0 +1,5 @@
+{
+ "version": 1,
+ "isRoot": true,
+ "tools": {}
+}
\ No newline at end of file
diff --git a/MP.IOC/Controllers/BenchController.cs b/MP.IOC/Controllers/BenchController.cs
new file mode 100644
index 00000000..c0671a00
--- /dev/null
+++ b/MP.IOC/Controllers/BenchController.cs
@@ -0,0 +1,378 @@
+using Microsoft.AspNetCore.Mvc;
+using MP.Data;
+using MP.IOC.Data;
+using NLog;
+using System.Diagnostics;
+
+namespace MP.IOC.Controllers
+{
+ [Route("api/[controller]")]
+ [ApiController]
+ public class BenchController : ControllerBase
+ {
+ #region Public Constructors
+
+ public BenchController(IConfiguration configuration, MpDataService DataService)
+ {
+ Log.Info("Starting BenchController");
+ _configuration = configuration;
+ DService = DataService;
+ Log.Info("Avviata BenchController");
+ }
+
+ #endregion Public Constructors
+
+ #region Public Methods
+
+ ///
+ /// Conteggio chiavi REDIS dato pattern api/Bench/CountKeys
+ ///
+ ///
+ ///
+ [HttpGet("CountKeys")]
+ public string CountKeys(string? id)
+ {
+ string answ = "ND";
+ if (id == null) id = "";
+ Stopwatch stopWatch = new Stopwatch();
+ stopWatch.Start();
+ // conto quanti oggetti ho in memoria REDIS...
+ string groupHash = ""; // DataLayer.mHash("");
+ if (id.Length > 0)
+ {
+ groupHash += id + ":";
+ }
+ groupHash += "*";
+ answ = $"Trovate {DService.RedisCountKey(groupHash)} Hash per {groupHash}";
+ stopWatch.Stop();
+ // Get the elapsed time as a TimeSpan value.
+ TimeSpan ts = stopWatch.Elapsed;
+ // accodo tempo!
+ answ += $"{Environment.NewLine}Elapsed: {ts.TotalMilliseconds}ms";
+ // ritorno
+ return answ;
+ }
+
+ ///
+ /// Bench recupero dati macchina api/Bench/DtMac?id=SIMUL_01
+ ///
+ ///
+ ///
+ [HttpGet("DatiMacc")]
+ public string DatiMacc(string id)
+ {
+ string answ = "ND";
+ Stopwatch stopWatch = new Stopwatch();
+ stopWatch.Start();
+ // se id nullo --> KO!
+ if (id == null)
+ {
+ answ = "KO";
+ }
+ else
+ {
+ answ = "";
+ try
+ {
+ Dictionary valori = DService.ResetDatiMacchina(id);
+ foreach (var item in valori)
+ {
+ answ += $"{item.Key}|{item.Value}{Environment.NewLine}";
+ }
+ }
+ catch
+ { }
+ }
+ stopWatch.Stop();
+ // Get the elapsed time as a TimeSpan value.
+ TimeSpan ts = stopWatch.Elapsed;
+ // accodo tempo!
+ answ += $"{Environment.NewLine}Elapsed: {ts.TotalMilliseconds}ms";
+ // ritorno
+ return answ;
+ }
+
+ /// Recupera riga traduzione microstato x processing da HASH table
+ /// api/Bench/FindSMI?id=60&idxMS=3&valore=1
+ [HttpGet("FindSMI")]
+ public string FindSMI(int? id, int? idxMS, int? valore)
+ {
+ string answ = "ND";
+ Stopwatch stopWatch = new Stopwatch();
+ stopWatch.Start();
+ // se id nullo --> KO!
+ if (id == null)
+ {
+ answ = "KO";
+ }
+ else
+ {
+ // recupero dati x sapere quale famiglia SMI è necessaria e quale stato / segnale si
+ // sia ricevuto
+ int idxFamIn = Convert.ToInt32(id);
+ int idxMicroStato = Convert.ToInt32(idxMS);
+ int valIOB = Convert.ToInt32(valore);
+ // recupero microstato macchina da chiave relativa
+ answ = "";
+ try
+ {
+ var fiHASH = Utils.hSMI(idxFamIn);
+ string outVal = "";
+ bool trovato = DService.RedisHashPresent(fiHASH);
+ if (!trovato)
+ {
+ // ricarico tabella!
+ KeyValuePair[] valori = DService.StateMachInByKey(idxFamIn);
+ answ = string.Format("Ricaricata SMI per famiglia {0}
", fiHASH);
+ }
+
+ // recupero singolo valore (stringa) x chiave
+ outVal = DService.ValoreSMI(idxFamIn, idxMicroStato, valIOB);
+ // mostro output
+ answ += $"idxFamIN: {idxFamIn} | idxMS: {idxMicroStato} | valIOB: {valIOB} | out: {outVal}";
+ }
+ catch
+ { }
+ }
+ stopWatch.Stop();
+ // Get the elapsed time as a TimeSpan value.
+ TimeSpan ts = stopWatch.Elapsed;
+ // accodo tempo!
+ answ += $"{Environment.NewLine}Total Time Elapsed: {ts.TotalMilliseconds}ms";
+ // ritorno
+ return answ;
+ }
+
+ ///
+ /// Test verifica insert enabled x macchina
+ ///
+ ///
+ ///
+ [HttpGet("InsEnab")]
+ public string InsEnab(string id)
+ {
+ string answ = "ND";
+ Stopwatch stopWatch = new Stopwatch();
+ stopWatch.Start();
+ // se id nullo --> KO!
+ if (id == null)
+ {
+ answ = "KO";
+ }
+ else
+ {
+ // recupero microstato macchina da chiave relativa
+ answ = "";
+ try
+ {
+ answ += $"Macchina {id}, insEnabled {DService.IobInsEnab(id)}{Environment.NewLine}";
+ }
+ catch
+ { }
+ }
+ stopWatch.Stop();
+ // Get the elapsed time as a TimeSpan value.
+ TimeSpan ts = stopWatch.Elapsed;
+ // accodo tempo!
+ answ += $"{Environment.NewLine}Total Time Elapsed: {ts.TotalMilliseconds}ms";
+ // ritorno
+ return answ;
+ }
+
+ ///
+ /// pulizia dati api/Bench/RClean?id=100
+ ///
+ ///
+ ///
+ [HttpGet("RClean")]
+ public string RClean(int? id)
+ {
+ string answ = "ND";
+ Stopwatch stopWatch = new Stopwatch();
+ stopWatch.Start();
+ // se id nullo --> KO!
+ if (id == null)
+ {
+ answ = "KO";
+ }
+ else
+ {
+ string chiave;
+ KeyValuePair[] valori = new KeyValuePair[2];
+ try
+ {
+ // svuoto i precedenti hash... CICLO!
+ for (int i = 0; i < id; i++)
+ {
+ chiave = string.Format("test:{0}", i);
+ DService.RedisDelKey(chiave);
+ }
+ answ = "OK";
+ }
+ catch
+ { }
+ }
+ stopWatch.Stop();
+ // Get the elapsed time as a TimeSpan value.
+ TimeSpan ts = stopWatch.Elapsed;
+ // accodo tempo!
+ answ += $"{Environment.NewLine}Elapsed: {ts.TotalMilliseconds}ms";
+ // ritorno
+ return answ;
+ }
+
+ //// GET: IOB (è un check alive)
+ //public string Index()
+ //{
+ // return "OK";
+ //}
+ ///
+ /// Setup dati di test hash api/Bench/RSetup?id=100
+ ///
+ ///
+ ///
+ [HttpGet("RSetup")]
+ public string RSetup(int? id)
+ {
+ string answ = "ND";
+ Stopwatch stopWatch = new Stopwatch();
+ stopWatch.Start();
+ // se id nullo --> KO!
+ if (id == null)
+ {
+ answ = "KO";
+ }
+ else
+ {
+ string chiave;
+ KeyValuePair[] valori = new KeyValuePair[2];
+ try
+ {
+ // salvo il datasetet come insieme di hash in redis...
+ for (int i = 0; i < id; i++)
+ {
+ chiave = string.Format("test:{0}", i);
+ valori[0] = new KeyValuePair("numero", i.ToString());
+ valori[1] = new KeyValuePair("doppio", (i * 2).ToString());
+ DService.RedisSetHash(chiave, valori);
+ }
+ answ = "OK";
+ }
+ catch
+ { }
+ }
+ stopWatch.Stop();
+ // Get the elapsed time as a TimeSpan value.
+ TimeSpan ts = stopWatch.Elapsed;
+ // accodo tempo!
+ answ += $"{Environment.NewLine}Elapsed: {ts.TotalMilliseconds}ms";
+ // ritorno
+ return answ;
+ }
+
+ ///
+ /// Recupero singolo valore hash api/Bench/RSingleHash?id=50
+ ///
+ ///
+ ///
+ [HttpGet("RSingleHash")]
+ public string RSingleHash(int? id)
+ {
+ string answ = "ND";
+ Stopwatch stopWatch = new Stopwatch();
+ stopWatch.Start();
+ // se id nullo --> KO!
+ if (id == null)
+ {
+ answ = "KO";
+ }
+ else
+ {
+ answ = "";
+ string chiave;
+ KeyValuePair[] valori = new KeyValuePair[2];
+ try
+ {
+ // ora restituisco record completo dell'hash con ID indicato
+ chiave = string.Format("test:{0}", id);
+ valori = DService.RedisGetHash(chiave);
+ foreach (var item in valori)
+ {
+ answ += string.Format("{0}|{1}
", item.Key, item.Value);
+ }
+ }
+ catch
+ { }
+ }
+ stopWatch.Stop();
+ // Get the elapsed time as a TimeSpan value.
+ TimeSpan ts = stopWatch.Elapsed;
+ // accodo tempo!
+ answ += $"{Environment.NewLine}Elapsed: {ts.TotalMilliseconds}ms";
+ // ritorno
+ return answ;
+ }
+
+ ///
+ /// Lettura tab StateMachineIngressi
+ ///
+ ///
+ ///
+ [HttpGet("StateMachineIn")]
+ public string StateMachineIn(int? id)
+ {
+ string answ = "ND";
+ long splitTime = 0;
+ Stopwatch stopWatch = new Stopwatch();
+ stopWatch.Start();
+ // se id nullo --> KO!
+ if (id == null)
+ {
+ answ = "KO";
+ }
+ else
+ {
+ int idxFamIn = Convert.ToInt32(id);
+ answ = "";
+ try
+ {
+ KeyValuePair[] valori = DService.StateMachInByKey(idxFamIn);
+ splitTime = stopWatch.ElapsedMilliseconds;
+ foreach (var item in valori)
+ {
+ answ += $"{item.Key}|{item.Value}{Environment.NewLine}";
+ }
+ }
+ catch
+ { }
+ }
+ stopWatch.Stop();
+ // Get the elapsed time as a TimeSpan value.
+ TimeSpan ts = stopWatch.Elapsed;
+ // accodo tempo!
+ answ += $"{Environment.NewLine}ReadTime: {splitTime}ms
Total Time Elapsed: {ts.TotalMilliseconds}ms";
+ // ritorno
+ return answ;
+ }
+
+ #endregion Public Methods
+
+ #region Protected Properties
+
+ ///
+ /// Dataservice x accesso DB
+ ///
+ protected MpDataService DService { get; set; }
+
+ #endregion Protected Properties
+
+ #region Private Fields
+
+ private static IConfiguration _configuration = null!;
+
+ private static Logger Log = LogManager.GetCurrentClassLogger();
+
+ #endregion Private Fields
+ }
+}
\ No newline at end of file
diff --git a/MP.IOC/Controllers/IOBController.cs b/MP.IOC/Controllers/IOBController.cs
new file mode 100644
index 00000000..be7837e9
--- /dev/null
+++ b/MP.IOC/Controllers/IOBController.cs
@@ -0,0 +1,2241 @@
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.Extensions.Configuration;
+using MP.Data;
+using MP.IOC.Data;
+using Newtonsoft.Json;
+using NLog;
+using NLog.Fluent;
+using System.Data;
+using System.Globalization;
+using System.IO;
+
+namespace MP.IOC.Controllers
+{
+ [Route("api/[controller]")]
+ [ApiController]
+ public class IOBController : ControllerBase
+ {
+
+ public IOBController(IConfiguration configuration, MpDataService DataService)
+ {
+ Log.Info("Starting IOBController");
+ _configuration = configuration;
+ DService = DataService;
+ Log.Info("Avviato IOBController");
+ }
+
+
+ private static IConfiguration _configuration = null!;
+
+ private static Logger Log = LogManager.GetCurrentClassLogger();
+
+ ///
+ /// Dataservice x accesso DB
+ ///
+ protected MpDataService DService { get; set; }
+
+ #region Public Methods
+
+ /// SALVA x macchina KVP parametro/valore:
+ ///
+ /// GET: api/IOB/addOptPar/SIMUL_03?pName=PZREQ&pValue=1000
+ ///
+ ///
+ [HttpGet("addOptPar/{id}")]
+ public string addOptPar(string id, string pName, string pValue)
+ {
+ string answ = "";
+ DService.ScriviKeepAlive(id, DateTime.Now);
+ try
+ {
+ DService.AddOptPar4Machine(id, pName, pValue);
+ answ = getOptPar(id);
+ }
+ catch
+ { }
+ return answ;
+ }
+ ///
+ /// Recupera TASK richiesto x macchina:
+ ///
+ /// GET: IOB/getOptPar/SIMUL_03
+ ///
+ ///
+ /// Json contenente 1..n task da eseguire
+ [HttpGet("getOptPar/{id}")]
+ public string getOptPar(string id)
+ {
+ string answ = "";
+ // scrivo keep alive!!! (se necessario, altrimenti è in cache...)
+ DService.ScriviKeepAlive(id, DateTime.Now);
+ try
+ {
+ // leggo da REDIS eventuale elenco task x macchina...
+ Dictionary valori = DService.mOptParMacchina(id);
+ answ = JsonConvert.SerializeObject(valori);
+ }
+ catch
+ { }
+ return answ;
+ }
+
+ ///// AGGIUNGE TASK richiesto x macchina:
+ /////
+ ///// GET: IOB/addTask2Exe/3010?taskName=startSetup&taskVal=T190406101512
+ ///// GET: IOB/addTask2Exe/3010?taskName=stopSetup&taskVal=T190406101512
+ ///// GET: IOB/addTask2Exe/SIMUL_03?taskName=setProg&taskVal=P00000001
+ ///// GET: IOB/addTask2Exe/SIMUL_03?taskName=setComm&taskVal=ODL_0000123
+ ///// GET: IOB/addTask2Exe/SIMUL_03?taskName=setArt&taskVal=ART_0000321
+ /////
+ /////
+ //public string addTask2Exe(string id, string taskName, string taskVal)
+ //{
+ // string answ = "";
+ // // scrivo keep alive!!! (se necessario, altrimenti è in cache...)
+ // MapoDb.MapoDb connDb = new MapoDb.MapoDb();
+ // DataLayer DataLayerObj = new DataLayer();
+ // connDb.scriviKeepAlive(id, DateTime.Now);
+ // try
+ // {
+ // // converto stringa in tipo task...
+ // taskType tName = taskType.nihil;
+ // bool fatto = Enum.TryParse(taskName, out tName);
+ // if (fatto)
+ // {
+ // DataLayerObj.addTask4Machine(id, tName, taskVal);
+ // }
+ // else
+ // {
+ // logger.lg.scriviLog($"addTask2Exe: impossibile riconoscere il comando {taskName} come uno dei tipi ammessi, NON aggiunto", tipoLog.ERROR);
+ // }
+ // answ = getTask2Exe(id);
+ // }
+ // catch
+ // { }
+ // return answ;
+ //}
+
+ /////
+ ///// Richiesta chiusura manuale ODL x macchina (popup utente):
+ /////
+ ///// GET: IOB/askCloseODL/SIMUL_03?idxOdl=123
+ /////
+ ///// id macchina
+ ///// idx dell'ODL da chiudere
+ ///// bool esecuzione
+ //public bool askCloseODL(string id, int idxOdl)
+ //{
+ // bool answ = false;
+ // // init obj DataLayer
+ // DataLayer DataLayerObj = new DataLayer();
+ // try
+ // {
+ // // preparo una richiesta di chiusura...
+ // DisplayAction CurrAction = new DisplayAction()
+ // {
+ // Topic = "Chiusura ODL",
+ // Message = "Rilevato possibile fine operazioni, Vuoi chiudere la commessa?",
+ // ShowCancel = true,
+ // ShowClose = true,
+ // ShowConfirm = true,
+ // CancelAction = "DisableAction",
+ // ConfirmAction = "CloseODL",
+ // DtReq = DateTime.Now,
+ // IsActive = true,
+ // Parameter = $"{idxOdl}"
+ // };
+ // answ = DataLayerObj.ActionSetReq(CurrAction);
+ // }
+ // catch
+ // { }
+ // return answ;
+ //}
+
+ /////
+ ///// Chiude ODL x macchina:
+ /////
+ ///// GET: IOB/closeODL/SIMUL_03?idxOdl=123
+ /////
+ ///// id macchina
+ ///// idx dell'ODL da chiudere
+ ///// bool esecuzione
+ //public bool closeODL(string id, int idxOdl)
+ //{
+ // bool answ = false;
+
+ // // init obj DataLayer
+ // DataLayer DataLayerObj = new DataLayer();
+ // try
+ // {
+ // // chiamata diretta sul DB...
+ // DataLayerObj.taODL.forceClose(idxOdl, id);
+ // answ = true;
+ // }
+ // catch
+ // { }
+ // return answ;
+ //}
+
+ //// GET: IOB/enabled/SIMUL_03
+ //public string enabled(string id)
+ //{
+ // string answ = "ND";
+ // // se id nullo --> KO!
+ // if (id == null)
+ // {
+ // answ = "KO";
+ // }
+ // else
+ // {
+ // try
+ // {
+ // DataLayer DataLayerObj = new DataLayer();
+ // // salvo risposta!
+ // answ = DataLayerObj.insEnab(id) ? "OK" : "NO";
+ // }
+ // catch (Exception exc)
+ // {
+ // logger.lg.scriviLog(string.Format("Errore in enabled{0}{1}", Environment.NewLine, exc));
+ // answ = "NO";
+ // }
+ // }
+ // return answ;
+ //}
+
+ /////
+ ///// Processa una chiamata POST per l'invio di un array Json di oggetti input (EVENTI)
+ ///// POST: IOB/evListJson/SIMUL_03
+ /////
+ ///// ID dell'IOB
+ /////
+ //[HttpPost]
+ //public string evListJson(string id)
+ //{
+ // int insDone = 0;
+ // string answ = "-";
+ // // questa classe è derivata da Controller.Response... x cui recupero lo stream in altro modo...
+ // string content = "";
+ // System.Web.HttpContext.Current.Request.InputStream.Position = 0;
+ // using (var reader = new StreamReader(
+ // Request.InputStream, System.Text.Encoding.UTF8, true, 4096, true))
+ // {
+ // content = reader.ReadToEnd();
+ // }
+ // //Rest
+ // System.Web.HttpContext.Current.Request.InputStream.Position = 0;
+ // // se ho dati...
+ // if (content != "")
+ // {
+ // DataLayer DataLayerObj = new DataLayer();
+ // // procedo a deserializzare in blocco l'oggetto...
+ // evJsonPayload receivedData = new evJsonPayload();
+ // try
+ // {
+ // // deserializzo.
+ // receivedData = JsonConvert.DeserializeObject(content);
+ // }
+ // catch (Exception exc)
+ // {
+ // logger.lg.scriviLog($"Errore in fase deserializzazione inputJson{Environment.NewLine}{exc}");
+ // answ = "NO";
+ // }
+ // // se ho qualcosa da processare...
+ // if (receivedData != null)
+ // {
+ // // per ogni valore --> processo!
+ // try
+ // {
+ // foreach (var item in receivedData.eventList)
+ // {
+ // if (memLayer.ML.CRI("_logLevel") > 6)
+ // {
+ // logger.lg.scriviLog($"Valori letti: idxMacchina: {id} | valore: {item.valore}", tipoLog.INFO);
+ // }
+
+ // // formato datetime come yyyyMMddHHmmssfff -->es: 20181223180600000
+ // answ = DataLayerObj.processInput(id, item.valore, item.dtEve.ToString("yyyyMMddHHmmssfff"), item.dtCurr.ToString("yyyyMMddHHmmssfff"), item.cnt.ToString());
+ // insDone++;
+ // }
+ // // se vuoto --> OK!
+ // if (string.IsNullOrEmpty(answ))
+ // {
+ // answ = $"OK {insDone} processed";
+ // }
+ // }
+ // catch (Exception exc)
+ // {
+ // logger.lg.scriviLog($"Errore in fase invio valori inputJson{Environment.NewLine}{exc}");
+ // answ = "NO";
+ // }
+ // }
+ // }
+ // return answ;
+ //}
+
+ /////
+ ///// Sistema Dossier/Snapshot giornalieri x impianto indicato, andando a generare 1 Dossier
+ ///// giornaliero x ogni giornata dall'ultimo registrato alla data corrente
+ ///// es: http://url_site/MP/IO/IOB/fixDailyDossier/SIMUL_03
+ /////
+ /////
+ /////
+ //public string fixDailyDossier(string id)
+ //{
+ // string answ = "";
+ // // attenzione! poiché nell'URL il carattere "#" viene filtrato ci aspettiamo il
+ // // carattere "|" che poi trasformiamo ora in "#"
+ // id = id.Replace("|", "#");
+ // // effettuo processing
+ // try
+ // {
+ // DataLayer DataLayerObj = new DataLayer();
+ // // verifico se si possa processare, ovvero tab ConfFlux x macchina sia valorizzata...
+ // var confDataMach = DataLayerObj.confFluxMach(id);
+ // if (confDataMach.Count > 0)
+ // {
+ // // determino ultima data da processare (inizio oggi, a mezzanotte)
+ // DateTime dtTo = DateTime.Today;
+ // DateTime dtFrom = dtTo;
+ // // determino data di partenza, prima da dossier esistenti
+ // var listaDoss = DataLayerObj.dossierLastByMach(id);
+ // if (listaDoss.Count > 0)
+ // {
+ // // primo giorno DOPO ultima registrazione
+ // dtFrom = listaDoss.OrderByDescending(x => x).FirstOrDefault().AddDays(1);
+ // }
+ // else
+ // {
+ // // ...o da fluxLog acquisiti...
+ // var listaFL = DataLayerObj.fluxLogFirstByMach(id);
+ // if (listaFL.Count > 0)
+ // {
+ // // giorno successivo a prima registrazione
+ // dtFrom = listaFL.OrderBy(x => x).FirstOrDefault().AddDays(1);
+ // }
+ // }
+ // string caller = $"takeFlogSnapshot({id})";
+ // DateTime dtStart = dtFrom.Date;
+ // DateTime dtEnd = dtFrom;
+ // int maxAdd = 5;
+ // if (dtStart < dtTo)
+ // {
+ // // verifico di avere almeno 1 dossier da produrre ciclo fino ad esaurire le
+ // // date da processare
+ // while (dtStart < dtTo && maxAdd > 0)
+ // {
+ // // sistemo end
+ // dtEnd = dtStart.AddDays(1);
+ // // effettuo chiamata registrazione snapshot!
+ // answ = doSaveFLSnapshot(id, dtStart, dtEnd, caller);
+ // // incremento START...
+ // dtStart = dtEnd;
+ // // riduco il numero di chiamate ammesse x singolo task
+ // maxAdd--;
+ // }
+ // // reset cache dossier...
+ // DataLayerObj.dossierLastByMachReset(id);
+ // }
+ // else
+ // {
+ // answ = "NO more to add";
+ // }
+ // }
+ // else
+ // {
+ // answ = "NO ConfFluxData";
+ // }
+ // }
+ // catch (Exception exc)
+ // {
+ // logger.lg.scriviLog($"Eccezione in recupero fixDailyDossier{Environment.NewLine}{exc}", tipoLog.EXCEPTION);
+ // }
+ // return answ;
+ //}
+
+ /////
+ ///// Sistema ODL giornalieri x impianto indicato, andando a generare 1 ODL giornaliero x ogni
+ ///// giornata dall'ultimo ODL aperto alla data corrente
+ ///// es: http://url_site/MP/IO/IOB/fixDailyOdl/SIMUL_03
+ /////
+ /////
+ /////
+ //public string fixDailyOdl(string id)
+ //{
+ // string answ = "";
+ // // attenzione! poiché nell'URL il carattere "#" viene filtrato ci aspettiamo il
+ // // carattere "|" che poi trasformiamo ora in "#"
+ // id = id.Replace("|", "#");
+ // // chiamo metodo redis/db...
+ // try
+ // {
+ // DataLayer DataLayerObj = new DataLayer();
+ // // recupero ultimo ODL macchina...
+ // var lastOdlStarted = DataLayerObj.taODL.getLastByMacc(id);
+ // if (lastOdlStarted != null && lastOdlStarted.Count > 0)
+ // {
+ // // calcolo data ultimo avviato e chiedo dal giorno dopo...
+ // DateTime dtFrom = lastOdlStarted[0].DataInizio.AddDays(1);
+ // DateTime dtTo = DateTime.Today;
+ // if (dtTo >= dtFrom)
+ // {
+ // string codArt = lastOdlStarted[0].CodArticolo;
+ // // chiamo la stored x sistemare gli ODL
+ // DataLayerObj.taODL.AutoDayGener(id, dtFrom, dtTo, codArt);
+ // }
+ // answ = "OK";
+ // }
+ // }
+ // catch (Exception exc)
+ // {
+ // logger.lg.scriviLog($"Eccezione in recupero fixDailyOdl{Environment.NewLine}{exc}", tipoLog.EXCEPTION);
+ // }
+ // return answ;
+ //}
+
+ //// GET: IOB/flog/SIMUL_03?flux=PROG&valore=P0001&dtEve=20161223180600000&dtCurr=20161223180600000&cnt=999
+ //public string flog(string id, string flux, string valore, string dtEve, string dtCurr, string cnt)
+ //{
+ // string answ = "";
+ // // formato yyyymmddHHMMSSnnn ovvero da anno a millisecondi
+ // if (cnt == null)
+ // {
+ // cnt = "0";
+ // }
+
+ // DateTime dataOraEvento = DateTime.Now;
+ // if (memLayer.ML.CRI("_logLevel") > 6)
+ // {
+ // logger.lg.scriviLog($"Valori letti: idxMacchina: {id} | flux: {flux} valore: {valore}", tipoLog.INFO);
+ // }
+ // try
+ // {
+ // DataLayer DataLayerObj = new DataLayer();
+ // int count = 0;
+ // Int32.TryParse(cnt, out count);
+ // answ = DataLayerObj.processFluxLog(id, flux, valore, dtEve, dtCurr, count);
+ // }
+ // catch (Exception exc)
+ // {
+ // logger.lg.scriviLog($"Errore in flog{Environment.NewLine}{exc}");
+ // answ = "NO";
+ // }
+ // return answ;
+ //}
+
+ /////
+ ///// Processa una chiamata POST per l'invio di un array Json di oggetti fluxLog
+ ///// PUT: IOB/flogJson/SIMUL_03
+ /////
+ ///// ID dell'IOB
+ /////
+ //[HttpPost]
+ //public string flogJson(string id)
+ //{
+ // int insDone = 0;
+ // string answ = "-";
+ // // questa classe è derivata da Controller.Response... x cui recupero lo stream in altro modo...
+ // string content = "";
+ // System.Web.HttpContext.Current.Request.InputStream.Position = 0;
+ // using (var reader = new StreamReader(
+ // Request.InputStream, System.Text.Encoding.UTF8, true, 4096, true))
+ // {
+ // content = reader.ReadToEnd();
+ // }
+ // //Rest
+ // System.Web.HttpContext.Current.Request.InputStream.Position = 0;
+ // // se ho dati...
+ // if (content != "")
+ // {
+ // DataLayer DataLayerObj = new DataLayer();
+ // // procedo a deserializzare in blocco l'oggetto...
+ // flogJsonPayload receivedData = new flogJsonPayload();
+ // try
+ // {
+ // // deserializzo.
+ // receivedData = JsonConvert.DeserializeObject(content);
+ // }
+ // catch (Exception exc)
+ // {
+ // logger.lg.scriviLog($"Errore in fase deserializzazione flogJson{Environment.NewLine}{exc}");
+ // answ = "NO";
+ // }
+ // // se ho qualcosa da processare...
+ // if (receivedData != null)
+ // {
+ // // per ogni valore --> salvo!
+ // try
+ // {
+ // foreach (var item in receivedData.fluxData)
+ // {
+ // // formato datetime come yyyyMMddHHmmssfff -->es: 20181223180600000
+ // answ = DataLayerObj.processFluxLog(id, item.flux, item.valore, item.dtEve.ToString("yyyyMMddHHmmssfff"), item.dtCurr.ToString("yyyyMMddHHmmssfff"), item.cnt);
+ // }
+ // // se vuoto --> OK!
+ // if (string.IsNullOrEmpty(answ))
+ // {
+ // answ = $"OK {insDone} processed";
+ // }
+ // }
+ // catch (Exception exc)
+ // {
+ // logger.lg.scriviLog($"Errore in fase invio valori flogJson{Environment.NewLine}{exc}");
+ // answ = "NO";
+ // }
+ // // leggo parametri correnti...
+ // try
+ // {
+ // List currParams = DataLayerObj.getCurrObjItems(id);
+ // // ora per ogni valore RICEVUTO costruisco un oggetto in innovazioni da
+ // // inviare...x salvare in stato parametri...
+ // List innovazioni = new List();
+ // foreach (var item in receivedData.fluxData)
+ // {
+ // // flux = uuid del parametro
+ // objItem trovato = currParams.Find(obj => obj.uid == item.flux);
+ // // se lo trovo aggiorno...
+ // if (trovato != null)
+ // {
+ // // aggiorno valore e data
+ // trovato.value = item.valore;
+ // trovato.lastRead = DateTime.Now;
+ // // se fosse un valore WRITE e mi ha dato un valore vuoto --> mando
+ // // un fix x riscrittura
+ // if (trovato.writable && string.IsNullOrEmpty(item.valore))
+ // {
+ // logger.lg.scriviLog($"flogJson | verifica parametri | {trovato.uid} | reqVal: {trovato.reqValue}");
+ // taskType currTask = (taskType)Enum.Parse(typeof(taskType), trovato.uid);
+ // DataLayerObj.addCheckTask4Machine(id, currTask, item.valore);
+ // }
+ // }
+ // // altrimenti AGGIUNGO (READ ONLY)...
+ // else
+ // {
+ // trovato = new objItem
+ // {
+ // uid = item.flux,
+ // name = item.flux,
+ // value = item.valore,
+ // lastRead = DateTime.Now,
+ // writable = false
+ // };
+ // }
+ // // lo carico in innovation
+ // innovazioni.Add(trovato);
+ // }
+ // // faccio upsert innovations!
+ // DataLayerObj.upsertCurrObjItems(id, innovazioni);
+ // }
+ // catch (Exception exc)
+ // {
+ // logger.lg.scriviLog($"Errore in fase salvataggio innovazioni parametri correnti da flogJson{Environment.NewLine}{exc}");
+ // answ = "NO";
+ // }
+ // }
+ // }
+ // return answ;
+ //}
+
+ /////
+ ///// Chiude ODL precedente ed avvia uno nuovo (duplicandolo e sitemando quantità RIMANENTE),
+ ///// e CONFERMA produzione...
+ /////
+ ///// GET: IOB/forceSplitOdl/SIMUL_03
+ /////
+ /////
+ ///// Esito chiamata (OK/vuoto)
+ //public string forceSplitOdl(string id)
+ //{
+ // // attenzione! poiché nell'URL il carattere "#" viene filtrato ci aspettiamo il
+ // // carattere "|" che poi trasformiamo ora in "#"
+ // id = id.Replace("|", "#");
+ // DataLayer DataLayerObj = new DataLayer();
+ // return DataLayerObj.AutoStartOdl(id, true, true, 100, "");
+ //}
+
+ ///// Chiude ODL precedente ed avvia uno nuovo (duplicandolo e sitemando quantità
+ ///// RIMANENTE), e CONFERMA produzione...
+ /////
+ ///// GET: IOB/forceSplitOdl/SIMUL_03?doConfirm=true&qtyFromLast=true&roundStep=150&extOrderCode=ABCDE1234
+ /////
+ ///// id impianto Cod esterno da legare all'ODL x tracciare lotti prod
+ ///// Esito chiamata (OK/vuoto)
+ //public string forceSplitOdlFull(string id, bool doConfirm, bool qtyFromLast, int? roundStep, string keyRichiesta = "")
+ //{
+ // // attenzione! poiché nell'URL il carattere "#" viene filtrato ci aspettiamo il
+ // // carattere "|" che poi trasformiamo ora in "#"
+ // id = id.Replace("|", "#");
+ // DataLayer DataLayerObj = new DataLayer();
+ // if (roundStep == null)
+ // {
+ // roundStep = 100;
+ // }
+ // return DataLayerObj.AutoStartOdl(id, doConfirm, qtyFromLast, (int)roundStep, keyRichiesta);
+ //}
+
+ /////
+ ///// Avvia PODL indicato
+ ///// - se esistesse un ODL da altro PODL --> chiude
+ ///// - se fosse già in essere ODL collegato --> lascia aperto
+ ///// - se fosse chiuso ODL collegato --> duplica PODL e poi avvia nuovo ODL.
+ /////
+ ///// GET: IOB/forceStartPOdl/SIMUL_03?idxPODL=123
+ /////
+ /////
+ ///// idx del PDL da avviare
+ ///// Esito chiamata (OK/vuoto)
+ //public string forceStartPOdl(string id, int idxPODL)
+ //{
+ // // attenzione! poiché nell'URL il carattere "#" viene filtrato ci aspettiamo il
+ // // carattere "|" che poi trasformiamo ora in "#"
+ // id = id.Replace("|", "#");
+ // DataLayer DataLayerObj = new DataLayer();
+ // return DataLayerObj.ForceStartPOdl(id, idxPODL, true);
+ //}
+
+ /////
+ ///// Recupera elenco articoli dei PODL correnti:
+ /////
+ ///// GET: IOB/getArtCurrPODL
+ /////
+ ///// Json contenente lista oggetti ARTICOLI serializzati
+ //public string getArtCurrPODL()
+ //{
+ // string answ = "";
+
+ // // init obj DataLayer
+ // DataLayer DataLayerObj = new DataLayer();
+ // try
+ // {
+ // // recupero dati macchina...
+ // var elencoArt = DataLayerObj.taAnagArt.getByCurrPODL();
+
+ // answ = JsonConvert.SerializeObject(elencoArt);
+ // }
+ // catch
+ // { }
+ // return answ;
+ //}
+
+ /////
+ ///// Recupera elenco articoli USATI:
+ /////
+ ///// GET: IOB/getArtUsed
+ /////
+ ///// Json contenente lista oggetti ARTICOLI serializzati
+ //public string getArtUsed()
+ //{
+ // string answ = "";
+
+ // // init obj DataLayer
+ // DataLayer DataLayerObj = new DataLayer();
+ // try
+ // {
+ // // recupero dati macchina...
+ // var elencoArt = DataLayerObj.taAnagArt.getUsed();
+
+ // answ = JsonConvert.SerializeObject(elencoArt);
+ // }
+ // catch
+ // { }
+ // return answ;
+ //}
+
+ /////
+ ///// Recupera COUNTER x macchina:
+ /////
+ ///// GET: IOB/getCounter/5
+ /////
+ /////
+ /////
+ //public string getCounter(string id)
+ //{
+ // string answ = "";
+ // try
+ // {
+ // DataLayer DataLayerObj = new DataLayer();
+ // answ = DataLayerObj.pzCounter(id).ToString();
+ // }
+ // catch (Exception exc)
+ // {
+ // logger.lg.scriviLog(string.Format("Errore in counter (get){0}{1}", Environment.NewLine, exc));
+ // answ = "NO";
+ // }
+ // return answ;
+ //}
+
+ /////
+ ///// Recupera COUNTER x macchina dal CONTEGGIO dei TCRecorded:
+ /////
+ ///// GET: IOB/getCounterTCRec/5
+ /////
+ /////
+ /////
+ //public string getCounterTCRec(string id)
+ //{
+ // string answ = "";
+ // try
+ // {
+ // DataLayer DataLayerObj = new DataLayer();
+ // answ = DataLayerObj.pzCounterTC(id).ToString();
+ // }
+ // catch (Exception exc)
+ // {
+ // logger.lg.scriviLog(string.Format("Errore in counter TC (get){0}{1}", Environment.NewLine, exc));
+ // answ = "NO";
+ // }
+ // return answ;
+ //}
+
+ /////
+ ///// Recupera DATI correnti x macchina:
+ /////
+ ///// GET: IOB/getCurrData/SIMUL_03
+ /////
+ /////
+ ///// Json contenente la riga di stato macchina
+ //public string getCurrData(string id)
+ //{
+ // // attenzione! poiché nell'URL il carattere "#" viene filtrato ci aspettiamo il
+ // // carattere "|" che poi trasformiamo ora in "#"
+ // id = id.Replace("|", "#");
+ // string answ = "";
+ // // scrivo keep alive!!! (se necessario, altrimenti è in cache...)
+ // MapoDb.MapoDb connDb = new MapoDb.MapoDb();
+ // DataLayer DataLayerObj = new DataLayer();
+ // connDb.scriviKeepAlive(id, DateTime.Now);
+ // try
+ // {
+ // // recupero dati macchina...
+ // Dictionary valori = DataLayerObj.mDatiMacchine(id);
+ // answ = JsonConvert.SerializeObject(valori);
+ // }
+ // catch
+ // { }
+ // return answ;
+ //}
+
+ /////
+ ///// Recupera ODL corrente x macchina:
+ /////
+ ///// GET: IOB/getCurrODL/SIMUL_03
+ /////
+ /////
+ /////
+ //public string getCurrODL(string id)
+ //{
+ // // attenzione! poiché nell'URL il carattere "#" viene filtrato ci aspettiamo il
+ // // carattere "|" che poi trasformiamo ora in "#"
+ // id = id.Replace("|", "#");
+ // string answ = "";
+ // try
+ // {
+ // DataLayer DataLayerObj = new DataLayer();
+ // answ = $"{DataLayerObj.currODL(id)}";
+ // }
+ // catch (Exception exc)
+ // {
+ // logger.lg.scriviLog(string.Format("Errore in currODL (get){0}{1}", Environment.NewLine, exc));
+ // answ = "NO";
+ // }
+ // return answ;
+ //}
+
+ /////
+ ///// Restituisce intera riga dell'odl correntemente in lavorazione sulla macchina...
+ ///// GET: IOB/getCurrOdlRow/SIMUL_01
+ /////
+ /////
+ /////
+ //public string getCurrOdlRow(string id)
+ //{
+ // // attenzione! poiché nell'URL il carattere "#" viene filtrato ci aspettiamo il
+ // // carattere "|" che poi trasformiamo ora in "#"
+ // id = id.Replace("|", "#");
+ // string answ = "";
+ // DS_ProdTempi.ODLDataTable currData = null;
+ // // chiamo metodo redis/db...
+ // try
+ // {
+ // DataLayer DataLayerObj = new DataLayer();
+ // currData = DataLayerObj.currODLRowTab(id);
+ // answ = JsonConvert.SerializeObject(currData);
+ // }
+ // catch (Exception exc)
+ // {
+ // logger.lg.scriviLog($"Eccezione in recupero getCurrOdlRow{Environment.NewLine}{exc}", tipoLog.EXCEPTION);
+ // }
+ // return answ;
+ //}
+
+ /////
+ ///// Restituisce data-ora inizio dell'odl correntemente in lavorazione sulla macchina...
+ ///// es: http://url_site/MP/IO/IOB/getCurrOdlStart/SIMUL_03
+ /////
+ /////
+ /////
+ //public string getCurrOdlStart(string id)
+ //{
+ // // attenzione! poiché nell'URL il carattere "#" viene filtrato ci aspettiamo il
+ // // carattere "|" che poi trasformiamo ora in "#"
+ // id = id.Replace("|", "#");
+ // DateTime answ = new DateTime(DateTime.Now.Year - 1, 12, 31);
+ // // chiamo metodo redis/db...
+ // try
+ // {
+ // DataLayer DataLayerObj = new DataLayer();
+ // DS_ProdTempi.ODLDataTable currTab = DataLayerObj.currODLRowTab(id);
+ // if (currTab.Count > 0)
+ // {
+ // DS_ProdTempi.ODLRow odlRow = currTab[0];
+ // answ = odlRow.DataInizio;
+ // }
+ // }
+ // catch (Exception exc)
+ // {
+ // logger.lg.scriviLog($"Eccezione in recupero getCurrOdlStart{Environment.NewLine}{exc}", tipoLog.EXCEPTION);
+ // }
+ // return answ.ToString("yyyy-MM-dd HH:mm:ss");
+ //}
+
+ /////
+ ///// Recupera DATI PODL correnti x macchina:
+ /////
+ ///// GET: IOB/getCurrPODL/SIMUL_03
+ /////
+ ///// id macchina, se "" mostra tutto
+ ///// Json contenente lista oggetti PODL serializzati
+ //public string getCurrPODL(string id)
+ //{
+ // // attenzione! poiché nell'URL il carattere "#" viene filtrato ci aspettiamo il
+ // // carattere "|" che poi trasformiamo ora in "#"
+ // if (!string.IsNullOrEmpty(id))
+ // {
+ // id = id.Replace("|", "#");
+ // }
+ // string answ = "";
+
+ // // init obj DataLayer
+ // DataLayer DataLayerObj = new DataLayer();
+ // try
+ // {
+ // // recupero dati macchina...
+ // var elencoOdl = DataLayerObj.taPODL.getByMaccArt(id, "", "", true);
+ // answ = JsonConvert.SerializeObject(elencoOdl);
+ // }
+ // catch
+ // { }
+ // return answ;
+ //}
+
+ /////
+ ///// Restituisce intera riga dello stato di macchina...
+ ///// GET: IOB/getCurrStatoRow/SIMUL_01
+ /////
+ /////
+ /////
+ //public string getCurrStatoRow(string id)
+ //{
+ // // attenzione! poiché nell'URL il carattere "#" viene filtrato ci aspettiamo il
+ // // carattere "|" che poi trasformiamo ora in "#"
+ // id = id.Replace("|", "#");
+ // string answ = "";
+ // DS_applicazione.StatoMacchineDataTable currData = null;
+ // // chiamo metodo redis/db...
+ // try
+ // {
+ // DataLayer DataLayerObj = new DataLayer();
+ // currData = DataLayerObj.currSMTab(id);
+ // answ = JsonConvert.SerializeObject(currData);
+ // }
+ // catch (Exception exc)
+ // {
+ // logger.lg.scriviLog($"Eccezione in recupero getCurrStatoRow{Environment.NewLine}{exc}", tipoLog.EXCEPTION);
+ // }
+ // return answ;
+ //}
+
+ /////
+ ///// Restituisce un array JSon di files di una IOB
+ ///// PUT: IOB/getFiles/SIMUL_03
+ /////
+ ///// ID dell'IOB
+ ///// Oggetto Json in formato MapoSDK.fileEmbed
+ //public string getFiles(string id)
+ //{
+ // string answ = "";
+ // // procedo a deserializzare in blocco l'oggetto...
+ // try
+ // {
+ // // recupero TUTTI i files della folder dell'IOB richiesta
+ // string basePath = Server.MapPath(memLayer.ML.CRS("uploadFileDir"));
+ // string dirPath = $"{basePath}\\{id}";
+ // var fileList = fileMover.obj.elencoFilesDir(dirPath);
+ // fileEmbed objFiles = new fileEmbed();
+ // MapoSDK.smallFile currFile = null;
+ // string fileContent = "";
+ // foreach (var item in fileList)
+ // {
+ // fileContent = System.IO.File.ReadAllText($"{dirPath}\\{item.Nome}");
+ // currFile = new MapoSDK.smallFile()
+ // {
+ // fileName = item.Nome,
+ // content = fileContent.Replace("\r\n", Environment.NewLine)
+ // };
+ // objFiles.fileList.Add(currFile);
+ // }
+ // // serializzo
+ // answ = JsonConvert.SerializeObject(objFiles);
+ // }
+ // catch (Exception exc)
+ // {
+ // logger.lg.scriviLog($"Errore in uploadFile{Environment.NewLine}{exc}");
+ // answ = "NO";
+ // }
+ // return answ;
+ //}
+
+ /////
+ ///// Restituisce il valore dello stato di IDLE della macchina, quindi SOLO SE NON é in lavoro
+ ///// e già convertito in minuti...
+ ///// GET: IOB/getIdlePeriod/SIMUL_01
+ /////
+ /////
+ /////
+ //public int getIdlePeriod(string id)
+ //{
+ // // attenzione! poiché nell'URL il carattere "#" viene filtrato ci aspettiamo il
+ // // carattere "|" che poi trasformiamo ora in "#"
+ // id = id.Replace("|", "#");
+ // int answ = 0;
+ // DataLayer DataLayerObj = new DataLayer();
+ // DS_applicazione.StatoMacchineDataTable currData = null;
+ // // chiamo metodo redis/db...
+ // try
+ // {
+ // currData = DataLayerObj.currSMTab(id);
+ // if (currData.Count > 0)
+ // {
+ // // recupero da redis elenco stati
+ // DS_applicazione.AnagraficaStatiDataTable anagStati = DataLayerObj.AnagraficaStati();
+ // DS_applicazione.AnagraficaStatiRow currStato = anagStati.FindByIdxStato(currData[0].IdxStato);
+ // // calcolo SE sia idle... OVVERO SEMAFORO NON VERDE!!!
+ // if (currStato.Semaforo != "sVe")
+ // {
+ // // calcolo durata...
+ // answ = (int)DateTime.Now.Subtract(currData[0].InizioStato).TotalMinutes;
+ // }
+ // }
+ // }
+ // catch (Exception exc)
+ // {
+ // logger.lg.scriviLog($"Eccezione in recupero getIdlePeriod{Environment.NewLine}{exc}", tipoLog.EXCEPTION);
+ // }
+ // return answ;
+ //}
+
+ /////
+ ///// Restituisce il (primo) codice IOB da dover gestire (se un IOBMAN chiede di gestirne uno
+ ///// in +...)
+ /////
+ ///// IP del Gateway
+ /////
+ //public string getIob2call(string GWIP)
+ //{
+ // string answ = "";
+
+ // // !!!FARE!!! temporanemanete genera a caso vuoto o 3000 x permettere test... altrimenti
+ // // gestisce VERA coda... secondi pari...
+ // int resto = 0;
+ // Math.DivRem(DateTime.Now.Second, 2, out resto);
+ // if (resto == 0)
+ // {
+ // answ = "3000";
+ // }
+
+ // return answ;
+ //}
+
+ /////
+ ///// Recupera elenco articoli USATI per ultimi:
+ ///// - quelli dei PODL correnti
+ ///// - quelli degli ultimi n (DOSS_LastArt in config) ODL lavorati
+ /////
+ ///// GET: IOB/getArtByMacc
+ /////
+ ///// Json contenente lista oggetti ARTICOLI serializzati
+ //public string getLastArtByMacc(string id)
+ //{
+ // string answ = "";
+
+ // // init obj DataLayer
+ // DataLayer DataLayerObj = new DataLayer();
+ // try
+ // {
+ // // recupero dati macchina...
+ // var elencoArt = DataLayerObj.taAnagArt.getLastByMacc(id);
+
+ // answ = JsonConvert.SerializeObject(elencoArt);
+ // }
+ // catch
+ // { }
+ // return answ;
+ //}
+
+ /////
+ ///// Recupera DATI dell'ultimo dossier dato articolo:
+ /////
+ ///// GET: IOB/getLastDossArt/cod_articolo
+ /////
+ ///// codice articolo, se vuoto --> non fa nulla
+ ///// Json contenente lista oggetti DOSSIER serializzati
+ //public string getLastDossArt(string id)
+ //{
+ // string answ = "";
+ // // attenzione! poiché nell'URL il carattere "#" viene filtrato ci aspettiamo il
+ // // carattere "|" che poi trasformiamo ora in "#"
+ // if (string.IsNullOrEmpty(id))
+ // {
+ // answ = "N.A.";
+ // }
+ // else
+ // {
+ // id = id.Replace("|", "#");
+
+ // // init obj DataLayer
+ // DataLayer DataLayerObj = new DataLayer();
+ // try
+ // {
+ // // recupero dati macchina...
+ // var elencoDoss = DataLayerObj.taDOSS.getLastByArt(id);
+
+ // answ = JsonConvert.SerializeObject(elencoDoss);
+ // }
+ // catch
+ // { }
+ // }
+ // return answ;
+ //}
+
+ /////
+ ///// Recupera DATI dell'ultimo dossier dato articolo:
+ /////
+ ///// GET: IOB/getLastDossArt/cod_articolo
+ /////
+ ///// codice articolo, se vuoto --> non fa nulla
+ ///// Json contenente lista oggetti DOSSIER serializzati
+ //public string getLastDossByMacc(string id)
+ //{
+ // string answ = "";
+ // // attenzione! poiché nell'URL il carattere "#" viene filtrato ci aspettiamo il
+ // // carattere "|" che poi trasformiamo ora in "#"
+ // if (string.IsNullOrEmpty(id))
+ // {
+ // answ = "N.A.";
+ // }
+ // else
+ // {
+ // id = id.Replace("|", "#");
+
+ // // init obj DataLayer
+ // DataLayer DataLayerObj = new DataLayer();
+ // try
+ // {
+ // // recupero dati macchina...
+ // var elencoDoss = DataLayerObj.taDOSS.getLastByMacc(id);
+
+ // answ = JsonConvert.SerializeObject(elencoDoss);
+ // }
+ // catch
+ // { }
+ // }
+ // return answ;
+ //}
+
+ /////
+ ///// Recupera DATI dell'ultimo dossier dato PODL correnti:
+ /////
+ ///// GET: IOB/getLastDossPODL
+ /////
+ ///// Json contenente lista oggetti DOSSIER serializzati
+ //public string getLastDossPODL()
+ //{
+ // string answ = "";
+
+ // // init obj DataLayer
+ // DataLayer DataLayerObj = new DataLayer();
+ // try
+ // {
+ // // recupero dati macchina...
+ // var elencoDoss = DataLayerObj.taDOSS.getLastByPODL();
+
+ // answ = JsonConvert.SerializeObject(elencoDoss);
+ // }
+ // catch
+ // { }
+ // return answ;
+ //}
+
+ /////
+ ///// Recupera elenco ListValues data tabella:
+ /////
+ ///// GET: IOB/getListValByTable
+ /////
+ ///// nome tabella x cui filtrare risultati, se "" mostra tutto
+ ///// Json contenente lista oggetti ListValue serializzati
+ //public string getListValByTable(string id)
+ //{
+ // string answ = "";
+
+ // // init obj DataLayer
+ // DataLayer DataLayerObj = new DataLayer();
+ // try
+ // {
+ // // recupero dati macchina...
+ // var elencoOdl = DataLayerObj.taListVal.getByTableField(id, "*");
+ // answ = JsonConvert.SerializeObject(elencoOdl);
+ // }
+ // catch
+ // { }
+ // return answ;
+ //}
+
+ /////
+ ///// Restituisce dati di associazione tra macchina, device IOB chiamante e sue info
+ /////
+ ///// Id della macchina
+ /////
+ //public string getM2IOB(string id)
+ //{
+ // string answ = "";
+ // try
+ // {
+ // // recupero da redis...
+ // string hM2IOB = DataLayer.hM2IOB(id);
+ // string dataSer = memLayer.ML.getRSV(hM2IOB);
+ // if (dataSer != "" && dataSer != null)
+ // {
+ // // restituisco Json
+ // answ = dataSer;
+ // }
+ // else
+ // {
+ // answ = "NO";
+ // }
+ // }
+ // catch
+ // {
+ // answ = "KO";
+ // }
+ // return answ;
+ //}
+
+ /////
+ ///// restituisce elenco parametri correnti come una List Json di oggetti objItem
+ ///// GET: IOB/getObjItems/SIMUL_03
+ /////
+ ///// ID dell'IOB
+ /////
+ //public string getObjItems(string id)
+ //{
+ // string answ = "";
+ // if (string.IsNullOrWhiteSpace(id))
+ // {
+ // answ = "Missing IOB";
+ // }
+ // else
+ // {
+ // // procedo a recuperare l'oggetto...
+ // List currParams = new List();
+ // try
+ // {
+ // DataLayer DataLayerObj = new DataLayer();
+ // // deserializzo
+ // currParams = DataLayerObj.getCurrObjItems(id);
+ // // se != null --> salvo!
+ // if (currParams != null)
+ // {
+ // answ = JsonConvert.SerializeObject(currParams);
+ // }
+ // }
+ // catch (Exception exc)
+ // {
+ // logger.lg.scriviLog($"Errore in getObjItems{Environment.NewLine}{exc}");
+ // answ = "NO";
+ // }
+ // }
+ // return answ;
+ //}
+
+ /////
+ ///// restituisce elenco parametri CHE RICHIEDONO scrittura su PLC come una List Json di
+ ///// oggetti objItem
+ ///// GET: IOB/getObjItems2Write/SIMUL_03
+ /////
+ ///// ID dell'IOB
+ /////
+ //public string getObjItems2Write(string id)
+ //{
+ // string answ = "";
+ // if (string.IsNullOrWhiteSpace(id))
+ // {
+ // answ = "Missing IOB";
+ // }
+ // else
+ // {
+ // // procedo a recuperare l'oggetto...
+ // List currParams = new List();
+ // try
+ // {
+ // DataLayer DataLayerObj = new DataLayer();
+ // // deserializzo
+ // currParams = DataLayerObj.getCurrObjItemsPendigWrite(id);
+ // // se != null --> salvo!
+ // if (currParams != null)
+ // {
+ // answ = JsonConvert.SerializeObject(currParams);
+ // }
+ // }
+ // catch (Exception exc)
+ // {
+ // logger.lg.scriviLog($"Errore in getCurrParams{Environment.NewLine}{exc}");
+ // answ = "NO";
+ // }
+ // }
+ // return answ;
+ //}
+
+ /////
+ ///// Recupera ODL x macchina e data, se + di 1 quello di durata maggiore:
+ /////
+ ///// GET: IOB/getOdlAtDate/SIMUL_03
+ /////
+ ///// IdxMacchina
+ ///// DataRiferimento, formato yyyyMMdd (8 cifre)
+ /////
+ //public string getOdlAtDate(string id, string dateRif)
+ //{
+ // string answ = "";
+ // // attenzione! poiché nell'URL il carattere "#" viene filtrato ci aspettiamo il
+ // // carattere "|" che poi trasformiamo ora in "#"
+ // id = id.Replace("|", "#");
+ // // converto la data in formato dateTime... e ottengo intervallo data indicata da
+ // // mezzanotte a 23:59:59...
+ // CultureInfo provider = CultureInfo.InvariantCulture;
+ // DateTime dtFrom = DateTime.Today;
+ // bool fatto = DateTime.TryParseExact(dateRif, "yyyyMMdd", provider, DateTimeStyles.None, out dtFrom);
+ // if (fatto)
+ // {
+ // // data fine giorno dopo
+ // DateTime dtTo = dtFrom.AddDays(1);
+ // // cerco ODL alla data (validi)
+ // DataLayer DataLayerObj = new DataLayer();
+ // DS_ProdTempi.ODLDataTable odlList = DataLayerObj.taODL.getByMacchinaPeriodoNoNull(id, dtFrom, dtTo);
+ // // se non trovo aumento ricerca all'indietro...
+ // int maxTry = 14;
+ // while (odlList.Count == 0 && maxTry > 0)
+ // {
+ // dtFrom = dtFrom.AddDays(-1);
+ // odlList = DataLayerObj.taODL.getByMacchinaPeriodoNoNull(id, dtFrom, dtTo);
+ // maxTry++;
+ // }
+ // int idxOdl = 0;
+ // // se > 1 --> prendo il + durevole
+ // if (odlList.Count > 1)
+ // {
+ // double maxPeriod = 0;
+ // foreach (var item in odlList)
+ // {
+ // DateTime dtStart = item.DataInizio > dtFrom ? item.DataInizio : dtFrom;
+ // DateTime dtEnd = item.DataFine < dtTo ? item.DataFine : dtTo;
+ // double currPeriod = dtEnd.Subtract(dtStart).TotalMinutes;
+ // if (currPeriod > maxPeriod)
+ // {
+ // maxPeriod = currPeriod;
+ // idxOdl = item.IdxODL;
+ // }
+ // }
+ // }
+ // else if (odlList.Count == 1)
+ // {
+ // idxOdl = odlList[0].IdxODL;
+ // }
+ // else
+ // {
+ // // cerco ODL prendendo qualche gg prima...
+ // }
+ // // conversione!
+ // answ = $"{idxOdl}";
+ // }
+ // return answ;
+ //}
+
+ /////
+ ///// Recupera TASK richiesto x macchina:
+ /////
+ ///// GET: IOB/getOptPar/SIMUL_03
+ /////
+ /////
+ ///// Json contenente 1..n task da eseguire
+ //public string getOptPar(string id)
+ //{
+ // string answ = "";
+ // // scrivo keep alive!!! (se necessario, altrimenti è in cache...)
+ // MapoDb.MapoDb connDb = new MapoDb.MapoDb();
+ // connDb.scriviKeepAlive(id, DateTime.Now);
+ // try
+ // {
+ // // leggo da REDIS eventuale elenco task x macchina...
+ // DataLayer DataLayerObj = new DataLayer();
+ // Dictionary valori = DataLayerObj.mOptParMacchina(id);
+ // answ = JsonConvert.SerializeObject(valori);
+ // }
+ // catch
+ // { }
+ // return answ;
+ //}
+
+ /////
+ ///// Recupera TASK richiesto x macchina:
+ /////
+ ///// GET: IOB/getTask2Exe/SIMUL_03
+ /////
+ /////
+ ///// Json contenente 1..n task da eseguire
+ //public string getTask2Exe(string id)
+ //{
+ // string answ = "";
+ // // scrivo keep alive!!! (se necessario, altrimenti è in cache...)
+ // MapoDb.MapoDb connDb = new MapoDb.MapoDb();
+ // DataLayer DataLayerObj = new DataLayer();
+ // connDb.scriviKeepAlive(id, DateTime.Now);
+ // try
+ // {
+ // // leggo da REDIS eventuale elenco task x macchina...
+ // Dictionary valori = DataLayerObj.mTaskMacchina(id);
+ // answ = JsonConvert.SerializeObject(valori);
+ // }
+ // catch
+ // { }
+ // return answ;
+ //}
+
+ //// GET: IOB (è un check alive del server)
+ //public string Index()
+ //{
+ // if (memLayer.ML.CRB("IOB_RedEnab"))
+ // {
+ // // conto la richiesta nel contatore REDIS
+ // long nCall = memLayer.ML.setRCntI(DataLayer.mHash("COUNT:pCall:IOB_INDEX"));
+ // //... se == nCall2Log scrivo su log e resetto
+ // long nCall2Log = memLayer.ML.cdvi("nCall2Log");
+ // if (nCall >= nCall2Log)
+ // {
+ // // loggo
+ // logger.lg.scriviLog(string.Format("IOB_INDEX: effettuate {0} call", nCall), tipoLog.INFO);
+ // // resetto!
+ // memLayer.ML.resetRCnt(DataLayer.mHash("COUNT:pCall:IOB_INDEX"));
+ // }
+ // }
+ // return "OK";
+ //}
+
+ //// GET: IOB/input/SIMUL_03?valore=3&dtEve=20181206180600000&dtCurr=20181206180600000&cnt=999
+ //public string input(string id, string valore, string dtEve, string dtCurr, string cnt)
+ //{
+ // string answ = "";
+ // // formato yyyymmddHHMMSSnnn ovvero da anno a millisecondi
+ // if (cnt == null)
+ // {
+ // cnt = "0";
+ // }
+
+ // DateTime dataOraEvento = DateTime.Now;
+ // if (memLayer.ML.CRI("_logLevel") > 6)
+ // {
+ // logger.lg.scriviLog($"Valori letti: idxMacchina: {id} | valore: {valore}", tipoLog.INFO);
+ // }
+ // try
+ // {
+ // DataLayer DataLayerObj = new DataLayer();
+ // answ = DataLayerObj.processInput(id, valore, dtEve, dtCurr, cnt);
+ // }
+ // catch (Exception exc)
+ // {
+ // logger.lg.scriviLog(string.Format("Errore in processInput{0}{1}", Environment.NewLine, exc));
+ // answ = "NO";
+ // }
+ // return answ;
+ //}
+
+ /////
+ ///// Processa una chiamata POST per l'invio di un array Json di oggetti LIVE REC
+ ///// PUT: IOB/liveJson/SIMUL_03
+ /////
+ ///// ID dell'IOB
+ /////
+ //[HttpPost]
+ //public string liveJson(string id)
+ //{
+ // string answ = "-";
+ // // questa classe è derivata da Controller.Response... x cui recupero lo stream in altro modo...
+ // string content = "";
+ // System.Web.HttpContext.Current.Request.InputStream.Position = 0;
+ // using (var reader = new StreamReader(
+ // Request.InputStream, System.Text.Encoding.UTF8, true, 4096, true))
+ // {
+ // content = reader.ReadToEnd();
+ // }
+ // //Rest
+ // System.Web.HttpContext.Current.Request.InputStream.Position = 0;
+ // // procedo a deserializzare in blocco l'oggetto...
+ // try
+ // {
+ // // deserializzo.
+ // liveIOB receivedData = JsonConvert.DeserializeObject(content);
+ // DataLayer DataLayerObj = new DataLayer();
+ // answ = DataLayerObj.processLiveJson(id, receivedData);
+ // // se vuoto --> OK!
+ // if (string.IsNullOrEmpty(answ))
+ // {
+ // answ = "OK 1 done";
+ // }
+ // }
+ // catch (Exception exc)
+ // {
+ // logger.lg.scriviLog($"Errore in liveJson{Environment.NewLine}{exc}");
+ // answ = "NO";
+ // }
+ // return answ;
+ //}
+
+ //// GET: IOB/liveRec/SIMUL_03?&liveData=chiave1|valore1#chiave2|valore#|chiave3|valore3
+ //public string liveRec(string id, string liveData)
+ //{
+ // string answ = "";
+ // DateTime dataOraEvento = DateTime.Now;
+ // if (memLayer.ML.CRI("_logLevel") > 6)
+ // {
+ // logger.lg.scriviLog($"Valori Live:{Environment.NewLine}idxMacchina: {id}{Environment.NewLine}liveData: {liveData}", tipoLog.INFO);
+ // }
+ // try
+ // {
+ // DataLayer DataLayerObj = new DataLayer();
+ // answ = DataLayerObj.processLiveRec(id, liveData);
+ // }
+ // catch (Exception exc)
+ // {
+ // logger.lg.scriviLog($"Errore in liveRec{Environment.NewLine}{exc}");
+ // answ = "NO";
+ // }
+ // return answ;
+ //}
+
+ /////
+ ///// Processa una chiamata POST per l'invio di un array Json di oggetti rawTransfer
+ ///// (generiche info da deserializzare)
+ ///// POST: IOB/rawTransfJson/SIMUL_03
+ /////
+ ///// ID dell'IOB
+ /////
+ //[HttpPost]
+ //public string rawTransfJson(string id)
+ //{
+ // int insDone = 0;
+ // string answ = "";
+ // // questa classe è derivata da Controller.Response... x cui recupero lo stream in altro modo...
+ // string content = "";
+ // System.Web.HttpContext.Current.Request.InputStream.Position = 0;
+ // using (var reader = new StreamReader(
+ // Request.InputStream, System.Text.Encoding.UTF8, true, 4096, true))
+ // {
+ // content = reader.ReadToEnd();
+ // }
+ // //Rest
+ // System.Web.HttpContext.Current.Request.InputStream.Position = 0;
+ // // se ho dati...
+ // if (content != "")
+ // {
+ // DataLayer DataLayerObj = new DataLayer();
+ // MagDataLayer DataLayerMagObj = new MagDataLayer();
+ // // deserializzo come un dictionary generico di oggetti rawDataType/string
+ // List receivedData = new List();
+ // // procedo a deserializzare in blocco l'oggetto...
+ // try
+ // {
+ // // deserializzo.
+ // receivedData = JsonConvert.DeserializeObject>(content);
+ // }
+ // catch (Exception exc)
+ // {
+ // logger.lg.scriviLog($"Errore in fase deserializzazione rawTransfJson{Environment.NewLine}{exc}");
+ // answ = "NO";
+ // }
+ // // se ho qualcosa da processare...
+ // if (receivedData != null)
+ // {
+ // try
+ // {
+ // foreach (var item in receivedData)
+ // {
+ // // per ora salvo su REDIS ultimo x tipo
+ // DataLayerObj.lastRawTrasfData = JsonConvert.SerializeObject(item.mesContent);
+
+ // // !!! FixMe ToDo fare deserializzazione e salvataggio su MongoDB
+ // // salvataggio su tab RawTrasf su DB IS
+
+ // // in base al tipo processo...
+ // switch (item.mesType)
+ // {
+ // case rawTransfType.IcoelBatch:
+ // break;
+
+ // case rawTransfType.IcoelVarInfo:
+ // break;
+
+ // case rawTransfType.RegGiacenze:
+ // // elenco ODL da svuotare preventivamente x insert...
+ // List listOdl = new List();
+ // // processo scrittura giacenze... processo 1:1 record di RegGiacenze
+ // List recData = new List();
+ // foreach (var singleRow in item.mesContent)
+ // {
+ // var listGiac = JsonConvert.DeserializeObject(singleRow.Value.ToString());
+ // recData.Add(listGiac);
+ // if (!listOdl.Contains(listGiac.IdxODL))
+ // {
+ // listOdl.Add(listGiac.IdxODL);
+ // }
+ // }
+ // // svuoto le giacenze degli ODL oggetto di import...
+ // bool fatto = DataLayerMagObj.resetRegGiacByOdl(listOdl);
+ // if (fatto)
+ // {
+ // // invio x salvare
+ // fatto = DataLayerMagObj.salvaRegGiac(recData);
+ // }
+ // break;
+
+ // case rawTransfType.ND:
+ // default:
+ // break;
+ // }
+ // insDone++;
+ // }
+ // // se vuoto --> OK!
+ // if (string.IsNullOrEmpty(answ))
+ // {
+ // answ = $"OK {insDone} processed";
+ // }
+ // }
+ // catch (Exception exc)
+ // {
+ // logger.lg.scriviLog($"Errore in fase invio valori rawTransfJson{Environment.NewLine}{exc}");
+ // answ = "NO";
+ // }
+ // }
+ // }
+ // return answ;
+ //}
+
+ /////
+ ///// ELIMINA TASK richiesto x macchina:
+ /////
+ ///// GET: IOB/remOptPar/SIMUL_03?pName=PZREQ
+ /////
+ /////
+ /////
+ //public string remOptPar(string id, string pName)
+ //{
+ // string answ = "";
+ // // scrivo keep alive!!! (se necessario, altrimenti è in cache...)
+ // MapoDb.MapoDb connDb = new MapoDb.MapoDb();
+ // DataLayer DataLayerObj = new DataLayer();
+ // connDb.scriviKeepAlive(id, DateTime.Now);
+ // try
+ // {
+ // DataLayerObj.remOptPar4Machine(id, pName);
+ // answ = getOptPar(id);
+ // }
+ // catch
+ // { }
+ // return answ;
+ //}
+
+ /////
+ ///// ELIMINA TASK richiesto x macchina:
+ /////
+ ///// GET: IOB/remTask2Exe/SIMUL_03?taskName=T180326160502
+ /////
+ /////
+ /////
+ //public string remTask2Exe(string id, string taskName)
+ //{
+ // string answ = "";
+ // // scrivo keep alive!!! (se necessario, altrimenti è in cache...)
+ // MapoDb.MapoDb connDb = new MapoDb.MapoDb();
+ // DataLayer DataLayerObj = new DataLayer();
+ // connDb.scriviKeepAlive(id, DateTime.Now);
+ // try
+ // {
+ // // converto stringa in tipo task...
+ // taskType tName = taskType.nihil;
+ // bool fatto = Enum.TryParse(taskName, out tName);
+ // if (fatto)
+ // {
+ // DataLayerObj.remTask4Machine(id, tName);
+ // }
+ // else
+ // {
+ // logger.lg.scriviLog($"remTask2Exe: impossibile riconoscere il comando {taskName} come uno dei tipi ammessi, NON rimosso", tipoLog.ERROR);
+ // }
+ // answ = getTask2Exe(id);
+ // }
+ // catch
+ // { }
+ // return answ;
+ //}
+
+ /////
+ ///// Effettua RESET dell'ODL corrente x macchina:
+ /////
+ ///// GET: IOB/resetCurrODL/5
+ /////
+ /////
+ /////
+ //public string resetCurrODL(string id)
+ //{
+ // DataLayer DataLayerObj = new DataLayer();
+ // return DataLayerObj.emptyCurrODL(id);
+ //}
+
+ /////
+ ///// Processa una chiamata POST per l'invio di un array Json di oggetti plcMemConf
+ ///// PUT: IOB/saveConf/SIMUL_03
+ /////
+ ///// ID dell'IOB
+ /////
+ //[HttpPost]
+ //public string saveConf(string id)
+ //{
+ // string answ = "";
+ // if (string.IsNullOrWhiteSpace(id))
+ // {
+ // answ = "Missing IOB";
+ // }
+ // else
+ // {
+ // // questa classe è derivata da Controller.Response... x cui recupero lo stream in
+ // // altro modo...
+ // string content = "";
+ // System.Web.HttpContext.Current.Request.InputStream.Position = 0;
+ // using (var reader = new StreamReader(Request.InputStream, System.Text.Encoding.UTF8, true, 4096, true))
+ // {
+ // content = reader.ReadToEnd();
+ // }
+ // //Rest
+ // System.Web.HttpContext.Current.Request.InputStream.Position = 0;
+ // // procedo a deserializzare in blocco l'oggetto...
+ // plcMemMap currMemMap = null;
+ // try
+ // {
+ // // deserializzo.
+ // currMemMap = JsonConvert.DeserializeObject(content);
+ // // se != null --> salvo!
+ // if (currMemMap != null)
+ // {
+ // DataLayer DataLayerObj = new DataLayer();
+ // DataLayerObj.setIobMemMap(id, currMemMap);
+ // answ = "OK";
+ // }
+ // }
+ // catch
+ // { }
+ // }
+ // return answ;
+ //}
+
+ /////
+ ///// Processa una chiamata POST per l'invio di un array Json di oggetti di conf DataItems (es
+ ///// per MTC)
+ ///// PUT: IOB/saveDataItems/SIMUL_03
+ /////
+ ///// ID dell'IOB
+ /////
+ //[HttpPost]
+ //public string saveDataItems(string id)
+ //{
+ // string answ = "";
+ // logger.lg.scriviLog($"Richiesta saveDataItems per id {id}");
+ // if (string.IsNullOrWhiteSpace(id))
+ // {
+ // answ = "Missing IOB";
+ // }
+ // else
+ // {
+ // // questa classe è derivata da Controller.Response... x cui recupero lo stream in
+ // // altro modo...
+ // string content = "";
+ // System.Web.HttpContext.Current.Request.InputStream.Position = 0;
+ // using (var reader = new StreamReader(Request.InputStream, System.Text.Encoding.UTF8, true, 4096, true))
+ // {
+ // content = reader.ReadToEnd();
+ // }
+ // // Rest
+ // System.Web.HttpContext.Current.Request.InputStream.Position = 0;
+
+ // // procedo a deserializzare in blocco l'oggetto...
+ // List dataItems = null;
+ // try
+ // {
+ // logger.lg.scriviLog($"Ricevuto payload di {content.Length} chars");
+ // // deserializzo.
+ // dataItems = JsonConvert.DeserializeObject>(content);
+ // // se != null --> salvo!
+ // if (dataItems != null)
+ // {
+ // // chiamo metodo update direttamente!
+ // MtcDataModelArchive.man.saveMachineDataItems(id, dataItems);
+ // answ = "OK";
+ // logger.lg.scriviLog($"Effettuato salvataggio saveDataItems per id {id}:{Environment.NewLine}{content}");
+ // }
+ // }
+ // catch
+ // { }
+ // }
+ // return answ;
+ //}
+
+ /////
+ ///// SALVA in blocco un incremento pezzi x macchina restituendo il valore appena inviato o,
+ ///// se mancasse chaive redis, del valore da DB
+ /////
+ ///// GET: IOB/savePzCountInc/5?qty=10
+ /////
+ ///// codice macchina
+ ///// num peziz da salvare in blocco
+ /////
+ //public string savePzCountInc(string id, string qty)
+ //{
+ // string answ = "";
+ // DateTime dataOraEvento = DateTime.Now;
+ // // salvo SEMPRE log x questo tipo di dati!
+ // logger.lg.scriviLog($"Salvataggio incremento contapezzi | idxMacchina: {id} | pezzi: {qty}", tipoLog.INFO);
+ // try
+ // {
+ // DataLayer DataLayerObj = new DataLayer();
+ // answ = DataLayerObj.saveCaricoPezzi(id, qty);
+ // }
+ // catch (Exception exc)
+ // {
+ // logger.lg.scriviLog($"Errore in savePzCountInc{Environment.NewLine}{exc}");
+ // answ = "NO";
+ // }
+ // return answ;
+ //}
+
+ /////
+ ///// Registrazione variazione allarmi
+ /////
+ ///// GET: IOB/sendAlarmBankUpdate/SIMUL_03
+ /////
+ /////
+ /////
+ //[HttpPost]
+ //public string sendAlarmBankUpdate(string id, string memAddr, int index, int currStatus)
+ //{
+ // DataLayer DataLayerObj = new DataLayer();
+ // // esempio valido x MAPO
+ // string answ = "";
+ // logger.lg.scriviLog($"Richiesta sendAlarmBankUpdate per id {id}");
+ // if (string.IsNullOrWhiteSpace(id))
+ // {
+ // answ = "Missing IOB";
+ // }
+ // else
+ // {
+ // // questa classe è derivata da Controller.Response... x cui recupero lo stream in
+ // // altro modo...
+ // string content = "";
+ // System.Web.HttpContext.Current.Request.InputStream.Position = 0;
+ // using (var reader = new StreamReader(Request.InputStream, System.Text.Encoding.UTF8, true, 4096, true))
+ // {
+ // content = reader.ReadToEnd();
+ // }
+ // // Rest
+ // System.Web.HttpContext.Current.Request.InputStream.Position = 0;
+
+ // // procedo a deserializzare in blocco l'oggetto...
+ // List ActiveAlarms = null;
+ // try
+ // {
+ // logger.lg.scriviLog($"Ricevuto payload di {content.Length} chars");
+ // // deserializzo.
+ // ActiveAlarms = JsonConvert.DeserializeObject>(content);
+ // // se != null --> salvo!
+ // if (ActiveAlarms != null)
+ // {
+ // string alarmDecoded = "-";
+ // if (ActiveAlarms != null && ActiveAlarms.Count > 0)
+ // {
+ // alarmDecoded = String.Join(" | ", ActiveAlarms);
+ // }
+ // DataLayerObj.taAlarmLog.insertQuery(DateTime.Now, id, memAddr, index, currStatus, alarmDecoded);
+ // answ = "OK";
+ // }
+ // }
+ // catch
+ // { }
+ // }
+ // return answ;
+
+ // // esempio GWMS
+ //}
+
+ ///// Salva MAC adress + IP dopo il reboot
+ ///// GET: IOB/sendReboot?idxMacchina=5&mac=18:C0:4D:37:3C:8C IP
+ ///// del Gateway
+ //public string sendReboot(string idxMacchina, string mac)
+ //{
+ // string answ = "NO";
+ // string IPv4 = "";
+ // string agent = "";
+ // try
+ // {
+ // // recupero IP del client remoto
+ // IPv4 = Request.UserHostName;
+ // agent = Request.UserAgent;
+ // }
+ // catch
+ // { }
+ // try
+ // {
+ // // ora salvo che la macchina è stata (ri)avviata...
+ // MapoDb.MapoDb MapoDbObj = new MapoDb.MapoDb();
+ // MapoDbObj.registraStartup(idxMacchina, IPv4, agent, mac);
+ // answ = "OK";
+ // }
+ // catch (Exception exc)
+ // {
+ // if (memLayer.ML.CRI("_logLevel") > 5)
+ // {
+ // string errore = string.Format("Errore: {0}{1}", Environment.NewLine, exc);
+ // logger.lg.scriviLog(errore, tipoLog.EXCEPTION);
+ // }
+ // }
+ // return answ;
+ //}
+
+ /////
+ ///// Salva IP del gateway dopo il reboot
+ /////
+ ///// IP del Gateway
+ /////
+ //public string sendRebootGateway(string GWIP)
+ //{
+ // string answ = "OK";
+
+ // // !!!FARE!!! deve salvare il riavvio dell'applicazione GATEWAY multiclient
+
+ // return answ;
+ //}
+
+ /////
+ ///// SALVA Counter x macchina restituendo il valore appena inviato o, se mancasse chiave
+ ///// redis, del valore da DB
+ /////
+ ///// GET: IOB/setCounter/5?counter=10
+ /////
+ ///// cod macchina
+ ///// contapezzi da salvare
+ /////
+ //public string setCounter(string id, string counter)
+ //{
+ // string answ = "-1";
+ // DateTime dataOraEvento = DateTime.Now;
+ // if (memLayer.ML.CRI("_logLevel") > 6)
+ // {
+ // logger.lg.scriviLog($"Salvataggio counter | idxMacchina: {id}", tipoLog.INFO);
+ // }
+ // try
+ // {
+ // DataLayer DataLayerObj = new DataLayer();
+ // answ = DataLayerObj.saveCounter(id, counter);
+ // }
+ // catch (Exception exc)
+ // {
+ // logger.lg.scriviLog(string.Format("Errore in counter (set){0}{1}", Environment.NewLine, exc));
+ // }
+ // return answ;
+ //}
+
+ /////
+ ///// Salva associazione tra macchina, device IOB chiamante e sue info
+ /////
+ ///// Id della macchina
+ ///// Nome dell'IOB di acquisizione della macchina
+ /////
+ //public string setM2IOB(string id, string IOB_name)
+ //{
+ // string answ = "";
+ // try
+ // {
+ // // recupero IP del client remoto
+ // string IPv4 = Request.UserHostName;
+ // string agent = Request.UserAgent;
+ // // creo oggetto IOB_data...
+ // IOB_data m2IOB = new IOB_data
+ // {
+ // name = IOB_name,
+ // IP = IPv4,
+ // iType = IobType.ND,
+ // typeCss = "fa fa-question-circle-o",
+ // CNC_Counter = false
+ // };
+ // // imposto tipo ed icona come windows/linux secondo UserAgent...
+ // if (agent.IndexOf("WIN") >= 0)
+ // {
+ // m2IOB.iType = IobType.WIN;
+ // m2IOB.typeCss = "fa fa-windows";
+ // m2IOB.CNC_Counter = true;
+ // }
+ // else if (agent.IndexOf("Python") >= 0)
+ // {
+ // m2IOB.iType = IobType.rPi;
+ // m2IOB.typeCss = "fa fa-linux";
+ // }
+ // // serializzo...
+ // string dataSer = JsonConvert.SerializeObject(m2IOB);
+ // // salvo in redis...
+ // string hM2IOB = DataLayer.hM2IOB(id);
+ // memLayer.ML.setRSV(hM2IOB, dataSer);
+ // // salvo tutto OK
+ // answ = "OK";
+ // }
+ // catch
+ // {
+ // answ = "KO";
+ // }
+ // return answ;
+ //}
+
+ /////
+ ///// Processa una chiamata POST per l'invio di una List Json di oggetti objItem
+ ///// POST: IOB/setObjItems/SIMUL_03
+ /////
+ ///// ID dell'IOB
+ /////
+ //[HttpPost]
+ //public string setObjItems(string id)
+ //{
+ // string answ = "";
+ // if (string.IsNullOrWhiteSpace(id))
+ // {
+ // answ = "Missing IOB";
+ // }
+ // else
+ // {
+ // // questa classe è derivata da Controller.Response... x cui recupero lo stream in
+ // // altro modo...
+ // string content = "";
+ // System.Web.HttpContext.Current.Request.InputStream.Position = 0;
+ // using (var reader = new StreamReader(Request.InputStream, System.Text.Encoding.UTF8, true, 4096, true))
+ // {
+ // content = reader.ReadToEnd();
+ // }
+ // //Rest
+ // System.Web.HttpContext.Current.Request.InputStream.Position = 0;
+ // // procedo a deserializzare in blocco l'oggetto...
+ // List currParams = new List();
+ // try
+ // {
+ // // deserializzo.
+ // currParams = JsonConvert.DeserializeObject>(content);
+ // // se != null --> salvo!
+ // if (currParams != null)
+ // {
+ // DataLayer DataLayerObj = new DataLayer();
+ // bool fatto = DataLayerObj.setCurrObjItems(id, currParams);
+ // answ = fatto ? "OK" : "KO";
+ // }
+ // }
+ // catch (Exception exc)
+ // {
+ // logger.lg.scriviLog($"Errore in setCurrParams{Environment.NewLine}{exc}");
+ // answ = "EXC";
+ // }
+ // }
+ // return answ;
+ //}
+
+ //// GET: IOB/slog/SIMUL_03
+ //public string slog(string id)
+ //{
+ // string answ = "ND";
+ // // se id nullo --> KO!
+ // if (id == null)
+ // {
+ // answ = "KO";
+ // }
+ // else
+ // {
+ // try
+ // {
+ // DataLayer DataLayerObj = new DataLayer();
+ // // salvo risposta
+ // answ = DataLayerObj.sLogEnab(id) ? "OK" : "NO";
+ // }
+ // catch (Exception exc)
+ // {
+ // logger.lg.scriviLog(string.Format("Errore in sLog{0}{1}", Environment.NewLine, exc));
+ // answ = "NO";
+ // }
+ // }
+ // return answ;
+ //}
+
+ //// GET: IOB/takeFlogSnapshot/SIMUL_03
+ //public string takeFlogSnapshot(string id)
+ //{
+ // string answ = "";
+ // string caller = $"takeFlogSnapshot({id})";
+
+ // DateTime adesso = DateTime.Now;
+ // DateTime dtEnd = adesso;
+ // DateTime dtStart = adesso.AddDays(-1);
+ // //effettuo chiamata!
+ // answ = doSaveFLSnapshot(id, dtStart, dtEnd, caller);
+ // return answ;
+ //}
+
+ //// GET: IOB/ulog/SIMUL_03?flux=PROG&valore=P0001&dtEve=20161223180600000&dtCurr=20161223180600000&cnt=999&matrOpr=0=0&label=&valNum
+ //public string ulog(string id, string flux, string valore, string dtEve, string dtCurr, string cnt, string matrOpr, string label, string valNum)
+ //{
+ // string answ = "";
+ // // formato yyyymmddHHMMSSnnn ovvero da anno a millisecondi
+ // if (cnt == null)
+ // {
+ // cnt = "0";
+ // }
+
+ // DateTime dataOraEvento = DateTime.Now;
+ // if (memLayer.ML.CRI("_logLevel") > 6)
+ // {
+ // logger.lg.scriviLog($"ulog | Valori letti: idxMacchina: {id} | flux: {flux} valore: {valore} | matrOpr: {matrOpr} | label: {label} | valNum: {valNum}", tipoLog.INFO);
+ // }
+ // try
+ // {
+ // DataLayer DataLayerObj = new DataLayer();
+ // int count = 0;
+ // int nMatrOpr = 0;
+ // int nValNum = 0;
+ // Int32.TryParse(cnt, out count);
+ // Int32.TryParse(matrOpr, out nMatrOpr);
+ // Int32.TryParse(valNum, out nValNum);
+ // answ = DataLayerObj.processUserLog(id, flux, valore, dtEve, dtCurr, count, nMatrOpr, label, nValNum);
+ // }
+ // catch (Exception exc)
+ // {
+ // logger.lg.scriviLog($"Errore in ulog{Environment.NewLine}{exc}");
+ // answ = "NO";
+ // }
+ // return answ;
+ //}
+
+ /////
+ ///// Processa una chiamata POST per l'invio di una List Json 1+ UserAction (contiene
+ ///// controlli, scarti, dichiarazioni)
+ ///// POST: IOB/ulogJson/SIMUL_03
+ /////
+ ///// ID dell'IOB
+ /////
+ //[HttpPost]
+ //public string ulogJson(string id)
+ //{
+ // int insDone = 0;
+ // string answ = "-";
+ // // questa classe è derivata da Controller.Response... x cui recupero lo stream in altro modo...
+ // string content = "";
+ // System.Web.HttpContext.Current.Request.InputStream.Position = 0;
+ // using (var reader = new StreamReader(
+ // Request.InputStream, System.Text.Encoding.UTF8, true, 4096, true))
+ // {
+ // content = reader.ReadToEnd();
+ // }
+ // //Rest
+ // System.Web.HttpContext.Current.Request.InputStream.Position = 0;
+ // // se ho dati...
+ // if (content != "")
+ // {
+ // DataLayer DataLayerObj = new DataLayer();
+ // // procedo a deserializzare in blocco l'oggetto...
+ // ulogJsonPayload receivedData = new ulogJsonPayload();
+ // try
+ // {
+ // // deserializzo.
+ // receivedData = JsonConvert.DeserializeObject(content);
+ // }
+ // catch (Exception exc)
+ // {
+ // logger.lg.scriviLog($"Errore in fase deserializzazione ulogJson{Environment.NewLine}{exc}");
+ // answ = "NO";
+ // }
+ // // se ho qualcosa da processare...
+ // if (receivedData != null)
+ // {
+ // // per ogni valore --> salvo!
+ // try
+ // {
+ // foreach (var item in receivedData.fluxData)
+ // {
+ // // formato datetime come yyyyMMddHHmmssfff -->es: 20181223180600000
+ // answ = DataLayerObj.processUserLog(id, item.flux, item.valore, item.dtEve.ToString("yyyyMMddHHmmssfff"), item.dtCurr.ToString("yyyyMMddHHmmssfff"), item.cnt, item.matrOpr, item.label, item.valNum);
+ // }
+ // // se vuoto --> OK!
+ // if (string.IsNullOrEmpty(answ))
+ // {
+ // answ = $"OK {insDone} processed";
+ // }
+ // }
+ // catch (Exception exc)
+ // {
+ // logger.lg.scriviLog($"Errore in fase invio valori ulogJson{Environment.NewLine}{exc}");
+ // answ = "NO";
+ // }
+ // }
+ // }
+ // return answ;
+ //}
+
+ /////
+ ///// Processa una chiamata POST per l'invio di un SET di file "a nome" di un IOB, formato MapoSDK.fileEmbed
+ ///// PUT: IOB/uploadFile/SIMUL_03
+ /////
+ ///// ID dell'IOB
+ /////
+ //[HttpPost]
+ //public string uploadFile(string id)
+ //{
+ // string answ = "";
+ // // questa classe è derivata da Controller.Response... x cui recupero lo stream in altro modo...
+ // string content = "";
+ // System.Web.HttpContext.Current.Request.InputStream.Position = 0;
+ // using (var reader = new StreamReader(Request.InputStream, System.Text.Encoding.UTF8, true, 4096, true))
+ // {
+ // content = reader.ReadToEnd();
+ // }
+ // //Rest
+ // System.Web.HttpContext.Current.Request.InputStream.Position = 0;
+ // // procedo a deserializzare in blocco l'oggetto...
+ // try
+ // {
+ // // deserializzo.
+ // fileEmbed receivedData = JsonConvert.DeserializeObject(content);
+ // // salvo nella cartella di Upload...
+ // string basePath = Server.MapPath(memLayer.ML.CRS("uploadFileDir"));
+ // string dirPath = $"{basePath}\\{id}";
+ // // fix directory...
+ // Directory.CreateDirectory(dirPath);
+ // foreach (var item in receivedData.fileList)
+ // {
+ // // scrivo!
+ // System.IO.File.WriteAllText($"{dirPath}\\{item.fileName}", item.content);
+ // }
+ // answ = "OK";
+ // }
+ // catch (Exception exc)
+ // {
+ // logger.lg.scriviLog($"Errore in uploadFile{Environment.NewLine}{exc}");
+ // answ = "NO";
+ // }
+ // return answ;
+ //}
+
+ /////
+ ///// Processa una chiamata POST per l'invio di una List Json di UNO O PIU' oggetti objItem
+ ///// POST: IOB/upsertObjItems/SIMUL_03
+ /////
+ ///// ID dell'IOB
+ /////
+ //[HttpPost]
+ //public string upsertObjItems(string id)
+ //{
+ // string answ = "";
+ // if (string.IsNullOrWhiteSpace(id))
+ // {
+ // answ = "Missing IOB";
+ // }
+ // else
+ // {
+ // // questa classe è derivata da Controller.Response... x cui recupero lo stream in
+ // // altro modo...
+ // string content = "";
+ // System.Web.HttpContext.Current.Request.InputStream.Position = 0;
+ // using (var reader = new StreamReader(Request.InputStream, System.Text.Encoding.UTF8, true, 4096, true))
+ // {
+ // content = reader.ReadToEnd();
+ // }
+ // //Rest
+ // System.Web.HttpContext.Current.Request.InputStream.Position = 0;
+ // // procedo a deserializzare in blocco l'oggetto...
+ // List innovazioni = new List();
+ // try
+ // {
+ // // deserializzo.
+ // innovazioni = JsonConvert.DeserializeObject>(content);
+ // // se != null --> salvo!
+ // if (innovazioni != null)
+ // {
+ // // salvo
+ // DataLayer DataLayerObj = new DataLayer();
+ // DataLayerObj.upsertCurrObjItems(id, innovazioni);
+ // answ = "OK";
+ // }
+ // }
+ // catch (Exception exc)
+ // {
+ // logger.lg.scriviLog($"Errore in upsertObjItems{Environment.NewLine}{exc}");
+ // answ = "NO";
+ // }
+ // }
+ // return answ;
+ //}
+
+ #endregion Public Methods
+
+ #region Private Methods
+
+ /////
+ ///// Effettua vera chiamata x salvataggio snapshot dati FluxLog
+ /////
+ /////
+ /////
+ /////
+ /////
+ //private static string doSaveFLSnapshot(string id, DateTime dtStart, DateTime dtEnd, string caller)
+ //{
+ // string answ;
+ // DateTime dataOraEvento = DateTime.Now;
+ // if (memLayer.ML.CRI("_logLevel") > 6)
+ // {
+ // logger.lg.scriviLog($"{caller} | Richiesta snapshot dati FluxLog macchina: idxMacchina: {id} | periodo: {dtStart} - {dtEnd}", tipoLog.INFO);
+ // }
+ // try
+ // {
+ // DataLayer DataLayerObj = new DataLayer();
+ // answ = DataLayerObj.takeFlogSnapshotLast(id, dtStart, dtEnd);
+ // }
+ // catch (Exception exc)
+ // {
+ // logger.lg.scriviLog($"Errore in {caller}{Environment.NewLine}{exc}");
+ // answ = "NO";
+ // }
+
+ // return answ;
+ //}
+
+ #endregion Private Methods
+ }
+}
diff --git a/MP.IOC/Controllers/RecipeArchiveController.cs b/MP.IOC/Controllers/RecipeArchiveController.cs
new file mode 100644
index 00000000..9e4059b1
--- /dev/null
+++ b/MP.IOC/Controllers/RecipeArchiveController.cs
@@ -0,0 +1,132 @@
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+using MP.IOC.Data;
+using NLog;
+using NLog.Fluent;
+
+namespace MP.IOC.Controllers
+{
+ [Route("api/[controller]")]
+ [ApiController]
+ public class RecipeArchiveController : ControllerBase
+ {
+ #region Public Constructors
+
+ public RecipeArchiveController(IConfiguration configuration, MpDataService DataService)
+ {
+ Log.Info("Starting RecipeArchiveController");
+ _configuration = configuration;
+ DService = DataService;
+ Log.Info("Avviata classe RecipeArchiveController");
+ }
+
+ #endregion Public Constructors
+
+ #region Public Methods
+
+ [HttpGet("GetByPODL")]
+ public async Task GetByPODL(string idxMacc, int idxPODL)
+ {
+ string answ = "NO DATA";
+ string archPath = await DService.MacchineRecipeArchive(idxMacc);
+ var podlData = await DService.POdlGetByKey(idxPODL);
+ if (podlData != null)
+ {
+ string fileName = podlData?.Recipe ?? "";
+ string fullPath = Path.Combine(archPath, fileName);
+ if (!string.IsNullOrEmpty(fullPath))
+ {
+ try
+ {
+ if (System.IO.File.Exists(fullPath))
+ {
+ answ = System.IO.File.ReadAllText(fullPath);
+ if (string.IsNullOrEmpty(answ))
+ {
+ Log.Error($"Errore in GetByPODL: contenuto file vuoto | idxMacc: {idxMacc} | idxPODL: {idxPODL}");
+ }
+ }
+ else
+ {
+ Log.Error($"Errore in GetByPODL: il file non esiste | fullPath {fullPath}");
+ }
+ }
+ catch (Exception exc)
+ {
+ Log.Error($"Eccezione in GetByPODL:{Environment.NewLine}{exc}");
+ }
+ }
+ else
+ {
+ Log.Error($"Errore in GetByPODL: fullPath null ");
+ }
+ }
+ else
+ {
+ Log.Error($"Errore in GetByPODL: podlData null | idxPODL: {idxPODL}");
+ }
+ return answ;
+ }
+
+ [HttpGet("GetFile")]
+ public async Task GetFile(string idxMacc, string fileName)
+ {
+ string answ = "NO DATA";
+ string archPath = await DService.MacchineRecipeArchive(idxMacc);
+ if (!string.IsNullOrEmpty(archPath))
+ {
+ string fullPath = Path.Combine(archPath, fileName);
+ if (!string.IsNullOrEmpty(fullPath))
+ {
+ try
+ {
+ if (System.IO.File.Exists(fullPath))
+ {
+ answ = System.IO.File.ReadAllText(fullPath);
+ if (string.IsNullOrEmpty(answ))
+ {
+ Log.Error($"Errore in GetFile: contenuto file vuoto | idxMacc: {idxMacc} | fileName: {fileName}");
+ }
+ }
+ else
+ {
+ Log.Error($"Errore in GetFile: il file non esiste | fullPath {fullPath}");
+ }
+ }
+ catch (Exception exc)
+ {
+ Log.Error($"Eccezione in GetFile:{Environment.NewLine}{exc}");
+ }
+ }
+ else
+ {
+ Log.Error($"Errore in GetFile: fullPath null ");
+ }
+ }
+ else
+ {
+ Log.Error($"Errore in GetFile: archPath null ");
+ }
+ return answ;
+ }
+
+ #endregion Public Methods
+
+ #region Protected Properties
+
+ ///
+ /// Dataservice x accesso DB
+ ///
+ protected MpDataService DService { get; set; }
+
+ #endregion Protected Properties
+
+ #region Private Fields
+
+ private static IConfiguration _configuration = null!;
+
+ private static Logger Log = LogManager.GetCurrentClassLogger();
+
+ #endregion Private Fields
+ }
+}
\ No newline at end of file
diff --git a/MP.IOC/Controllers/RecipeController.cs b/MP.IOC/Controllers/RecipeController.cs
new file mode 100644
index 00000000..6ebf6944
--- /dev/null
+++ b/MP.IOC/Controllers/RecipeController.cs
@@ -0,0 +1,73 @@
+using Microsoft.AspNetCore.Mvc;
+using MP.IOC.Data;
+using Newtonsoft.Json;
+using NLog;
+using System.Xml;
+
+namespace MP.IOC.Controllers
+{
+ [Route("api/[controller]")]
+ [ApiController]
+ public class RecipeController : ControllerBase
+ {
+ #region Public Constructors
+
+ public RecipeController(IConfiguration configuration, MpDataService DataService)
+ {
+ Log.Info("Starting RecipeController");
+ _configuration = configuration;
+ DService = DataService;
+ Log.Info("Avviata RecipeController");
+ }
+
+ #endregion Public Constructors
+
+ #region Public Methods
+
+ [HttpGet("GetRecipe")]
+ public async Task GetRecipe(int idxPODL)
+ {
+ string answ = "";
+ var reqRecipe = await DService.RecipeGetByPODL(idxPODL);
+ if (reqRecipe != null)
+ {
+ answ = DService.CalcRecipe(reqRecipe);
+ }
+ return answ;
+ }
+
+ [HttpGet("GetRecipeXML")]
+ public async Task GetRecipeXML(int idxPODL)
+ {
+ // aggiungo root node?
+ string answ = "";
+ // recupero versione json
+ string rawData = await GetRecipe(idxPODL);
+ if (!string.IsNullOrEmpty(rawData))
+ {
+ XmlDocument doc = (XmlDocument)(JsonConvert.DeserializeXmlNode(rawData) ?? new XmlDocument());
+ answ += doc.InnerXml;
+ }
+ return answ;
+ }
+
+ #endregion Public Methods
+
+ #region Protected Properties
+
+ ///
+ /// Dataservice x accesso DB
+ ///
+ protected MpDataService DService { get; set; }
+
+ #endregion Protected Properties
+
+ #region Private Fields
+
+ private static IConfiguration _configuration = null!;
+
+ private static Logger Log = LogManager.GetCurrentClassLogger();
+
+ #endregion Private Fields
+ }
+}
\ No newline at end of file
diff --git a/MP.IOC/Data/MpDataService.cs b/MP.IOC/Data/MpDataService.cs
new file mode 100644
index 00000000..64a1a716
--- /dev/null
+++ b/MP.IOC/Data/MpDataService.cs
@@ -0,0 +1,2179 @@
+using MP.Data;
+using MP.Data.Conf;
+using MP.Data.DatabaseModels;
+using MP.Data.DTO;
+using MP.Data.MgModels;
+using Newtonsoft.Json;
+using NLog;
+using StackExchange.Redis;
+using System.Data;
+using System.Diagnostics;
+
+namespace MP.IOC.Data
+{
+ public class MpDataService : IDisposable
+ {
+ #region Public Constructors
+
+ public MpDataService(IConfiguration configuration, ILogger logger)
+ {
+ _logger = logger;
+ _logger.LogInformation("Starting MpDataService INIT");
+ _configuration = configuration;
+
+ // setup compoenti REDIS
+ redisConn = ConnectionMultiplexer.Connect(_configuration.GetConnectionString("Redis"));
+ redisConnAdmin = ConnectionMultiplexer.Connect(_configuration.GetConnectionString("RedisAdmin"));
+ redisDb = redisConn.GetDatabase();
+ BroadastMsgPipe = new MessagePipe(redisConn, Constants.BROADCAST_M_PIPE);
+ // leggo cache lungo periodo
+ int.TryParse(_configuration.GetValue("ServerConf:redisLongTimeCache"), out redisLongTimeCache);
+
+ _logger.LogInformation("Redis INIT");
+
+ // conf DB
+ string connStr = _configuration.GetConnectionString("Mp.Data");
+ if (string.IsNullOrEmpty(connStr))
+ {
+ _logger.LogError("DbController: ConnString empty!");
+ }
+ else
+ {
+ SpecDbController = new MP.Data.Controllers.MpSpecController(configuration);
+ IocDbController = new MP.Data.Controllers.MpIocController(configuration);
+ _logger.LogInformation("DbControllers INIT OK");
+ }
+
+ // conf mongo...
+ connStr = _configuration.GetConnectionString("mdbConnString");
+ if (string.IsNullOrEmpty(connStr))
+ {
+ _logger.LogError("MongoController: ConnString empty!");
+ }
+ else
+ {
+ mongoController = new MP.Data.Controllers.MpMongoController(configuration);
+ _logger.LogInformation("MongoController INIT OK");
+ }
+ }
+
+ #endregion Public Constructors
+
+ #region Public Properties
+
+ public static MP.Data.Controllers.MpIocController IocDbController { get; set; } = null!;
+
+ public static MP.Data.Controllers.MpMongoController mongoController { get; set; } = null!;
+
+ public static MP.Data.Controllers.MpSpecController SpecDbController { get; set; } = null!;
+
+ public MessagePipe BroadastMsgPipe { get; set; } = null!;
+
+ ///
+ /// Dizionario dei tag configurati per IOB
+ ///
+ public Dictionary> currTagConf { get; set; } = new Dictionary>();
+
+ #endregion Public Properties
+
+ #region Public Methods
+
+ ///
+ /// Recupera eventuali azioni richieste
+ ///
+ ///
+ public async Task ActionGetReq()
+ {
+ Stopwatch stopWatch = new Stopwatch();
+ stopWatch.Start();
+ DisplayAction? result = null;
+ // cerco in redis...
+ RedisValue rawData = await redisDb.StringGetAsync(Utils.redisActionReq);
+ if (!string.IsNullOrEmpty($"{rawData}"))
+ {
+ result = JsonConvert.DeserializeObject($"{rawData}");
+ stopWatch.Stop();
+ TimeSpan ts = stopWatch.Elapsed;
+ Log.Debug($"ActionGetReq Read from REDIS: {ts.TotalMilliseconds}ms");
+ }
+ if (result == null)
+ {
+ result = new DisplayAction();
+ }
+ return result;
+ }
+
+ ///
+ /// Salva richiesta azione
+ ///
+ ///
+ ///
+ public bool ActionSetReq(DisplayAction? act2save)
+ {
+ bool fatto = false;
+ Stopwatch stopWatch = new Stopwatch();
+ stopWatch.Start();
+ // cerco in redis...
+ string rawData = JsonConvert.SerializeObject(act2save);
+ // invio broadcast + salvo in redis
+ BroadastMsgPipe.saveAndSendMessage(Utils.redisActionReq, rawData);
+ stopWatch.Stop();
+ TimeSpan ts = stopWatch.Elapsed;
+ Log.Debug($"ActionSetReq REDIS send to broadcast + Write cache: {ts.TotalMilliseconds}ms");
+ return fatto;
+ }
+
+ ///
+ /// Aggiunge un PARAMETRO OPZIONALE all'elenco di quelli salvati (in modalità upsert)
+ ///
+ ///
+ ///
+ ///
+ ///
+ public bool AddOptPar4Machine(string idxMacchina, string taskKey, string taskVal)
+ {
+ bool answ = false;
+ RedisKey currHash = Utils.OptParHash(idxMacchina);
+ try
+ {
+ // leggo task attuali...
+ var currVal = mOptParMacchina(idxMacchina);
+ currVal[taskKey] = taskVal;
+ answ = RedisSetHashDict(currHash, currVal);
+ }
+ catch (Exception exc)
+ {
+ Log.Error($"Eccezione in addOptPar4Machine{Environment.NewLine}{exc}");
+ }
+ return answ;
+ }
+
+ public async Task> AnagStatiComm()
+ {
+ Stopwatch stopWatch = new Stopwatch();
+ stopWatch.Start();
+ List? result = new List();
+ // cerco in redis...
+ RedisValue rawData = await redisDb.StringGetAsync(Utils.redisStatoCom);
+ if (!string.IsNullOrEmpty($"{rawData}"))
+ {
+ result = JsonConvert.DeserializeObject>($"{rawData}");
+ stopWatch.Stop();
+ TimeSpan ts = stopWatch.Elapsed;
+ Log.Debug($"AnagStatiComm Read from REDIS: {ts.TotalMilliseconds}ms");
+ }
+ else
+ {
+ result = await Task.FromResult(SpecDbController.AnagStatiComm());
+ // serializzo e salvo...
+ rawData = JsonConvert.SerializeObject(result);
+ await redisDb.StringSetAsync(Utils.redisStatoCom, rawData, getRandTOut(redisLongTimeCache));
+ stopWatch.Stop();
+ TimeSpan ts = stopWatch.Elapsed;
+ Log.Debug($"AnagStatiComm Read from DB: {ts.TotalMilliseconds}ms");
+ }
+ if (result == null)
+ {
+ result = new List();
+ }
+ return result;
+ }
+
+ public async Task> AnagTipoArtLV()
+ {
+ Stopwatch stopWatch = new Stopwatch();
+ stopWatch.Start();
+ string source = "DB";
+ List? result = new List();
+ // cerco in redis...
+ RedisValue rawData = await redisDb.StringGetAsync(Utils.redisTipoArt);
+ if (!string.IsNullOrEmpty($"{rawData}"))
+ {
+ result = JsonConvert.DeserializeObject>($"{rawData}");
+ source = "REDIS";
+ }
+ else
+ {
+ result = await Task.FromResult(SpecDbController.AnagTipoArtLV());
+ // serializzo e salvo...
+ rawData = JsonConvert.SerializeObject(result);
+ await redisDb.StringSetAsync(Utils.redisTipoArt, rawData, getRandTOut(redisLongTimeCache));
+ }
+ stopWatch.Stop();
+ TimeSpan ts = stopWatch.Elapsed;
+ Log.Debug($"AnagTipoArtLV Read from {source}: {ts.TotalMilliseconds}ms");
+ if (result == null)
+ {
+ result = new List();
+ }
+ return result;
+ }
+
+ ///
+ /// Elenco Codice articolo con dati dossier gestiti
+ ///
+ ///
+ public async Task> ArticleWithDossier()
+ {
+ List? result = new List();
+ Stopwatch stopWatch = new Stopwatch();
+ stopWatch.Start();
+ string readType = "DB";
+ string currKey = Utils.redisArtByDossier;
+ // cerco in redis dato valore sel macchina...
+ RedisValue rawData = redisDb.StringGet(currKey);
+ if (rawData.HasValue)
+ {
+ result = JsonConvert.DeserializeObject>($"{rawData}");
+ readType = "REDIS";
+ }
+ else
+ {
+ result = await Task.FromResult(SpecDbController.ArticleWithDossier());
+ // serializzo e salvo...
+ rawData = JsonConvert.SerializeObject(result);
+ redisDb.StringSet(currKey, rawData, getRandTOut(redisLongTimeCache));
+ }
+ if (result == null)
+ {
+ result = new List();
+ }
+ stopWatch.Stop();
+ TimeSpan ts = stopWatch.Elapsed;
+ Log.Debug($"ArticleWithDossier | Read from {readType}: {ts.TotalMilliseconds}ms");
+ return result;
+ }
+
+ ///
+ /// Eliminazione record selezionato
+ ///
+ ///
+ ///
+ public async Task ArticoliDeleteRecord(AnagArticoli currRec)
+ {
+ bool fatto = await SpecDbController.ArticoliDeleteRecord(currRec);
+ await resetCacheArticoli();
+ return fatto;
+ }
+
+ ///
+ /// Restitusice elenco articoli cercati
+ ///
+ ///
+ ///
+ ///
+ public async Task> ArticoliGetSearch(int numRecord, string azienda, string searchVal)
+ {
+ List? result = new List();
+ Stopwatch stopWatch = new Stopwatch();
+ stopWatch.Start();
+ string readType = "DB";
+ string sKey = string.IsNullOrEmpty(searchVal) ? "***" : searchVal;
+ string currKey = $"{Utils.redisArtList}:{azienda}:{sKey}";
+ // cerco in redis dato valore sel macchina...
+ RedisValue rawData = redisDb.StringGet(currKey);
+ if (rawData.HasValue)
+ {
+ result = JsonConvert.DeserializeObject>($"{rawData}");
+ readType = "REDIS";
+ }
+ else
+ {
+ result = await Task.FromResult(SpecDbController.ArticoliGetSearch(numRecord, azienda, searchVal));
+ // serializzo e salvo...
+ rawData = JsonConvert.SerializeObject(result);
+ redisDb.StringSet(currKey, rawData, getRandTOut(redisLongTimeCache / 5));
+ }
+ if (result == null)
+ {
+ result = new List();
+ }
+ stopWatch.Stop();
+ TimeSpan ts = stopWatch.Elapsed;
+ Log.Debug($"ArticoliGetSearch | Read from {readType}: {ts.TotalMilliseconds}ms");
+ return result;
+ }
+
+ ///
+ /// Aggiornamento record selezionato
+ ///
+ ///
+ ///
+ public async Task ArticoliUpdateRecord(AnagArticoli currRec)
+ {
+ bool fatto = await SpecDbController.ArticoliUpdateRecord(currRec);
+ await resetCacheArticoli();
+ return fatto;
+ }
+
+ ///
+ /// Verifica se sia possiubile cancellare articolo dato suo CodArt cercando su redis o su
+ /// tab veto da DB
+ ///
+ ///
+ ///
+ public bool ArticoloDelEnabled(object CodArt)
+ {
+ bool answ = false;
+ string codArticolo = $"{CodArt}";
+ int cacheCheckArtUsato = 1;
+ int.TryParse(_configuration.GetValue("ServerConf:cacheCheckArtUsato"), out cacheCheckArtUsato);
+ TimeSpan TTLCache = getRandTOut(cacheCheckArtUsato);
+ // cerco in cache redis...
+ string redKeyArtUsed = $"{Utils.redKeyArtUsed}:{codArticolo}";
+ string redKeyTabCheckArt = Utils.redKeyTabCheckArt;
+ var rawData = redisDb.StringGet(redKeyArtUsed);
+ if (!string.IsNullOrEmpty(rawData))
+ {
+ bool.TryParse(rawData, out answ);
+ }
+ else
+ {
+ // controllo non sia stato mai prodotto sennò non posso cancellare...
+ try
+ {
+ // cerco in cache se ci sia la tabella con gli articoli impiegati...
+ var rawTable = redisDb.StringGet(redKeyTabCheckArt);
+ List? artList = new List();
+ if (!string.IsNullOrEmpty(rawTable))
+ {
+ artList = JsonConvert.DeserializeObject>($"{rawTable}");
+ }
+ // rileggo...
+ if (artList == null || artList.Count == 0)
+ {
+ artList = new List();
+ var tabArticoli = SpecDbController.ArticoliGetUsed();
+ var codList = tabArticoli.Select(x => x.CodArticolo);
+ foreach (string cod in codList)
+ {
+ artList.Add(cod);
+ }
+ // SE fosse vuoto aggiungo comunque il cado "ND"...
+ if (artList.Count == 0)
+ {
+ artList.Add("ND");
+ }
+ // salvo
+ rawTable = JsonConvert.SerializeObject(artList);
+ redisDb.StringSet(redKeyTabCheckArt, rawTable, TTLCache);
+ }
+ // cerco nella tabella: se ci fosse --> disabilitato delete
+ bool usato = false;
+ if (artList != null && artList.Count > 0)
+ {
+ usato = artList.Contains(codArticolo);
+ }
+ answ = !usato;
+ redisDb.StringSet(redKeyArtUsed, $"{answ}", TTLCache);
+ }
+ catch
+ { }
+ }
+ return answ;
+ }
+
+ public string CalcRecipe(RecipeModel currRecipe)
+ {
+ return mongoController.CalcRecipe(currRecipe);
+ }
+
+ public async Task> ConfigGetAll()
+ {
+ Stopwatch stopWatch = new Stopwatch();
+ stopWatch.Start();
+ List? result = new List();
+ // cerco in redis...
+ RedisValue rawData = await redisDb.StringGetAsync(Utils.redisConfKey);
+ if (!string.IsNullOrEmpty($"{rawData}"))
+ {
+ result = JsonConvert.DeserializeObject>($"{rawData}");
+ stopWatch.Stop();
+ TimeSpan ts = stopWatch.Elapsed;
+ Log.Debug($"ConfigGetAll Read from REDIS: {ts.TotalMilliseconds}ms");
+ }
+ else
+ {
+ result = await Task.FromResult(SpecDbController.ConfigGetAll());
+ // serializzo e salvo...
+ rawData = JsonConvert.SerializeObject(result);
+ await redisDb.StringSetAsync(Utils.redisConfKey, rawData, getRandTOut(redisLongTimeCache));
+ stopWatch.Stop();
+ TimeSpan ts = stopWatch.Elapsed;
+ Log.Debug($"ConfigGetAll Read from DB: {ts.TotalMilliseconds}ms");
+ }
+ if (result == null)
+ {
+ result = new List();
+ }
+ return result;
+ }
+
+ ///
+ /// Reset dati cache config
+ ///
+ ///
+ public async Task ConfigResetCache()
+ {
+ await redisDb.StringSetAsync(Utils.redisConfKey, "");
+ }
+
+ ///
+ /// Update chiave config
+ ///
+ ///
+ public async Task ConfigUpdate(ConfigModel updRec)
+ {
+ return await Task.FromResult(SpecDbController.ConfigUpdate(updRec));
+ }
+
+ ///
+ /// Elenco completo valori DatiMacchine
+ ///
+ ///
+ public async Task> DatiMacchineGetAll()
+ {
+ List? result = new List();
+ Stopwatch stopWatch = new Stopwatch();
+ stopWatch.Start();
+ string readType = "DB";
+ string currKey = $"{Utils.redisBaseAddr}:TabDatiMacchine:ALL";
+ // cerco in redis dato valore sel macchina...
+ RedisValue rawData = redisDb.StringGet(currKey);
+ if (rawData.HasValue)
+ {
+ result = JsonConvert.DeserializeObject>($"{rawData}");
+ readType = "REDIS";
+ }
+ else
+ {
+ result = await Task.FromResult(SpecDbController.DatiMacchineGetAll());
+ // serializzo e salvo...
+ rawData = JsonConvert.SerializeObject(result);
+ redisDb.StringSet(currKey, rawData, getRandTOut(redisLongTimeCache));
+ }
+ if (result == null)
+ {
+ result = new List();
+ }
+ stopWatch.Stop();
+ TimeSpan ts = stopWatch.Elapsed;
+ Log.Debug($"DatiMacchineGetAll | Read from {readType}: {ts.TotalMilliseconds}ms");
+ return result;
+ }
+
+ ///
+ /// Dispose del connettore ai dati
+ ///
+ public void Dispose()
+ {
+ // Clear database controller
+ SpecDbController.Dispose();
+ mongoController.Dispose();
+ redisConn.Dispose();
+ }
+
+ ///
+ /// Eliminazione di un dossier
+ ///
+ /// record dossier da eliminare
+ ///
+ public async Task DossiersDeleteRecord(DossierModel selRecord)
+ {
+ bool result = false;
+ Stopwatch stopWatch = new Stopwatch();
+ stopWatch.Start();
+ result = await SpecDbController.DossiersDeleteRecord(selRecord);
+ // elimino cache redis...
+ RedisValue pattern = new RedisValue($"{Utils.redisDossByMac}:*");
+ bool answ = await RedisFlushPatternAsync(pattern);
+ stopWatch.Stop();
+ TimeSpan ts = stopWatch.Elapsed;
+ Log.Debug($"DossiersDeleteRecord | IdxMacchina {selRecord.IdxMacchina} | DtRif {selRecord.DtRif} | IdxODL {selRecord.IdxODL} | {ts.TotalMilliseconds}ms");
+ return result;
+ }
+
+ ///
+ /// Elenco ultimi n record DOssiers (che contengono ad esempio "salvataggi" di FLuxLog) dato
+ /// macchina (ordinato x data registrazione)
+ ///
+ /// * = tutte, altrimenti solo x una data macchina
+ /// Data minima per estrazione records
+ /// Data Massima per estrazione records
+ ///
+ public async Task> DossiersGetLastFilt(string IdxMacchina, string CodArticolo, DateTime DtStart, DateTime DtEnd)
+ {
+ List? result = new List();
+ Stopwatch stopWatch = new Stopwatch();
+ stopWatch.Start();
+ string readType = "DB";
+ string currKey = $"{Utils.redisDossByMac}:{IdxMacchina}:{CodArticolo}:{DtStart:yyyyMMddHHmm}:{DtEnd:yyyyMMddHHmm}";
+ // cerco in redis dato valore sel macchina...
+ RedisValue rawData = redisDb.StringGet(currKey);
+ if (rawData.HasValue)
+ {
+ result = JsonConvert.DeserializeObject>($"{rawData}");
+ readType = "REDIS";
+ }
+ else
+ {
+ result = await Task.FromResult(SpecDbController.DossiersGetLastFilt(IdxMacchina, CodArticolo, DtStart, DtEnd));
+ // serializzo e salvo...
+ rawData = JsonConvert.SerializeObject(result);
+ redisDb.StringSet(currKey, rawData, getRandTOut(redisLongTimeCache / 5));
+ }
+ if (result == null)
+ {
+ result = new List();
+ }
+ stopWatch.Stop();
+ TimeSpan ts = stopWatch.Elapsed;
+ Log.Debug($"DossiersGetLastFilt | Read from {readType}: {ts.TotalMilliseconds}ms");
+ return result;
+ }
+
+ ///
+ /// Inserimento nuovo record dossier
+ ///
+ ///
+ ///
+ public async Task DossiersInsert(DossierModel currDoss)
+ {
+ // aggiorno record sul DB
+ bool answ = await SpecDbController.DossiersInsert(currDoss);
+
+ return answ;
+ }
+
+ ///
+ /// Effettua salvataggio snapshot parametri (con stored) + svuota eventuale cache redis
+ ///
+ /// macchina
+ /// NUm massimo secondi per recuperare dati correnti
+ /// DataOra riferimento x cui prendere valori antecedenti
+ ///
+ public async Task DossiersTakeParamsSnapshotLast(string IdxMacchina, DateTime dtMin, DateTime dtMax)
+ {
+ bool answ = false;
+ await Task.Delay(1);
+ Log.Info($"Richiesta snapshot per macchina {IdxMacchina} | periodo {dtMin} --> {dtMax}");
+ // chiamo stored x salvare parametri
+ SpecDbController.DossiersTakeParamsSnapshotLast(IdxMacchina, dtMin, dtMax);
+ // elimino cache redis...
+ RedisValue pattern = new RedisValue($"{Utils.redisDossByMac}:*");
+ answ = await RedisFlushPatternAsync(pattern);
+ Log.Info($"Svuotata cache dossier | {pattern}");
+ return answ;
+ }
+
+ ///
+ /// Update valore dossier
+ ///
+ ///
+ ///
+ public async Task DossiersUpdateValore(DossierModel currDoss)
+ {
+ // aggiorno record sul DB
+ bool answ = await SpecDbController.DossiersUpdateValore(currDoss);
+
+ return answ;
+ }
+
+ ///
+ /// Restitusice elenco aziende
+ ///
+ ///
+ public Task> ElencoAziende()
+ {
+ return Task.FromResult(SpecDbController.AnagGruppiAziende());
+ }
+
+ ///
+ /// Restitusice elenco fasi
+ ///
+ ///
+ public Task> ElencoGruppiFase()
+ {
+ List result = new List();
+ Stopwatch stopWatch = new Stopwatch();
+ stopWatch.Start();
+ string readType = "DB";
+ string currKey = $"{Utils.redisAnagGruppi}";
+ // cerco in redis dato valore sel macchina...
+ RedisValue rawData = redisDb.StringGet(currKey);
+ if (rawData.HasValue)
+ {
+ var rawResult = JsonConvert.DeserializeObject>($"{rawData}");
+ if (rawResult != null)
+ {
+ result = rawResult;
+ }
+ readType = "REDIS";
+ }
+ else
+ {
+ result = SpecDbController.AnagGruppiFase();
+ // serializzo e salvo...
+ rawData = JsonConvert.SerializeObject(result);
+ redisDb.StringSet(currKey, rawData, getRandTOut(redisLongTimeCache / 5));
+ }
+ if (result == null)
+ {
+ result = new List();
+ }
+ stopWatch.Stop();
+ TimeSpan ts = stopWatch.Elapsed;
+ Log.Debug($"ElencoGruppiFase | Read from {readType}: {ts.TotalMilliseconds}ms");
+ return Task.FromResult(result);
+ }
+
+ public Task> ElencoLink()
+ {
+ return Task.FromResult(SpecDbController.ElencoLink());
+ }
+
+ ///
+ /// Aggiunta record EventList
+ ///
+ ///
+ ///
+ public async Task EvListInsert(EventListModel newRec)
+ {
+ return await SpecDbController.EvListInsert(newRec);
+ }
+
+ ///
+ /// Imposta in redis la scadenza della pagina x il reload
+ ///
+ ///
+ ///
+ public DateTime ExpiryReloadParamGet()
+ {
+ DateTime dtRif = DateTime.Now;
+ string currKey = $"{Utils.redisParamPageExp}";
+ RedisValue rawData = redisDb.StringGet(currKey);
+ if (rawData.HasValue)
+ {
+ dtRif = JsonConvert.DeserializeObject($"{rawData}");
+ }
+ return dtRif;
+ }
+
+ ///
+ /// Imposta in redis la scadenza della pagina x il reload
+ ///
+ ///
+ ///
+ public bool ExpiryReloadParamSet(DateTime expTime)
+ {
+ bool fatto = false;
+ string currKey = $"{Utils.redisParamPageExp}";
+ string rawData = JsonConvert.SerializeObject(expTime);
+ fatto = redisDb.StringSet(currKey, rawData);
+ return fatto;
+ }
+
+ public async Task FlushRedisCache()
+ {
+ await Task.Delay(1);
+ RedisValue pattern = Utils.RedValue("*");
+ bool answ = await RedisFlushPatternAsync(pattern);
+ // rileggo vocabolario.,..
+ ObjVocabolario = VocabolarioGetAll();
+ return answ;
+ }
+
+ public async Task FlushRedisKey(string redKey)
+ {
+ await Task.Delay(1);
+ RedisValue pattern = Utils.RedValue(redKey);
+ bool answ = await RedisFlushPatternAsync(pattern);
+ return answ;
+ }
+
+ public List FluxLogDtoGetByFlux(string Valore)
+ {
+ List answ = new List();
+ DossierFluxLogDTO? result = JsonConvert.DeserializeObject(Valore);
+ if (result != null)
+ {
+ if (result.ODL != null)
+ {
+ answ = result
+ .ODL
+ .OrderBy(x => x.CodFlux)
+ .ToList();
+ // inizializzo SE necessario
+ foreach (var item in answ)
+ {
+ item.ValoreEdit = String.IsNullOrEmpty(item.ValoreEdit) ? item.Valore : item.ValoreEdit;
+ }
+ }
+ }
+ return answ;
+ }
+
+ ///
+ /// Elenco ultimi n record flux log dato macchina e flusso (ordinato x data registrazione)
+ ///
+ /// Data massima x eventi
+ /// Data minima x eventi
+ /// * = tutte, altrimenti solo x una data macchina
+ /// *=tutti, altrimenti solo selezionato
+ /// numero massimo record da restituire
+ ///
+ public async Task> FluxLogGetLastFilt(DateTime DtMax, DateTime DtMin, string IdxMacchina, string CodFlux, int MaxRec, double redisCacheSec)
+ {
+ List? result = new List();
+ Stopwatch stopWatch = new Stopwatch();
+ stopWatch.Start();
+ string readType = "DB";
+ string currKey = $"{Utils.redisFluxLogFilt}:{IdxMacchina}:{CodFlux}:{MaxRec}:{DtMax:yyyyMMddHHmm}:{DtMin:yyyyMMddHHmm}";
+ // cerco in redis dato valore sel macchina...
+ RedisValue rawData = redisDb.StringGet(currKey);
+ if (rawData.HasValue)
+ {
+ result = JsonConvert.DeserializeObject>($"{rawData}");
+ readType = "REDIS";
+ }
+ else
+ {
+ result = await Task.FromResult(SpecDbController.FluxLogGetLastFilt(DtMax, DtMin, IdxMacchina, CodFlux, MaxRec));
+ // serializzo e salvo...
+ rawData = JsonConvert.SerializeObject(result);
+ if (string.IsNullOrEmpty(canCacheParametri))
+ {
+ canCacheParametri = await tryGetConfig("SPEC_ParametriEnableRedisCache");
+ }
+ if (canCacheParametri != "false")
+ {
+ redisDb.StringSet(currKey, rawData, TimeSpan.FromSeconds(redisCacheSec));
+ }
+ }
+ if (result == null)
+ {
+ result = new List();
+ }
+ stopWatch.Stop();
+ TimeSpan ts = stopWatch.Elapsed;
+ Log.Debug($"FluxLogGetLastFilt | Read from {readType}: {ts.TotalMilliseconds}ms");
+ return result;
+ }
+
+ ///
+ /// Init ricetta
+ ///
+ ///
+ ///
+ ///
+ ///
+ public RecipeModel InitRecipe(string confPath, int idxPODL, Dictionary CalcArgs)
+ {
+ return mongoController.InitRecipe(confPath, idxPODL, CalcArgs);
+ }
+
+ ///
+ /// Restituisce il valore booleano se la macchina sia abilitata all'input
+ ///
+ ///
+ ///
+ public bool IobInsEnab(string idxMacchina)
+ {
+ bool answ = Convert.ToBoolean(mDatiMacchinaVal(idxMacchina, "insEnabled"));
+ return answ;
+ }
+
+ ///
+ ///
+ /// id odl da cercare
+ ///
+ public async Task> ListGiacenze(int IdxOdl)
+ {
+ List? result = new List();
+ Stopwatch stopWatch = new Stopwatch();
+ stopWatch.Start();
+ string readType = "DB";
+ string currKey = $"{Utils.redisGiacenzaList}:{IdxOdl}";
+ // cerco in redis dato valore sel macchina...
+ RedisValue rawData = redisDb.StringGet(currKey);
+ if (rawData.HasValue)
+ {
+ result = JsonConvert.DeserializeObject>($"{rawData}");
+ readType = "REDIS";
+ }
+ else
+ {
+ result = await Task.FromResult(SpecDbController.ListGiacenze(IdxOdl));
+ // serializzo e salvo...
+ rawData = JsonConvert.SerializeObject(result);
+ redisDb.StringSet(currKey, rawData, TimeSpan.FromSeconds(redisShortTimeCache));
+ }
+ if (result == null)
+ {
+ result = new List();
+ }
+ stopWatch.Stop();
+ TimeSpan ts = stopWatch.Elapsed;
+ Log.Debug($"ListGiacenze | Read from {readType}: {ts.TotalMilliseconds}ms");
+ return result;
+ }
+
+ ///
+ /// Elenco completo valori Macchine 2 Slave
+ ///
+ ///
+ public List Macchine2SlaveGetAll()
+ {
+ List? result = new List();
+ Stopwatch stopWatch = new Stopwatch();
+ stopWatch.Start();
+ string readType = "DB";
+ string currKey = $"{Utils.redisBaseAddr}:M2STab";
+ // cerco in redis dato valore sel macchina...
+ RedisValue rawData = redisDb.StringGet(currKey);
+ if (rawData.HasValue)
+ {
+ result = JsonConvert.DeserializeObject>($"{rawData}");
+ readType = "REDIS";
+ }
+ else
+ {
+ result = IocDbController.Macchine2Slave();
+ // serializzo e salvo...
+ rawData = JsonConvert.SerializeObject(result);
+ redisDb.StringSet(currKey, rawData, getRandTOut(redisLongTimeCache));
+ }
+ if (result == null)
+ {
+ result = new List();
+ }
+ stopWatch.Stop();
+ TimeSpan ts = stopWatch.Elapsed;
+ Log.Debug($"Macchine2SlaveGetAll | Read from {readType}: {ts.TotalMilliseconds}ms");
+ return result;
+ }
+
+ ///
+ /// Elenco di tutte le macchine gestite
+ ///
+ ///
+ ///
+ public async Task> MacchineGetFilt(string codGruppo)
+ {
+ List? result = new List();
+ Stopwatch stopWatch = new Stopwatch();
+ stopWatch.Start();
+ string readType = "DB";
+ string keyGrp = codGruppo != "*" ? codGruppo : "ALL";
+ string currKey = $"{Utils.redisMacList}:{keyGrp}";
+ // cerco in redis dato valore sel macchina...
+ RedisValue rawData = redisDb.StringGet(currKey);
+ if (rawData.HasValue)
+ {
+ result = JsonConvert.DeserializeObject>($"{rawData}");
+ readType = "REDIS";
+ }
+ else
+ {
+ result = await Task.FromResult(SpecDbController.MacchineGetFilt(codGruppo));
+ // serializzo e salvo...
+ rawData = JsonConvert.SerializeObject(result);
+ redisDb.StringSet(currKey, rawData, getRandTOut(redisLongTimeCache));
+ }
+ if (result == null)
+ {
+ result = new List();
+ }
+ stopWatch.Stop();
+ TimeSpan ts = stopWatch.Elapsed;
+ Log.Debug($"MacchineGetAll | Read from {readType}: {ts.TotalMilliseconds}ms");
+ return result;
+ }
+
+ ///
+ /// Verifica se la macchina abbia un codice PATH ricette associato
+ ///
+ ///
+ ///
+ public async Task MacchineRecipeArchive(string idxMacchina)
+ {
+ string? result = "";
+ Stopwatch stopWatch = new Stopwatch();
+ stopWatch.Start();
+ string readType = "DB";
+ string currKey = $"{Utils.redisMacRecipePath}:{idxMacchina}";
+ // cerco in redis dato valore sel macchina...
+ RedisValue rawData = redisDb.StringGet(currKey);
+ if (rawData.HasValue)
+ {
+ result = JsonConvert.DeserializeObject($"{rawData}");
+ readType = "REDIS";
+ }
+ else
+ {
+ //recupero elenco macchine...
+ var machineList = await MacchineGetFilt("*");
+ var currMach = machineList.Where(x => x.IdxMacchina == idxMacchina).FirstOrDefault();
+ result = currMach != null ? currMach.RecipeArchivePath : null;
+ // serializzo e salvo...
+ rawData = JsonConvert.SerializeObject(result);
+ redisDb.StringSet(currKey, rawData, getRandTOut(redisLongTimeCache));
+ }
+ stopWatch.Stop();
+ TimeSpan ts = stopWatch.Elapsed;
+ Log.Debug($"MacchineRecipeArchive | Read from {readType}: {ts.TotalMilliseconds}ms");
+ return result ?? "";
+ }
+
+ ///
+ /// Verifica se la macchina abbia un codice CONF ricetta associato
+ ///
+ ///
+ ///
+ public async Task MacchineRecipeConf(string idxMacchina)
+ {
+ string? result = "";
+ Stopwatch stopWatch = new Stopwatch();
+ stopWatch.Start();
+ string readType = "DB";
+ string currKey = $"{Utils.redisMacRecipeConf}:{idxMacchina}";
+ // cerco in redis dato valore sel macchina...
+ RedisValue rawData = redisDb.StringGet(currKey);
+ if (rawData.HasValue)
+ {
+ result = JsonConvert.DeserializeObject($"{rawData}");
+ readType = "REDIS";
+ }
+ else
+ {
+ //recupero elenco macchine...
+ var machineList = await MacchineGetFilt("*");
+ var currMach = machineList.Where(x => x.IdxMacchina == idxMacchina).FirstOrDefault();
+ result = currMach != null ? currMach.RecipePath : null;
+ // serializzo e salvo...
+ rawData = JsonConvert.SerializeObject(result);
+ redisDb.StringSet(currKey, rawData, getRandTOut(redisLongTimeCache));
+ }
+ stopWatch.Stop();
+ TimeSpan ts = stopWatch.Elapsed;
+ Log.Debug($"MacchineRecipeConf | Read from {readType}: {ts.TotalMilliseconds}ms");
+ return result ?? "";
+ }
+
+ ///
+ /// Elenco id Macchine che abbiano dati FLuxLog, nel periodo indicato
+ ///
+ ///
+ ///
+ ///
+ public async Task> MacchineWithFlux(DateTime dtStart, DateTime dtEnd)
+ {
+ List? result = new List();
+ Stopwatch stopWatch = new Stopwatch();
+ stopWatch.Start();
+ string readType = "DB";
+ string currKey = $"{Utils.redisMacByFlux}:{dtStart:yyyyMMddHHmm}:{dtEnd:yyyyMMddHHmm}";
+ // cerco in redis dato valore sel macchina...
+ RedisValue rawData = redisDb.StringGet(currKey);
+ if (rawData.HasValue)
+ {
+ result = JsonConvert.DeserializeObject>($"{rawData}");
+ readType = "REDIS";
+ }
+ else
+ {
+ result = await SpecDbController.MacchineWithFlux(dtStart, dtEnd);
+ // serializzo e salvo...
+ rawData = JsonConvert.SerializeObject(result);
+ redisDb.StringSet(currKey, rawData, getRandTOut(redisLongTimeCache));
+ }
+ if (result == null)
+ {
+ result = new List();
+ }
+ stopWatch.Stop();
+ TimeSpan ts = stopWatch.Elapsed;
+ Log.Debug($"MacchineWithFlux | Read from {readType}: {ts.TotalMilliseconds}ms");
+ return result;
+ }
+
+ ///
+ /// Restituisce valore di una singola chiave del dizionario DatiMacchina
+ ///
+ ///
+ ///
+ ///
+ public string mDatiMacchinaVal(string idxMacchina, string chiave)
+ {
+ string answ = "";
+ try
+ {
+ answ = mDatiMacchine(idxMacchina)[chiave];
+ }
+ catch { }
+ return answ;
+ }
+
+ ///
+ /// Restitusice elenco KVP dei campi DatiMacchine + StatoMacchine per l'impianto indicato
+ ///
+ ///
+ ///
+ public Dictionary mDatiMacchine(string idxMacchina)
+ {
+ // hard coded dimensione vettore DatiMacchine
+ Dictionary answ = new Dictionary();
+ // ORA recupero da memoria redis...
+ try
+ {
+ var currHash = Utils.dtMaccHash(idxMacchina);
+ answ = RedisGetHashDict(currHash);
+ // se è vuoto... leggo da DB e popolo!
+ if (answ.Count == 0)
+ {
+ answ = ResetDatiMacchina(idxMacchina);
+ }
+ }
+ catch (Exception exc)
+ {
+ Log.Error($"Errore in compilazione dati Macchine x Redis - idxMacchina {idxMacchina}:{Environment.NewLine}{exc}");
+ }
+ return answ;
+ }
+
+ ///
+ /// Restitusice elenco KVP dei TASK (da passare a IOB-WIN) per l'impianto indicato
+ ///
+ ///
+ ///
+ public Dictionary mOptParMacchina(string idxMacchina)
+ {
+ // hard coded dimensione vettore DatiMacchine
+ Dictionary answ = new Dictionary();
+ // ORA recupero da memoria redis...
+ try
+ {
+ RedisKey currHash = Utils.OptParHash(idxMacchina);
+ answ = RedisGetHashDict(currHash);
+ }
+ catch (Exception exc)
+ {
+ Log.Error($"Errore in compilazione dati OPT PARAM x Redis - idxMacchina {idxMacchina}{Environment.NewLine}{exc}");
+ }
+ return answ;
+ }
+
+ ///
+ /// Elenco ODL dato batch selezionato
+ ///
+ /// Batch richiesto
+ ///
+ public async Task> OdlByBatch(string BatchSel)
+ {
+ List? result = new List();
+ Stopwatch stopWatch = new Stopwatch();
+ stopWatch.Start();
+ string readType = "DB";
+ string currKey = Utils.redisOdlByBatch;
+ // cerco in redis dato valore sel macchina...
+ RedisValue rawData = redisDb.StringGet(currKey);
+ if (rawData.HasValue)
+ {
+ result = JsonConvert.DeserializeObject>($"{rawData}");
+ readType = "REDIS";
+ }
+ else
+ {
+ result = await Task.FromResult(SpecDbController.OdlByBatch(BatchSel));
+ // serializzo e salvo...
+ rawData = JsonConvert.SerializeObject(result);
+ redisDb.StringSet(currKey, rawData, getRandTOut(redisLongTimeCache));
+ }
+ if (result == null)
+ {
+ result = new List();
+ }
+ stopWatch.Stop();
+ TimeSpan ts = stopWatch.Elapsed;
+ Log.Debug($"OdlByBatch | Read from {readType}: {ts.TotalMilliseconds}ms");
+ return result;
+ }
+
+ ///
+ /// ODL da chiave
+ ///
+ ///
+ ///
+ public ODLExpModel OdlByKey(int IdxOdl)
+ {
+ ODLExpModel? result = new ODLExpModel();
+ Stopwatch stopWatch = new Stopwatch();
+ stopWatch.Start();
+ string readType = "DB";
+ result = SpecDbController.OdlByKey(IdxOdl);
+ stopWatch.Stop();
+ TimeSpan ts = stopWatch.Elapsed;
+ Log.Debug($"OdlByKey | Read from {readType}: {ts.TotalMilliseconds}ms");
+ return result;
+ }
+
+ ///
+ /// Effettua chiusura dell'ODL indicato, andand
+ ///
+ /// idx odl da chiudere
+ /// idx macchina
+ /// matricola operatore
+ /// indica se confermare i pezzi priam di chiudere ODL
+ public async Task ODLClose(int idxOdl, string idxMacchina, int matrOpr, bool confPezzi)
+ {
+ bool fatto = false;
+ await Task.Delay(1);
+ // recupero dati x conf modalità conferma
+ var configData = await ConfigGetAll();
+ if (configData != null)
+ {
+ bool confRett = false;
+ var currRec = configData.FirstOrDefault(x => x.Chiave == "confRett");
+ if (currRec != null)
+ {
+ bool.TryParse(currRec.Valore, out confRett);
+ }
+ int modoConfProd = 0;
+ currRec = configData.FirstOrDefault(x => x.Chiave == "modoConfProd");
+ if (currRec != null)
+ {
+ int.TryParse(currRec.Valore, out modoConfProd);
+ }
+ // chiamo metodo conferma!
+ fatto = await SpecDbController.ODLClose(idxOdl, idxMacchina, matrOpr, confPezzi, confRett, modoConfProd);
+ }
+
+ return fatto;
+ }
+
+ ///
+ /// Record ODL da chaive
+ ///
+ ///
+ public async Task OdlGetByKey(int IdxOdl)
+ {
+ await Task.Delay(1);
+ var dbResult = SpecDbController.OdlGetByKey(IdxOdl);
+ return dbResult;
+ }
+
+ ///
+ /// ODL correnti (tutti)
+ ///
+ ///
+ ///
+ public List OdlGetCurrent()
+ {
+ List? dbResult = new List();
+ Stopwatch stopWatch = new Stopwatch();
+ stopWatch.Start();
+ string readType = "DB";
+ string currKey = $"{Utils.redisOdlCurrByMac}";
+ // cerco in redis dato valore sel macchina...
+ RedisValue rawData = redisDb.StringGet(currKey);
+ if (rawData.HasValue)
+ {
+ try
+ {
+ dbResult = JsonConvert.DeserializeObject>($"{rawData}");
+ }
+ catch
+ { }
+ readType = "REDIS";
+ }
+ else
+ {
+ dbResult = SpecDbController.OdlGetCurrent().Select(x => x.IdxMacchina).Distinct().ToList();
+ rawData = JsonConvert.SerializeObject(dbResult);
+ redisDb.StringSet(currKey, rawData, TimeSpan.FromSeconds(3));
+ }
+ if (dbResult == null)
+ {
+ dbResult = new List();
+ }
+ stopWatch.Stop();
+ TimeSpan ts = stopWatch.Elapsed;
+ Log.Debug($"OdlGetCurrent | Read from {readType}: {ts.TotalMilliseconds}ms");
+
+ return dbResult;
+ }
+
+ ///
+ /// elenco TUTTI gli ODL
+ ///
+ ///
+ ///
+ public List OdlListAll()
+ {
+ List? result = new List();
+ Stopwatch stopWatch = new Stopwatch();
+ stopWatch.Start();
+ string readType = "DB";
+ result = SpecDbController.OdlListAll();
+ stopWatch.Stop();
+ TimeSpan ts = stopWatch.Elapsed;
+ Log.Debug($"OdlListAll | Read from {readType}: {ts.TotalMilliseconds}ms");
+ return result;
+ }
+
+ ///
+ /// Elenco ODL filtrati x stato, articolo, KeyRich (che contiene stato)
+ ///
+ /// Stato ODL: true=in corso/completato
+ /// Cod articolo
+ /// KeyRich (parziale) da cercare (es cod stato x yacht)
+ /// Reparto selezionato
+ /// Macchina selezionata
+ /// Data inizio
+ /// Data fine
+ ///
+ public async Task> OdlListGetFilt(bool inCorso, string codArt, string keyRichPart, string Reparto, string IdxMacchina, DateTime startDate, DateTime endDate)
+ {
+ List? result = new List();
+ Stopwatch stopWatch = new Stopwatch();
+ stopWatch.Start();
+ string readType = "DB";
+ string currKey = $"{Utils.redisOdlList}:{inCorso}:{codArt}:{keyRichPart}:{Reparto}:{IdxMacchina}:{startDate:yyyyMMdd_HHmmss}:{endDate:yyyyMMdd_HHmmss}";
+ // cerco in redis dato valore sel macchina...
+ RedisValue rawData = redisDb.StringGet(currKey);
+ if (rawData.HasValue)
+ {
+ result = JsonConvert.DeserializeObject>($"{rawData}");
+ readType = "REDIS";
+ }
+ else
+ {
+ result = await Task.FromResult(SpecDbController.ListODLFilt(inCorso, codArt, keyRichPart, Reparto, IdxMacchina, startDate, endDate));
+ // serializzo e salvo...
+ rawData = JsonConvert.SerializeObject(result);
+ redisDb.StringSet(currKey, rawData, TimeSpan.FromSeconds(redisShortTimeCache));
+ }
+ if (result == null)
+ {
+ result = new List();
+ }
+ stopWatch.Stop();
+ TimeSpan ts = stopWatch.Elapsed;
+ Log.Debug($"OdlListGetFilt | Read from {readType}: {ts.TotalMilliseconds}ms");
+ return result;
+ }
+
+ ///
+ /// Elenco di tutti i parametri filtrati x macchina
+ ///
+ /// * = tutte, altrimenti solo x una data macchina
+ ///
+ public async Task> ParametriGetFilt(string IdxMacchina)
+ {
+ List? result = new List();
+ Stopwatch stopWatch = new Stopwatch();
+ stopWatch.Start();
+ string readType = "DB";
+ string currKey = $"{Utils.redisFluxByMac}:{IdxMacchina}";
+ // cerco in redis dato valore sel macchina...
+ RedisValue rawData = redisDb.StringGet(currKey);
+ if (rawData.HasValue)
+ {
+ result = JsonConvert.DeserializeObject>($"{rawData}");
+ readType = "REDIS";
+ }
+ else
+ {
+ result = await Task.FromResult(SpecDbController.ParametriGetFilt(IdxMacchina));
+ // serializzo e salvo...
+ rawData = JsonConvert.SerializeObject(result);
+ redisDb.StringSet(currKey, rawData, getRandTOut(redisLongTimeCache));
+ }
+ if (result == null)
+ {
+ result = new List();
+ }
+ stopWatch.Stop();
+ TimeSpan ts = stopWatch.Elapsed;
+ Log.Debug($"ParametriGetFilt | Read from {readType}: {ts.TotalMilliseconds}ms");
+ return result;
+ }
+
+ ///
+ /// Eliminazione record selezionato
+ ///
+ ///
+ ///
+ public async Task POdlDeleteRecord(PODLExpModel currRec)
+ {
+ var dbResult = await SpecDbController.PODLDeleteRecord(currRec);
+ // elimino cache redis...
+ await POdlFlushCache();
+ await Task.Delay(1);
+ return dbResult;
+ }
+
+ ///
+ /// Avvio fase setup per il record selezionato
+ ///
+ ///
+ ///
+ public async Task POdlDoSetup(PODLExpModel currRec)
+ {
+ var dbResult = await SpecDbController.PODL_startSetup(currRec, 0, 1, 1, "", DateTime.Now);
+ // elimino cache redis...
+ await POdlFlushCache();
+ await Task.Delay(1);
+ return dbResult;
+ }
+
+ ///
+ /// Recupero PODL da chiave
+ ///
+ ///
+ ///
+ public async Task POdlGetByKey(int idxPODL)
+ {
+ PODLModel result = new PODLModel();
+ if (idxPODL != 0)
+ {
+ Stopwatch stopWatch = new Stopwatch();
+ stopWatch.Start();
+ string readType = "DB";
+ string currKey = $"{Utils.redisPOdlByPOdl}:{idxPODL}";
+ // cerco in redis dato valore sel macchina...
+ RedisValue rawData = redisDb.StringGet(currKey);
+ if (rawData.HasValue)
+ {
+ var rawResult = JsonConvert.DeserializeObject($"{rawData}");
+ if (rawResult != null)
+ {
+ result = rawResult;
+ readType = "REDIS";
+ }
+ }
+ else
+ {
+ result = await SpecDbController.PODL_getByKey(idxPODL);
+ // serializzo e salvo...
+ rawData = JsonConvert.SerializeObject(result);
+ redisDb.StringSet(currKey, rawData, getRandTOut(redisLongTimeCache));
+ }
+ if (result == null)
+ {
+ result = new PODLModel();
+ }
+ stopWatch.Stop();
+ TimeSpan ts = stopWatch.Elapsed;
+ Log.Trace($"POdlGetByKey | Read from {readType}: {ts.TotalMilliseconds}ms");
+ }
+ else
+ {
+ Log.Debug("Errore IdxPODL = 0");
+ }
+ return result;
+ }
+
+ ///
+ /// Recupero PODL da IdxODL
+ ///
+ ///
+ ///
+ public PODLModel POdlGetByOdl(int idxODL)
+ {
+ PODLModel result = new PODLModel();
+ if (idxODL != 0)
+ {
+ Stopwatch stopWatch = new Stopwatch();
+ stopWatch.Start();
+ string readType = "DB";
+ string currKey = $"{Utils.redisPOdlByOdl}:{idxODL}";
+ // cerco in redis dato valore sel macchina...
+ RedisValue rawData = redisDb.StringGet(currKey);
+ if (rawData.HasValue)
+ {
+ var rawResult = JsonConvert.DeserializeObject($"{rawData}");
+ if (rawResult != null)
+ {
+ result = rawResult;
+ }
+ readType = "REDIS";
+ }
+ else
+ {
+ result = SpecDbController.PODL_getByOdl(idxODL);
+ // serializzo e salvo...
+ rawData = JsonConvert.SerializeObject(result);
+ redisDb.StringSet(currKey, rawData, getRandTOut(redisLongTimeCache));
+ }
+ if (result == null)
+ {
+ result = new PODLModel();
+ }
+ stopWatch.Stop();
+ TimeSpan ts = stopWatch.Elapsed;
+ Log.Trace($"POdlGetByOdl | Read from {readType}: {ts.TotalMilliseconds}ms");
+ }
+ else
+ {
+ Log.Debug("Errore IdxODL = 0");
+ }
+ return result;
+ }
+
+ ///
+ /// Elenco PODL non avviati filtrati x articolo, KeyRich (che contiene stato)
+ ///
+ /// Solo lanciati (1) o ancora disponibili (0)
+ /// KeyRich (parziale) da cercare (es cod stato x yacht)
+ /// Macchina
+ /// Gruppo
+ /// Data inizio
+ /// Data fine
+ ///
+ public async Task> POdlListGetFilt(bool lanciato, string keyRichPart, string idxMacchina, string codGruppo, DateTime startDate, DateTime endDate)
+ {
+ List? result = new List();
+ Stopwatch stopWatch = new Stopwatch();
+ stopWatch.Start();
+ string readType = "DB";
+ string currKey = $"{Utils.redisPOdlList}:{codGruppo}:{idxMacchina}:{keyRichPart}:{lanciato}:{startDate:yyyyMMdd_HHmmss}:{endDate:yyyyMMdd_HHmmss}";
+ // cerco in redis dato valore sel macchina...
+ RedisValue rawData = redisDb.StringGet(currKey);
+ if (rawData.HasValue)
+ {
+ result = JsonConvert.DeserializeObject>($"{rawData}");
+ readType = "REDIS";
+ }
+ else
+ {
+ result = await Task.FromResult(SpecDbController.ListPODLFilt(lanciato, keyRichPart, idxMacchina, codGruppo, startDate, endDate));
+ // serializzo e salvo...
+ rawData = JsonConvert.SerializeObject(result);
+ redisDb.StringSet(currKey, rawData, TimeSpan.FromSeconds(redisShortTimeCache));
+ }
+ if (result == null)
+ {
+ result = new List();
+ }
+ stopWatch.Stop();
+ TimeSpan ts = stopWatch.Elapsed;
+ Log.Debug($"POdlListGetFilt | Read from {readType}: {ts.TotalMilliseconds}ms");
+ return result;
+ }
+
+ ///
+ /// Aggiornamento record selezionato
+ ///
+ ///
+ ///
+ public async Task POdlUpdateRecord(PODLModel currRec)
+ {
+ var dbResult = await SpecDbController.PODLUpdateRecord(currRec);
+ // elimino cache redis...
+ await POdlFlushCache();
+ return dbResult;
+ }
+
+ ///
+ /// Ricerca ricetta su MongoDB dato PODL
+ ///
+ ///
+ ///
+ public async Task RecipeGetByPODL(int idxPODL)
+ {
+ RecipeModel? result = null;
+ Stopwatch stopWatch = new Stopwatch();
+ stopWatch.Start();
+ string readType = "MongoDB";
+ result = await mongoController.RecipeGetByPODL(idxPODL);
+ stopWatch.Stop();
+ TimeSpan ts = stopWatch.Elapsed;
+ Log.Debug($"RecipeGetByPODL | Read from {readType}: {ts.TotalMilliseconds}ms");
+ return result;
+ }
+
+ ///
+ /// Salva ricetta su MongoDB
+ ///
+ ///
+ ///
+ public async Task RecipeSetByPODL(RecipeModel currRecord)
+ {
+ bool answ = false;
+ answ = await mongoController.RecipeSetByPODL(currRecord);
+ if (answ)
+ {
+ await POdlFlushCache();
+ }
+ return answ;
+ }
+
+ ///
+ /// Effettua conteggio chaivi REDIS dato pattern ricerca
+ ///
+ ///
+ ///
+ public int RedisCountKey(string keyPattern)
+ {
+ int num = 0;
+ keyPattern = (string.IsNullOrEmpty(keyPattern) ? "**" : keyPattern);
+ try
+ {
+ var listEndpoints = redisConnAdmin.GetEndPoints();
+ foreach (var endPoint in listEndpoints)
+ {
+ var server = redisConnAdmin.GetServer(endPoint);
+ foreach (RedisKey item in server.Keys(pattern: keyPattern, database: redisDb.Database, pageSize: 250, cursor: 0L))
+ {
+ num++;
+ }
+ }
+ }
+ catch (Exception arg)
+ {
+ Log.Error($"Eccezione in RedisCountKey{Environment.NewLine}{arg}");
+ }
+
+ return num;
+ }
+
+ ///
+ /// Esegue eliminazione memoria redis keyVal
+ ///
+ ///
+ ///
+ public bool RedisDelKey(string keyVal)
+ {
+ bool answ = false;
+ var listEndpoints = redisConnAdmin.GetEndPoints();
+ foreach (var endPoint in listEndpoints)
+ {
+ var server = redisConnAdmin.GetServer(endPoint);
+ if (server != null)
+ {
+ redisDb.KeyDelete((RedisKey)keyVal);
+ answ = true;
+ }
+ }
+ return answ;
+ }
+
+ ///
+ /// Esegue flush memoria redis dato keyVal
+ ///
+ ///
+ ///
+ public bool RedisFlushPattern(string pattern)
+ {
+ bool answ = false;
+ var listEndpoints = redisConnAdmin.GetEndPoints();
+ foreach (var endPoint in listEndpoints)
+ {
+ //var server = redisConnAdmin.GetServer(listEndpoints[0]);
+ var server = redisConnAdmin.GetServer(endPoint);
+ if (server != null)
+ {
+ var keyList = server.Keys(redisDb.Database, pattern);
+ foreach (var item in keyList)
+ {
+ redisDb.KeyDelete(item);
+ }
+ answ = true;
+ }
+ }
+ return answ;
+ }
+
+ ///
+ /// Esegue flush memoria redis dato keyVal, async
+ ///
+ ///
+ ///
+ public async Task RedisFlushPatternAsync(RedisValue pattern)
+ {
+ bool answ = false;
+ var listEndpoints = redisConnAdmin.GetEndPoints();
+ foreach (var endPoint in listEndpoints)
+ {
+ var server = redisConnAdmin.GetServer(endPoint);
+ if (server != null)
+ {
+ var keyList = server.Keys(redisDb.Database, pattern);
+ foreach (var item in keyList)
+ {
+ await redisDb.KeyDeleteAsync(item);
+ }
+ answ = true;
+ }
+ }
+ return answ;
+ }
+
+ public KeyValuePair[] RedisGetHash(RedisKey redKey)
+ {
+ HashEntry[] rawData = redisDb.HashGetAll(redKey);
+ var result = rawData.Where(x => !x.Name.IsNull).Select(x => new KeyValuePair($"{x.Name}", $"{x.Value}")).ToArray();
+ return result;
+ }
+
+ public async Task[]> RedisGetHashAsync(string redKey)
+ {
+ HashEntry[] rawData = await redisDb.HashGetAllAsync(redKey);
+ var result = rawData.Where(x => !x.Name.IsNull).Select(x => new KeyValuePair($"{x.Name}", $"{x.Value}")).ToArray();
+ return result;
+ }
+
+ public Dictionary RedisGetHashDict(RedisKey hashKey)
+ {
+ HashEntry[] rawData = redisDb.HashGetAll(hashKey);
+ var result = rawData.Where(x => !x.Name.IsNull).ToDictionary(x => x.Name.ToString(), x => x.Value.ToString());
+ return result;
+ }
+
+ public string RedisGetHashField(RedisKey key, string hashField)
+ {
+ string result = "";
+ try
+ {
+ RedisValue hashField2 = hashField;
+ result = redisDb.HashGet(key, hashField2).ToString();
+ }
+ catch (Exception exc)
+ {
+ Log.Error($"Errore in RedisGetHashField{Environment.NewLine}{exc}");
+ }
+
+ return result;
+ }
+
+ public bool RedisHashPresent(RedisKey key)
+ {
+ bool result = false;
+ try
+ {
+ result = redisDb.HashGetAll(key).Length != 0;
+ }
+ catch (Exception arg)
+ {
+ Log.Error($"Errore in redHashPresent per la key {key}{Environment.NewLine}{arg}");
+ }
+
+ return result;
+ }
+
+ public bool RedisHashPresentSz(string key)
+ {
+ return RedisHashPresent((RedisKey)key);
+ }
+
+ public bool RedisKeyPresent(RedisKey key)
+ {
+ bool result = false;
+ try
+ {
+ result = redisDb.KeyExists(key);
+ }
+ catch (Exception arg)
+ {
+ Log.Error($"Errore in redKeyPresent per la key {key}:{Environment.NewLine}{arg}");
+ }
+
+ return result;
+ }
+
+ public bool RedisKeyPresentSz(string key)
+ {
+ bool result = false;
+ try
+ {
+ RedisKey key2 = key;
+ result = RedisKeyPresent(key2);
+ }
+ catch
+ {
+ }
+
+ return result;
+ }
+
+ public bool RedisSetHash(RedisKey redKey, KeyValuePair[] valori, double expireSeconds = -1.0)
+ {
+ bool answ = false;
+ answ = RedisSetHash(redKey, valori);
+ if (expireSeconds > 0.0)
+ {
+ redisDb.KeyExpire(redKey, DateTime.Now.AddSeconds(expireSeconds));
+ }
+ return answ;
+ }
+
+ public bool RedisSetHash(RedisKey redKey, KeyValuePair[] valori)
+ {
+ bool answ = false;
+ HashEntry[] redHash = valori.Select(x => new HashEntry(x.Key, x.Value)).ToArray();
+ redisDb.HashSet(redKey, redHash);
+ answ = true;
+ return answ;
+ }
+
+ public bool RedisSetHashDict(RedisKey redKey, Dictionary valori, double expireSeconds = -1.0)
+ {
+ bool answ = false;
+ answ = RedisSetHashDict(redKey, valori);
+ if (expireSeconds > 0.0)
+ {
+ redisDb.KeyExpire(redKey, DateTime.Now.AddSeconds(expireSeconds));
+ }
+ return answ;
+ }
+
+ public bool RedisSetHashDict(RedisKey redKey, Dictionary valori)
+ {
+ bool answ = false;
+ HashEntry[] redHash = valori.Select(x => new HashEntry(x.Key, x.Value)).ToArray();
+ redisDb.HashSet(redKey, redHash);
+ answ = true;
+ return answ;
+ }
+
+ public bool RedisSetKey(string valKey, string redVal)
+ {
+ bool answ = redisDb.StringSet(Utils.RedKeyHash(valKey), redVal);
+ return answ;
+ }
+
+ public bool RedisSetKey(RedisKey valKey, string redVal, int TTL_sec)
+ {
+ bool answ = redisDb.StringSet(Utils.RedKeyHash(valKey), redVal, TimeSpan.FromSeconds(TTL_sec));
+ return answ;
+ }
+
+ ///
+ /// Restitusice elenco KVP dei campi DatiMacchine + StatoMacchine per l'impianto indicato
+ ///
+ ///
+ ///
+ public Dictionary ResetDatiMacchina(string idxMacc)
+ {
+ var currHash = Utils.dtMaccHash(idxMacc);
+ // inizio con un bel reset...
+ RedisFlushPattern($"{currHash}");
+ Dictionary? result = new Dictionary();
+ Stopwatch stopWatch = new Stopwatch();
+ stopWatch.Start();
+ string readType = "DB";
+ var dbResults = IocDbController.VMSFDGetByMacc(idxMacc);
+ // converto in formato dizionario...
+ if (dbResults != null && dbResults.Count > 0)
+ {
+ var rowResult = dbResults[0];
+ // salvo 1:1 i valori... STATO
+ result.Add("IdxMicroStato", $"{rowResult.IdxMicroStato}");
+ result.Add("IdxStato", $"{rowResult.IdxStato}");
+ result.Add("CodArticolo", $"{rowResult.CodArticolo}");
+ result.Add("insEnabled", $"{rowResult.InsEnabled}");
+ result.Add("sLogEnabled", $"{rowResult.SLogEnabled}");
+ result.Add("pallet", $"{rowResult.Pallet}");
+ result.Add("CodArticolo_A", $"{rowResult.CodArticoloA}");
+ result.Add("CodArticolo_B", $"{rowResult.CodArticoloB}");
+ result.Add("TempoCicloBase", $"{rowResult.TempoCicloBase}");
+ result.Add("PzPalletProd", $"{rowResult.PzPalletProd}");
+ result.Add("MatrOpr", $"{rowResult.MatrOpr}");
+ result.Add("lastVal", $"{rowResult.LastVal}");
+ result.Add("TCBase", $"{rowResult.TempoCicloBase}");
+
+ //...e SETUP
+ result.Add("CodMacc", $"{rowResult.Codmacchina}");
+ result.Add("IdxFamIn", $"{rowResult.IdxFamigliaIngresso}");
+ result.Add("Multi", $"{rowResult.Multi}");
+ result.Add("BitFilt", $"{rowResult.BitFilt}");
+ result.Add("MaxVal", $"{rowResult.MaxVal}");
+ result.Add("BSR", $"{rowResult.Bsr}");
+ result.Add("ExplodeBit", $"{rowResult.ExplodeBit}");
+ result.Add("NumBit", $"{rowResult.NumBit}");
+ result.Add("IdxFamMacc", $"{rowResult.IdxFamiglia}");
+ result.Add("simplePallet", $"{rowResult.SimplePallet}");
+ result.Add("palletChange", $"{rowResult.PalletChange}");
+ }
+ // cerco info Master/slave...
+ var m2sTab = Macchine2SlaveGetAll();
+ string isMaster = m2sTab.Where(x => x.IdxMacchina == idxMacc).Count() > 0 ? "1" : "0";
+ string isSlave = m2sTab.Where(x => x.IdxMacchinaSlave == idxMacc).Count() > 0 ? "1" : "0";
+ result.Add("Master", isMaster);
+ result.Add("Slave", isSlave);
+
+ // durata cache in secondi dal valore insEnabled...
+ double numSecCache = 60 * ((result["insEnabled"].ToLower() == "true") ? redisShortTimeCache / 4 : redisShortTimeCache);
+ // ...e salvo...
+ RedisSetHashDict(currHash, result, numSecCache);
+
+ if (result == null)
+ {
+ result = new Dictionary();
+ }
+ stopWatch.Stop();
+ TimeSpan ts = stopWatch.Elapsed;
+ Log.Debug($"GetCurrMSFDMacc | Read from {readType}: {ts.TotalMilliseconds}ms");
+ return result;
+ }
+
+ ///
+ /// Resetta (rileggendo) i dati della State Machine ingressi nel formato
+ /// key: cState_nVal (current MICRO-STATE + "_" + new Value)
+ /// value: iTipoEv_nState (IdxTipoEv da trasmettere + New MICRO-STATE)
+ ///
+ ///
+ ///
+ public KeyValuePair[] resetSMI(int idxFamIn)
+ {
+ var currHash = Utils.hSMI(idxFamIn);
+ // leggo da DB...
+ var tabSMI = IocDbController.StateMachineIngressi(idxFamIn);
+
+ KeyValuePair