diff --git a/CDP4Orm.Tests/UtilsTestFixture.cs b/CDP4Orm.Tests/UtilsTestFixture.cs index 263529ff..39ad22cb 100644 --- a/CDP4Orm.Tests/UtilsTestFixture.cs +++ b/CDP4Orm.Tests/UtilsTestFixture.cs @@ -92,8 +92,8 @@ public void VerifyOrderedListDeserialization() var expected = (IEnumerable)new List { - new OrderedItem { K = 0, V = "item0" }, - new OrderedItem { K = 1, V = "item1" } + new() { K = 0, V = "item0" }, + new() { K = 1, V = "item1" } }; Assert.That(Utils.ParseOrderedList(orderdListSource), Is.EquivalentTo(expected)); diff --git a/CDP4Orm/AutoGenDao/DataModelUtils.cs b/CDP4Orm/AutoGenDao/DataModelUtils.cs index caf3f594..e233c9b2 100644 --- a/CDP4Orm/AutoGenDao/DataModelUtils.cs +++ b/CDP4Orm/AutoGenDao/DataModelUtils.cs @@ -41,8 +41,8 @@ public class DataModelUtils : IDataModelUtils /// /// The derived properties per class. /// - private readonly HashSet derivedProperties = new HashSet - { + private readonly HashSet derivedProperties = new() + { { "ActualFiniteState.Name" }, { "ActualFiniteState.Owner" }, { "ActualFiniteState.ShortName" }, @@ -124,8 +124,8 @@ public class DataModelUtils : IDataModelUtils /// /// The type source partition mapping for each concrete class. /// - private readonly Dictionary> typePartitionMap = new Dictionary> - { + private readonly Dictionary> typePartitionMap = new() + { { "EngineeringModel", diff --git a/CDP4Orm/Dao/Authentication/AuthenticationPersonDao.cs b/CDP4Orm/Dao/Authentication/AuthenticationPersonDao.cs index 93315cc1..0e37d90d 100644 --- a/CDP4Orm/Dao/Authentication/AuthenticationPersonDao.cs +++ b/CDP4Orm/Dao/Authentication/AuthenticationPersonDao.cs @@ -117,9 +117,9 @@ private static AuthenticationPerson MapToDto(NpgsqlDataReader reader) var dto = new AuthenticationPerson(iid, revisionNumber) { - Role = reader["Role"] is DBNull ? (Guid?)null : Guid.Parse(reader["Role"].ToString()), - DefaultDomain = reader["DefaultDomain"] is DBNull? (Guid?)null : Guid.Parse(reader["DefaultDomain"].ToString()), - Organization = reader["Organization"] is DBNull ? (Guid?)null : Guid.Parse(reader["Organization"].ToString()) + Role = reader["Role"] is DBNull ? null : Guid.Parse(reader["Role"].ToString()), + DefaultDomain = reader["DefaultDomain"] is DBNull? null : Guid.Parse(reader["DefaultDomain"].ToString()), + Organization = reader["Organization"] is DBNull ? null : Guid.Parse(reader["Organization"].ToString()) }; if (valueDict.TryGetValue("IsActive", out var tempIsActive)) diff --git a/CDP4Orm/Dao/BaseDao.cs b/CDP4Orm/Dao/BaseDao.cs index b5f2690c..1ec7b236 100644 --- a/CDP4Orm/Dao/BaseDao.cs +++ b/CDP4Orm/Dao/BaseDao.cs @@ -303,8 +303,7 @@ private DateTime GetTransactionDateTime(NpgsqlTransaction transaction) { this.currentTransactionDataTimeTransaction = transaction; - using var command = new NpgsqlCommand( - $"SELECT * FROM \"SiteDirectory\".\"get_transaction_time\"();", + using var command = new NpgsqlCommand("SELECT * FROM \"SiteDirectory\".\"get_transaction_time\"();", transaction.Connection, transaction); this.currentTransactionDatetime = (DateTime)command.ExecuteScalar(); @@ -322,7 +321,7 @@ protected Thing MapJsonbToDto(NpgsqlDataReader reader) { var jsonObject = JObject.Parse(reader.GetValue(0).ToString()); - Thing thing = null; + Thing thing; try { diff --git a/CDP4Orm/Dao/Cache/CacheDao.cs b/CDP4Orm/Dao/Cache/CacheDao.cs index b8c62f2f..f76e4030 100644 --- a/CDP4Orm/Dao/Cache/CacheDao.cs +++ b/CDP4Orm/Dao/Cache/CacheDao.cs @@ -75,16 +75,6 @@ public class CacheDao : ICacheDao /// public IFileDao FileDao { get; set; } - /// - /// Gets or sets the folder dao. - /// - public IFolderDao FolderDao { get; set; } - - /// - /// Gets or sets the fileRevision dao. - /// - public IFileRevisionDao FileRevisionDao { get; set; } - /// /// Gets or sets the injected /// @@ -100,19 +90,18 @@ public void Write(NpgsqlTransaction transaction, string partition, Thing thing) { var table = GetThingCacheTableName(thing); - var columns = string.Format("(\"{0}\", \"{1}\", \"{2}\")", IidKey, RevisionColumnName, JsonColumnName); + var columns = $"(\"{IidKey}\", \"{RevisionColumnName}\", \"{JsonColumnName}\")"; var values = "(:iid, :revisionnumber, :jsonb)"; - var sqlQuery = string.Format("INSERT INTO \"{0}\".\"{1}\" {2} VALUES {3} ON CONFLICT (\"{4}\") DO UPDATE SET \"{5}\"=:revisionnumber, \"{6}\"=:jsonb;", partition, table, columns, values, IidKey, RevisionColumnName, JsonColumnName); + var sqlQuery = $"INSERT INTO \"{partition}\".\"{table}\" {columns} VALUES {values} ON CONFLICT (\"{IidKey}\") DO UPDATE SET \"{RevisionColumnName}\"=:revisionnumber, \"{JsonColumnName}\"=:jsonb;"; - using (var command = new NpgsqlCommand(sqlQuery, transaction.Connection, transaction)) - { - command.Parameters.Add("iid", NpgsqlDbType.Uuid).Value = thing.Iid; - command.Parameters.Add("revisionnumber", NpgsqlDbType.Integer).Value = thing.RevisionNumber; - command.Parameters.Add("jsonb", NpgsqlDbType.Jsonb).Value = thing.ToJsonObject().ToString(Formatting.None); + using var command = new NpgsqlCommand(sqlQuery, transaction.Connection, transaction); - // log the sql command - command.ExecuteNonQuery(); - } + command.Parameters.Add("iid", NpgsqlDbType.Uuid).Value = thing.Iid; + command.Parameters.Add("revisionnumber", NpgsqlDbType.Integer).Value = thing.RevisionNumber; + command.Parameters.Add("jsonb", NpgsqlDbType.Jsonb).Value = thing.ToJsonObject().ToString(Formatting.None); + + // log the sql command + command.ExecuteNonQuery(); } /// diff --git a/CDP4Orm/Dao/Resolve/ContainerDao.cs b/CDP4Orm/Dao/Resolve/ContainerDao.cs index ba0b98a5..9d417e95 100644 --- a/CDP4Orm/Dao/Resolve/ContainerDao.cs +++ b/CDP4Orm/Dao/Resolve/ContainerDao.cs @@ -134,17 +134,15 @@ private IEnumerable> ReadInternalFromSiteDirectory(Np var sql = sqlBuilder.ToString(); - using (var command = new NpgsqlCommand(sql, transaction.Connection, transaction)) + using var command = new NpgsqlCommand(sql, transaction.Connection, transaction); + + command.Parameters.Add("ids", NpgsqlDbType.Array | NpgsqlDbType.Uuid).Value = ids.ToList(); + + using var reader = command.ExecuteReader(); + + while (reader.Read()) { - command.Parameters.Add("ids", NpgsqlDbType.Array | NpgsqlDbType.Uuid).Value = ids.ToList(); - - using (var reader = command.ExecuteReader()) - { - while (reader.Read()) - { - yield return MapToSiteDirectoryContainmentInfo(reader, connectedPartition); - } - } + yield return MapToSiteDirectoryContainmentInfo(reader, connectedPartition); } } @@ -197,7 +195,7 @@ private static Tuple MapToSiteDirectoryContainmentInfo(Npgs /// private IEnumerable> ReadInternalFromEngineeringModel(NpgsqlTransaction transaction, string partition, string typeName, IEnumerable ids) { - var sqlBuilder = new System.Text.StringBuilder(); + var sqlBuilder = new StringBuilder(); var connectedPartition = partition; var otherPartition = partition.Replace(Utils.EngineeringModelPartition, Utils.IterationSubPartition); @@ -225,17 +223,15 @@ private IEnumerable> ReadInternalFromEngineeringModel var sql = sqlBuilder.ToString(); - using (var command = new NpgsqlCommand(sql, transaction.Connection, transaction)) - { - command.Parameters.Add("ids", NpgsqlDbType.Array | NpgsqlDbType.Uuid).Value = ids.ToList(); + using var command = new NpgsqlCommand(sql, transaction.Connection, transaction); - using (var reader = command.ExecuteReader()) - { - while (reader.Read()) - { - yield return MapToEngineeringModelContainmentInfo(reader, connectedPartition, otherPartition); - } - } + command.Parameters.Add("ids", NpgsqlDbType.Array | NpgsqlDbType.Uuid).Value = ids.ToList(); + + using var reader = command.ExecuteReader(); + + while (reader.Read()) + { + yield return MapToEngineeringModelContainmentInfo(reader, connectedPartition, otherPartition); } } diff --git a/CDP4Orm/Dao/Resolve/ResolveDao.cs b/CDP4Orm/Dao/Resolve/ResolveDao.cs index becf5c36..cc1d1d06 100644 --- a/CDP4Orm/Dao/Resolve/ResolveDao.cs +++ b/CDP4Orm/Dao/Resolve/ResolveDao.cs @@ -91,17 +91,15 @@ private static IEnumerable ReadSiteDirectoryThing(NpgsqlTransaction var sql = sqlBuilder.ToString(); - using (var command = new NpgsqlCommand(sql, transaction.Connection, transaction)) + using var command = new NpgsqlCommand(sql, transaction.Connection, transaction); + + command.Parameters.Add("ids", NpgsqlDbType.Array | NpgsqlDbType.Uuid).Value = ids.ToList(); + + using var reader = command.ExecuteReader(); + + while (reader.Read()) { - command.Parameters.Add("ids", NpgsqlDbType.Array | NpgsqlDbType.Uuid).Value = ids.ToList(); - - using (var reader = command.ExecuteReader()) - { - while (reader.Read()) - { - yield return MapToSiteDirectoryDto(reader); - } - } + yield return MapToSiteDirectoryDto(reader); } } @@ -145,17 +143,15 @@ private static IEnumerable ReadEngineeringModelInternal(NpgsqlTrans connectedPartition, subPartition); - using (var command = new NpgsqlCommand(sql, transaction.Connection, transaction)) + using var command = new NpgsqlCommand(sql, transaction.Connection, transaction); + + command.Parameters.Add("ids", NpgsqlDbType.Array | NpgsqlDbType.Uuid).Value = ids.ToList(); + + using var reader = command.ExecuteReader(); + + while (reader.Read()) { - command.Parameters.Add("ids", NpgsqlDbType.Array | NpgsqlDbType.Uuid).Value = ids.ToList(); - - using (var reader = command.ExecuteReader()) - { - while (reader.Read()) - { - yield return MapToEngineeringModelDto(reader, connectedPartition, subPartition); - } - } + yield return MapToEngineeringModelDto(reader, connectedPartition, subPartition); } } diff --git a/CDP4Orm/Dao/Revision/RevisionDao.cs b/CDP4Orm/Dao/Revision/RevisionDao.cs index 112a0f14..19bd1deb 100644 --- a/CDP4Orm/Dao/Revision/RevisionDao.cs +++ b/CDP4Orm/Dao/Revision/RevisionDao.cs @@ -484,7 +484,7 @@ private static ReadOnlyCollection ReadSiteDirectoryRevisions(Npgsq { var result = new List(); - var sqlBuilder = new System.Text.StringBuilder(); + var sqlBuilder = new StringBuilder(); // get all Thing 'concepts' whose revisions are as per the supplied revision comparator sqlBuilder.Append( @@ -557,7 +557,7 @@ private static ReadOnlyCollection ReadEngineeringModelRevisions(Np { var result = new List(); - var sqlBuilder = new System.Text.StringBuilder(); + var sqlBuilder = new StringBuilder(); var connectedPartition = partition; var subPartition = partition.Replace(Utils.EngineeringModelPartition, Utils.IterationSubPartition); diff --git a/CDP4Orm/Dao/Supplemental/IIterationSetupDao.cs b/CDP4Orm/Dao/Supplemental/IIterationSetupDao.cs index a0829d61..44ba9fdb 100644 --- a/CDP4Orm/Dao/Supplemental/IIterationSetupDao.cs +++ b/CDP4Orm/Dao/Supplemental/IIterationSetupDao.cs @@ -55,25 +55,5 @@ public partial interface IIterationSetupDao /// List of instances of . /// IEnumerable ReadByIteration(NpgsqlTransaction transaction, string partition, Guid iterationId, DateTime? instant = null); - - /// - /// Read the data from the database based on . - /// - /// - /// The current transaction to the database. - /// - /// - /// The database partition (schema) where the requested resource is stored. - /// - /// - /// The Id. - /// - /// - /// The instant as a - /// - /// - /// List of instances of . - /// - IEnumerable ReadByEngineeringModelSetup(NpgsqlTransaction transaction, string partition, Guid engineeringModelSetupId, DateTime? instant = null); } } diff --git a/CDP4Orm/Dao/Supplemental/IPersonDao.cs b/CDP4Orm/Dao/Supplemental/IPersonDao.cs index 1cc9b4e0..aa80d991 100644 --- a/CDP4Orm/Dao/Supplemental/IPersonDao.cs +++ b/CDP4Orm/Dao/Supplemental/IPersonDao.cs @@ -24,8 +24,6 @@ namespace CDP4Orm.Dao { - using System; - using Npgsql; /// @@ -38,20 +36,6 @@ public partial interface IPersonDao /// string PasswordChangeToken { get; } - /// - /// Gets the given name of a person. - /// - /// - /// The transaction. - /// - /// - /// The person id. - /// - /// - /// The . - /// - string GivenName(NpgsqlTransaction transaction, Guid personIid); - /// /// Update user credentials after migration /// diff --git a/CDP4Orm/Dao/Supplemental/IterationSetupDao.cs b/CDP4Orm/Dao/Supplemental/IterationSetupDao.cs index 71924db1..7c30b7e3 100644 --- a/CDP4Orm/Dao/Supplemental/IterationSetupDao.cs +++ b/CDP4Orm/Dao/Supplemental/IterationSetupDao.cs @@ -91,54 +91,6 @@ public virtual IEnumerable ReadByIteration(NpgsqlTransaction tra } } - /// - /// Read the data from the database based on . - /// - /// - /// The current transaction to the database. - /// - /// - /// The database partition (schema) where the requested resource is stored. - /// - /// - /// The Id. - /// - /// - /// The instant as a nullable - /// - /// - /// List of instances of . - /// - public IEnumerable ReadByEngineeringModelSetup(NpgsqlTransaction transaction, string partition, Guid engineeringModelSetupId, DateTime? instant = null) - { - using var command = new NpgsqlCommand(); - - var sqlBuilder = new StringBuilder(); - - sqlBuilder.Append($"SELECT * FROM {this.BuildReadQuery(partition, instant)}"); - sqlBuilder.Append($" WHERE \"Iid\"::text = ANY(SELECT unnest(\"IterationSetup\") FROM ({this.EngineeringModelSetupDao.BuildReadQuery(partition, instant)}) EngineeringModelSetup WHERE \"Iid\"::text = :engineeringModelSetupId)"); - - command.Parameters.Add("engineeringModelSetupId", NpgsqlDbType.Text).Value = engineeringModelSetupId.ToString(); - - if (instant.HasValue && instant.Value != DateTime.MaxValue) - { - command.Parameters.Add("instant", NpgsqlDbType.Timestamp).Value = instant; - } - - sqlBuilder.Append(';'); - - command.Connection = transaction.Connection; - command.Transaction = transaction; - command.CommandText = sqlBuilder.ToString(); - - using var reader = command.ExecuteReader(); - - while (reader.Read()) - { - yield return this.MapToDto(reader); - } - } - /// /// Execute additional logic before each delete function call. /// diff --git a/CDP4Orm/Dao/Supplemental/PersonDao.cs b/CDP4Orm/Dao/Supplemental/PersonDao.cs index 769b1f0e..826c5f1f 100644 --- a/CDP4Orm/Dao/Supplemental/PersonDao.cs +++ b/CDP4Orm/Dao/Supplemental/PersonDao.cs @@ -26,8 +26,7 @@ namespace CDP4Orm.Dao { using System; using System.Collections.Generic; - using System.Linq; - + using CDP4Authentication; using CDP4Common.DTO; @@ -139,26 +138,6 @@ public string PasswordChangeToken return true; } - /// - /// Gets the given name of a person. - /// - /// - /// The transaction. - /// - /// - /// The person id. - /// - /// - /// The . - /// - public string GivenName(NpgsqlTransaction transaction, Guid personIid) - { - var partition = "SiteDirectory"; - var personObject = this.Read(transaction, partition).SingleOrDefault(person => person.Iid == personIid); - - return personObject != null ? personObject.GivenName : null; - } - /// /// Extracts the salt property from the hstore in the beiung updated and adds it to the the valueType dictionary /// @@ -251,12 +230,12 @@ internal static void ApplyPasswordChange(Thing thing, Dictionary /// /// The database transaction. /// The database schema - /// The person + /// The person /// The new credentials from migration.json /// /// The true if operation finished with success /// - public bool UpdateCredentials(NpgsqlTransaction transaction, string partition, CDP4Common.DTO.Person person, MigrationPasswordCredentials credentials) + public bool UpdateCredentials(NpgsqlTransaction transaction, string partition, Person person, MigrationPasswordCredentials credentials) { var operationSuccess = true; diff --git a/CDP4Orm/Dao/Utils.cs b/CDP4Orm/Dao/Utils.cs index 63f658d0..73d7851d 100644 --- a/CDP4Orm/Dao/Utils.cs +++ b/CDP4Orm/Dao/Utils.cs @@ -67,11 +67,6 @@ public static class Utils /// public const string DateTimeUtcSerializationFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'"; - /// - /// The UTC (zulu) date time SQL format. - /// - public const string DateTimeUtcSqlFormat = "yyyy-MM-dd HH:mm:ss.fff"; - /// /// The class kind key. /// @@ -90,12 +85,12 @@ public static class Utils /// /// The key value pair entry separator. /// - private static readonly string[] EntrySeparator = new[] { "," }; + private static readonly string[] EntrySeparator = { "," }; /// /// The key value pair separator. /// - private static readonly string[] KvpSeparator = new[] { "=>" }; + private static readonly string[] KvpSeparator = { "=>" }; /// /// Parse a database HSTORE text representation to a Dictionary instance @@ -311,32 +306,6 @@ public static void ReadSqlFromResource(this NpgsqlCommand command, string resour AssignCommandText(command, strText, replace); } - /// - /// Extension method that reads the contents of the passed in SQL file to the NPGSQL command text. - /// - /// - /// The command object to which the SQL file contents will be set. - /// - /// - /// The embedded resource Name. - /// - /// - /// Optional encoding to be used when reading in the file. By default UTF8 encoding is used. - /// - /// - /// Optional replacement information expressed in the form of Tuples (item1 = text to replace, item2 = replacement text), these are executed in order. - /// - public static void ReadSqlFromFile(this NpgsqlCommand command, string filePath, System.Text.Encoding enc = null, IEnumerable> replace = null) - { - string strText; - using (var reader = new StreamReader(filePath, enc ?? System.Text.Encoding.UTF8)) - { - strText = reader.ReadToEnd(); - } - - AssignCommandText(command, strText, replace); - } - /// /// Assign the sql text to the supplied command. /// diff --git a/CDP4Orm/MigrationEngine/GenericMigration.cs b/CDP4Orm/MigrationEngine/GenericMigration.cs index 0d940bb9..8399b10a 100644 --- a/CDP4Orm/MigrationEngine/GenericMigration.cs +++ b/CDP4Orm/MigrationEngine/GenericMigration.cs @@ -49,7 +49,12 @@ public class GenericMigration : MigrationBase /// /// Initializes a new instance of the class /// - /// Themigration metadata + /// + /// The migration metadata + /// + /// + /// The (injected) logger + /// internal GenericMigration(MigrationMetaData migrationMetadata, ILogger logger) : base(migrationMetadata) { this.logger = logger; @@ -97,15 +102,14 @@ public override void ApplyMigration(NpgsqlTransaction transaction, IReadOnlyList } } - using (var sqlCommand = new NpgsqlCommand()) - { - sqlCommand.ReadSqlFromResource(this.MigrationMetaData.ResourceName, null, replaceList); + using var sqlCommand = new NpgsqlCommand(); - sqlCommand.Connection = transaction.Connection; - sqlCommand.Transaction = transaction; - sqlCommand.ExecuteNonQuery(); - this.logger.LogInformation("End migration script {ResourceName}", this.MigrationMetaData.ResourceName); - } + sqlCommand.ReadSqlFromResource(this.MigrationMetaData.ResourceName, null, replaceList); + + sqlCommand.Connection = transaction.Connection; + sqlCommand.Transaction = transaction; + sqlCommand.ExecuteNonQuery(); + this.logger.LogInformation("End migration script {ResourceName}", this.MigrationMetaData.ResourceName); } base.ApplyMigration(transaction, existingSchemas); diff --git a/CDP4Orm/MigrationEngine/MigrationMetaData.cs b/CDP4Orm/MigrationEngine/MigrationMetaData.cs index b074a2ca..b37fecaa 100644 --- a/CDP4Orm/MigrationEngine/MigrationMetaData.cs +++ b/CDP4Orm/MigrationEngine/MigrationMetaData.cs @@ -56,7 +56,7 @@ public class MigrationMetaData { protected const char SCRIPT_VERSION_SEPARATOR = '_'; protected const char CODE_VERSION_SEPARATOR = '.'; - protected static Regex MIGRATION_FILENAME_PATTERN = new Regex(@"^(?[a-zA-Z]+)(_(?[a-zA-Z]+))?_(?\d{8})_(?\d+_\d+_\d+_\d+)_(?.*\.sql)$"); + protected static Regex MIGRATION_FILENAME_PATTERN = new(@"^(?[a-zA-Z]+)(_(?[a-zA-Z]+))?_(?\d{8})_(?\d+_\d+_\d+_\d+)_(?.*\.sql)$"); /// /// Initializes a new instance of the class diff --git a/CDP4Orm/MigrationEngine/MigrationService.cs b/CDP4Orm/MigrationEngine/MigrationService.cs index 1cfb50dd..c629b9fb 100644 --- a/CDP4Orm/MigrationEngine/MigrationService.cs +++ b/CDP4Orm/MigrationEngine/MigrationService.cs @@ -67,7 +67,7 @@ public MigrationService(ILoggerFactory loggerFactory) /// Asserts whether the is called on startup public void ApplyMigrations(NpgsqlTransaction transaction, string partition, bool isStartup) { - var migrations = GetMigrations(isStartup).Where(x => partition.StartsWith(x.MigrationMetaData.MigrationScriptApplicationKind.ToString()) || x.MigrationMetaData.MigrationScriptApplicationKind == MigrationScriptApplicationKind.All); + var migrations = this.GetMigrations(isStartup).Where(x => partition.StartsWith(x.MigrationMetaData.MigrationScriptApplicationKind.ToString()) || x.MigrationMetaData.MigrationScriptApplicationKind == MigrationScriptApplicationKind.All); foreach (var migrationBase in migrations.OrderBy(x => x.MigrationMetaData.Version)) { diff --git a/CDP4WspDatabaseAuthentication/WspEncryptionUtils.cs b/CDP4WspDatabaseAuthentication/WspEncryptionUtils.cs index 196799b1..5c2a0407 100644 --- a/CDP4WspDatabaseAuthentication/WspEncryptionUtils.cs +++ b/CDP4WspDatabaseAuthentication/WspEncryptionUtils.cs @@ -77,17 +77,14 @@ public static string BuildWspSaltedString(string password, string salt, string s var saltBytes = Encoding.UTF8.GetBytes(salt); var serverSaltBytes = Encoding.UTF8.GetBytes(serverSalt); - string hashedPassword; + using var hasher = SHA256.Create(); - using (var hasher = SHA256.Create()) - { - hasher.Initialize(); - hasher.TransformBlock(serverSaltBytes, 0, serverSaltBytes.Length, null, 0); - hasher.TransformBlock(passwordBytes, 0, passwordBytes.Length, null, 0); - hasher.TransformFinalBlock(saltBytes, 0, saltBytes.Length); + hasher.Initialize(); + hasher.TransformBlock(serverSaltBytes, 0, serverSaltBytes.Length, null, 0); + hasher.TransformBlock(passwordBytes, 0, passwordBytes.Length, null, 0); + hasher.TransformFinalBlock(saltBytes, 0, saltBytes.Length); - hashedPassword = BitConverter.ToString(hasher.Hash).Replace("-", ""); - } + var hashedPassword = BitConverter.ToString(hasher.Hash).Replace("-", ""); return hashedPassword; } diff --git a/CometServer.Tests/Authorization/PermissionServiceTestFixture.cs b/CometServer.Tests/Authorization/PermissionServiceTestFixture.cs index 3a6a8e46..8f034b46 100644 --- a/CometServer.Tests/Authorization/PermissionServiceTestFixture.cs +++ b/CometServer.Tests/Authorization/PermissionServiceTestFixture.cs @@ -91,7 +91,7 @@ public class PermissionServiceTestFixture private static SiteDirectory siteDirectory = new(Guid.NewGuid(), 0); private Participant participant; - private Thing addContainerThingToCache = null; + private Thing addContainerThingToCache; [SetUp] public void SetUp() @@ -109,7 +109,7 @@ public void SetUp() this.participant = new Participant(Guid.NewGuid(), 0) { - Domain = new List { domain.Iid }, + Domain = [domain.Iid], Person = this.authenticationPerson.Iid }; @@ -120,10 +120,11 @@ public void SetUp() this.credentialsService = new Mock(); this.credentialsService.Setup(x => x.Credentials).Returns(credentials); - this.permissionService = new PermissionService(); - - this.permissionService.CredentialsService = this.credentialsService.Object; - this.permissionService.Logger = this.logger.Object; + this.permissionService = new PermissionService + { + CredentialsService = this.credentialsService.Object, + Logger = this.logger.Object + }; this.resolveService = new Mock(); @@ -328,7 +329,7 @@ public void VerifySameAsContainerPermissionAutorization(Thing containerThing, Th /// /// Different Cases we want to check access rights for /// - /// an of type + /// an of type object[] /// containing the method's parameters. public static IEnumerable TestCases() { diff --git a/CometServer.Tests/Health/CometHasStartedServiceTestFixture.cs b/CometServer.Tests/Health/CometHasStartedServiceTestFixture.cs index faee8235..bf173f6b 100644 --- a/CometServer.Tests/Health/CometHasStartedServiceTestFixture.cs +++ b/CometServer.Tests/Health/CometHasStartedServiceTestFixture.cs @@ -31,8 +31,6 @@ namespace CometServer.Tests.Health using Microsoft.Extensions.Caching.Memory; - using Moq; - using NUnit.Framework; [TestFixture] diff --git a/CometServer.Tests/OperationProcessorTestFixture.cs b/CometServer.Tests/OperationProcessorTestFixture.cs index 8f2ada8c..a619a927 100644 --- a/CometServer.Tests/OperationProcessorTestFixture.cs +++ b/CometServer.Tests/OperationProcessorTestFixture.cs @@ -86,16 +86,16 @@ public class OperationProcessorTestFixture private readonly IRequestUtils requestUtils = new RequestUtils { QueryParameters = new QueryParameters() }; - private readonly OperationSideEffectProcessor operationSideEffectProcessor = new OperationSideEffectProcessor(new List()); + private readonly OperationSideEffectProcessor operationSideEffectProcessor = new(new List()); - private readonly SimpleQuantityKindMetaInfo simpleQuantityKindMetaInfo = new SimpleQuantityKindMetaInfo(); + private readonly SimpleQuantityKindMetaInfo simpleQuantityKindMetaInfo = new(); - private readonly QuantityKindMetaInfo quantityKindMetaInfo = new QuantityKindMetaInfo(); - private readonly ThingMetaInfo thingMetaInfo = new ThingMetaInfo(); + private readonly QuantityKindMetaInfo quantityKindMetaInfo = new(); + private readonly ThingMetaInfo thingMetaInfo = new (); - private readonly EngineeringModelMetaInfo engineeringModelMetaInfo = new EngineeringModelMetaInfo(); + private readonly EngineeringModelMetaInfo engineeringModelMetaInfo = new (); - private readonly Dictionary fileStore = new Dictionary(); + private readonly Dictionary fileStore = new(); private Mock mockedMetaInfoProvider; private Mock transactionManager; @@ -114,16 +114,20 @@ public void TestSetup() this.operationSideEffectProcessor.RequestUtils = this.requestUtils; this.operationSideEffectProcessor.MetaInfoProvider = this.mockedMetaInfoProvider.Object; - this.operationProcessor = new OperationProcessor(); - this.operationProcessor.OperationSideEffectProcessor = this.operationSideEffectProcessor; - this.operationProcessor.MetaInfoProvider = this.mockedMetaInfoProvider.Object; - + this.operationProcessor = new OperationProcessor + { + OperationSideEffectProcessor = this.operationSideEffectProcessor, + MetaInfoProvider = this.mockedMetaInfoProvider.Object + }; + this.serviceProvider = new Mock(); this.resolveService = new Mock(); - var copyservice = new CopySourceService(); - copyservice.TransactionManager = this.transactionManager.Object; - copyservice.ServiceProvider = this.serviceProvider.Object; + var copyservice = new CopySourceService + { + TransactionManager = this.transactionManager.Object, + ServiceProvider = this.serviceProvider.Object + }; this.operationProcessor.CopySourceService = copyservice; this.operationProcessor.ServiceProvider = this.serviceProvider.Object; @@ -555,8 +559,11 @@ public void VerifyCopyElementDefWorks() parameter2.ValueSet.Add(pvs2.Iid); sourceElementDef2.Parameter.Add(parameter2.Iid); - var override2 = new ParameterOverride(Guid.NewGuid(), 1); - override2.Parameter = parameter2.Iid; + var override2 = new ParameterOverride(Guid.NewGuid(), 1) + { + Parameter = parameter2.Iid + }; + var ovs = new ParameterOverrideValueSet(Guid.NewGuid(), 1) {ParameterValueSet = pvs2.Iid}; override2.ValueSet.Add(ovs.Iid); sourceUsage1.ParameterOverride.Add(override2.Iid); @@ -761,12 +768,12 @@ public void VerifyCopyElementDefWorks() } } - public class TestSourceService : ServiceBase, IPersistService, IModelReferenceDataLibraryService, IParameterValueSetService + public class TestSourceService : ServiceBase, IModelReferenceDataLibraryService, IParameterValueSetService { private IReadOnlyList dtos; private string type; - private readonly List writtenThings = new List(); + private readonly List writtenThings = new(); public TestSourceService(IReadOnlyList dtos, string type) { @@ -879,7 +886,7 @@ public IEnumerable QueryReferenceDataLibrary(NpgsqlTransac public class TestParameterDao : IParameterDao { - private List writtenThings = new List(); + private List writtenThings = new(); public int WrittenThingCount => this.writtenThings.Count; public IEnumerable Read(NpgsqlTransaction transaction, string partition, IEnumerable ids = null, bool isCachedDtoReadEnabledAndInstant = false, DateTime? instant = null) @@ -954,7 +961,7 @@ public string GetValueTypeSet() public class TestParameterOverrideDao : IParameterOverrideDao { - private List writtenThings = new List(); + private List writtenThings = new(); public int WrittenThingCount => this.writtenThings.Count; public IEnumerable Read(NpgsqlTransaction transaction, string partition, IEnumerable ids = null, bool isCachedDtoReadEnabledAndInstant = false, DateTime? instant = null) @@ -1029,7 +1036,7 @@ public string GetValueTypeSet() public class TestElementDefinitionDao : IElementDefinitionDao { - private List writtenThings = new List(); + private List writtenThings = new(); public int WrittenThingCount => this.writtenThings.Count; diff --git a/CometServer.Tests/Services/BusinessLogic/ChainOfRdlComputationServiceTestFixture.cs b/CometServer.Tests/Services/BusinessLogic/ChainOfRdlComputationServiceTestFixture.cs index 58921955..2328012f 100644 --- a/CometServer.Tests/Services/BusinessLogic/ChainOfRdlComputationServiceTestFixture.cs +++ b/CometServer.Tests/Services/BusinessLogic/ChainOfRdlComputationServiceTestFixture.cs @@ -47,11 +47,11 @@ namespace CometServer.Tests.Services.BusinessLogic [TestFixture] public class ChainOfRdlComputationServiceTestFixture { - private Mock> logger = new Mock>(); + private Mock> logger = new (); - private Mock modelReferenceDataLibraryDao = new Mock(); + private Mock modelReferenceDataLibraryDao = new (); - private Mock siteReferenceDataLibraryDao = new Mock(); + private Mock siteReferenceDataLibraryDao = new (); private List modelReferenceDataLibraries; diff --git a/CometServer.Tests/Services/BusinessLogic/DefaultValueArrayFactoryTestFixture.cs b/CometServer.Tests/Services/BusinessLogic/DefaultValueArrayFactoryTestFixture.cs index a8de70df..235a53df 100644 --- a/CometServer.Tests/Services/BusinessLogic/DefaultValueArrayFactoryTestFixture.cs +++ b/CometServer.Tests/Services/BusinessLogic/DefaultValueArrayFactoryTestFixture.cs @@ -62,7 +62,7 @@ public class DefaultValueArrayFactoryTestFixture private Dictionary independentParameterTypeAssignments; private Dictionary dependentParameterTypeAssignments; - private Mock> logger = new Mock>(); + private Mock> logger = new (); private Mock cachedReferenceDataService; private Mock secutrityContext; private NpgsqlTransaction transaction; @@ -117,7 +117,7 @@ private void PopulateParameterTypes() var orderedItemY = new OrderedItem { K = 2, V = y.Iid }; var orderedItemZ = new OrderedItem { K = 3, V = z.Iid }; - var vector = new CDP4Common.DTO.ArrayParameterType(this.vectorIid, 0); + var vector = new ArrayParameterType(this.vectorIid, 0); vector.Component.Add(orderedItemX); vector.Component.Add(orderedItemY); vector.Component.Add(orderedItemZ); @@ -136,7 +136,7 @@ private void PopulateParameterTypes() var jaggedOrderedItemOne = new OrderedItem { K = 1, V = jaggedComponentOne.Iid }; var jaggedOrderedItemTwo = new OrderedItem { K = 1, V = jaggedComponentTwo.Iid }; - var jaggedArray = new CDP4Common.DTO.CompoundParameterType(this.jaggedArrayIid, 0); + var jaggedArray = new CompoundParameterType(this.jaggedArrayIid, 0); jaggedArray.Component.Add(jaggedOrderedItemOne); jaggedArray.Component.Add(jaggedOrderedItemTwo); @@ -173,7 +173,7 @@ public void VerifyThatScalarParameterTypeReturnsExpectedValueArray() var value = new List() {"-"}; var expectedValueArray = new ValueArray(value); - this.defaultValueArrayFactory.Load(transaction, this.secutrityContext.Object); + this.defaultValueArrayFactory.Load(this.transaction, this.secutrityContext.Object); this.cachedReferenceDataService.Verify(x => x.QueryParameterTypes(this.transaction, this.secutrityContext.Object), Times.Exactly(1)); this.cachedReferenceDataService.Verify(x => x.QueryParameterTypeComponents(this.transaction, this.secutrityContext.Object), Times.Exactly(1)); @@ -195,7 +195,7 @@ public void VerifyThatArrayParameterTypeReturnsExpectedValueArray() var value = new List() { "-", "-", "-" }; var expectedValueArray = new ValueArray(value); - this.defaultValueArrayFactory.Load(transaction, this.secutrityContext.Object); + this.defaultValueArrayFactory.Load(this.transaction, this.secutrityContext.Object); this.cachedReferenceDataService.Verify(x => x.QueryParameterTypes(this.transaction, this.secutrityContext.Object), Times.Exactly(1)); this.cachedReferenceDataService.Verify(x => x.QueryParameterTypeComponents(this.transaction, this.secutrityContext.Object), Times.Exactly(1)); @@ -217,7 +217,7 @@ public void VerifyThatJaggedArrayReturnsExpectedValueArray() var value = new List() { "-", "-", "-", "-" }; var expectedValueArray = new ValueArray(value); - this.defaultValueArrayFactory.Load(transaction, this.secutrityContext.Object); + this.defaultValueArrayFactory.Load(this.transaction, this.secutrityContext.Object); this.cachedReferenceDataService.Verify(x => x.QueryParameterTypes(this.transaction, this.secutrityContext.Object), Times.Exactly(1)); this.cachedReferenceDataService.Verify(x => x.QueryParameterTypeComponents(this.transaction, this.secutrityContext.Object), Times.Exactly(1)); @@ -239,7 +239,7 @@ public void VerifyThatAComponentlessCompoundReturnsAnEmptyValueArray() var value = new List(0); var expectedValueArray = new ValueArray(value); - this.defaultValueArrayFactory.Load(transaction, this.secutrityContext.Object); + this.defaultValueArrayFactory.Load(this.transaction, this.secutrityContext.Object); this.cachedReferenceDataService.Verify(x => x.QueryParameterTypes(this.transaction, this.secutrityContext.Object), Times.Exactly(1)); this.cachedReferenceDataService.Verify(x => x.QueryParameterTypeComponents(this.transaction, this.secutrityContext.Object), Times.Exactly(1)); diff --git a/CometServer.Tests/Services/BusinessLogic/ParameterSubscriptionValueSetFactoryTestFixture.cs b/CometServer.Tests/Services/BusinessLogic/ParameterSubscriptionValueSetFactoryTestFixture.cs index b9caff1f..64c7a857 100644 --- a/CometServer.Tests/Services/BusinessLogic/ParameterSubscriptionValueSetFactoryTestFixture.cs +++ b/CometServer.Tests/Services/BusinessLogic/ParameterSubscriptionValueSetFactoryTestFixture.cs @@ -68,7 +68,7 @@ public void VerifyThatParameterValueSetIsCreatedWithDefaultValues() var parameterSubscriptionValueSet = this.parameterSubscriptionValueSetFactory.CreateWithDefaultValueArray(subscribedValueSetIid, this.defaultValueArray); Assert.That(parameterSubscriptionValueSet.SubscribedValueSet, Is.EqualTo(subscribedValueSetIid)); - Assert.That(parameterSubscriptionValueSet.Manual, Is.EqualTo(defaultValueArray)); + Assert.That(parameterSubscriptionValueSet.Manual, Is.EqualTo(this.defaultValueArray)); Assert.That(parameterSubscriptionValueSet.ValueSwitch, Is.EqualTo(CDP4Common.EngineeringModelData.ParameterSwitchKind.MANUAL)); } diff --git a/CometServer.Tests/Services/JsonExchangeFileReaderTestFixture.cs b/CometServer.Tests/Services/JsonExchangeFileReaderTestFixture.cs index e8cec575..a0bf092a 100644 --- a/CometServer.Tests/Services/JsonExchangeFileReaderTestFixture.cs +++ b/CometServer.Tests/Services/JsonExchangeFileReaderTestFixture.cs @@ -26,7 +26,6 @@ namespace CometServer.Tests.Services { using System; using System.IO; - using System.Linq; using CDP4Common.DTO; diff --git a/CometServer.Tests/Services/Resolver/ResolveServiceTestFixture.cs b/CometServer.Tests/Services/Resolver/ResolveServiceTestFixture.cs index c61c0ce6..c0929719 100644 --- a/CometServer.Tests/Services/Resolver/ResolveServiceTestFixture.cs +++ b/CometServer.Tests/Services/Resolver/ResolveServiceTestFixture.cs @@ -88,15 +88,15 @@ public void TestSetup() this.engineeringModelIid = Guid.NewGuid(); - this.siteDirectoryInfo = new DtoInfo(typeof(SiteDirectory).Name, Guid.NewGuid()); - this.simpleQuantityKindInfo = new DtoInfo(typeof(SimpleQuantityKind).Name, Guid.NewGuid()); + this.siteDirectoryInfo = new DtoInfo(nameof(SiteDirectory), Guid.NewGuid()); + this.simpleQuantityKindInfo = new DtoInfo(nameof(SimpleQuantityKind), Guid.NewGuid()); - this.engineeringModelInfo = new DtoInfo(typeof(EngineeringModel).Name, Guid.NewGuid()); - this.bookInfo = new DtoInfo(typeof(Book).Name, Guid.NewGuid()); + this.engineeringModelInfo = new DtoInfo(nameof(EngineeringModel), Guid.NewGuid()); + this.bookInfo = new DtoInfo(nameof(Book), Guid.NewGuid()); - this.optionInfo = new DtoInfo(typeof(Option).Name, Guid.NewGuid()); - this.parameterInfo = new DtoInfo(typeof(Parameter).Name, Guid.NewGuid()); - this.aliasInfo = new DtoInfo(typeof(Alias).Name, Guid.NewGuid()); + this.optionInfo = new DtoInfo(nameof(Option), Guid.NewGuid()); + this.parameterInfo = new DtoInfo(nameof(Parameter), Guid.NewGuid()); + this.aliasInfo = new DtoInfo(nameof(Alias), Guid.NewGuid()); } [Test] @@ -106,8 +106,8 @@ public void VerifyStaticSiteDirectoryConceptPartitionResolvement() var expectedPartition = partitionString; var unresolvedItems = new List { - new DtoResolveHelper(this.siteDirectoryInfo), - new DtoResolveHelper(this.simpleQuantityKindInfo), + new(this.siteDirectoryInfo), + new(this.simpleQuantityKindInfo), }; this.resolveService.ResolvePartitionStatically(partitionString, unresolvedItems); @@ -125,8 +125,8 @@ public void VerifyStaticEngineeringModelConceptPartitionResolvement() var unresolvedItems = new List { - new DtoResolveHelper(this.engineeringModelInfo), - new DtoResolveHelper(this.bookInfo), + new(this.engineeringModelInfo), + new(this.bookInfo), }; this.resolveService.ResolvePartitionStatically(partitionString, unresolvedItems); @@ -145,8 +145,8 @@ public void VerifyStaticIterationConceptPartitionResolvement() var unresolvedItems = new List { - new DtoResolveHelper(this.optionInfo), - new DtoResolveHelper(this.parameterInfo), + new(this.optionInfo), + new(this.parameterInfo), }; this.resolveService.ResolvePartitionStatically(partitionString, unresolvedItems); @@ -164,7 +164,7 @@ public void VerifyStaticIterationConceptPartitionNotFound() var unresolvedItems = new List { - new DtoResolveHelper(this.aliasInfo) + new(this.aliasInfo) }; this.resolveService.ResolvePartitionStatically(partitionString, unresolvedItems); diff --git a/CometServer.Tests/Services/Revision/RevisionResolverTestFixture.cs b/CometServer.Tests/Services/Revision/RevisionResolverTestFixture.cs index ac920355..1fa56418 100644 --- a/CometServer.Tests/Services/Revision/RevisionResolverTestFixture.cs +++ b/CometServer.Tests/Services/Revision/RevisionResolverTestFixture.cs @@ -52,11 +52,11 @@ public class RevisionResolverTestFixture private RevisionRegistryInfo revision3; private RevisionRegistryInfo revision4; private RevisionRegistryInfo revision5; - private static readonly DateTime timestamp1 = new DateTime(2020, 1, 1); - private static readonly DateTime timestamp2 = new DateTime(2020, 1, 2); - private static readonly DateTime timestamp3 = new DateTime(2020, 1, 2, 10, 0, 0); - private static readonly DateTime timestamp4 = new DateTime(2020, 1, 2, 14, 0, 0); - private static readonly DateTime timestamp5 = new DateTime(2020, 1, 3); + private static readonly DateTime timestamp1 = new(2020, 1, 1); + private static readonly DateTime timestamp2 = new(2020, 1, 2); + private static readonly DateTime timestamp3 = new(2020, 1, 2, 10, 0, 0); + private static readonly DateTime timestamp4 = new(2020, 1, 2, 14, 0, 0); + private static readonly DateTime timestamp5 = new(2020, 1, 3); [SetUp] public void TestSetup() diff --git a/CometServer.Tests/Services/ServiceBaseTestFixture.cs b/CometServer.Tests/Services/ServiceBaseTestFixture.cs index 230823df..9f39a0f0 100644 --- a/CometServer.Tests/Services/ServiceBaseTestFixture.cs +++ b/CometServer.Tests/Services/ServiceBaseTestFixture.cs @@ -40,15 +40,15 @@ namespace CometServer.Tests.Services [TestFixture] public class ServiceBaseTestFixture : ServiceBase { - ParameterTypeComponent parameterTypeComponent1 = new ParameterTypeComponent( + ParameterTypeComponent parameterTypeComponent1 = new( Guid.Parse("7c59e9ff-f673-4543-bb8b-71f32c4b2f19"), 1); - ParameterTypeComponent parameterTypeComponent2 = new ParameterTypeComponent( + ParameterTypeComponent parameterTypeComponent2 = new( Guid.Parse("fa9c0bc9-5172-483f-8ecf-6ee8b825b57f"), 1); - ParameterTypeComponent parameterTypeComponent3 = new ParameterTypeComponent( + ParameterTypeComponent parameterTypeComponent3 = new( Guid.Parse("88bda1de-0b5e-4094-af0c-c51ccf15bca6"), 1); @@ -56,9 +56,9 @@ public class ServiceBaseTestFixture : ServiceBase public void Setup() { this.RequestUtils = new RequestUtils(); - this.RequestUtils.Cache.Add(parameterTypeComponent1); - this.RequestUtils.Cache.Add(parameterTypeComponent2); - this.RequestUtils.Cache.Add(parameterTypeComponent3); + this.RequestUtils.Cache.Add(this.parameterTypeComponent1); + this.RequestUtils.Cache.Add(this.parameterTypeComponent2); + this.RequestUtils.Cache.Add(this.parameterTypeComponent3); } [Test] @@ -66,19 +66,19 @@ public void VerifyThatCorrectIEnumerableIsReturnedWhenResolveFromRequestCacheIsC { var list = new List { - new OrderedItem - { + new() + { K = 1, V = Guid.Parse( "7c59e9ff-f673-4543-bb8b-71f32c4b2f19") }, - new OrderedItem + new() { K = 2, V = Guid.Parse( "fa9c0bc9-5172-483f-8ecf-6ee8b825b57f") }, - new OrderedItem + new() { K = 3, V = Guid.Parse( @@ -90,9 +90,9 @@ public void VerifyThatCorrectIEnumerableIsReturnedWhenResolveFromRequestCacheIsC var outputResolvedList = new List { - new OrderedItem { K = 3, V = parameterTypeComponent3 }, - new OrderedItem { K = 2, V = parameterTypeComponent2 }, - new OrderedItem { K = 1, V = parameterTypeComponent1 } + new() { K = 3, V = this.parameterTypeComponent3 }, + new() { K = 2, V = this.parameterTypeComponent2 }, + new() { K = 1, V = this.parameterTypeComponent1 } }; Assert.That(outputResolvedList, Is.EquivalentTo(resolvedList)); diff --git a/CometServer.Tests/Services/Supplemental/AccessRightKindValidationServiceTestFixture.cs b/CometServer.Tests/Services/Supplemental/AccessRightKindValidationServiceTestFixture.cs index 2b749814..a0a0be43 100644 --- a/CometServer.Tests/Services/Supplemental/AccessRightKindValidationServiceTestFixture.cs +++ b/CometServer.Tests/Services/Supplemental/AccessRightKindValidationServiceTestFixture.cs @@ -45,13 +45,10 @@ public class AccessRightKindValidationServiceTestFixture private Mock requestUtils; - private Mock metaInfoProvider; - [SetUp] public void Setup() { this.requestUtils = new Mock(); - this.metaInfoProvider = new Mock(); this.service = new AccessRightKindValidationService() { RequestUtils = this.requestUtils.Object }; } diff --git a/CometServer.Tests/Services/Supplemental/CommonFileStoreServiceTestFixture.cs b/CometServer.Tests/Services/Supplemental/CommonFileStoreServiceTestFixture.cs index 9b80b85e..39b31f30 100644 --- a/CometServer.Tests/Services/Supplemental/CommonFileStoreServiceTestFixture.cs +++ b/CometServer.Tests/Services/Supplemental/CommonFileStoreServiceTestFixture.cs @@ -28,7 +28,6 @@ namespace CometServer.Tests.Services.Supplemental using System.Collections; using System.Collections.Generic; using System.Data; - using System.Security; using CDP4Authentication; @@ -53,9 +52,9 @@ namespace CometServer.Tests.Services.Supplemental [TestFixture] public class CommonFileStoreServiceTestFixture { - private static Folder folder = new Folder(Guid.NewGuid(), 0); - private static File file = new File(Guid.NewGuid(), 0); - private static CommonFileStore commonFileStore = new CommonFileStore(Guid.NewGuid(), 0); + private static Folder folder = new(Guid.NewGuid(), 0); + private static File file = new(Guid.NewGuid(), 0); + private static CommonFileStore commonFileStore = new(Guid.NewGuid(), 0); private CommonFileStoreService commonFileStoreService; private Mock permissionService; @@ -64,7 +63,6 @@ public class CommonFileStoreServiceTestFixture private Mock transaction; private Mock transactionManager; private string engineeringModelPartitionName; - private EngineeringModel engineeringModel; [SetUp] public void Setup() @@ -91,14 +89,6 @@ public void Setup() commonFileStore.Folder.Clear(); commonFileStore.Folder.Add(folder.Iid); - this.engineeringModel = new EngineeringModel(Guid.NewGuid(), 0) - { - CommonFileStore = new List - { - commonFileStore.Iid - } - }; - this.permissionService.Setup(x => x.IsOwner(It.IsAny(), commonFileStore)).Returns(true); this.permissionService.Setup(x => x.IsOwner(It.IsAny(), folder)).Returns(true); this.permissionService.Setup(x => x.IsOwner(It.IsAny(), file)).Returns(true); @@ -195,13 +185,5 @@ public static IEnumerable TestWriteCases() yield return new object[] { commonFileStore, false }; yield return new object[] { new ElementDefinition(), true }; } - - public static IEnumerable TestReadCases() - { - yield return new object[] { file, false }; - yield return new object[] { folder, false }; - yield return new object[] { commonFileStore, false }; - yield return new object[] { new ElementDefinition(), true }; - } } } diff --git a/CometServer.Tests/Services/Supplemental/DomainFileStoreServiceTestFixture.cs b/CometServer.Tests/Services/Supplemental/DomainFileStoreServiceTestFixture.cs index a316d51b..98f44161 100644 --- a/CometServer.Tests/Services/Supplemental/DomainFileStoreServiceTestFixture.cs +++ b/CometServer.Tests/Services/Supplemental/DomainFileStoreServiceTestFixture.cs @@ -54,9 +54,9 @@ namespace CometServer.Tests.Services.Supplemental [TestFixture] public class DomainFileStoreServiceTestFixture { - private static Folder folder = new Folder(Guid.NewGuid(), 0); - private static File file = new File(Guid.NewGuid(), 0); - private static DomainFileStore domainFileStore = new DomainFileStore(Guid.NewGuid(), 0); + private static Folder folder = new(Guid.NewGuid(), 0); + private static File file = new(Guid.NewGuid(), 0); + private static DomainFileStore domainFileStore = new(Guid.NewGuid(), 0); private DomainFileStoreService domainFileStoreService; private Mock permissionService; @@ -256,13 +256,5 @@ public static IEnumerable TestWriteCases() yield return new object[] { domainFileStore, false }; yield return new object[] { new ElementDefinition(), true }; } - - public static IEnumerable TestReadCases() - { - yield return new object[] { file, false }; - yield return new object[] { folder, false }; - yield return new object[] { domainFileStore, false }; - yield return new object[] { new ElementDefinition(), true }; - } } } diff --git a/CometServer.Tests/Services/Supplemental/PermissionInstanceFilterServiceTestFixture.cs b/CometServer.Tests/Services/Supplemental/PermissionInstanceFilterServiceTestFixture.cs index 3d8c9220..e795a5a2 100644 --- a/CometServer.Tests/Services/Supplemental/PermissionInstanceFilterServiceTestFixture.cs +++ b/CometServer.Tests/Services/Supplemental/PermissionInstanceFilterServiceTestFixture.cs @@ -105,8 +105,8 @@ public void Setup() this.personRoles = new List { - new PersonRole - { + new() + { Iid = Guid.NewGuid(), RevisionNumber = 1, PersonPermission = @@ -123,8 +123,8 @@ public void Setup() }; this.participantRoles = new List { - new ParticipantRole - { + new() + { Iid = Guid.NewGuid(), RevisionNumber = 1, ParticipantPermission = diff --git a/CometServer.Tests/SideEffects/ActualFiniteStateListSideEffectTestFixture.cs b/CometServer.Tests/SideEffects/ActualFiniteStateListSideEffectTestFixture.cs index fde87885..169ee25c 100644 --- a/CometServer.Tests/SideEffects/ActualFiniteStateListSideEffectTestFixture.cs +++ b/CometServer.Tests/SideEffects/ActualFiniteStateListSideEffectTestFixture.cs @@ -43,7 +43,7 @@ namespace CometServer.Tests.SideEffects [TestFixture] public class ActualFiniteStateListSideEffectTestFixture { - private ActualFiniteStateListSideEffect sideEffect = new ActualFiniteStateListSideEffect(); + private ActualFiniteStateListSideEffect sideEffect = new(); private NpgsqlTransaction transaction; @@ -107,9 +107,7 @@ public class ActualFiniteStateListSideEffectTestFixture private ParameterSubscriptionValueSet psvs21; private ParameterSubscriptionValueSet psvs22; - private Guid owner = Guid.NewGuid(); - - private List initValue = new List { "init" }; + private List initValue = new() { "init" }; [SetUp] public void Setup() diff --git a/CometServer.Tests/SideEffects/ArrayParameterTypeSideEffectTestFixture.cs b/CometServer.Tests/SideEffects/ArrayParameterTypeSideEffectTestFixture.cs index c2d6835f..95f3861c 100644 --- a/CometServer.Tests/SideEffects/ArrayParameterTypeSideEffectTestFixture.cs +++ b/CometServer.Tests/SideEffects/ArrayParameterTypeSideEffectTestFixture.cs @@ -242,8 +242,8 @@ public void VerifyThatExceptionIsThrownWhenParameterTypeComponentLeadsToCircular TestKey, new List { - new OrderedItem - { + new() + { K = 3, V = this .parameterTypeComponentC @@ -272,8 +272,8 @@ public void VerifyThatExceptionIsNotThrownWhenParameterTypeComponentDoesNotLeadT TestKey, new List { - new OrderedItem - { + new() + { K = 4, V = this .parameterTypeComponentD diff --git a/CometServer.Tests/SideEffects/BooleanExpressionSideEffectTestFixture.cs b/CometServer.Tests/SideEffects/BooleanExpressionSideEffectTestFixture.cs index b8b87f15..568e616c 100644 --- a/CometServer.Tests/SideEffects/BooleanExpressionSideEffectTestFixture.cs +++ b/CometServer.Tests/SideEffects/BooleanExpressionSideEffectTestFixture.cs @@ -42,7 +42,7 @@ namespace CometServer.Tests.SideEffects using NUnit.Framework; /// - /// Suite of tests for the + /// Suite of tests for the /// [TestFixture] public class BooleanExpressionSideEffectTestFixture diff --git a/CometServer.Tests/SideEffects/CompoundParameterTypeSideEffectTestFixture.cs b/CometServer.Tests/SideEffects/CompoundParameterTypeSideEffectTestFixture.cs index 57c1f227..1996266c 100644 --- a/CometServer.Tests/SideEffects/CompoundParameterTypeSideEffectTestFixture.cs +++ b/CometServer.Tests/SideEffects/CompoundParameterTypeSideEffectTestFixture.cs @@ -223,8 +223,8 @@ public void VerifyThatExceptionIsThrownWhenParameterTypeComponentLeadsToCircular TestKey, new List { - new OrderedItem - { + new() + { K = 3, V = this .parameterTypeComponentC @@ -253,8 +253,8 @@ public void VerifyThatExceptionIsNotThrownWhenParameterTypeComponentDoesNotLeadT TestKey, new List { - new OrderedItem - { + new() + { K = 4, V = this .parameterTypeComponentD diff --git a/CometServer.Tests/SideEffects/DerivedQuantityKindSideEffectTestFixture.cs b/CometServer.Tests/SideEffects/DerivedQuantityKindSideEffectTestFixture.cs index ecee5c92..dc744a46 100644 --- a/CometServer.Tests/SideEffects/DerivedQuantityKindSideEffectTestFixture.cs +++ b/CometServer.Tests/SideEffects/DerivedQuantityKindSideEffectTestFixture.cs @@ -218,7 +218,7 @@ public void VerifyOutOfRdlChainError() { var rawUpdateInfo = new ClasslessDTO { - { "QuantityKindFactor", new List { new OrderedItem { K = 2, V = this.derivedQkOutsideRdlFactor.Iid } } } + { "QuantityKindFactor", new List { new() { K = 2, V = this.derivedQkOutsideRdlFactor.Iid } } } }; Assert.Throws( @@ -236,7 +236,7 @@ public void VerifyCircularDependencyError() { var rawUpdateInfo = new ClasslessDTO { - { "QuantityKindFactor", new List { new OrderedItem { K = 2, V = this.derivedQkCyclicFactor.Iid } } } + { "QuantityKindFactor", new List { new() { K = 2, V = this.derivedQkCyclicFactor.Iid } } } }; Assert.Throws( @@ -254,7 +254,7 @@ public void VerifyNoCircularDependency() { var rawUpdateInfo = new ClasslessDTO { - { "QuantityKindFactor", new List { new OrderedItem { K = 2, V = this.derivedQkFactor.Iid } } } + { "QuantityKindFactor", new List { new() { K = 2, V = this.derivedQkFactor.Iid } } } }; Assert.DoesNotThrow( diff --git a/CometServer.Tests/SideEffects/DerivedUnitSideEffectTestFixture.cs b/CometServer.Tests/SideEffects/DerivedUnitSideEffectTestFixture.cs index bdee72cb..a7c61294 100644 --- a/CometServer.Tests/SideEffects/DerivedUnitSideEffectTestFixture.cs +++ b/CometServer.Tests/SideEffects/DerivedUnitSideEffectTestFixture.cs @@ -183,7 +183,7 @@ public void VerifyThatExceptionIsThrownWhenUnitFactorLeadsToCircularDependency() this.siteReferenceDataLibraryService.Object }; - this.rawUpdateInfo = new ClasslessDTO() { { TestKey, new List { new OrderedItem{K = 3, V = this.unitFactorC.Iid} } } }; + this.rawUpdateInfo = new ClasslessDTO() { { TestKey, new List { new() {K = 3, V = this.unitFactorC.Iid} } } }; Assert.Throws( () => this.sideEffect.BeforeUpdate( @@ -206,7 +206,7 @@ public void VerifyThatExceptionIsNotThrownWhenUnitFactorDoesNotLeadToCircularDep this.siteReferenceDataLibraryService.Object }; - this.rawUpdateInfo = new ClasslessDTO() { { TestKey, new List { new OrderedItem { K = 4, V = this.unitFactorD.Iid } } } }; + this.rawUpdateInfo = new ClasslessDTO() { { TestKey, new List { new() { K = 4, V = this.unitFactorD.Iid } } } }; Assert.DoesNotThrow( () => this.sideEffect.BeforeUpdate( diff --git a/CometServer.Tests/SideEffects/EngineeringModelSetupSideEffectTestFixture.cs b/CometServer.Tests/SideEffects/EngineeringModelSetupSideEffectTestFixture.cs index d8222271..d807f2b9 100644 --- a/CometServer.Tests/SideEffects/EngineeringModelSetupSideEffectTestFixture.cs +++ b/CometServer.Tests/SideEffects/EngineeringModelSetupSideEffectTestFixture.cs @@ -30,8 +30,6 @@ namespace CometServer.Tests.SideEffects using CDP4Common.DTO; using CDP4Common.Types; - using CDP4Authentication; - using CDP4Orm.Dao; using CometServer.Authorization; @@ -53,7 +51,6 @@ namespace CometServer.Tests.SideEffects [TestFixture] public class EngineeringModelSetupSideEffectTestFixture { - private AuthenticationPerson authenticatedPerson; private EngineeringModelSetupSideEffect engineeringModelSetupSideEffect; private ModelCreatorManager modelCreatorManager; @@ -77,8 +74,6 @@ public class EngineeringModelSetupSideEffectTestFixture [SetUp] public void Setup() { - this.authenticatedPerson = new AuthenticationPerson(Guid.NewGuid(), 1) { DefaultDomain = Guid.NewGuid() }; - this.iterationService = new Mock(); this.iterationSetupService = new Mock(); this.engineeringModelService = new Mock(); diff --git a/CometServer.Tests/SideEffects/GlossarySideEffectTestFixture.cs b/CometServer.Tests/SideEffects/GlossarySideEffectTestFixture.cs index 229a6d4c..a761a213 100644 --- a/CometServer.Tests/SideEffects/GlossarySideEffectTestFixture.cs +++ b/CometServer.Tests/SideEffects/GlossarySideEffectTestFixture.cs @@ -105,7 +105,7 @@ public void VerifyThatIfTheGlossaryIsNotDeprecateNoServiceCallsAreMade() this.glossarySideEffect.AfterUpdate(this.glossary, null, originalThing, this.npgsqlTransaction, "partition", this.securityContext.Object); - this.permittingPermissionService.Verify(x => x.CanWrite(this.npgsqlTransaction, originalThing, typeof(Term).Name, "partition", "update", this.securityContext.Object), Times.Never); + this.permittingPermissionService.Verify(x => x.CanWrite(this.npgsqlTransaction, originalThing, nameof(Term), "partition", "update", this.securityContext.Object), Times.Never); this.termService.Verify(x => x.Get(this.npgsqlTransaction, "partition", this.glossary.Term, this.securityContext.Object), Times.Never); @@ -123,7 +123,7 @@ public void VerifyThatIfThereAreNoTermsInTheGlossaryNoServiceCalssAreMade() this.glossarySideEffect.AfterUpdate(this.glossary, null, originalThing, this.npgsqlTransaction, "partition", this.securityContext.Object); - this.permittingPermissionService.Verify(x => x.CanWrite(this.npgsqlTransaction, originalThing, typeof(Term).Name, "partition", "update", this.securityContext.Object), Times.Never); + this.permittingPermissionService.Verify(x => x.CanWrite(this.npgsqlTransaction, originalThing, nameof(Term), "partition", "update", this.securityContext.Object), Times.Never); this.termService.Verify(x => x.Get(this.npgsqlTransaction, "partition", this.glossary.Term, this.securityContext.Object), Times.Never); @@ -142,7 +142,7 @@ public void VerifyThatIfNoWritePermissionsExistForTermNoTermServiceCallsAreMade( this.glossarySideEffect.AfterUpdate(this.glossary, null, originalThing, this.npgsqlTransaction, "partition", this.securityContext.Object); - this.denyingPermissionService.Verify(x => x.CanWrite(this.npgsqlTransaction, originalThing, typeof(Term).Name, "partition", "update", this.securityContext.Object), Times.Once); + this.denyingPermissionService.Verify(x => x.CanWrite(this.npgsqlTransaction, originalThing, nameof(Term), "partition", "update", this.securityContext.Object), Times.Once); this.termService.Verify(x => x.UpdateConcept(this.npgsqlTransaction, "partition", It.IsAny(), It.IsAny()), Times.Never); } @@ -169,7 +169,7 @@ public void VerifyThatTheTermServiceIsInvokedToUpdateTerms() this.glossarySideEffect.AfterUpdate(this.glossary, null, originalThing, this.npgsqlTransaction, "partition", this.securityContext.Object); - this.permittingPermissionService.Verify(x => x.CanWrite(this.npgsqlTransaction, originalThing, typeof(Term).Name, "partition", "update", this.securityContext.Object), Times.Once); + this.permittingPermissionService.Verify(x => x.CanWrite(this.npgsqlTransaction, originalThing, nameof(Term), "partition", "update", this.securityContext.Object), Times.Once); this.termService.Verify(x => x.UpdateConcept(this.npgsqlTransaction, "partition", It.IsAny(), It.IsAny()), Times.Exactly(2)); } diff --git a/CometServer.Tests/SideEffects/IterationSetupSideEffectTestFixture.cs b/CometServer.Tests/SideEffects/IterationSetupSideEffectTestFixture.cs index 39daa60f..c7cbfb21 100644 --- a/CometServer.Tests/SideEffects/IterationSetupSideEffectTestFixture.cs +++ b/CometServer.Tests/SideEffects/IterationSetupSideEffectTestFixture.cs @@ -90,8 +90,8 @@ public void Setup() this.iterationSetupSideEffect.RevisionService = this.mockedRevisionService.Object; var returnedEngineeringModels = new List { this.engineeringModel }; - var returnedIterations = new List { new Iteration(Guid.NewGuid(), 1) }; - var returnedIterationSetups = new List { new IterationSetup(Guid.NewGuid(), 1) }; + var returnedIterations = new List { new(Guid.NewGuid(), 1) }; + var returnedIterationSetups = new List { new(Guid.NewGuid(), 1) }; this.mockedIterationSetupService.Setup(x => x.GetShallow(It.IsAny(), It.IsAny(), It.IsAny>(), this.mockedSecurityContext.Object)).Returns(returnedIterationSetups); this.mockedIterationSetupService.Setup(x => x.UpdateConcept(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())).Returns(true); diff --git a/CometServer.Tests/SideEffects/OptionSideEffectTestFixture.cs b/CometServer.Tests/SideEffects/OptionSideEffectTestFixture.cs index 4807590f..1b60ea7b 100644 --- a/CometServer.Tests/SideEffects/OptionSideEffectTestFixture.cs +++ b/CometServer.Tests/SideEffects/OptionSideEffectTestFixture.cs @@ -99,7 +99,7 @@ public void SetUp() this.option2 = new Option(Guid.NewGuid(), 0); this.options = new List /// - /// the username of the that is to be authenticated + /// the username of the that is to be authenticated /// /// - /// the password of the that is to be authenticated + /// the password of the that is to be authenticated /// /// an instance of or null if not found /// diff --git a/CometServer/Authorization/CredentialsService.cs b/CometServer/Authorization/CredentialsService.cs index 7e4d4f92..20354e79 100644 --- a/CometServer/Authorization/CredentialsService.cs +++ b/CometServer/Authorization/CredentialsService.cs @@ -38,8 +38,7 @@ namespace CometServer.Authorization using CDP4Orm.Dao.Authentication; using CometServer.Exceptions; - using CometServer.Services; - + using Microsoft.Extensions.Logging; using Npgsql; diff --git a/CometServer/Authorization/ICredentialsService.cs b/CometServer/Authorization/ICredentialsService.cs index faecc3f6..3eec245e 100644 --- a/CometServer/Authorization/ICredentialsService.cs +++ b/CometServer/Authorization/ICredentialsService.cs @@ -39,7 +39,7 @@ public interface ICredentialsService public Credentials Credentials { get; } /// - /// Resolves the username to + /// Resolves the username to /// /// /// The current transaction to the database. diff --git a/CometServer/Authorization/OrganizationalParticipationResolverService.cs b/CometServer/Authorization/OrganizationalParticipationResolverService.cs index cf1c706b..41ab3f62 100644 --- a/CometServer/Authorization/OrganizationalParticipationResolverService.cs +++ b/CometServer/Authorization/OrganizationalParticipationResolverService.cs @@ -26,7 +26,6 @@ namespace CometServer.Authorization { using System; using System.Collections.Generic; - using System.Diagnostics; using System.Linq; using CDP4Common.CommonData; diff --git a/CometServer/AutoGenServices/ActionItemService.cs b/CometServer/AutoGenServices/ActionItemService.cs index 30743989..75f3e935 100644 --- a/CometServer/AutoGenServices/ActionItemService.cs +++ b/CometServer/AutoGenServices/ActionItemService.cs @@ -34,10 +34,13 @@ namespace CometServer.Services using System.Collections.Generic; using System.Linq; using System.Security; + using CDP4Common.DTO; + using CDP4Orm.Dao; + using CometServer.Services.Authorization; - using Microsoft.Extensions.Logging; + using Npgsql; /// diff --git a/CometServer/ChangeNotification/ChangeNoticationService.cs b/CometServer/ChangeNotification/ChangeNoticationService.cs index 8470688e..b9f12fc9 100644 --- a/CometServer/ChangeNotification/ChangeNoticationService.cs +++ b/CometServer/ChangeNotification/ChangeNoticationService.cs @@ -128,7 +128,7 @@ public async Task Execute() var startDateTime = endDateTime.AddDays(-7); var htmlStringBuilder = new StringBuilder(); var textStringBuilder = new StringBuilder(); - var subject = $"Weekly Changelog from COMET server"; + var subject = "Weekly Changelog from COMET server"; htmlStringBuilder.AppendLine($"

