From d3c66041567ec8e68822233d9a7bf47d636f1a9a Mon Sep 17 00:00:00 2001 From: Stoyan Zlatev Date: Tue, 2 May 2023 11:46:59 +0200 Subject: [PATCH] Tests for ModelResult[T] and WildcardInputModel --- .../Interfaces/ISqlClient.cs | 3 +- .../Interfaces/ISqlReader.cs | 2 + .../LaaProductionWeb.Data.csproj | 1 + .../LaaProductionWeb.Data/SqlClient.cs | 10 +- .../SqlClientExtensions.cs | 18 +- .../LaaProductionWeb.Data/SqlReader.cs | 52 ++++-- .../LaaProductionWeb.Data/app.config | 8 +- .../LaaProductionWeb.Services.csproj | 1 - .../ReportService.queries.cs | 59 ------ .../LaaProductionWeb.Tests.csproj | 28 +++ .../Models/ModelResultTests.cs | 171 ++++++++++++++++++ .../Models/WildcardInputModelTests.cs | 145 +++++++++++++++ .../Attributes/AllowedCharachtersAttribute.cs | 6 + .../RequiresASCIILettersAttribute.cs | 51 ++++++ .../Attributes/RequiresDigitsAttribute.cs | 51 ++++++ .../LaaProductionWeb.Validation.csproj | 51 ++++++ .../Properties/AssemblyInfo.cs | 36 ++++ LaaProductionWeb/LaaProductionWeb.sln | 6 + .../App_Start/WebApiConfig.cs | 7 +- .../Search/Controllers/WildcardController.cs | 8 +- .../Areas/Search/SearchAreaRegistration.cs | 2 +- .../Serach/Controllers/WildcardController.cs | 20 +- .../Models/Interfaces/IWildcardModel.cs | 14 ++ .../Areas/Serach/Models/WildcardInputModel.cs | 33 ++++ .../Areas/Serach/Models/WildcardModel.cs | 134 ++++++++++++++ .../Areas/Serach/Models/WildcardResult.cs | 8 + .../ErrorMessages.Designer.cs | 90 +++++++++ .../LaaProductionWebCore/ErrorMessages.resx | 129 +++++++++++++ .../LaaProductionWebCore.csproj | 19 ++ .../Models/ApplicationSettings.cs | 2 +- .../Models/ModelResult[T].cs | 77 ++++++++ .../LaaProductionWebCore/Startup.cs | 16 +- 32 files changed, 1151 insertions(+), 107 deletions(-) delete mode 100644 LaaProductionWeb/LaaProductionWeb.Services/ReportService.queries.cs create mode 100644 LaaProductionWeb/LaaProductionWeb.Tests/LaaProductionWeb.Tests.csproj create mode 100644 LaaProductionWeb/LaaProductionWeb.Tests/Models/ModelResultTests.cs create mode 100644 LaaProductionWeb/LaaProductionWeb.Tests/Models/WildcardInputModelTests.cs create mode 100644 LaaProductionWeb/LaaProductionWeb.Validation/Attributes/AllowedCharachtersAttribute.cs create mode 100644 LaaProductionWeb/LaaProductionWeb.Validation/Attributes/RequiresASCIILettersAttribute.cs create mode 100644 LaaProductionWeb/LaaProductionWeb.Validation/Attributes/RequiresDigitsAttribute.cs create mode 100644 LaaProductionWeb/LaaProductionWeb.Validation/LaaProductionWeb.Validation.csproj create mode 100644 LaaProductionWeb/LaaProductionWeb.Validation/Properties/AssemblyInfo.cs create mode 100644 LaaProductionWeb/LaaProductionWebCore/Areas/Serach/Models/Interfaces/IWildcardModel.cs create mode 100644 LaaProductionWeb/LaaProductionWebCore/Areas/Serach/Models/WildcardInputModel.cs create mode 100644 LaaProductionWeb/LaaProductionWebCore/Areas/Serach/Models/WildcardModel.cs create mode 100644 LaaProductionWeb/LaaProductionWebCore/Areas/Serach/Models/WildcardResult.cs create mode 100644 LaaProductionWeb/LaaProductionWebCore/ErrorMessages.Designer.cs create mode 100644 LaaProductionWeb/LaaProductionWebCore/ErrorMessages.resx create mode 100644 LaaProductionWeb/LaaProductionWebCore/Models/ModelResult[T].cs diff --git a/LaaProductionWeb/LaaProductionWeb.Data/Interfaces/ISqlClient.cs b/LaaProductionWeb/LaaProductionWeb.Data/Interfaces/ISqlClient.cs index e2a923d8..d5dca1bd 100644 --- a/LaaProductionWeb/LaaProductionWeb.Data/Interfaces/ISqlClient.cs +++ b/LaaProductionWeb/LaaProductionWeb.Data/Interfaces/ISqlClient.cs @@ -3,7 +3,8 @@ using System; using System.Collections.Generic; using System.Data.SqlClient; - + using System.Threading.Tasks; + public interface ISqlClient { int ExecuteNonQuery(string query, Action parameters, SqlInfoMessageEventHandler errorCallback = null); diff --git a/LaaProductionWeb/LaaProductionWeb.Data/Interfaces/ISqlReader.cs b/LaaProductionWeb/LaaProductionWeb.Data/Interfaces/ISqlReader.cs index 038f614b..2d72f6d7 100644 --- a/LaaProductionWeb/LaaProductionWeb.Data/Interfaces/ISqlReader.cs +++ b/LaaProductionWeb/LaaProductionWeb.Data/Interfaces/ISqlReader.cs @@ -7,5 +7,7 @@ string GetString(int index = -1); T GetValue(int index = -1); + + object GetValue(string field); } } \ No newline at end of file diff --git a/LaaProductionWeb/LaaProductionWeb.Data/LaaProductionWeb.Data.csproj b/LaaProductionWeb/LaaProductionWeb.Data/LaaProductionWeb.Data.csproj index fc37f0ef..8c648053 100644 --- a/LaaProductionWeb/LaaProductionWeb.Data/LaaProductionWeb.Data.csproj +++ b/LaaProductionWeb/LaaProductionWeb.Data/LaaProductionWeb.Data.csproj @@ -12,6 +12,7 @@ v4.6.2 512 true + true diff --git a/LaaProductionWeb/LaaProductionWeb.Data/SqlClient.cs b/LaaProductionWeb/LaaProductionWeb.Data/SqlClient.cs index 3d6e8d70..bcdc38d9 100644 --- a/LaaProductionWeb/LaaProductionWeb.Data/SqlClient.cs +++ b/LaaProductionWeb/LaaProductionWeb.Data/SqlClient.cs @@ -6,7 +6,7 @@ using System.Collections.Generic; using System.Data; using System.Data.SqlClient; - + public class SqlClient : ISqlClient { private readonly string connectionString; @@ -27,7 +27,6 @@ parameters(sqlCommand.Parameters); sqlCommand.CommandText = query; - // SqlClientExtensions.Log(sqlCommand.CommandText); rowsAffected = sqlCommand.ExecuteNonQuery(); } } @@ -44,7 +43,6 @@ using (var sqlCommand = sqlConnection.CreateCommand()) { sqlCommand.CommandText = query; - // SqlClientExtensions.Log(sqlCommand.CommandText); using (SqlReader sqlReader = sqlCommand.ExecuteReader()) { @@ -68,7 +66,6 @@ parameters(sqlCommand.Parameters); sqlCommand.CommandText = query; - // SqlClientExtensions.Log(sqlCommand.CommandText); using (SqlReader sqlReader = sqlCommand.ExecuteReader()) { @@ -90,7 +87,6 @@ using (var sqlCommand = sqlConnection.CreateCommand()) { sqlCommand.CommandText = query; - // SqlClientExtensions.Log(sqlCommand.CommandText); using (SqlReader sqlReader = sqlCommand.ExecuteReader()) { @@ -116,7 +112,6 @@ parameters(sqlCommand.Parameters); sqlCommand.CommandText = query; - // SqlClientExtensions.Log(sqlCommand.CommandText); using (SqlReader sqlReader = sqlCommand.ExecuteReader()) { @@ -144,7 +139,6 @@ parameters(sqlCommand.Parameters); sqlCommand.CommandText = query; - // SqlClientExtensions.Log(sqlCommand.CommandText); var scalarObject = sqlCommand.ExecuteScalar(); @@ -169,7 +163,6 @@ using (var sqlCommand = sqlConnection.CreateCommand()) { sqlCommand.CommandText = query; - // SqlClientExtensions.Log(sqlCommand.CommandText); using (SqlReader sqlReader = sqlCommand.ExecuteReader(CommandBehavior.SequentialAccess)) { @@ -197,7 +190,6 @@ parameters(sqlCommand.Parameters); sqlCommand.CommandText = query; - // SqlClientExtensions.Log(sqlCommand.CommandText); using (SqlReader sqlReader = sqlCommand.ExecuteReader(CommandBehavior.SequentialAccess)) { diff --git a/LaaProductionWeb/LaaProductionWeb.Data/SqlClientExtensions.cs b/LaaProductionWeb/LaaProductionWeb.Data/SqlClientExtensions.cs index bce819d3..e04fb0e7 100644 --- a/LaaProductionWeb/LaaProductionWeb.Data/SqlClientExtensions.cs +++ b/LaaProductionWeb/LaaProductionWeb.Data/SqlClientExtensions.cs @@ -8,6 +8,7 @@ using System.Data.SqlClient; using System.Diagnostics; using System.IO; + using System.Threading.Tasks; using System.Web; public static class SqlClientExtensions @@ -32,6 +33,19 @@ sqlConnection.Open(); } + internal static async Task OpenWithErrorHandlingAsync(this SqlConnection sqlConnection, SqlInfoMessageEventHandler messageHandler = null) + { + sqlConnection.FireInfoMessageEventOnUserErrors = true; + sqlConnection.InfoMessage += SqlConnectionInfoMessage; + + if (messageHandler != null) + { + sqlConnection.InfoMessage += messageHandler; + } + + await sqlConnection.OpenAsync(); + } + internal static void SqlConnectionInfoMessage(object sender, SqlInfoMessageEventArgs e) { Debug.WriteLine(e); @@ -43,9 +57,7 @@ internal static void Log(string message) { - var file = HttpContext.Current.Server.MapPath($"~/App_Data/{DateTime.Now:yyyy_MM_dd}.log"); - - File.AppendAllText(file, $"{Environment.NewLine}{message}{Environment.NewLine}"); + // File.AppendAllText($"{Environment.CurrentDirectory}/App_Data/{DateTime.Now:yyyy_MM_dd}.log", $"{Environment.NewLine}{message}{Environment.NewLine}"); } } } diff --git a/LaaProductionWeb/LaaProductionWeb.Data/SqlReader.cs b/LaaProductionWeb/LaaProductionWeb.Data/SqlReader.cs index a5f81cba..3d857fc4 100644 --- a/LaaProductionWeb/LaaProductionWeb.Data/SqlReader.cs +++ b/LaaProductionWeb/LaaProductionWeb.Data/SqlReader.cs @@ -3,16 +3,32 @@ using LaaProductionWeb.Data.Interfaces; using System; + using System.Collections.Generic; using System.Data.SqlClient; + using System.Linq; + using System.Threading.Tasks; public class SqlReader : ISqlReader, IDisposable { private readonly SqlDataReader sqlDataReader; + private readonly IDictionary columns; private int column; - private SqlReader(SqlDataReader sqlDataReader) - => this.sqlDataReader = sqlDataReader; + private SqlReader(SqlDataReader sqlDataReader) + { + this.sqlDataReader = sqlDataReader; + this.columns = new Dictionary(); + + var columnsCount = this.sqlDataReader.FieldCount; + var columns = new string[columnsCount]; + + for (int i = 0; i < columnsCount; i++) + { + var columnName = this.sqlDataReader.GetName(i); + this.columns[columnName] = i; + } + } public void Dispose() { @@ -38,17 +54,7 @@ } internal string[] GetColumns() - { - var columnsCount = this.sqlDataReader.FieldCount; - var columns = new string[columnsCount]; - - for (int i = 0; i < columnsCount; i++) - { - columns[i] = this.sqlDataReader.GetName(i); - } - - return columns; - } + => this.columns.Keys.ToArray(); public string GetString(int index = -1) { @@ -90,6 +96,26 @@ return this.sqlDataReader.Read(); } + internal Task ReadAsync() + { + this.column = 0; + + return this.sqlDataReader.ReadAsync(); + } + + public object GetValue(string field) + { + if (this.columns.TryGetValue($"{field}", out int index)) + { + if (!this.sqlDataReader.IsDBNull(index)) + { + return this.sqlDataReader.GetValue(index); + } + } + + return default(object); + } + public static implicit operator SqlReader(SqlDataReader sqlDataReader) => new SqlReader(sqlDataReader); } diff --git a/LaaProductionWeb/LaaProductionWeb.Data/app.config b/LaaProductionWeb/LaaProductionWeb.Data/app.config index 1696df66..2e74a2ee 100644 --- a/LaaProductionWeb/LaaProductionWeb.Data/app.config +++ b/LaaProductionWeb/LaaProductionWeb.Data/app.config @@ -1,11 +1,11 @@ - + - - + + - \ No newline at end of file + diff --git a/LaaProductionWeb/LaaProductionWeb.Services/LaaProductionWeb.Services.csproj b/LaaProductionWeb/LaaProductionWeb.Services/LaaProductionWeb.Services.csproj index 10413531..5984ce17 100644 --- a/LaaProductionWeb/LaaProductionWeb.Services/LaaProductionWeb.Services.csproj +++ b/LaaProductionWeb/LaaProductionWeb.Services/LaaProductionWeb.Services.csproj @@ -99,7 +99,6 @@ - diff --git a/LaaProductionWeb/LaaProductionWeb.Services/ReportService.queries.cs b/LaaProductionWeb/LaaProductionWeb.Services/ReportService.queries.cs deleted file mode 100644 index 7eec5fbd..00000000 --- a/LaaProductionWeb/LaaProductionWeb.Services/ReportService.queries.cs +++ /dev/null @@ -1,59 +0,0 @@ -namespace LaaProductionWeb.Services -{ - public partial class ReportService - { - private const string SELECT_HELIUM_REPORT_QUERY = @" - SELECT [PT].[CordonelPressureTest_FertigungsAuftragsNr] AS [FertigungNr] -- 0 Filter - , [POS].[AuftragNr] AS [AuftragNr] -- 1 Filter - , [POS].[PositionNr] AS [PositionNr] -- 2 Filter - , [PCB2SN].[MapPcbIdToSerialNumber_SerialNumber] AS [SerialNr] -- 3 - , [ID].[IdentNr] AS [IdentNr] -- 4 Filter - , [PT_HE].[CordonelPressureTestHe_Id] AS [HeId] -- 5 - , [PT_HE].[CordonelPressureTestHe_TestID] AS [HeTestId] -- 6 - , [PT].[CordonelPressureTest_PcbId] AS [PcbId] -- 7 Filter - , [ID].[Nennweite] AS [Nennweite] -- 8 Filter - , [ID].[Baulaenge] AS [Baulaenge] -- 9 Filter - , [ID].[Typ] AS [Typ] -- 10 Filter - , [ID].[Druck] AS [Druck] -- 11 Filter - , [ID].[Temperatur] AS [Temperatur] -- 12 Filter - , [PT_HE].[CordonelPressureTestHe_LeakRate] AS [HeLakeRate] -- 13 - , [PT_HE].[CordonelPressureTestHe_TestPressure] AS [HeTestPressure] -- 14 - , [PT].[CordonelPressureTest_Valid] AS [IsValid] -- 15 Filter - , [PT].[CordonelPressureTest_Date] AS [TestDate] -- 16 Filter - , [PT].[CordonelPressureTest_Text] AS [Text] -- 17 Filter - , [PT_HE].[CordonelPressureTestHe_TesterName] AS [Tester] -- 18 - FROM [Cordonel_PressureTest] AS [PT] - JOIN [Cordonel_PressureTest_He] AS [PT_HE] ON [PT_HE].[CordonelPressureTestHe_TestID] = [PT].[CordonelPressureTest_Id] - LEFT JOIN [Druckpruefung] AS [DP] ON [DP].[FabNr] = [PT].[CordonelPressureTest_PcbId] - JOIN [MapPcbIdToSerialNumber] AS [PCB2SN] ON [PCB2SN].[MapPcbIdToSerialNumber_PcbId] = [PT].[CordonelPressureTest_PcbId] - JOIN [AuftragPosition_Gesamt] AS [POS] ON [POS].[FertigungsauftragNr] = [PT].[CordonelPressureTest_FertigungsAuftragsNr] - JOIN [Identnr] AS [ID] ON [ID].[IdentNr] = [POS].[Identnr]"; - - private const string KottmanReportQuery = @" - SELECT [PT].[CordonelPressureTest_FertigungsAuftragsNr] AS [FertigungNr] -- 0 Filter - , [POS].[AuftragNr] AS [AuftragNr] -- 1 Filter - , [POS].[PositionNr] AS [PositionNr] -- 2 Filter - , [PCB2SN].[MapPcbIdToSerialNumber_SerialNumber] AS [SerialNr] -- 3 - , [ID].[IdentNr] AS [IdentNr] -- 4 Filter - , [PT_HE].[CordonelPressureTestHe_Id] AS [HeId] -- 5 - , [PT_HE].[CordonelPressureTestHe_TestID] AS [HeTestId] -- 6 - , [PT].[CordonelPressureTest_PcbId] AS [PcbId] -- 7 Filter - , [ID].[Nennweite] AS [Nennweite] -- 8 Filter - , [ID].[Baulaenge] AS [Baulaenge] -- 9 Filter - , [ID].[Typ] AS [Typ] -- 10 Filter - , [ID].[Druck] AS [Druck] -- 11 Filter - , [ID].[Temperatur] AS [Temperatur] -- 12 Filter - , [PT_HE].[CordonelPressureTestHe_LeakRate] AS [HeLakeRate] -- 13 - , [PT_HE].[CordonelPressureTestHe_TestPressure] AS [HeTestPressure] -- 14 - , [PT].[CordonelPressureTest_Valid] AS [IsValid] -- 15 Filter - , [PT].[CordonelPressureTest_Date] AS [TestDate] -- 16 Filter - , [PT].[CordonelPressureTest_Text] AS [Text] -- 17 Filter - , [PT_HE].[CordonelPressureTestHe_TesterName] AS [Tester] -- 18 - FROM [Cordonel_PressureTest] AS [PT] - JOIN [Cordonel_PressureTest_He] AS [PT_HE] ON [PT_HE].[CordonelPressureTestHe_TestID] = [PT].[CordonelPressureTest_Id] - LEFT JOIN [Druckpruefung] AS [DP] ON [DP].[FabNr] = [PT].[CordonelPressureTest_PcbId] - JOIN [MapPcbIdToSerialNumber] AS [PCB2SN] ON [PCB2SN].[MapPcbIdToSerialNumber_PcbId] = [PT].[CordonelPressureTest_PcbId] - JOIN [AuftragPosition_Gesamt] AS [POS] ON [POS].[FertigungsauftragNr] = [PT].[CordonelPressureTest_FertigungsAuftragsNr] - JOIN [Identnr] AS [ID] ON [ID].[IdentNr] = [POS].[Identnr]"; - } -} diff --git a/LaaProductionWeb/LaaProductionWeb.Tests/LaaProductionWeb.Tests.csproj b/LaaProductionWeb/LaaProductionWeb.Tests/LaaProductionWeb.Tests.csproj new file mode 100644 index 00000000..824d4af2 --- /dev/null +++ b/LaaProductionWeb/LaaProductionWeb.Tests/LaaProductionWeb.Tests.csproj @@ -0,0 +1,28 @@ + + + + netcoreapp2.1 + + false + + + + + + + + + + + + + + + ..\..\..\..\..\..\..\Program Files\dotnet\sdk\NuGetFallbackFolder\microsoft.aspnetcore.mvc.abstractions\2.1.1\lib\netstandard2.0\Microsoft.AspNetCore.Mvc.Abstractions.dll + + + ..\..\..\..\..\..\..\Program Files\dotnet\sdk\NuGetFallbackFolder\microsoft.aspnetcore.mvc.core\2.1.1\lib\netstandard2.0\Microsoft.AspNetCore.Mvc.Core.dll + + + + \ No newline at end of file diff --git a/LaaProductionWeb/LaaProductionWeb.Tests/Models/ModelResultTests.cs b/LaaProductionWeb/LaaProductionWeb.Tests/Models/ModelResultTests.cs new file mode 100644 index 00000000..d1d41470 --- /dev/null +++ b/LaaProductionWeb/LaaProductionWeb.Tests/Models/ModelResultTests.cs @@ -0,0 +1,171 @@ +namespace LaaProductionWeb.Tests.Models +{ + using LaaProductionWebCore.Models; + + using Microsoft.AspNetCore.Mvc; + using Microsoft.AspNetCore.Mvc.ModelBinding; + + using NUnit.Framework; + + using System.Linq; + using System.Reflection; + + public class ModelResultTests + { + [Test] + public void ModelResult_ShouldBeImplicitlyCreated_FromModelStateDictionary() + { + // Act + ModelResult modelResult = default(ModelStateDictionary); + + // Assert + Assert.IsNotNull(modelResult); + } + + [Test] + public void ModelResult_ShouldInitializeModelErrors_WhenCreatedFrom_ModelStateDictionary() + { + // Act + ModelResult modelResult = default(ModelStateDictionary); + + // Assert + Assert.IsNotNull(modelResult.ModelErrors); + } + + [Test] + public void ModelResult_ShouldNotSucceeded_WhenCreatedFrom_ModelStateDictionary() + { + // Act + ModelResult modelResult = default(ModelStateDictionary); + + // Assert + Assert.IsFalse(modelResult.Succeeded); + } + + [Test] + public void ModelResult_ShouldBeImplicitlyCreated_FromOtherObjects() + { + // Act + ModelResult modelResult = default(object); + + // Assert + Assert.IsNotNull(modelResult); + } + + [Test] + public void ModelResult_ShouldSucceeded_WhenCreated_FromOtherObjects() + { + // Act + ModelResult modelResult = default(object); + + // Assert + Assert.IsTrue(modelResult.Succeeded); + } + + [Test] + public void ModelResult_ShouldHaveSameValue_WhenCreated_FromOtherObjects() + { + // Arrange + var value = nameof(ModelResult); + ModelResult modelResult = value; + + // Act + var fieldValue = typeof(ModelResult) + .GetFields(BindingFlags.NonPublic | BindingFlags.Instance) + .FirstOrDefault(x => x.Name == nameof(value)) + ?.GetValue(modelResult); + + // Assert + Assert.AreEqual(value, fieldValue); + } + + [Test] + public void ModelResult_AddModelError_ShuldNotAddError_WhenKeyIsNull() + { + // Arrange + ModelResult modelResult = default(ModelStateDictionary); + var modelErrors = modelResult.ModelErrors; + + // Act + var errorsCountBefore = modelErrors.Count; + modelResult.AddModelError(null, null); + var errorsCountAfter = modelErrors.Count; + + // Assert + Assert.AreEqual(errorsCountBefore, errorsCountAfter); + } + + [Test] + public void ModelResult_AddModelError_ShuldAddErrors_WhenKeyIsNotNull() + { + // Arrange + ModelResult modelResult = default(ModelStateDictionary); + var modelErrors = modelResult.ModelErrors; + + // Act + var errorsCountBefore = modelErrors.Count; + modelResult.AddModelError(string.Empty, null); + var errorsCountAfter = modelErrors.Count; + + // Assert + Assert.Greater(errorsCountAfter, errorsCountBefore); + } + + [Test] + public void ModelResult_AddModelError_ShuldOverrideError_WhenKeyExists() + { + // Arrange + ModelResult modelResult = default(ModelStateDictionary); + var modelErrors = modelResult.ModelErrors; + + // Act + modelResult.AddModelError(string.Empty, "1"); + var valueBefore = modelErrors[string.Empty]; + + modelResult.AddModelError(string.Empty, "2"); + var valueAfter = modelErrors[string.Empty]; + + // Assert + Assert.AreNotEqual(valueBefore, valueAfter); + } + + [Test] + public void ModelResult_ReturnsNotFoundResult_WhenModelResult_IsNull() + { + // Arrange + ModelResult modelResult = null; + + // Act + ActionResult actionResult = modelResult; + + // Assert + Assert.AreEqual(actionResult.GetType(), typeof(NotFoundResult)); + } + + [Test] + public void ModelResult_ReturnsBadRequestObjectResult_WhenCreatedFrom_ModelStateDictionary() + { + // Arrange + ModelResult modelResult = default(ModelStateDictionary); + + // Act + ActionResult actionResult = modelResult; + + // Assert + Assert.AreEqual(actionResult.GetType(), typeof(BadRequestObjectResult)); + } + + [Test] + public void ModelResult_ReturnsOkObjectResult_WhenCreatedWhitValue() + { + // Arrange + ModelResult modelResult = default(string); + + // Act + ActionResult actionResult = modelResult; + + // Assert + Assert.AreEqual(actionResult.GetType(), typeof(OkObjectResult)); + } + } +} diff --git a/LaaProductionWeb/LaaProductionWeb.Tests/Models/WildcardInputModelTests.cs b/LaaProductionWeb/LaaProductionWeb.Tests/Models/WildcardInputModelTests.cs new file mode 100644 index 00000000..05dcd44a --- /dev/null +++ b/LaaProductionWeb/LaaProductionWeb.Tests/Models/WildcardInputModelTests.cs @@ -0,0 +1,145 @@ +namespace LaaProductionWeb.Tests.Models +{ + using LaaProductionWebCore.Areas.Serach.Models; + + using NUnit.Framework; + + using System.Collections.Generic; + using System.ComponentModel.DataAnnotations; + using System.Linq; + using System.Reflection; + + public class WildcardInputModelTests + { + private readonly WildcardInputModel model; + private readonly PropertyInfo tokenPropertyInfo; + + public WildcardInputModelTests() + { + this.model = new WildcardInputModel(); + this.tokenPropertyInfo = typeof(WildcardInputModel) + .GetProperty(nameof(WildcardInputModel.Token), BindingFlags.Instance | BindingFlags.Public); + } + + [Test] + public void ModelValidation_ShouldNotValidate_WhenTokenIsNull() + { + // Arrange + var errorMessage = this.ValidateModelWhitValue(default(string)); + + // Act + var attributeMessage = this.GetAttributeMessage(); + + // Assert + Assert.AreEqual(errorMessage, attributeMessage); + } + + [Test] + public void ModelValidation_ShouldNotValidate_WhenTokenIsUnder_1CharLength() + { + // Act + var errorMessage = this.ValidateModelWhitValue(string.Empty); + + // Act + var attributeMessage = this.GetAttributeMessage(); + + // Assert + Assert.AreEqual(errorMessage, attributeMessage); + } + + [Test] + public void ModelValidation_ShouldNotValidate_WhenTokenIsOver_50CharsLength() + { + // Arrange + var errorMessage = this.ValidateModelWhitValue(new string('0', 51)); + + // Act + var attributeMessage = this.GetAttributeMessage(); + + // Assert + Assert.AreEqual(errorMessage, attributeMessage); + } + + [Test] + [TestCase("^")] + [TestCase("°")] + [TestCase("\"")] + [TestCase("§")] + [TestCase("$")] + [TestCase("%")] + [TestCase("&")] + [TestCase("/")] + [TestCase("(")] + [TestCase(")")] + [TestCase("=")] + [TestCase("?")] + [TestCase("`")] + [TestCase("´")] + [TestCase("'")] + [TestCase("#")] + [TestCase("*")] + [TestCase("+")] + [TestCase("|")] + [TestCase("\t")] + [TestCase("\n")] + [TestCase("<")] + [TestCase(">")] + [TestCase(".")] + [TestCase(";")] + [TestCase(":")] + [TestCase("_")] + [TestCase("ä")] + [TestCase("ö")] + [TestCase("ü")] + [TestCase("Ä")] + [TestCase("Ö")] + [TestCase("Ü")] + [TestCase("ß")] + public void ModelValidation_ShouldNotValidate_WhenTokenContains_NonWordCharachters(string token) + { + // Arrange + var errorMessage = this.ValidateModelWhitValue(token); + + // Act + var attributeMessage = this.GetAttributeMessage(); + + // Assert + Assert.AreEqual(errorMessage, attributeMessage); + } + + [Test] + [TestCase("0123245 5575689-ARWQGVVJALR fasdkfawe irfoelvm")] + public void ModelValidation_ShouldValidate_WhenTokenIsValidNr(string token) + { + // Arrange + var nullMessage = default(string); + + // Act + var errorMessage = this.ValidateModelWhitValue(token); + + // Assert + Assert.AreEqual(errorMessage, nullMessage); + } + + private string ValidateModelWhitValue(string value) + { + var validationResults = new List(); + var validationContext = new ValidationContext(this.model); + + if (Validator.TryValidateObject(this.model, validationContext, validationResults)) + { + return validationResults + .Where(x => x.MemberNames.Contains(nameof(WildcardInputModel.Token))) + .FirstOrDefault(x => !string.IsNullOrWhiteSpace(x.ErrorMessage)) + ?.ErrorMessage ?? default(string); + } + + return default(string); + } + + private string GetAttributeMessage() where T : ValidationAttribute + => this.tokenPropertyInfo + .GetCustomAttribute() + .ErrorMessage; + } +} diff --git a/LaaProductionWeb/LaaProductionWeb.Validation/Attributes/AllowedCharachtersAttribute.cs b/LaaProductionWeb/LaaProductionWeb.Validation/Attributes/AllowedCharachtersAttribute.cs new file mode 100644 index 00000000..f8961baf --- /dev/null +++ b/LaaProductionWeb/LaaProductionWeb.Validation/Attributes/AllowedCharachtersAttribute.cs @@ -0,0 +1,6 @@ +namespace LaaProductionWeb.Validation.Attributes +{ + public class AllowedCharachtersAttribute + { + } +} diff --git a/LaaProductionWeb/LaaProductionWeb.Validation/Attributes/RequiresASCIILettersAttribute.cs b/LaaProductionWeb/LaaProductionWeb.Validation/Attributes/RequiresASCIILettersAttribute.cs new file mode 100644 index 00000000..1e900503 --- /dev/null +++ b/LaaProductionWeb/LaaProductionWeb.Validation/Attributes/RequiresASCIILettersAttribute.cs @@ -0,0 +1,51 @@ +namespace LaaProductionWeb.Validation.Attributes +{ + using System; + using System.ComponentModel.DataAnnotations; + using System.Linq; + + [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] + public class RequiresASCIILettersAttribute : ValidationAttribute + { + private readonly int minCount; + private readonly int maxCount; + + public RequiresASCIILettersAttribute(int minCount = 1, int maxCount = 0) + { + this.minCount = minCount; + this.maxCount = maxCount; + + if (this.maxCount >= this.minCount) + { + this.ErrorMessage = "{0} requires at least {1} and up to {2} letter{3}."; + } + else + { + this.ErrorMessage = "{0} requires at least {1} letter{2}."; + } + } + + protected override ValidationResult IsValid(object value, ValidationContext validationContext) + { + if (this.minCount > 0) + { + var stringValue = $"{value}"; + var countLetters = stringValue.Count(x => (x >= 'a' && x <= 'z') || (x >= 'A' && x <= 'Z')); + var errorMessage = this.ErrorMessageString ?? this.ErrorMessage; + var propertyName = validationContext.DisplayName ?? validationContext.MemberName; + var digitsSufix = this.minCount != 1 ? "s" : string.Empty; + + if (this.maxCount >= this.minCount && this.minCount < countLetters && countLetters > this.maxCount) + { + return new ValidationResult(string.Format(errorMessage, propertyName, this.minCount, this.maxCount, digitsSufix)); + } + else if (this.minCount < countLetters) + { + return new ValidationResult(string.Format(errorMessage, propertyName, this.minCount, digitsSufix)); + } + } + + return ValidationResult.Success; + } + } +} diff --git a/LaaProductionWeb/LaaProductionWeb.Validation/Attributes/RequiresDigitsAttribute.cs b/LaaProductionWeb/LaaProductionWeb.Validation/Attributes/RequiresDigitsAttribute.cs new file mode 100644 index 00000000..3fda05b3 --- /dev/null +++ b/LaaProductionWeb/LaaProductionWeb.Validation/Attributes/RequiresDigitsAttribute.cs @@ -0,0 +1,51 @@ +namespace LaaProductionWeb.Validation.Attributes +{ + using System; + using System.ComponentModel.DataAnnotations; + using System.Linq; + + [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] + public class RequiresDigitsAttribute : RegularExpressionAttribute + { + private readonly int minCount; + private readonly int maxCount; + + public RequiresDigitsAttribute(int minCount = 1, int maxCount = 0) + { + this.minCount = minCount; + this.maxCount = maxCount; + + if (this.maxCount >= this.minCount) + { + this.ErrorMessage = "{0} requires at least {1} and up to {2} digit{3}."; + } + else + { + this.ErrorMessage = "{0} requires at least {1} digit{2}."; + } + } + + protected override ValidationResult IsValid(object value, ValidationContext validationContext) + { + if (this.minCount > 0) + { + var stringValue = $"{value}"; + var countDigits = stringValue.Count(x => x >= '0' && x <= '9'); + var errorMessage = this.ErrorMessageString ?? this.ErrorMessage; + var propertyName = validationContext.DisplayName ?? validationContext.MemberName; + var digitsSufix = this.minCount != 1 ? "s" : string.Empty; + + if (this.maxCount >= this.minCount && this.minCount < countDigits && countDigits > this.maxCount) + { + return new ValidationResult(string.Format(errorMessage, propertyName, this.minCount, this.maxCount, digitsSufix)); + } + else if (this.minCount < countDigits) + { + return new ValidationResult(string.Format(errorMessage, propertyName, this.minCount, digitsSufix)); + } + } + + return ValidationResult.Success; + } + } +} diff --git a/LaaProductionWeb/LaaProductionWeb.Validation/LaaProductionWeb.Validation.csproj b/LaaProductionWeb/LaaProductionWeb.Validation/LaaProductionWeb.Validation.csproj new file mode 100644 index 00000000..85b31e70 --- /dev/null +++ b/LaaProductionWeb/LaaProductionWeb.Validation/LaaProductionWeb.Validation.csproj @@ -0,0 +1,51 @@ + + + + + Debug + AnyCPU + {DDFEAFC1-4AA3-48E4-87C4-1DAAE109E633} + Library + Properties + LaaProductionWeb.Validation + LaaProductionWeb.Validation + v4.7.2 + 512 + true + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/LaaProductionWeb/LaaProductionWeb.Validation/Properties/AssemblyInfo.cs b/LaaProductionWeb/LaaProductionWeb.Validation/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..81ddf519 --- /dev/null +++ b/LaaProductionWeb/LaaProductionWeb.Validation/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("LaaProductionWeb.Validation")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("LaaProductionWeb.Validation")] +[assembly: AssemblyCopyright("Copyright © 2023")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("ddfeafc1-4aa3-48e4-87c4-1daae109e633")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/LaaProductionWeb/LaaProductionWeb.sln b/LaaProductionWeb/LaaProductionWeb.sln index b97bd1a1..51aeac10 100644 --- a/LaaProductionWeb/LaaProductionWeb.sln +++ b/LaaProductionWeb/LaaProductionWeb.sln @@ -16,6 +16,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Documents", "Documents", "{ EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LaaProductionWebCore", "LaaProductionWebCore\LaaProductionWebCore.csproj", "{8ECCC382-B680-4851-AC2A-2E45C4A04041}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LaaProductionWeb.Tests", "LaaProductionWeb.Tests\LaaProductionWeb.Tests.csproj", "{17301A7F-42C1-4418-BAB9-F58F060B48D7}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -38,6 +40,10 @@ Global {8ECCC382-B680-4851-AC2A-2E45C4A04041}.Debug|Any CPU.Build.0 = Debug|Any CPU {8ECCC382-B680-4851-AC2A-2E45C4A04041}.Release|Any CPU.ActiveCfg = Release|Any CPU {8ECCC382-B680-4851-AC2A-2E45C4A04041}.Release|Any CPU.Build.0 = Release|Any CPU + {17301A7F-42C1-4418-BAB9-F58F060B48D7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {17301A7F-42C1-4418-BAB9-F58F060B48D7}.Debug|Any CPU.Build.0 = Debug|Any CPU + {17301A7F-42C1-4418-BAB9-F58F060B48D7}.Release|Any CPU.ActiveCfg = Release|Any CPU + {17301A7F-42C1-4418-BAB9-F58F060B48D7}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/LaaProductionWeb/LaaProductionWeb/App_Start/WebApiConfig.cs b/LaaProductionWeb/LaaProductionWeb/App_Start/WebApiConfig.cs index b0a9546c..e7992b64 100644 --- a/LaaProductionWeb/LaaProductionWeb/App_Start/WebApiConfig.cs +++ b/LaaProductionWeb/LaaProductionWeb/App_Start/WebApiConfig.cs @@ -13,10 +13,9 @@ /// - passed by calling this method. public static void Register(HttpConfiguration config) { - config.MapHttpAttributeRoutes(); - - config.Routes.MapHttpRoute(name: "AreaApi", routeTemplate: "{area}/{controller}/{action}"); - config.Routes.MapHttpRoute(name: "DefaultApi", routeTemplate: "{controller}"); + //config.MapHttpAttributeRoutes(); + + config.Routes.MapHttpRoute(name: "DefaultApi", routeTemplate: "{area}/{controller}/{action}", defaults: new { action = "Get" }); } } } diff --git a/LaaProductionWeb/LaaProductionWeb/Areas/Search/Controllers/WildcardController.cs b/LaaProductionWeb/LaaProductionWeb/Areas/Search/Controllers/WildcardController.cs index 0a590e7b..ef2e1c0c 100644 --- a/LaaProductionWeb/LaaProductionWeb/Areas/Search/Controllers/WildcardController.cs +++ b/LaaProductionWeb/LaaProductionWeb/Areas/Search/Controllers/WildcardController.cs @@ -1,10 +1,12 @@ namespace LaaProductionWeb.Areas.Search { using System.Web.Http; - - public class WildcardController : SearchAPIController + using System.Web.Mvc; + + [RouteArea("Search")] + public class WildcardController : ApiController { - [HttpGet] + [System.Web.Mvc.HttpGet] public IHttpActionResult Get(string token) => this.Json($"Found: {token}"); } diff --git a/LaaProductionWeb/LaaProductionWeb/Areas/Search/SearchAreaRegistration.cs b/LaaProductionWeb/LaaProductionWeb/Areas/Search/SearchAreaRegistration.cs index b75b14fa..c3ec0232 100644 --- a/LaaProductionWeb/LaaProductionWeb/Areas/Search/SearchAreaRegistration.cs +++ b/LaaProductionWeb/LaaProductionWeb/Areas/Search/SearchAreaRegistration.cs @@ -7,6 +7,6 @@ public override string AreaName => "Search"; public override void RegisterArea(AreaRegistrationContext context) - => context.MapRoute("Search_Default", "Search/{controller}/{action}"); + => context.MapRoute("Search_Default", "Search/{controller}/{action}", new { action = "Get" }); } } \ No newline at end of file diff --git a/LaaProductionWeb/LaaProductionWebCore/Areas/Serach/Controllers/WildcardController.cs b/LaaProductionWeb/LaaProductionWebCore/Areas/Serach/Controllers/WildcardController.cs index dde705c3..86954e3b 100644 --- a/LaaProductionWeb/LaaProductionWebCore/Areas/Serach/Controllers/WildcardController.cs +++ b/LaaProductionWeb/LaaProductionWebCore/Areas/Serach/Controllers/WildcardController.cs @@ -1,14 +1,24 @@ namespace LaaProductionWebCore.Areas.Serach.Controllers { + using LaaProductionWebCore.Areas.Serach.Models; + using LaaProductionWebCore.Areas.Serach.Models.Interfaces; + using Microsoft.AspNetCore.Mvc; [Route("Search/[controller]")] public class WildcardController : SearchController { - [HttpGet("{token}")] - public IActionResult Get(string token, string fields) - { - return this.Ok($"[{{ \"token\": \"{token}\", \"fields\": \"{fields}\" }}]"); - } + private readonly IWildcardModel wildcardModel; + + public WildcardController(IWildcardModel wildcardModel) + => this.wildcardModel = wildcardModel; + + [HttpOptions] + public ActionResult Options() + => this.wildcardModel.Options(); + + [HttpGet] + public ActionResult Get([FromQuery] WildcardInputModel model) + => this.wildcardModel.Find(this.ModelState, model); } } \ No newline at end of file diff --git a/LaaProductionWeb/LaaProductionWebCore/Areas/Serach/Models/Interfaces/IWildcardModel.cs b/LaaProductionWeb/LaaProductionWebCore/Areas/Serach/Models/Interfaces/IWildcardModel.cs new file mode 100644 index 00000000..26b8f8f3 --- /dev/null +++ b/LaaProductionWeb/LaaProductionWebCore/Areas/Serach/Models/Interfaces/IWildcardModel.cs @@ -0,0 +1,14 @@ +namespace LaaProductionWebCore.Areas.Serach.Models.Interfaces +{ + using LaaProductionWebCore.Models; + using Microsoft.AspNetCore.Mvc.ModelBinding; + + using System.Collections.Generic; + + public interface IWildcardModel + { + ModelResult> Find(ModelStateDictionary validationState, WildcardInputModel model); + + ModelResult> Options(); + } +} diff --git a/LaaProductionWeb/LaaProductionWebCore/Areas/Serach/Models/WildcardInputModel.cs b/LaaProductionWeb/LaaProductionWebCore/Areas/Serach/Models/WildcardInputModel.cs new file mode 100644 index 00000000..025efde7 --- /dev/null +++ b/LaaProductionWeb/LaaProductionWebCore/Areas/Serach/Models/WildcardInputModel.cs @@ -0,0 +1,33 @@ +namespace LaaProductionWebCore.Areas.Serach.Models +{ + using System; + using System.Collections.Generic; + using System.ComponentModel.DataAnnotations; + using System.Linq; + + public class WildcardInputModel + { + private IEnumerable fields = Array.Empty(); + + [Required(ErrorMessageResourceType = typeof(ErrorMessages), ErrorMessageResourceName = nameof(ErrorMessages.Required))] + [StringLength(50, ErrorMessageResourceType = typeof(ErrorMessages), ErrorMessageResourceName = nameof(ErrorMessages.StringLength), MinimumLength = 1)] + [RegularExpression("^[0-9 a-z-A-Z]+$", ErrorMessageResourceType = typeof(ErrorMessages), ErrorMessageResourceName = nameof(ErrorMessages.RegularExpression))] + public string Token { get; set; } + + public string Fields + { + get => string.Join(",", this.fields); + set => this.fields = $"{value}".Split(',', StringSplitOptions.RemoveEmptyEntries); + } + + internal IEnumerable GetRequiredFields(IEnumerable allFields) + { + if (this.fields.Any()) + { + return allFields.Where(x => this.fields.Contains(x, StringComparer.OrdinalIgnoreCase)); + } + + return allFields; + } + } +} diff --git a/LaaProductionWeb/LaaProductionWebCore/Areas/Serach/Models/WildcardModel.cs b/LaaProductionWeb/LaaProductionWebCore/Areas/Serach/Models/WildcardModel.cs new file mode 100644 index 00000000..eff3296d --- /dev/null +++ b/LaaProductionWeb/LaaProductionWebCore/Areas/Serach/Models/WildcardModel.cs @@ -0,0 +1,134 @@ +namespace LaaProductionWebCore.Areas.Serach.Models +{ + using LaaProductionWeb.Data.Interfaces; + using LaaProductionWebCore.Areas.Serach.Models.Interfaces; + using LaaProductionWebCore.Models; + + using Microsoft.AspNetCore.Mvc.ModelBinding; + + using System.Collections.Generic; + using System.Linq; + + public class WildcardModel : IWildcardModel + { + public static readonly IEnumerable fields = new[] + { + "Client", + "OrderNo", + "PosNo", + "SerialNo", + "ClientSerialNo", + "KurzBez", + "Typ", + "Nennweite", + "Baulaenge", + "Quantity", + "FabricNo", + "IdentNr", + "PcbId", + "ERAddress", + "GMAddress", + }; + + private readonly ISqlClient sqlClient; + + public WildcardModel(ISqlClient sqlClient) + => this.sqlClient = sqlClient; + + public ModelResult> Find(ModelStateDictionary validationState, WildcardInputModel model) + { + if (validationState.IsValid) + { + var requiredFields = model.GetRequiredFields(fields); + + return sqlClient.ExecuteReader($@" + DECLARE @serienNr TABLE([Nr] VARCHAR(50)); + ----------------------------------------------------------------------------- + -- 1. LOOK FOR SERIAL NUMBER ------------------------------------------------ + ----------------------------------------------------------------------------- + INSERT INTO @serienNr + SELECT [APS].[SerienNr] + FROM [AuftragPositionSerienNr] AS [APS] + WHERE [APS].[SerienNr] LIKE @{nameof(model.Token)} + OR [APS].[KundeneigeneSerienNr] LIKE @{nameof(model.Token)}; + ----------------------------------------------------------------------------- + -- 2. LOOK FOR PCB NUMBER --------------------------------------------------- + ----------------------------------------------------------------------------- + INSERT INTO @serienNr + SELECT [PCBS].[MapPcbIdToSerialNumber_SerialNumber] + FROM [MapPcbIdToSerialNumber] AS [PCBS] + WHERE [PCBS].[MapPcbIdToSerialNumber_PcbId] LIKE @{nameof(model.Token)}; + ----------------------------------------------------------------------------- + -- 3. LOOK FOR FUNK ADDRESS E-REGISTER -------------------------------------- + ----------------------------------------------------------------------------- + INSERT INTO @serienNr + SELECT [ER].[Seriennummer] + FROM [eRegister] AS [ER] + WHERE [ER].[Adresse] LIKE @{nameof(model.Token)}; + ----------------------------------------------------------------------------- + -- 4. LOOK FOR FUNK ADDRESS GENESIS ----------------------------------------- + ----------------------------------------------------------------------------- + INSERT INTO @serienNr + SELECT [GM].[Seriennummer] + FROM [Genesis_Meter] AS [GM] + WHERE [GM].[Adresse] LIKE @{nameof(model.Token)}; + ----------------------------------------------------------------------------- + -- 5. IF FOUND TAKE ORDER INFO ---------------------------------------------- + ----------------------------------------------------------------------------- + SELECT DISTINCT + [KN].[Name] AS [Client] + , [APS].[AuftragNr] AS [OrderNo] + , [APS].[PositionNr] AS [PosNo] + , [APS].[SerienNr] AS [SerialNo] + , [APS].[KundeneigeneSerienNr] AS [ClientSerialNo] + , [IDN].[KurzBez] AS [KurzBez] + , [IDN].[Typ] AS [Typ] + , [IDN].[Nennweite] AS [Nennweite] + , [IDN].[Baulaenge] AS [Baulaenge] + , [AP].[Menge] AS [Quantity] + , [APS].[FabNr] AS [FabricNo] + , [IDN].[IdentNr] AS [IdentNr] + , [PCBS].[MapPcbIdToSerialNumber_PcbId] AS [PcbId] + , [ER].[Adresse] AS [ERAddress] + , [GM].[Adresse] AS [GMAddress] + FROM [AuftragPositionSerienNr] AS [APS] + LEFT JOIN [AuftragPosition_Gesamt] AS [AP] + ON [AP].[AuftragNr] = [APS].[AuftragNr] + AND [AP].[PositionNr] = [APS].[PositionNr] + LEFT JOIN [Auftrag_Gesamt] AS [AG] + ON [AG].[AuftragNr] = [APS].[AuftragNr] + LEFT JOIN [Kunde] AS [KN] + ON [KN].[KundenNr] = [AG].[KundenNr] + LEFT JOIN [Identnr] AS [IDN] + ON [IDN].[IdentNr] = [AP].[Identnr] + LEFT JOIN [MapPcbIdToSerialNumber] AS [PCBS] + ON [PCBS].[MapPcbIdToSerialNumber_SerialNumber] = [APS].[SerienNr] + LEFT JOIN [eRegister] AS [ER] + ON [ER].[Seriennummer] = [APS].[SerienNr] + LEFT JOIN [Genesis_Meter] AS [GM] + ON [GM].[Seriennummer] = [APS].[SerienNr] + WHERE [APS].[SerienNr] IN (SELECT [Nr] FROM @serienNr)", + parameters => parameters.Add(nameof(model.Token), model.Token), + reader => this.ToWildcardResult(reader, requiredFields)) + .ToList(); + } + + return validationState; + } + + public ModelResult> Options() + => fields.ToList(); + + internal WildcardResult ToWildcardResult(ISqlReader reader, IEnumerable fields) + { + var wildcardResult = new WildcardResult(); + + foreach (var field in fields) + { + wildcardResult[field] = reader.GetValue(field); + } + + return wildcardResult; + } + } +} diff --git a/LaaProductionWeb/LaaProductionWebCore/Areas/Serach/Models/WildcardResult.cs b/LaaProductionWeb/LaaProductionWebCore/Areas/Serach/Models/WildcardResult.cs new file mode 100644 index 00000000..0ff73db4 --- /dev/null +++ b/LaaProductionWeb/LaaProductionWebCore/Areas/Serach/Models/WildcardResult.cs @@ -0,0 +1,8 @@ +namespace LaaProductionWebCore.Areas.Serach.Models +{ + using System.Collections.Generic; + + public class WildcardResult : Dictionary + { + } +} diff --git a/LaaProductionWeb/LaaProductionWebCore/ErrorMessages.Designer.cs b/LaaProductionWeb/LaaProductionWebCore/ErrorMessages.Designer.cs new file mode 100644 index 00000000..1b9a9a68 --- /dev/null +++ b/LaaProductionWeb/LaaProductionWebCore/ErrorMessages.Designer.cs @@ -0,0 +1,90 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace LaaProductionWebCore { + using System; + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + public class ErrorMessages { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal ErrorMessages() { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + public static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("LaaProductionWebCore.ErrorMessages", typeof(ErrorMessages).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + public static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + + /// + /// Looks up a localized string similar to Field {0} is not well formatted.. + /// + public static string RegularExpression { + get { + return ResourceManager.GetString("RegularExpression", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Field {0} is required.. + /// + public static string Required { + get { + return ResourceManager.GetString("Required", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Field {0} requires at liest {2} and up to {1} charachters.. + /// + public static string StringLength { + get { + return ResourceManager.GetString("StringLength", resourceCulture); + } + } + } +} diff --git a/LaaProductionWeb/LaaProductionWebCore/ErrorMessages.resx b/LaaProductionWeb/LaaProductionWebCore/ErrorMessages.resx new file mode 100644 index 00000000..6b389d4c --- /dev/null +++ b/LaaProductionWeb/LaaProductionWebCore/ErrorMessages.resx @@ -0,0 +1,129 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Field {0} is not well formatted. + + + Field {0} is required. + + + Field {0} requires at liest {2} and up to {1} charachters. + + \ No newline at end of file diff --git a/LaaProductionWeb/LaaProductionWebCore/LaaProductionWebCore.csproj b/LaaProductionWeb/LaaProductionWebCore/LaaProductionWebCore.csproj index 103dab67..15219e9c 100644 --- a/LaaProductionWeb/LaaProductionWebCore/LaaProductionWebCore.csproj +++ b/LaaProductionWeb/LaaProductionWebCore/LaaProductionWebCore.csproj @@ -14,4 +14,23 @@ + + + + + + + True + True + ErrorMessages.resx + + + + + + PublicResXFileCodeGenerator + ErrorMessages.Designer.cs + + + diff --git a/LaaProductionWeb/LaaProductionWebCore/Models/ApplicationSettings.cs b/LaaProductionWeb/LaaProductionWebCore/Models/ApplicationSettings.cs index e8059b0a..131e3e38 100644 --- a/LaaProductionWeb/LaaProductionWebCore/Models/ApplicationSettings.cs +++ b/LaaProductionWeb/LaaProductionWebCore/Models/ApplicationSettings.cs @@ -16,6 +16,6 @@ /// public class ConnectionStrings { - + public string DefaultConnection { get; set; } } } diff --git a/LaaProductionWeb/LaaProductionWebCore/Models/ModelResult[T].cs b/LaaProductionWeb/LaaProductionWebCore/Models/ModelResult[T].cs new file mode 100644 index 00000000..5d60e9c8 --- /dev/null +++ b/LaaProductionWeb/LaaProductionWebCore/Models/ModelResult[T].cs @@ -0,0 +1,77 @@ +namespace LaaProductionWebCore.Models +{ + using Microsoft.AspNetCore.Mvc; + using Microsoft.AspNetCore.Mvc.ModelBinding; + + using System.Collections.Generic; + using System.Linq; + + public class ModelResult + { + private readonly T value; + private readonly Dictionary errors; + + private ModelResult(bool succeeded) + { + this.Succeeded = succeeded; + this.errors = new Dictionary(); + } + + private ModelResult(T value) + { + this.Succeeded = true; + this.value = value; + } + + public bool Succeeded { get; } + + public IReadOnlyDictionary ModelErrors + => this.errors; + + public void AddModelError(string key, string value) + { + if (key != null) + { + this.errors[key] = value; + } + } + + public static implicit operator ModelResult(T value) + => new ModelResult(value); + + public static implicit operator ModelResult(ModelStateDictionary modelState) + { + var validationResults = new ModelResult(false); + + if (modelState != null) + { + foreach (var entry in modelState) + { + var errorKey = entry.Key; + var errorValue = entry.Value; + + if (errorValue.ValidationState == ModelValidationState.Invalid && errorValue.Errors.Any()) + { + validationResults.AddModelError(errorKey, errorValue.Errors.First().ErrorMessage); + } + } + } + + return validationResults; + } + + public static implicit operator ActionResult(ModelResult modelState) + { + if (modelState is null) + { + return new NotFoundResult(); + } + else if (modelState.Succeeded) + { + return new OkObjectResult(modelState.value); + } + + return new BadRequestObjectResult(modelState.errors); + } + } +} diff --git a/LaaProductionWeb/LaaProductionWebCore/Startup.cs b/LaaProductionWeb/LaaProductionWebCore/Startup.cs index a9948ade..69b744d4 100644 --- a/LaaProductionWeb/LaaProductionWebCore/Startup.cs +++ b/LaaProductionWeb/LaaProductionWebCore/Startup.cs @@ -1,5 +1,11 @@ namespace LaaProductionWebCore { + using LaaProductionWeb.Data; + using LaaProductionWeb.Data.Interfaces; + using LaaProductionWebCore.Areas.Serach.Models; + using LaaProductionWebCore.Areas.Serach.Models.Interfaces; + using LaaProductionWebCore.Models; + using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; @@ -15,7 +21,10 @@ public void ConfigureServices(IServiceCollection services) { - + var connectionString = this.configuration + .GetConnectionString(nameof(ConnectionStrings.DefaultConnection)); + services.AddTransient(_ => new SqlClient(connectionString)); + services.AddTransient(); services .AddMvc() @@ -25,10 +34,11 @@ public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseHsts(); - //Can be outcommented when needed - //app.UseHttpsRedirection(); + app.UseDeveloperExceptionPage(); + app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseCookiePolicy(); + app.UseMvc(routes => { routes.MapRoute(name: "default", template: "{controller=Home}/{action=Index}/{id?}");