{subject}
{startDateTime:R} - {endDateTime:R}

"); textStringBuilder.AppendLine($"{subject}\n{startDateTime:R} - {endDateTime:R}"); diff --git a/CometServer/Configuration/AppConfig.cs b/CometServer/Configuration/AppConfig.cs index 67ac50df..0e74a92f 100644 --- a/CometServer/Configuration/AppConfig.cs +++ b/CometServer/Configuration/AppConfig.cs @@ -99,7 +99,7 @@ public AppConfig(IConfiguration configuration) public ServiceMessagingConfig ServiceMessagingConfig { get; set; } /// - /// Gets or sets the configuration for managing long running s + /// Gets or sets the configuration for managing long running task /// public LongRunningTasksConfig LongRunningTasksConfig { get; set; } } diff --git a/CometServer/Configuration/LongRunningTasksConfig.cs b/CometServer/Configuration/LongRunningTasksConfig.cs index 2d7d904a..8141e7eb 100644 --- a/CometServer/Configuration/LongRunningTasksConfig.cs +++ b/CometServer/Configuration/LongRunningTasksConfig.cs @@ -74,7 +74,7 @@ public LongRunningTasksConfig(IConfiguration configuration) } /// - /// Gets or sets the time in seconds for which the long running s + /// Gets or sets the time in seconds for which the long running task /// are kept in the cache. If the value is set to 0 the Tasks are not cached. /// /// @@ -88,7 +88,7 @@ public int RetentionTime { if (value < 0) { - throw new ArgumentOutOfRangeException(nameof(this.RetentionTime), $"Value cannot be less than 0 seconds."); + throw new ArgumentOutOfRangeException(nameof(this.RetentionTime), "Value cannot be less than 0 seconds."); } if (value > MaxRetentionTime) @@ -101,8 +101,8 @@ public int RetentionTime } /// - /// Gets or sets the time in seconds to wait for a long running to complete. If the task takes - /// longer to complete the corresponding is returned to the caller which the user can poll to + /// Gets or sets the time in seconds to wait for a long running task to complete. If the task takes + /// longer to complete the corresponding task is returned to the caller which the user can poll to /// inspect its status. /// public int WaitTime @@ -113,7 +113,7 @@ public int WaitTime { if (value < 0) { - throw new ArgumentOutOfRangeException(nameof(this.WaitTime), $"Value cannot be less than 0 seconds."); + throw new ArgumentOutOfRangeException(nameof(this.WaitTime), "Value cannot be less than 0 seconds."); } if (value > MaxWaitTime) diff --git a/CometServer/Exceptions/BadRequestException.cs b/CometServer/Exceptions/BadRequestException.cs index eb9fb3e7..b426bde0 100644 --- a/CometServer/Exceptions/BadRequestException.cs +++ b/CometServer/Exceptions/BadRequestException.cs @@ -28,7 +28,7 @@ namespace CometServer.Exceptions /// /// The BAdRequestException error exception is an exception that indicates that a bas request was send. - /// [Serializable] public class BadRequestException : Exception { diff --git a/CometServer/Exceptions/Cdp4DatabaseDumpException.cs b/CometServer/Exceptions/Cdp4DatabaseDumpException.cs deleted file mode 100644 index d861a808..00000000 --- a/CometServer/Exceptions/Cdp4DatabaseDumpException.cs +++ /dev/null @@ -1,66 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) 2015-2024 Starion Group S.A. -// -// Author: Sam Gerené, Alex Vorobiev, Alexander van Delft, Nathanael Smiechowski, Antoine Théate -// -// This file is part of CDP4-COMET Webservices Community Edition. -// The CDP4-COMET Webservices Community Edition is the STARION implementation of ECSS-E-TM-10-25 Annex A and Annex C. -// -// The CDP4-COMET Webservices Community Edition is free software; you can redistribute it and/or -// modify it under the terms of the GNU Affero General Public -// License as published by the Free Software Foundation; either -// version 3 of the License, or (at your option) any later version. -// -// The CDP4-COMET Webservices Community Edition is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see . -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace CometServer.Exceptions -{ - using System; - - /// - /// The CDP 4 database dump exception. - /// - public class Cdp4DatabaseDumpException : Exception - { - /// - /// Initializes a new instance of the class. - /// - public Cdp4DatabaseDumpException() - { - } - - /// - /// Initializes a new instance of the class. - /// - /// - /// The exception message - /// - public Cdp4DatabaseDumpException(string message) - : base(message) - { - } - - /// - /// Initializes a new instance of the class. - /// - /// - /// The exception message - /// - /// - /// A reference to the inner - /// - public Cdp4DatabaseDumpException(string message, Exception innerException) - : base(message, innerException) - { - } - } -} \ No newline at end of file diff --git a/CometServer/Extensions/HttpRequestExtensions.cs b/CometServer/Extensions/HttpRequestExtensions.cs index c1081060..82f20cec 100644 --- a/CometServer/Extensions/HttpRequestExtensions.cs +++ b/CometServer/Extensions/HttpRequestExtensions.cs @@ -93,7 +93,7 @@ public static string QueryNameMethodPath(this HttpRequest httpRequest) userInfo = $"ANONYMOUS:{httpRequest.Method}:{httpRequest.Path}:{httpRequest.QueryString}"; } - userInfo = $"{httpRequest.HttpContext.User.Identity.Name}:{httpRequest.Method}:{httpRequest.Path}:{httpRequest.QueryString}"; + userInfo = $"{httpRequest.HttpContext.User.Identity?.Name}:{httpRequest.Method}:{httpRequest.Path}:{httpRequest.QueryString}"; return userInfo.Sanitize(); } diff --git a/CometServer/Extensions/StringExtensions.cs b/CometServer/Extensions/StringExtensions.cs index ca49b3cb..21ad9b88 100644 --- a/CometServer/Extensions/StringExtensions.cs +++ b/CometServer/Extensions/StringExtensions.cs @@ -156,28 +156,6 @@ public static bool TryParseEnumerableOfGuid(this string values, out List i } } - /// - /// Coverts the first characther of a string to lowercase - /// - /// - /// The input instring - /// - /// - /// The updated . - /// - /// - /// If supplied input is null or empty - /// - public static string FirstLetterToLower(this string input) - { - if (string.IsNullOrWhiteSpace(input)) - { - throw new ArgumentException("string can't be empty!"); - } - - return $"{input.First().ToString(CultureInfo.InvariantCulture).ToLower()}{input.Substring(1)}"; - } - /// /// Coverts the first characther of a string to uppercase /// diff --git a/CometServer/Helpers/Cdp4TransactionManager.cs b/CometServer/Helpers/Cdp4TransactionManager.cs index 78d0585e..6db27dad 100644 --- a/CometServer/Helpers/Cdp4TransactionManager.cs +++ b/CometServer/Helpers/Cdp4TransactionManager.cs @@ -192,13 +192,12 @@ public DateTime GetSessionInstant(NpgsqlTransaction transaction) /// public object GetRawSessionInstant(NpgsqlTransaction transaction) { - using (var command = new NpgsqlCommand( - "SELECT * FROM \"SiteDirectory\".\"get_session_instant\"();", - transaction.Connection, - transaction)) - { - return command.ExecuteScalar(); - } + using var command = new NpgsqlCommand( + "SELECT * FROM \"SiteDirectory\".\"get_session_instant\"();", + transaction.Connection, + transaction); + + return command.ExecuteScalar(); } /// @@ -255,26 +254,6 @@ public bool IsFullAccessEnabled() return this.isFullAccessGranted; } - /// - /// Get the session timeframe start time. - /// - /// - /// The current transaction to the database. - /// - /// - /// The . - /// - public DateTime GetSessionTimeFrameStart(NpgsqlTransaction transaction) - { - using (var command = new NpgsqlCommand( - string.Format("SELECT * FROM \"SiteDirectory\".\"{0}\"();", "get_session_timeframe_start"), - transaction.Connection, - transaction)) - { - return (DateTime)command.ExecuteScalar(); - } - } - /// /// Get the current transaction time. /// @@ -286,13 +265,11 @@ public DateTime GetSessionTimeFrameStart(NpgsqlTransaction transaction) /// public DateTime GetTransactionTime(NpgsqlTransaction transaction) { - using (var command = new NpgsqlCommand( - string.Format("SELECT * FROM \"SiteDirectory\".\"{0}\"();", "get_transaction_time"), - transaction.Connection, - transaction)) - { - return (DateTime)command.ExecuteScalar(); - } + using var command = new NpgsqlCommand("SELECT * FROM \"SiteDirectory\".get_transaction_time();", + transaction.Connection, + transaction); + + return (DateTime)command.ExecuteScalar(); } /// @@ -303,14 +280,11 @@ public DateTime GetTransactionTime(NpgsqlTransaction transaction) /// public void SetDefaultContext(NpgsqlTransaction transaction) { - var sqlBuilder = new StringBuilder(); - sqlBuilder.AppendFormat( - "UPDATE {0} SET ({1}, {2}) = ('-infinity', 'infinity');", TransactionInfoTable, PeriodStartColumn, PeriodEndColumn); + var sql = $"UPDATE {TransactionInfoTable} SET ({PeriodStartColumn}, {PeriodEndColumn}) = ('-infinity', 'infinity');"; - using (var command = new NpgsqlCommand(sqlBuilder.ToString(), transaction.Connection, transaction)) - { - command.ExecuteNonQuery(); - } + using var command = new NpgsqlCommand(sql, transaction.Connection, transaction); + + command.ExecuteNonQuery(); } /// @@ -326,12 +300,11 @@ public void SetAuditLoggingState(NpgsqlTransaction transaction, bool enabled) { var sql = $"UPDATE {TransactionInfoTable} SET {TransactionAuditEnabled} = :{TransactionAuditEnabled};"; - using (var command = new NpgsqlCommand(sql, transaction.Connection, transaction)) - { - command.Parameters.Add($"{TransactionAuditEnabled}", NpgsqlDbType.Boolean).Value = enabled; + using var command = new NpgsqlCommand(sql, transaction.Connection, transaction); - command.ExecuteNonQuery(); - } + command.Parameters.Add($"{TransactionAuditEnabled}", NpgsqlDbType.Boolean).Value = enabled; + + command.ExecuteNonQuery(); } /// @@ -412,17 +385,16 @@ private static void ApplyIterationContext(NpgsqlTransaction transaction, string var sqlBuilder = new StringBuilder(); sqlBuilder.AppendFormat("UPDATE {0} SET ({1}, {2}) =", TransactionInfoTable, PeriodStartColumn, PeriodEndColumn); sqlBuilder.Append(" (SELECT \"ValidFrom\", \"ValidTo\""); - sqlBuilder.Append($" FROM (SELECT iteration_log.\"IterationIid\", revision_from.\"Revision\" AS \"FromRevision\", revision_from.\"Instant\" AS \"ValidFrom\", revision_to.\"Revision\" AS \"ToRevision\","); + sqlBuilder.Append(" FROM (SELECT iteration_log.\"IterationIid\", revision_from.\"Revision\" AS \"FromRevision\", revision_from.\"Instant\" AS \"ValidFrom\", revision_to.\"Revision\" AS \"ToRevision\","); sqlBuilder.Append(" CASE WHEN iteration_log.\"ToRevision\" IS NULL THEN 'infinity' ELSE revision_to.\"Instant\" END AS \"ValidTo\" "); sqlBuilder.AppendFormat("FROM \"{0}\".\"IterationRevisionLog\" iteration_log LEFT JOIN \"{0}\".\"RevisionRegistry\" revision_from ON iteration_log.\"FromRevision\" = revision_from.\"Revision\" LEFT JOIN \"{0}\".\"RevisionRegistry\" revision_to ON iteration_log.\"ToRevision\" = revision_to.\"Revision\") IterationLogRevision", partition); - sqlBuilder.Append(" WHERE \"IterationIid\" = :iterationIid);"); + sqlBuilder.Append(" WHERE \"IterationIid\" = :iterationIid);"); - using (var command = new NpgsqlCommand(sqlBuilder.ToString(), transaction.Connection, transaction)) - { - command.Parameters.Add("iterationIid", NpgsqlDbType.Uuid).Value = iterationSetup.IterationIid; + using var command = new NpgsqlCommand(sqlBuilder.ToString(), transaction.Connection, transaction); - command.ExecuteNonQuery(); - } + command.Parameters.Add("iterationIid", NpgsqlDbType.Uuid).Value = iterationSetup.IterationIid; + + command.ExecuteNonQuery(); } /// @@ -489,15 +461,14 @@ private static void CreateDefaultTransactionInfoEntry(NpgsqlTransaction transact sqlBuilder.AppendFormat("INSERT INTO {0} ({1}, {2})", TransactionInfoTable, UserIdColumn, TransactionTimeColumn); sqlBuilder.AppendFormat(" VALUES({0}, statement_timestamp());", isCredentialSet ? $":{UserIdColumn}" : "null"); - using (var command = new NpgsqlCommand(sqlBuilder.ToString(), transaction.Connection, transaction)) - { - if (isCredentialSet) - { - command.Parameters.Add(UserIdColumn, NpgsqlDbType.Uuid).Value = credentials.Person.Iid; - } + using var command = new NpgsqlCommand(sqlBuilder.ToString(), transaction.Connection, transaction); - command.ExecuteNonQuery(); + if (isCredentialSet) + { + command.Parameters.Add(UserIdColumn, NpgsqlDbType.Uuid).Value = credentials.Person.Iid; } + + command.ExecuteNonQuery(); } /// @@ -520,10 +491,9 @@ private static void CreateTransactionInfoTable(NpgsqlTransaction transaction) sqlBuilder.AppendFormat("{0} boolean NOT NULL DEFAULT 'true'", TransactionAuditEnabled); sqlBuilder.Append(") ON COMMIT DROP;"); - using (var command = new NpgsqlCommand(sqlBuilder.ToString(), transaction.Connection, transaction)) - { - command.ExecuteNonQuery(); - } + using var command = new NpgsqlCommand(sqlBuilder.ToString(), transaction.Connection, transaction); + + command.ExecuteNonQuery(); } } } diff --git a/CometServer/Helpers/ICdp4TransactionManager.cs b/CometServer/Helpers/ICdp4TransactionManager.cs index ced3d2fa..c385192d 100644 --- a/CometServer/Helpers/ICdp4TransactionManager.cs +++ b/CometServer/Helpers/ICdp4TransactionManager.cs @@ -28,8 +28,6 @@ namespace CometServer.Helpers using CDP4Common.DTO; - using CDP4Orm.Dao; - using CometServer.Authorization; using Npgsql; @@ -86,17 +84,6 @@ public interface ICdp4TransactionManager /// DateTime GetTransactionTime(NpgsqlTransaction transaction); - /// - /// Get the session timeframe start time. - /// - /// - /// The transaction. - /// - /// - /// The . - /// - DateTime GetSessionTimeFrameStart(NpgsqlTransaction transaction); - /// /// Get the current session time instant. /// diff --git a/CometServer/MigrationEngine/MigrationEngine.cs b/CometServer/MigrationEngine/MigrationEngine.cs index 106ccd04..7a920b6b 100644 --- a/CometServer/MigrationEngine/MigrationEngine.cs +++ b/CometServer/MigrationEngine/MigrationEngine.cs @@ -141,15 +141,13 @@ public bool MigrateAllAtStartUp() if (doesMigrationTableExist) { - using (var appliedMigrationCmd = new NpgsqlCommand("SELECT \"version\" FROM \"SiteDirectory\".\"MigrationManagement\"", transaction.Connection, transaction)) + using var appliedMigrationCmd = new NpgsqlCommand("SELECT \"version\" FROM \"SiteDirectory\".\"MigrationManagement\"", transaction.Connection, transaction); + + using var reader = appliedMigrationCmd.ExecuteReader(); + + while (reader.Read()) { - using (var reader = appliedMigrationCmd.ExecuteReader()) - { - while (reader.Read()) - { - existingMigrations.Add(new Version(reader[0].ToString())); - } - } + existingMigrations.Add(new Version(reader[0].ToString())); } } diff --git a/CometServer/Modules/10-25/ApiBase.cs b/CometServer/Modules/10-25/ApiBase.cs index 3b96a7cb..8ddeafdd 100644 --- a/CometServer/Modules/10-25/ApiBase.cs +++ b/CometServer/Modules/10-25/ApiBase.cs @@ -195,7 +195,7 @@ protected async Task Authorize(IAppConfigService appConfigService, ICredentialsS { try { - await using var connection = new NpgsqlConnection(Services.Utils.GetConnectionString(appConfigService.AppConfig.Backtier, appConfigService.AppConfig.Backtier.Database)); + await using var connection = new NpgsqlConnection(Utils.GetConnectionString(appConfigService.AppConfig.Backtier, appConfigService.AppConfig.Backtier.Database)); await connection.OpenAsync(); @@ -289,7 +289,7 @@ public IEnumerable ProcessRequestPath(IRequestUtils requestUtils, ICdp4Tr ? topContainer : processor.GetContainmentType(containmentColl, containerProperty); - if (serviceType == typeof(Iteration).Name && !generalResourceRequest) + if (serviceType == nameof(Iteration) && !generalResourceRequest) { // switch to iteration context for further processing, // in case of Iteration generalResource request, this is handled separately below @@ -306,7 +306,7 @@ public IEnumerable ProcessRequestPath(IRequestUtils requestUtils, ICdp4Tr var container = processor.GetContainmentResource(serviceType, partition, identifier, authorizedContext); - if (serviceType == typeof(Iteration).Name) + if (serviceType == nameof(Iteration)) { // switch the partition (schema) for further processing, allowing retrieval of Iteration contained data partition = partition.Replace("EngineeringModel", "Iteration"); @@ -324,7 +324,7 @@ public IEnumerable ProcessRequestPath(IRequestUtils requestUtils, ICdp4Tr // get containment info var containmentInfo = processor.GetContainment(containmentColl, containerProperty); - if (serviceType == typeof(Iteration).Name && containmentInfo != null) + if (serviceType == nameof(Iteration) && containmentInfo != null) { // support temporal retrieval if iteration general resource is requested // should only contain 1 element @@ -523,6 +523,9 @@ protected async Task WriteMessagePackResponse(IHeaderInfoProvider headerInfoProv /// /// The resource response. /// + /// + /// The model + /// /// /// The to which the results will be written /// @@ -588,29 +591,6 @@ protected void WriteArchivedResponse(IHeaderInfoProvider headerInfoProvider, IMe this.PrepareArchivedResponse(metaInfoProvider,jsonSerializer, fileArchiveService, permissionInstanceFilterService, httpResponse.Body, resourceResponse, version, partition, routeSegments); } - /// - /// Read the current state of the top container. - /// - /// - /// The that provides the service registry - /// - /// - /// The databse transaction. - /// - /// - /// The database partition (schema) where the requested resource is stored. - /// - /// - /// The Top Container type name. - /// - /// - /// A top container instance. - /// - protected Thing GetTopContainer(Services.IServiceProvider serviceProvider, NpgsqlTransaction transaction, string partition, string topContainer) - { - return serviceProvider.MapToReadService(topContainer).GetShallow(transaction, partition, null, new RequestSecurityContext { ContainerReadAllowed = true }).FirstOrDefault(); - } - /// /// Collect and return the reference data library chain. /// @@ -800,6 +780,7 @@ private void PrepareMultiPartResponse(IMetaInfoProvider metaInfoProvider, ICdp4J { byte[] buffer; long fileSize; + using (var fileStream = fileBinaryService.RetrieveBinaryData(hash)) { fileSize = fileStream.Length; @@ -880,6 +861,7 @@ private void PrepareArchivedResponse(IMetaInfoProvider metaInfoProvider, ICdp4Js byte[] buffer; long fileSize; + using (var fileStream = new FileStream(temporaryTopFolder + ".zip", FileMode.Open)) { fileSize = fileStream.Length; diff --git a/CometServer/Modules/10-25/EngineeringModelApi.cs b/CometServer/Modules/10-25/EngineeringModelApi.cs index 8c00e287..d6f570a7 100644 --- a/CometServer/Modules/10-25/EngineeringModelApi.cs +++ b/CometServer/Modules/10-25/EngineeringModelApi.cs @@ -246,7 +246,7 @@ public override void AddRoutes(IEndpointRouteBuilder app) { this.logger.LogWarning("Request {requestToken} failed as BadRequest: a POST request may not have a wait time when it is multipart", requestToken); - this.CometTaskService.AddOrUpdateTask(cometTask, finishedAt: DateTime.Now, statusKind: StatusKind.FAILED, error: $"BAD REQUEST - a POST request may not have a wait time when it is multipart"); + this.CometTaskService.AddOrUpdateTask(cometTask, finishedAt: DateTime.Now, statusKind: StatusKind.FAILED, error: "BAD REQUEST - a POST request may not have a wait time when it is multipart"); res.StatusCode = (int)HttpStatusCode.BadRequest; await res.AsJson("a POST request may not have a wait time when it is multipart"); diff --git a/CometServer/Modules/10-25/ExchangeFileExportApi.cs b/CometServer/Modules/10-25/ExchangeFileExportApi.cs index bbf618ca..23851cc3 100644 --- a/CometServer/Modules/10-25/ExchangeFileExportApi.cs +++ b/CometServer/Modules/10-25/ExchangeFileExportApi.cs @@ -167,6 +167,9 @@ public override void AddRoutes(IEndpointRouteBuilder app) /// /// The used to provide metadata for any kind of /// + /// + /// The used to write to a 10-25 annex C.3 archive + /// /// /// An awaitable /// diff --git a/CometServer/Modules/10-25/ExchangeFileImportyApi.cs b/CometServer/Modules/10-25/ExchangeFileImportyApi.cs index aa8cb5fe..490d081c 100644 --- a/CometServer/Modules/10-25/ExchangeFileImportyApi.cs +++ b/CometServer/Modules/10-25/ExchangeFileImportyApi.cs @@ -248,6 +248,25 @@ private async Task SaveTemporarySeedFile(HttpRequest request) /// /// The (injected) used to read the provided Annex C3 archive /// + /// + /// The (injected) responsile for execution of migration scripts + /// + /// + /// The (injected) that supports revision based retrievel of data + /// + /// + /// The (injected) + /// + /// + /// The that can be used to resolve other services + /// + /// + /// + /// + /// + /// + /// + /// /// /// The . /// @@ -501,7 +520,7 @@ private bool InsertModelData(IRequestUtils requestUtils, ICdp4TransactionManager } // apply migration on new SiteDirectory partition - migrationService.ApplyMigrations(transaction, typeof(SiteDirectory).Name, false); + migrationService.ApplyMigrations(transaction, nameof(SiteDirectory), false); var result = false; @@ -555,7 +574,7 @@ private bool InsertModelData(IRequestUtils requestUtils, ICdp4TransactionManager .ReadEngineeringModelFromfile(version, fileName, password, engineeringModelSetup).ToList(); // should return one engineeringmodel topcontainer - var engineeringModel = engineeringModelItems.OfType().Single(); + var engineeringModel = engineeringModelItems.OfType().SingleOrDefault(); if (engineeringModel == null) { @@ -652,12 +671,7 @@ private bool InsertModelData(IRequestUtils requestUtils, ICdp4TransactionManager finally { transaction?.Dispose(); - - if (connection != null) - { - connection.Close(); - connection.Dispose(); - } + connection?.Dispose(); } } @@ -928,11 +942,8 @@ private bool UpsertModelData(IRequestUtils requestUtils, ICdp4TransactionManager } catch (Exception ex) { - if (transaction != null) - { - transaction.Rollback(); - } - + transaction?.Rollback(); + this.logger.LogError(ex, "Error occured during data store import"); return false; @@ -940,12 +951,7 @@ private bool UpsertModelData(IRequestUtils requestUtils, ICdp4TransactionManager finally { transaction?.Dispose(); - - if (connection != null) - { - connection.Close(); - connection.Dispose(); - } + connection?.Dispose(); } } @@ -980,6 +986,7 @@ private static void ExecuteSiteDirectorySchemaScripts(NpgsqlCommand sqlCommand) private static void PersistFileBinaryData(IRequestUtils requestUtils, IJsonExchangeFileReader jsonExchangeFileReader, string fileName, EngineeringModelSetup engineeringModelSetup, string password = null) { var fileRevisions = requestUtils.Cache.OfType().ToList(); + if (fileRevisions.Count == 0) { // nothing to do @@ -1025,31 +1032,30 @@ private static void FixSingleIterationSetups(List items) private static void ClearDatabaseSchemas(NpgsqlTransaction transaction) { // clear the current database data (except public and pg_catalog schemas) - using (var cleanSchemaCommand = new NpgsqlCommand()) - { - var sqlBuilder = new StringBuilder(); - - // setup clear schema function if not existent - // source: https://chawlasumit.wordpress.com/2014/07/29/drop-all-schemas-in-postgres/ - sqlBuilder.AppendLine("CREATE OR REPLACE FUNCTION public.clear_schemas()") - .AppendLine(" RETURNS VOID AS").AppendLine(" $$").AppendLine(" DECLARE rec RECORD;") - .AppendLine(" BEGIN").AppendLine(" -- Get all schemas").AppendLine(" FOR rec IN") - .AppendLine(" SELECT DISTINCT schema_name") - .AppendLine(" FROM information_schema.schemata").AppendLine(" -- exclude schemas") - .AppendLine( - " WHERE schema_name NOT LIKE 'pg_%' AND schema_name NOT LIKE 'information_schema' AND schema_name <> 'public'") - .AppendLine(" LOOP") - .AppendLine(" EXECUTE 'DROP SCHEMA \"' || rec.schema_name || '\" CASCADE';") - .AppendLine(" END LOOP;").AppendLine(" RETURN;").AppendLine(" END;") - .AppendLine(" $$ LANGUAGE plpgsql;"); - - sqlBuilder.AppendLine("SELECT clear_schemas();"); - - cleanSchemaCommand.CommandText = sqlBuilder.ToString(); - cleanSchemaCommand.Connection = transaction.Connection; - cleanSchemaCommand.Transaction = transaction; - cleanSchemaCommand.ExecuteNonQuery(); - } + using var cleanSchemaCommand = new NpgsqlCommand(); + + var sqlBuilder = new StringBuilder(); + + // setup clear schema function if not existent + // source: https://chawlasumit.wordpress.com/2014/07/29/drop-all-schemas-in-postgres/ + sqlBuilder.AppendLine("CREATE OR REPLACE FUNCTION public.clear_schemas()") + .AppendLine(" RETURNS VOID AS").AppendLine(" $$").AppendLine(" DECLARE rec RECORD;") + .AppendLine(" BEGIN").AppendLine(" -- Get all schemas").AppendLine(" FOR rec IN") + .AppendLine(" SELECT DISTINCT schema_name") + .AppendLine(" FROM information_schema.schemata").AppendLine(" -- exclude schemas") + .AppendLine( + " WHERE schema_name NOT LIKE 'pg_%' AND schema_name NOT LIKE 'information_schema' AND schema_name <> 'public'") + .AppendLine(" LOOP") + .AppendLine(" EXECUTE 'DROP SCHEMA \"' || rec.schema_name || '\" CASCADE';") + .AppendLine(" END LOOP;").AppendLine(" RETURN;").AppendLine(" END;") + .AppendLine(" $$ LANGUAGE plpgsql;"); + + sqlBuilder.AppendLine("SELECT clear_schemas();"); + + cleanSchemaCommand.CommandText = sqlBuilder.ToString(); + cleanSchemaCommand.Connection = transaction.Connection; + cleanSchemaCommand.Transaction = transaction; + cleanSchemaCommand.ExecuteNonQuery(); } /// @@ -1139,7 +1145,7 @@ private void CreateRevisionHistoryForSiteDirectory(IRequestUtils requestUtils, I // Get first person Id (so that actor isnt guid.empty), it is hard to determine who it should be. var person = personService.GetShallow(transaction, TopContainer, null, new RequestSecurityContext { ContainerReadAllowed = true }).OfType().FirstOrDefault(); - personId = person != null ? person.Iid : Guid.Empty; + personId = person?.Iid ?? Guid.Empty; // Save revision history for SiteDirectory's entries revisionService.SaveRevisions(transaction, TopContainer, personId, EngineeringModelSetupSideEffect.FirstRevision); diff --git a/CometServer/Modules/10-25/SiteDirectoryApi.cs b/CometServer/Modules/10-25/SiteDirectoryApi.cs index c069b081..a493710e 100644 --- a/CometServer/Modules/10-25/SiteDirectoryApi.cs +++ b/CometServer/Modules/10-25/SiteDirectoryApi.cs @@ -267,7 +267,7 @@ public override void AddRoutes(IEndpointRouteBuilder app) { this.logger.LogWarning("Request {requestToken} failed as BadRequest: The SiteDirectory does not support MultiPart POST request", requestToken); - this.CometTaskService.AddOrUpdateTask(cometTask, finishedAt: DateTime.Now, statusKind: StatusKind.FAILED, error: $"BAD REQUEST - The SiteDirectory does not support MultiPart POST request"); + this.CometTaskService.AddOrUpdateTask(cometTask, finishedAt: DateTime.Now, statusKind: StatusKind.FAILED, error: "BAD REQUEST - The SiteDirectory does not support MultiPart POST request"); res.StatusCode = (int)HttpStatusCode.BadRequest; await res.AsJson("The SiteDirectory does not support MultiPart POST request"); @@ -355,7 +355,7 @@ protected async Task GetResponseData(HttpRequest httpRequest, HttpResponse httpR var fromRevision = requestUtils.QueryParameters.RevisionNumber; - IReadOnlyList things = null; + IReadOnlyList things; var dbsw = Stopwatch.StartNew(); this.logger.LogDebug("{request}:{requestToken} - Database operations started", httpRequest.QueryNameMethodPath(), requestToken); diff --git a/CometServer/Modules/Health/HealthModule.cs b/CometServer/Modules/Health/HealthModule.cs index 03765fa1..b1824670 100644 --- a/CometServer/Modules/Health/HealthModule.cs +++ b/CometServer/Modules/Health/HealthModule.cs @@ -83,6 +83,9 @@ public class HealthModule : CarterModule /// /// The (injected) used generate HTTP request tokens /// + /// + /// The used to verify that the COMET REST API has started + /// public HealthModule(ILogger logger, IAppConfigService appConfigService, ITokenGeneratorService tokenGeneratorService, ICometHasStartedService cometHasStartedService) { this.logger = logger; diff --git a/CometServer/Modules/Tasks/CometTasksModule.cs b/CometServer/Modules/Tasks/CometTasksModule.cs index fbbb92ae..e972df27 100644 --- a/CometServer/Modules/Tasks/CometTasksModule.cs +++ b/CometServer/Modules/Tasks/CometTasksModule.cs @@ -32,6 +32,8 @@ namespace CometServer.Modules.Tasks using Carter; using Carter.Response; + using CDP4DalCommon.Tasks; + using CometServer.Authorization; using CometServer.Configuration; using CometServer.Exceptions; @@ -83,6 +85,12 @@ public class CometTasksModule : CarterModule /// The (injected) that is used to check whether CDP4-COMET is ready to start /// acceptng requests /// + /// + /// The (injected) used to query tasks + /// + /// + /// The (injected) used to access application settings + /// public CometTasksModule(ILogger logger, ICometHasStartedService cometHasStartedService, ICometTaskService cometTaskService, IAppConfigService appConfigService) { this.logger = logger; @@ -153,7 +161,6 @@ public async Task QueryTasks(HttpRequest req, HttpResponse res, ICredentialsServ res.UpdateWithNotAutherizedSettings(); await res.AsJson("not authorized"); - return; } } @@ -207,7 +214,6 @@ public async Task QueryTask(HttpRequest req, HttpResponse res, ICredentialsServi res.UpdateWithNotAutherizedSettings(); await res.AsJson("not authorized"); - return; } } diff --git a/CometServer/Properties/AssemblyInfo.cs b/CometServer/Properties/AssemblyInfo.cs index 6c4e30bf..33f5387c 100644 --- a/CometServer/Properties/AssemblyInfo.cs +++ b/CometServer/Properties/AssemblyInfo.cs @@ -22,8 +22,6 @@ // // -------------------------------------------------------------------------------------------------------------------- -using System.Reflection; using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; [assembly: InternalsVisibleTo("CometServer.Tests")] \ No newline at end of file diff --git a/CometServer/Services/BusinessLogic/CachedReferenceDataService.cs b/CometServer/Services/BusinessLogic/CachedReferenceDataService.cs index 99a3b698..6845b919 100644 --- a/CometServer/Services/BusinessLogic/CachedReferenceDataService.cs +++ b/CometServer/Services/BusinessLogic/CachedReferenceDataService.cs @@ -76,11 +76,6 @@ public class CachedReferenceDataService : ICachedReferenceDataService /// private Dictionary measurementScaleCache; - /// - /// the (per request) cached - /// - private Dictionary measurementUnitCache; - /// /// the (per request) cached /// @@ -276,37 +271,6 @@ public Dictionary QueryMeasurementScales(NpgsqlTransacti return this.measurementScaleCache; } - /// - /// Queries the s from the data from the datasource or from the cached list - /// - /// - /// An - /// - public Dictionary QueryMeasurementUnits(NpgsqlTransaction transaction, ISecurityContext securityContext) - { - if (this.measurementUnitCache == null || this.measurementUnitCache.Count == 0) - { - var sw = new Stopwatch(); - - this.Logger.LogDebug("Querying MeasurementUnits"); - - this.measurementUnitCache = new Dictionary(); - - var measurementUnits = this.MeasurementUnitService - .GetShallow(transaction, CDP4Orm.Dao.Utils.SiteDirectoryPartition, null, securityContext) - .OfType(); - - foreach (var measurementUnit in measurementUnits) - { - this.measurementUnitCache.Add(measurementUnit.Iid, measurementUnit); - } - - this.Logger.LogDebug("MeasurementUnits Queried in {ElapsedMilliseconds} [ms]", sw.ElapsedMilliseconds); - } - - return this.measurementUnitCache; - } - /// /// Queries the s from the data from the datasource or from the cached list /// @@ -350,7 +314,6 @@ public void Reset() this.dependentParameterTypeAssignment?.Clear(); this.independentParameterTypeAssignment?.Clear(); this.measurementScaleCache?.Clear(); - this.measurementUnitCache?.Clear(); this.enumerationValueDefinitionCache?.Clear(); this.Logger.LogDebug("Cache Reset"); diff --git a/CometServer/Services/BusinessLogic/ChainOfRdlComputationService.cs b/CometServer/Services/BusinessLogic/ChainOfRdlComputationService.cs index c6b7bc85..ba22174e 100644 --- a/CometServer/Services/BusinessLogic/ChainOfRdlComputationService.cs +++ b/CometServer/Services/BusinessLogic/ChainOfRdlComputationService.cs @@ -134,7 +134,6 @@ public IEnumerable QueryReferenceDataLibraryDependency(NpgsqlTransaction t if (modelReferenceDataLibarary == null) { this.Logger.LogWarning("The ModelReferenceDataLibarary { modelReferenceDataLibararyIid } could not be found, there is a fault in the data, the EngineeringModelSetup {engineeringModelSetupIid} is ignored", modelReferenceDataLibararyIid, engineeringModelSetup.Iid); - continue; } else { diff --git a/CometServer/Services/BusinessLogic/DefaultValueArrayFactory.cs b/CometServer/Services/BusinessLogic/DefaultValueArrayFactory.cs index 667ad8d1..a9cf2092 100644 --- a/CometServer/Services/BusinessLogic/DefaultValueArrayFactory.cs +++ b/CometServer/Services/BusinessLogic/DefaultValueArrayFactory.cs @@ -50,34 +50,34 @@ public class DefaultValueArrayFactory : IDefaultValueArrayFactory public ILogger Logger { get; set; } /// - /// A cache of that has been computed for + /// A cache of that has been computed for /// that is used for fast access so taht the default ValueArray does not have to be recomputed. /// - private readonly Dictionary> defaultValueArrayCache = new Dictionary>(); + private readonly Dictionary> defaultValueArrayCache = new(); /// /// a cache of s that is populated in the context of the current /// /// - private Dictionary parameterTypeCache = new Dictionary(); + private Dictionary parameterTypeCache = new(); /// /// a cache of s that is populated in the context of the current /// /// - private readonly Dictionary parameterTypeAssignmentCache = new Dictionary(); + private readonly Dictionary parameterTypeAssignmentCache = new(); /// /// a cache of s that is populated in the context of the current /// /// - private Dictionary parameterTypeComponentCache = new Dictionary(); + private Dictionary parameterTypeComponentCache = new(); /// /// a cache of the s and their number-of-values in the context of the current /// /// - private readonly Dictionary parameterTypeNumberOfValuesMap = new Dictionary(); + private readonly Dictionary parameterTypeNumberOfValuesMap = new(); /// /// Gets or sets the (injected) @@ -155,16 +155,12 @@ public void Reset() /// public ValueArray CreateDefaultValueArray(Guid parameterTypeIid) { - ValueArray defaultValueArray; - - if (this.defaultValueArrayCache.TryGetValue(parameterTypeIid, out defaultValueArray)) + if (this.defaultValueArrayCache.TryGetValue(parameterTypeIid, out var defaultValueArray)) { return defaultValueArray; } - ParameterType parameterType; - - if (!this.parameterTypeCache.TryGetValue(parameterTypeIid, out parameterType)) + if (!this.parameterTypeCache.TryGetValue(parameterTypeIid, out var parameterType)) { var execptionMessage = $"The ParameterType with iid {parameterTypeIid} could not be found in the DefaultValueArrayFactory cache. A Default ValueArray could not be created"; this.Logger.LogError(execptionMessage); @@ -214,9 +210,7 @@ public ValueArray CreateDefaultValueArray(int numberOfValues) /// private int ComputeNumberOfValues(ParameterType parameterType) { - int numberOfValues; - - if (this.parameterTypeNumberOfValuesMap.TryGetValue(parameterType, out numberOfValues)) + if (this.parameterTypeNumberOfValuesMap.TryGetValue(parameterType, out var numberOfValues)) { return numberOfValues; } @@ -348,18 +342,15 @@ private int ComputeNumberOfValuesForCompoundParamterType(CompoundParameterType c foreach (var parameterTypeComponentKeyVaulePair in compoundParameterType.Component) { var parameterTypeComponentIid = Guid.Parse(parameterTypeComponentKeyVaulePair.V.ToString()); - ParameterTypeComponent parameterTypeComponent; - if (!this.parameterTypeComponentCache.TryGetValue(parameterTypeComponentIid, out parameterTypeComponent)) + if (!this.parameterTypeComponentCache.TryGetValue(parameterTypeComponentIid, out var parameterTypeComponent)) { var exceptionMessage = $"The ParameterTypeComponent with Iid {parameterTypeComponentIid} could not be found in the DefaultValueArrayFactory cache. A Default ValueArray could not be created"; this.Logger.LogError(exceptionMessage); throw new KeyNotFoundException(exceptionMessage); } - ParameterType parameterType; - - if (!this.parameterTypeCache.TryGetValue(parameterTypeComponent.ParameterType, out parameterType)) + if (!this.parameterTypeCache.TryGetValue(parameterTypeComponent.ParameterType, out var parameterType)) { var exceptionMessage = $"The ParameterType {parameterTypeComponent.ParameterType} of the ParameterTypeComponent {parameterTypeComponent.Iid} could not be found in the DefaultValueArrayFactory cache. A Default ValueArray could not be created"; this.Logger.LogError(exceptionMessage); diff --git a/CometServer/Services/BusinessLogic/FileBinaryService.cs b/CometServer/Services/BusinessLogic/FileBinaryService.cs index 2bfb267b..f8779069 100644 --- a/CometServer/Services/BusinessLogic/FileBinaryService.cs +++ b/CometServer/Services/BusinessLogic/FileBinaryService.cs @@ -73,8 +73,7 @@ public FileBinaryService() /// public bool IsFilePersisted(string hash) { - string filePath; - return this.TryGetFileStoragePath(hash, out filePath); + return this.TryGetFileStoragePath(hash, out _); } /// diff --git a/CometServer/Services/BusinessLogic/FiniteStateLogicService.cs b/CometServer/Services/BusinessLogic/FiniteStateLogicService.cs index a9b6db9d..689bba9d 100644 --- a/CometServer/Services/BusinessLogic/FiniteStateLogicService.cs +++ b/CometServer/Services/BusinessLogic/FiniteStateLogicService.cs @@ -149,7 +149,7 @@ public void UpdateActualFinisteStateList(ActualFiniteStateList actualFiniteState { if (!this.ActualFiniteStateService.DeleteConcept(transaction, partition, actualState, actualFiniteStateList)) { - throw new InvalidOperationException(string.Format("The actual finite state {0} could not be deleted", actualState.Iid)); + throw new InvalidOperationException($"The actual finite state {actualState.Iid} could not be deleted"); } } } diff --git a/CometServer/Services/BusinessLogic/ICachedReferenceDataService.cs b/CometServer/Services/BusinessLogic/ICachedReferenceDataService.cs index d30b42ac..35d95209 100644 --- a/CometServer/Services/BusinessLogic/ICachedReferenceDataService.cs +++ b/CometServer/Services/BusinessLogic/ICachedReferenceDataService.cs @@ -75,7 +75,7 @@ public interface ICachedReferenceDataService : IBusinessLogicService /// /// Gets or sets the (injected) used to query the s from the data-store /// - IEnumerationValueDefinitionService EnumerationValueDefinitionService { get; set; } + public IEnumerationValueDefinitionService EnumerationValueDefinitionService { get; set; } /// /// Queries the s from the data from the datasource or from the cached list @@ -118,15 +118,7 @@ public interface ICachedReferenceDataService : IBusinessLogicService public Dictionary QueryMeasurementScales(NpgsqlTransaction transaction, ISecurityContext securityContext); /// - /// Queries the s from the data from the datasource or from the cached list - /// - /// - /// An - /// - public Dictionary QueryMeasurementUnits(NpgsqlTransaction transaction, ISecurityContext securityContext); - - /// - /// Resets (clears) the cached data from the . + /// Resets (clears) the cached data from the . /// public void Reset(); diff --git a/CometServer/Services/BusinessLogic/IDefaultValueArrayFactory.cs b/CometServer/Services/BusinessLogic/IDefaultValueArrayFactory.cs index 6a722a85..459cf390 100644 --- a/CometServer/Services/BusinessLogic/IDefaultValueArrayFactory.cs +++ b/CometServer/Services/BusinessLogic/IDefaultValueArrayFactory.cs @@ -26,6 +26,7 @@ namespace CometServer.Services { using System; + using CDP4Common.DTO; using CDP4Common.Types; using CometServer.Services.Authorization; diff --git a/CometServer/Services/Cache/CacheService.cs b/CometServer/Services/Cache/CacheService.cs index 7a622d95..d6295054 100644 --- a/CometServer/Services/Cache/CacheService.cs +++ b/CometServer/Services/Cache/CacheService.cs @@ -42,17 +42,6 @@ public class CacheService : ICacheService /// public ICacheDao CacheDao { get; set; } - /// - /// Save a to a cache table - /// - /// The current transaction - /// The database partition (schema) where the requested resource is stored. - /// The revised - public void WriteToCache(NpgsqlTransaction transaction, string partition, Thing thing) - { - this.CacheDao.Write(transaction, partition, thing); - } - /// /// Save a collection of s to cache tables /// diff --git a/CometServer/Services/Cache/ICacheService.cs b/CometServer/Services/Cache/ICacheService.cs index cad9feae..53543eb4 100644 --- a/CometServer/Services/Cache/ICacheService.cs +++ b/CometServer/Services/Cache/ICacheService.cs @@ -35,14 +35,6 @@ namespace CometServer.Services /// public interface ICacheService { - /// - /// Save a to a cache table - /// - /// The current transaction - /// The database partition (schema) where the requested resource is stored. - /// The revised - void WriteToCache(NpgsqlTransaction transaction, string partition, Thing thing); - /// /// Save a collection of s to cache tables /// diff --git a/CometServer/Services/ChangeLog/AffectedThingsData.cs b/CometServer/Services/ChangeLog/AffectedThingsData.cs index 21812c33..f2e28ab4 100644 --- a/CometServer/Services/ChangeLog/AffectedThingsData.cs +++ b/CometServer/Services/ChangeLog/AffectedThingsData.cs @@ -38,18 +38,18 @@ public class AffectedThingsData /// A of type that contains s from items that need to be added /// to a the and properties. /// - public HashSet AffectedItemIds { get; } = new HashSet(); + public HashSet AffectedItemIds { get; } = new(); /// /// A of type that contains s from items that need to be added /// to a the and properties. /// - public HashSet AffectedDomainIds { get; } = new HashSet(); + public HashSet AffectedDomainIds { get; } = new(); /// /// A of type that holds extra data. /// - public List ExtraChangeDescriptions { get; } = new List(); + public List ExtraChangeDescriptions { get; } = new(); /// /// Add data from another to this diff --git a/CometServer/Services/ChangeLog/ChangeLogService.cs b/CometServer/Services/ChangeLog/ChangeLogService.cs index 94692e35..a7c31011 100644 --- a/CometServer/Services/ChangeLog/ChangeLogService.cs +++ b/CometServer/Services/ChangeLog/ChangeLogService.cs @@ -411,9 +411,6 @@ private LogEntryChangelogItem CreateAddOrUpdateLogEntryChangelogItem(NpgsqlTrans /// /// The database partition (schema) where the requested resource is stored. /// - /// - /// The - /// /// /// The . /// @@ -938,11 +935,11 @@ private AffectedThingsData GetAffectedThingsData(NpgsqlTransaction transaction, foreach (var category in elementUsage.Category) { - AddIfNotExists(affectedThingsData.AffectedItemIds, category); + AddIfNotExists(affectedThingsData.AffectedItemIds, category); } - AddIfNotExists(affectedThingsData.AffectedDomainIds, elementUsage.Owner); - AddIfNotExists(affectedThingsData.AffectedItemIds, elementUsage.Iid); + AddIfNotExists(affectedThingsData.AffectedDomainIds, elementUsage.Owner); + AddIfNotExists(affectedThingsData.AffectedItemIds, elementUsage.Iid); } break; @@ -955,11 +952,11 @@ private AffectedThingsData GetAffectedThingsData(NpgsqlTransaction transaction, foreach (var category in elementDefinition.Category) { - AddIfNotExists(affectedThingsData.AffectedItemIds, category); - } - - AddIfNotExists(affectedThingsData.AffectedDomainIds, elementDefinition.Owner); - AddIfNotExists(affectedThingsData.AffectedItemIds, elementDefinition.Iid); + AddIfNotExists(affectedThingsData.AffectedItemIds, category); + } + + AddIfNotExists(affectedThingsData.AffectedDomainIds, elementDefinition.Owner); + AddIfNotExists(affectedThingsData.AffectedItemIds, elementDefinition.Iid); } break; @@ -1145,6 +1142,9 @@ private Thing GetContainer(NpgsqlTransaction transaction, string partition, Thin /// /// The updated /// + /// + /// the changed s + /// /// /// 's container if found, otherwise null /// diff --git a/CometServer/Services/DataStore/DataStoreController.cs b/CometServer/Services/DataStore/DataStoreController.cs index c4789f37..e820a407 100644 --- a/CometServer/Services/DataStore/DataStoreController.cs +++ b/CometServer/Services/DataStore/DataStoreController.cs @@ -57,26 +57,25 @@ public void CloneDataStore() var backtier = this.AppConfigService.AppConfig.Backtier; - using (var connection = new NpgsqlConnection(Utils.GetConnectionString(backtier, backtier.DatabaseManage))) - { - connection.Open(); + using var connection = new NpgsqlConnection(Utils.GetConnectionString(backtier, backtier.DatabaseManage)); - // Create a clone of the database - using (var cmd = new NpgsqlCommand()) - { - this.Logger.LogDebug("Clone the data store"); + connection.Open(); - this.DropDataStoreConnections(backtier.Database, connection); + // Create a clone of the database + using (var cmd = new NpgsqlCommand()) + { + this.Logger.LogDebug("Clone the data store"); - cmd.Connection = connection; - - cmd.CommandText = $"CREATE DATABASE {backtier.DatabaseRestore} WITH OWNER = {backtier.UserName} TEMPLATE = {backtier.Database} ENCODING = 'UTF8';"; + this.DropDataStoreConnections(backtier.Database, connection); - cmd.ExecuteNonQuery(); - } + cmd.Connection = connection; + + cmd.CommandText = $"CREATE DATABASE {backtier.DatabaseRestore} WITH OWNER = {backtier.UserName} TEMPLATE = {backtier.Database} ENCODING = 'UTF8';"; - connection.Close(); + cmd.ExecuteNonQuery(); } + + connection.Close(); } /// @@ -92,38 +91,37 @@ public void RestoreDataStore() var backtier = this.AppConfigService.AppConfig.Backtier; // Connect to the restore database - using (var connection = new NpgsqlConnection(Utils.GetConnectionString(backtier, backtier.DatabaseManage))) - { - connection.Open(); + using var connection = new NpgsqlConnection(Utils.GetConnectionString(backtier, backtier.DatabaseManage)); - // Drop the existing database - using (var cmd = new NpgsqlCommand()) - { - this.Logger.LogDebug("Drop the data store"); + connection.Open(); - this.DropDataStoreConnections(backtier.Database, connection); + // Drop the existing database + using (var cmd = new NpgsqlCommand()) + { + this.Logger.LogDebug("Drop the data store"); - cmd.Connection = connection; - - cmd.CommandText = $"DROP DATABASE IF EXISTS {backtier.Database};"; + this.DropDataStoreConnections(backtier.Database, connection); - cmd.ExecuteNonQuery(); - } + cmd.Connection = connection; + + cmd.CommandText = $"DROP DATABASE IF EXISTS {backtier.Database};"; - // Create a new database with a restore template - using (var cmd = new NpgsqlCommand()) - { - this.Logger.LogDebug("Clone the restore data store"); + cmd.ExecuteNonQuery(); + } - cmd.Connection = connection; + // Create a new database with a restore template + using (var cmd = new NpgsqlCommand()) + { + this.Logger.LogDebug("Clone the restore data store"); - cmd.CommandText = $"CREATE DATABASE {backtier.Database} WITH OWNER = {backtier.UserName} TEMPLATE = {backtier.DatabaseRestore} ENCODING = 'UTF8';"; + cmd.Connection = connection; - cmd.ExecuteNonQuery(); - } + cmd.CommandText = $"CREATE DATABASE {backtier.Database} WITH OWNER = {backtier.UserName} TEMPLATE = {backtier.DatabaseRestore} ENCODING = 'UTF8';"; - connection.Close(); + cmd.ExecuteNonQuery(); } + + connection.Close(); } /// @@ -137,19 +135,18 @@ public void RestoreDataStore() /// public void DropDataStoreConnections(string dataStoreName, NpgsqlConnection connection) { - using (var cmd = new NpgsqlCommand()) - { - this.Logger.LogDebug("Drop all connections to the data store"); + using var cmd = new NpgsqlCommand(); - NpgsqlConnection.ClearPool(new NpgsqlConnection(Utils.GetConnectionString(this.AppConfigService.AppConfig.Backtier, dataStoreName))); + this.Logger.LogDebug("Drop all connections to the data store"); - cmd.Connection = connection; + NpgsqlConnection.ClearPool(new NpgsqlConnection(Utils.GetConnectionString(this.AppConfigService.AppConfig.Backtier, dataStoreName))); - cmd.CommandText = $"SELECT pg_terminate_backend(pg_stat_activity.pid) FROM pg_stat_activity WHERE pg_stat_activity.datname = :dataStoreName AND pid <> pg_backend_pid();"; - cmd.Parameters.Add("dataStoreName", NpgsqlDbType.Varchar).Value = dataStoreName; + cmd.Connection = connection; - cmd.ExecuteNonQuery(); - } + cmd.CommandText = "SELECT pg_terminate_backend(pg_stat_activity.pid) FROM pg_stat_activity WHERE pg_stat_activity.datname = :dataStoreName AND pid <> pg_backend_pid();"; + cmd.Parameters.Add("dataStoreName", NpgsqlDbType.Varchar).Value = dataStoreName; + + cmd.ExecuteNonQuery(); } } } diff --git a/CometServer/Services/Email/EmailService.cs b/CometServer/Services/Email/EmailService.cs index 6fcebe06..20aee586 100644 --- a/CometServer/Services/Email/EmailService.cs +++ b/CometServer/Services/Email/EmailService.cs @@ -136,7 +136,7 @@ private IEnumerable CreateAttachments(IEnumerable filepaths) var attachment = new MimePart(MimeTypes.GetMimeType(filepath)) { Content = new MimeContent(System.IO.File.OpenRead(filepath), ContentEncoding.Binary), - ContentDisposition = new MimeKit.ContentDisposition("multipart/form-data"), + ContentDisposition = new ContentDisposition("multipart/form-data"), ContentTransferEncoding = ContentEncoding.Base64, FileName = Path.GetFileName(filepath) }; diff --git a/CometServer/Services/Headers/HeaderInfoProvider.cs b/CometServer/Services/Headers/HeaderInfoProvider.cs index da09c6b9..77f5222b 100644 --- a/CometServer/Services/Headers/HeaderInfoProvider.cs +++ b/CometServer/Services/Headers/HeaderInfoProvider.cs @@ -38,22 +38,22 @@ public class HeaderInfoProvider : IHeaderInfoProvider /// /// The response headers. /// - private readonly Dictionary responseHeaders = new Dictionary(); + private readonly Dictionary responseHeaders = new(); /// /// The version of the /// - private static readonly Lazy Cdp4ServerHeaderVersion = new Lazy(() => GetAssemblyVersion(typeof(Startup))); + private static readonly Lazy Cdp4ServerHeaderVersion = new(() => GetAssemblyVersion(typeof(Startup))); /// /// The version of the /// - private static readonly Lazy CometServerHeaderVersion = new Lazy(() => GetAssemblyVersion(typeof(Startup))); + private static readonly Lazy CometServerHeaderVersion = new(() => GetAssemblyVersion(typeof(Startup))); /// /// The version of the /// - private static readonly Lazy Cdp4CommonHeaderVersion = new Lazy(() => GetAssemblyVersion(typeof(CDP4Common.DTO.Thing))); + private static readonly Lazy Cdp4CommonHeaderVersion = new(() => GetAssemblyVersion(typeof(CDP4Common.DTO.Thing))); /// /// Initializes a new instance of the class. @@ -120,6 +120,9 @@ public string ContentTypeVersion /// The that is used to determine what the value of the /// Content-Type header needs to be /// + /// + /// the boundary string used in the HTTP request + /// public void RegisterResponseHeaders(HttpResponse response, ContentTypeKind contentTypeKind, string boundary) { response.Headers.TryAdd(HttpConstants.Cdp4ServerHeader, this.Cdp4ServerVersion); diff --git a/CometServer/Services/Headers/IHeaderInfoProvider.cs b/CometServer/Services/Headers/IHeaderInfoProvider.cs index 881d81b2..cf34b24d 100644 --- a/CometServer/Services/Headers/IHeaderInfoProvider.cs +++ b/CometServer/Services/Headers/IHeaderInfoProvider.cs @@ -46,11 +46,6 @@ public interface IHeaderInfoProvider /// string Cdp4CommonVersion { get; } - /// - /// Gets the Content type version. - /// - string ContentTypeVersion { get; } - /// /// Register the CDP4 headers to the passed in response. /// @@ -61,6 +56,9 @@ public interface IHeaderInfoProvider /// The that is used to determine what the value of the /// Content-Type header needs to be /// + /// + /// the boundary that is used in the response + /// public void RegisterResponseHeaders(HttpResponse response, ContentTypeKind contentTypeKind, string boundary); } } diff --git a/CometServer/Services/JsonExchangeFile/IJsonExchangeFileReader.cs b/CometServer/Services/JsonExchangeFile/IJsonExchangeFileReader.cs index 861924e4..3d2bb7f9 100644 --- a/CometServer/Services/JsonExchangeFile/IJsonExchangeFileReader.cs +++ b/CometServer/Services/JsonExchangeFile/IJsonExchangeFileReader.cs @@ -28,11 +28,8 @@ namespace CometServer.Services using CDP4Common.DTO; - using CDP4JsonSerializer; - using CDP4Orm.Dao; - using System.Collections.Generic; using System.Collections.ObjectModel; /// diff --git a/CometServer/Services/JsonExchangeFile/JsonExchangeFileWriter.cs b/CometServer/Services/JsonExchangeFile/JsonExchangeFileWriter.cs index 63e57bab..93bbd510 100644 --- a/CometServer/Services/JsonExchangeFile/JsonExchangeFileWriter.cs +++ b/CometServer/Services/JsonExchangeFile/JsonExchangeFileWriter.cs @@ -35,7 +35,6 @@ namespace CometServer.Services using CDP4Common.Exceptions; using CometServer.Authorization; - using CometServer.Exceptions; using CometServer.Services.Authorization; using CometServer.Services.Protocol; @@ -326,6 +325,9 @@ private Dictionary PopulateSiteDirectoryDataCache(NpgsqlTransaction /// /// The s that are to be included /// + /// + /// the cache + /// /// /// Participants that are not inlcuded in any of the EngineeringModelSetups are removed with the exception of the Person that is performing the request /// ParticipantRoles that are not referenced by any of the Participants are removed diff --git a/CometServer/Services/Operations/ModelCreatorManager.cs b/CometServer/Services/Operations/ModelCreatorManager.cs index d27b060d..40baea1d 100644 --- a/CometServer/Services/Operations/ModelCreatorManager.cs +++ b/CometServer/Services/Operations/ModelCreatorManager.cs @@ -32,8 +32,7 @@ namespace CometServer.Services.Operations using Authorization; using CDP4Common.DTO; - using CDP4Common.MetaInfo; - + using CometServer.Helpers; using Microsoft.Extensions.Logging; @@ -105,14 +104,6 @@ public class ModelCreatorManager : IModelCreatorManager /// public IRevisionService RevisionService { get; set; } - /// - /// Gets the original and their copy - /// - public IReadOnlyDictionary OriginalToCopyMap - { - get { return this.originalToCopyMap; } - } - /// /// Gets or sets the transaction manager. /// @@ -276,7 +267,7 @@ public void CopyEngineeringModelData(EngineeringModelSetup newModelSetup, Npgsql foreach (var modelThing in modelThings) { - if (modelThing is EngineeringModel model) + if (modelThing is EngineeringModel) { continue; } diff --git a/CometServer/Services/Operations/OperationProcessor.cs b/CometServer/Services/Operations/OperationProcessor.cs index c0690f51..5d711c98 100644 --- a/CometServer/Services/Operations/OperationProcessor.cs +++ b/CometServer/Services/Operations/OperationProcessor.cs @@ -430,7 +430,7 @@ internal static void ValidateUpdateOperations(CdpPostOperation operation) } // verify no updates on FileRevision - if (operation.Update.Any(x => x[ClasskindKey].ToString() == typeof(FileRevision).Name)) + if (operation.Update.Any(x => x[ClasskindKey].ToString() == nameof(FileRevision))) { throw new InvalidOperationException("FileRevisions updates are not allowed"); } @@ -488,6 +488,12 @@ private IMetaInfo GetTypeMetaInfo(string typeName) /// /// The file Store. /// + /// + /// the used to write to the underlying database + /// + /// + /// The database partition + /// private void ValidatePostMessage(CdpPostOperation operation, Dictionary fileStore, NpgsqlTransaction transaction, string partition) { this.ValidateDeleteOperations(operation, transaction, partition); @@ -547,8 +553,7 @@ private bool TryFindContainerInUpdates(CdpPostOperation operation, Thing thing, var typeInfo = updateInfo[ClasskindKey].ToString(); var iidInfo = (Guid)updateInfo[IidKey]; - PropertyMetaInfo containerPropertyInfo; - if (!metaInfo.TryGetContainerProperty(typeInfo, out containerPropertyInfo)) + if (!metaInfo.TryGetContainerProperty(typeInfo, out var containerPropertyInfo)) { continue; } @@ -636,10 +641,9 @@ private bool TryFindContainerInCreateSection(CdpPostOperation operation, Thing t foreach (var createInfo in operation.Create) { var typeInfo = createInfo.GetType().Name; - PropertyMetaInfo containerPropertyInfo; ContainerInfo containerInfo; - if (!metaInfo.TryGetContainerProperty(typeInfo, out containerPropertyInfo)) + if (!metaInfo.TryGetContainerProperty(typeInfo, out var containerPropertyInfo)) { continue; } @@ -721,8 +725,7 @@ private bool TryFindContainerInCreateSection(CdpPostOperation operation, Thing t /// private DtoResolveHelper GetContainerInfo(Thing thing) { - DtoResolveHelper resolvedThing; - if (!this.operationThingCache.TryGetValue(thing.GetInfoPlaceholder(), out resolvedThing)) + if (!this.operationThingCache.TryGetValue(thing.GetInfoPlaceholder(), out var resolvedThing)) { throw new InvalidOperationException( $"The resolved information fo '{thing.GetType().Name}' with iid: '{thing.Iid}' was not found."); @@ -734,8 +737,7 @@ private DtoResolveHelper GetContainerInfo(Thing thing) $"The container information for '{thing.GetType().Name}' with iid: '{thing.Iid}' was not found."); } - DtoResolveHelper resolvedThingContainer; - if (!this.operationThingCache.TryGetValue(resolvedThing.ContainerInfo, out resolvedThingContainer)) + if (!this.operationThingCache.TryGetValue(resolvedThing.ContainerInfo, out var resolvedThingContainer)) { throw new InvalidOperationException( $"Expected container for '{thing.GetType().Name}' with iid: '{thing.Iid}' not found in operation message."); @@ -875,6 +877,9 @@ private static Thing GetPersistedItem(NpgsqlTransaction transaction, string part /// /// The current transaction to the database. /// + /// + /// the database partition + /// private void ApplyDeleteOperations(CdpPostOperation operation, NpgsqlTransaction transaction, string requestPartition) { foreach (var deleteInfo in operation.Delete) @@ -1069,8 +1074,8 @@ private void ApplyCopyOperations(CdpPostOperation operation, NpgsqlTransaction t } // re-order create - var targetModelPartition = requestPartition.Contains(typeof(EngineeringModel).Name) ? requestPartition : requestPartition.Replace(typeof(Iteration).Name, typeof(EngineeringModel).Name); - var targetIterationPartition = requestPartition.Contains(typeof(EngineeringModel).Name) ? requestPartition.Replace(typeof(EngineeringModel).Name, typeof(Iteration).Name) : requestPartition; + var targetModelPartition = requestPartition.Contains(nameof(EngineeringModel)) ? requestPartition : requestPartition.Replace(nameof(Iteration), nameof(EngineeringModel)); + var targetIterationPartition = requestPartition.Contains(nameof(EngineeringModel)) ? requestPartition.Replace(nameof(EngineeringModel), nameof(Iteration)) : requestPartition; var modelSetupService = (IEngineeringModelSetupService)this.ServiceProvider.MapToReadService(ClassKind.EngineeringModelSetup.ToString()); @@ -1094,8 +1099,8 @@ private void ApplyCopyOperations(CdpPostOperation operation, NpgsqlTransaction t throw new InvalidOperationException("The container for the copy operation cannot be found."); } - var mrdlService = (IModelReferenceDataLibraryService)this.ServiceProvider.MapToReadService(typeof(ModelReferenceDataLibrary).Name); - var iterationservice = this.ServiceProvider.MapToReadService(typeof(Iteration).Name); + var mrdlService = (IModelReferenceDataLibraryService)this.ServiceProvider.MapToReadService(nameof(ModelReferenceDataLibrary)); + var iterationservice = this.ServiceProvider.MapToReadService(nameof(Iteration)); var targetIteration = (Iteration)iterationservice.GetShallow(transaction, targetModelPartition, new[] {copyinfo.Target.IterationId.Value}, securityContext).SingleOrDefault(); if (targetIteration == null) @@ -1136,7 +1141,7 @@ private void ApplyCopyOperations(CdpPostOperation operation, NpgsqlTransaction t var elementDefContainer = elementDefCopies.SingleOrDefault(x => x.Iid == idmap[sourceElementDefContainer.Iid]); if (elementDefContainer == null) { - throw new InvalidOperationException($"The target element definition container could not be found for the usage to copy."); + throw new InvalidOperationException("The target element definition container could not be found for the usage to copy."); } ((ServiceBase)usageService).Copy(transaction, targetIterationPartition, elementUsage, elementDefContainer, sourceThings, copyinfo, idmap, rdls, targetEngineeringModelSetup, securityContext); diff --git a/CometServer/Services/Operations/SideEffects/Implementation/ActualFiniteStateListSideEffect.cs b/CometServer/Services/Operations/SideEffects/Implementation/ActualFiniteStateListSideEffect.cs index 21e67b68..fd35d518 100644 --- a/CometServer/Services/Operations/SideEffects/Implementation/ActualFiniteStateListSideEffect.cs +++ b/CometServer/Services/Operations/SideEffects/Implementation/ActualFiniteStateListSideEffect.cs @@ -37,21 +37,11 @@ namespace CometServer.Services.Operations.SideEffects /// public sealed class ActualFiniteStateListSideEffect : OperationSideEffect { - /// - /// Gets or sets the - /// - public IActualFiniteStateService ActualFiniteStateService { get; set; } - /// /// Gets or sets the /// public IStateDependentParameterUpdateService StateDependentParameterUpdateService { get; set; } - /// - /// Gets or sets the - /// - public IPossibleFiniteStateListService PossibleFiniteStateListService { get; set; } - /// /// Gets or sets the /// diff --git a/CometServer/Services/Operations/SideEffects/Implementation/EngineeringModelSetupSideEffect.cs b/CometServer/Services/Operations/SideEffects/Implementation/EngineeringModelSetupSideEffect.cs index ea74be84..f3d1af5f 100644 --- a/CometServer/Services/Operations/SideEffects/Implementation/EngineeringModelSetupSideEffect.cs +++ b/CometServer/Services/Operations/SideEffects/Implementation/EngineeringModelSetupSideEffect.cs @@ -271,9 +271,7 @@ public override void BeforeUpdate(EngineeringModelSetup thing, Thing container, /// Creates a new from a source /// /// The - /// The container /// The current transaction - /// The partition /// The security context private void CreateCopyEngineeringModel(EngineeringModelSetup thing, NpgsqlTransaction transaction, ISecurityContext securityContext) { @@ -292,7 +290,6 @@ private void CreateCopyEngineeringModel(EngineeringModelSetup thing, NpgsqlTrans /// The container /// The current transaction /// The partition - /// The security context private void CreateDefaultEngineeringModel(EngineeringModelSetup thing, Thing container, NpgsqlTransaction transaction, string partition) { // No need to create a model RDL for the created EngineeringModelSetup since is handled in the client. It happens in the same transaction as the creation of the EngineeringModelSetup itself diff --git a/CometServer/Services/Operations/SideEffects/Implementation/GlossarySideEffect.cs b/CometServer/Services/Operations/SideEffects/Implementation/GlossarySideEffect.cs index e5e4f228..17ac045d 100644 --- a/CometServer/Services/Operations/SideEffects/Implementation/GlossarySideEffect.cs +++ b/CometServer/Services/Operations/SideEffects/Implementation/GlossarySideEffect.cs @@ -79,7 +79,7 @@ public override void AfterUpdate(Glossary glossary, Thing container, Glossary or return; } - if (!this.PermissionService.CanWrite(transaction, originalThing, typeof(Term).Name, partition, "update", securityContext)) + if (!this.PermissionService.CanWrite(transaction, originalThing, nameof(Term), partition, "update", securityContext)) { return; } diff --git a/CometServer/Services/Operations/SideEffects/Implementation/OptionSideEffect.cs b/CometServer/Services/Operations/SideEffects/Implementation/OptionSideEffect.cs index c803bdc3..a6b40145 100644 --- a/CometServer/Services/Operations/SideEffects/Implementation/OptionSideEffect.cs +++ b/CometServer/Services/Operations/SideEffects/Implementation/OptionSideEffect.cs @@ -33,7 +33,6 @@ namespace CometServer.Services.Operations.SideEffects using CDP4Orm.Dao; - using CometServer.Exceptions; using CometServer.Services.Authorization; using Npgsql; @@ -47,12 +46,12 @@ public sealed class OptionSideEffect : OperationSideEffect