diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml index ffa991d..5fb5ab3 100644 --- a/.github/workflows/codeql-analysis.yml +++ b/.github/workflows/codeql-analysis.yml @@ -38,11 +38,11 @@ jobs: steps: - name: Checkout repository - uses: actions/checkout@v3 + uses: actions/checkout@v4 # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL - uses: github/codeql-action/init@v2 + uses: github/codeql-action/init@v3 with: languages: ${{ matrix.language }} # If you wish to specify custom queries, you can do so here or in a config file. @@ -53,7 +53,7 @@ jobs: # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). # If this step fails, then you should remove it and run the build manually (see below) - name: Autobuild - uses: github/codeql-action/autobuild@v2 + uses: github/codeql-action/autobuild@v3 # ℹ️ Command-line programs to run using the OS shell. # 📚 https://git.io/JvXDl @@ -67,4 +67,4 @@ jobs: # make release - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@v2 + uses: github/codeql-action/analyze@v3 diff --git a/.github/workflows/dotnetcore.yml b/.github/workflows/dotnetcore.yml index 6f8ee46..71ead73 100644 --- a/.github/workflows/dotnetcore.yml +++ b/.github/workflows/dotnetcore.yml @@ -12,21 +12,35 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v4 - name: Setup .NET Core - uses: actions/setup-dotnet@v1 + uses: actions/setup-dotnet@v4 with: - dotnet-version: '6.0.x' - include-prerelease: false + dotnet-version: '8.0.x' - name: Build with dotnet run: dotnet build --configuration Release - name: Run tests - run: dotnet test Nbic.References.Tests/Nbic.References.Tests.csproj -- MaxCpuCount=1 - - name: Build and push Docker images - uses: docker/build-push-action@v1 + run: dotnet test --no-restore --verbosity normal --logger "trx;LogFileName=test-results.trx" Nbic.References.Tests/Nbic.References.Tests.csproj -- MaxCpuCount=1 || True + - name: Test Report + uses: dorny/test-reporter@v1 + if: always() with: - username: ${{ secrets.DOCKER_USERNAME }} - password: ${{ secrets.DOCKER_PASSWORD }} - dockerfile: Nbic.References/Dockerfile - repository: artsdatabanken/nbicreferences - tags: latest + name: DotNET Tests + path: "**/test-results.trx" + reporter: dotnet-trx + fail-on-error: true + - name: Login to Docker Hub + uses: docker/login-action@v3 + with: + username: ${{ secrets.ORG_DOCKER_USER }} + password: ${{ secrets.ORG_DOCKER_PASS }} + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + - name: Build and push Docker image api + uses: docker/build-push-action@v5 + if: github.event.pull_request.merged == 'true' && ${{ github.actor != 'dependabot[bot]' }} + with: +# context: ./src + file: ./Nbic.References/Dockerfile + tags: artsdatabanken/nbicreferences:latest + push: true \ No newline at end of file diff --git a/.github/workflows/metrics.yml b/.github/workflows/metrics.yml index 7f6f666..961ead6 100644 --- a/.github/workflows/metrics.yml +++ b/.github/workflows/metrics.yml @@ -18,7 +18,7 @@ jobs: pull-requests: write steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v4 # Analyze repositories source metrics: # Create (or update) CODE_METRICS.md file. diff --git a/Nbic.References.Core/Interfaces/Repositories/IReferenceUsageRepository.cs b/Nbic.References.Core/Interfaces/Repositories/IReferenceUsageRepository.cs index b5ce58f..50ad8cc 100644 --- a/Nbic.References.Core/Interfaces/Repositories/IReferenceUsageRepository.cs +++ b/Nbic.References.Core/Interfaces/Repositories/IReferenceUsageRepository.cs @@ -1,19 +1,13 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Nbic.References.Core.Models; +using Nbic.References.Core.Models; -namespace Nbic.References.Core.Interfaces.Repositories +namespace Nbic.References.Core.Interfaces.Repositories; + +public interface IReferenceUsageRepository : IRepository { - public interface IReferenceUsageRepository : IRepository - { - Task> GetAll(int offset, int limit); - Task> GetFromReferenceId(Guid referenceId); - void DeleteForReference(Guid id); - void DeleteUsage(Guid id, int applicationId, Guid userId); - Task Add(ReferenceUsage referenceUsage); - Task AddRange(ReferenceUsage[] referenceUsages); - } -} + Task> GetAll(int offset, int limit); + Task> GetFromReferenceId(Guid referenceId); + void DeleteForReference(Guid id); + void DeleteUsage(Guid id, int applicationId, Guid userId); + Task Add(ReferenceUsage referenceUsage); + Task AddRange(IEnumerable referenceUsages); +} \ No newline at end of file diff --git a/Nbic.References.Core/Nbic.References.Core.csproj b/Nbic.References.Core/Nbic.References.Core.csproj index eb2460e..8a91831 100644 --- a/Nbic.References.Core/Nbic.References.Core.csproj +++ b/Nbic.References.Core/Nbic.References.Core.csproj @@ -1,7 +1,7 @@ - net6.0 + net8.0 enable enable diff --git a/Nbic.References.Infrastructure/Nbic.References.Infrastructure.csproj b/Nbic.References.Infrastructure/Nbic.References.Infrastructure.csproj index f18bc40..d06ee25 100644 --- a/Nbic.References.Infrastructure/Nbic.References.Infrastructure.csproj +++ b/Nbic.References.Infrastructure/Nbic.References.Infrastructure.csproj @@ -1,17 +1,17 @@ - net6.0 + net8.0 enable enable - + all runtime; build; native; contentfiles; analyzers; buildtransitive - - + + diff --git a/Nbic.References.Infrastructure/Repositories/DbContext/Migrations/SqlServerMigrations/20200203141446_Initial.Designer.cs b/Nbic.References.Infrastructure/Repositories/DbContext/Migrations/SqlServerMigrations/20200203141446_Initial.Designer.cs index c569381..5c91beb 100644 --- a/Nbic.References.Infrastructure/Repositories/DbContext/Migrations/SqlServerMigrations/20200203141446_Initial.Designer.cs +++ b/Nbic.References.Infrastructure/Repositories/DbContext/Migrations/SqlServerMigrations/20200203141446_Initial.Designer.cs @@ -1,13 +1,11 @@ // -using System; + using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; -using Microsoft.EntityFrameworkCore.Storage.ValueConversion; -using Nbic.References.EFCore; -namespace Nbic.References.EFCore.Migrations.SqlServerMigrations +namespace Nbic.References.Infrastructure.Repositories.DbContext.Migrations.SqlServerMigrations { [DbContext(typeof(SqlServerReferencesDbContext))] [Migration("20200203141446_Initial")] diff --git a/Nbic.References.Infrastructure/Repositories/DbContext/Migrations/SqlServerMigrations/20200203141446_Initial.cs b/Nbic.References.Infrastructure/Repositories/DbContext/Migrations/SqlServerMigrations/20200203141446_Initial.cs index f9a4845..7cc4832 100644 --- a/Nbic.References.Infrastructure/Repositories/DbContext/Migrations/SqlServerMigrations/20200203141446_Initial.cs +++ b/Nbic.References.Infrastructure/Repositories/DbContext/Migrations/SqlServerMigrations/20200203141446_Initial.cs @@ -1,72 +1,70 @@ -using System; -using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Migrations; -namespace Nbic.References.EFCore.Migrations.SqlServerMigrations +namespace Nbic.References.Infrastructure.Repositories.DbContext.Migrations.SqlServerMigrations; + +public partial class Initial : Migration { - public partial class Initial : Migration + protected override void Up(MigrationBuilder migrationBuilder) { - protected override void Up(MigrationBuilder migrationBuilder) - { - migrationBuilder.CreateTable( - name: "Reference", - columns: table => new - { - Id = table.Column(nullable: false), - ApplicationId = table.Column(nullable: true), - UserId = table.Column(nullable: false), - Author = table.Column(unicode: false, nullable: true), - Year = table.Column(unicode: false, nullable: true), - Title = table.Column(unicode: false, nullable: true), - Summary = table.Column(unicode: false, nullable: true), - Journal = table.Column(unicode: false, nullable: true), - Volume = table.Column(unicode: false, nullable: true), - Pages = table.Column(unicode: false, nullable: true), - Bibliography = table.Column(unicode: false, nullable: true), - Lastname = table.Column(unicode: false, nullable: true), - Middlename = table.Column(unicode: false, nullable: true), - Firstname = table.Column(unicode: false, nullable: true), - Url = table.Column(unicode: false, nullable: true), - Keywords = table.Column(unicode: false, nullable: true), - ReferenceString = table.Column(nullable: true), - EditDate = table.Column(type: "datetime", nullable: false, defaultValueSql: "GetUtcDate()") - }, - constraints: table => - { - table.PrimaryKey("PK_Id", x => x.Id); - }); + migrationBuilder.CreateTable( + name: "Reference", + columns: table => new + { + Id = table.Column(nullable: false), + ApplicationId = table.Column(nullable: true), + UserId = table.Column(nullable: false), + Author = table.Column(unicode: false, nullable: true), + Year = table.Column(unicode: false, nullable: true), + Title = table.Column(unicode: false, nullable: true), + Summary = table.Column(unicode: false, nullable: true), + Journal = table.Column(unicode: false, nullable: true), + Volume = table.Column(unicode: false, nullable: true), + Pages = table.Column(unicode: false, nullable: true), + Bibliography = table.Column(unicode: false, nullable: true), + Lastname = table.Column(unicode: false, nullable: true), + Middlename = table.Column(unicode: false, nullable: true), + Firstname = table.Column(unicode: false, nullable: true), + Url = table.Column(unicode: false, nullable: true), + Keywords = table.Column(unicode: false, nullable: true), + ReferenceString = table.Column(nullable: true), + EditDate = table.Column(type: "datetime", nullable: false, defaultValueSql: "GetUtcDate()") + }, + constraints: table => + { + table.PrimaryKey("PK_Id", x => x.Id); + }); - migrationBuilder.CreateTable( - name: "ReferenceUsage", - columns: table => new - { - ReferenceId = table.Column(nullable: false), - ApplicationId = table.Column(nullable: false), - UserId = table.Column(nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_ReferenceUsage", x => new { x.ReferenceId, x.ApplicationId, x.UserId }); - table.ForeignKey( - name: "FK_ReferenceUsage_Reference", - column: x => x.ReferenceId, - principalTable: "Reference", - principalColumn: "Id", - onDelete: ReferentialAction.Restrict); - }); + migrationBuilder.CreateTable( + name: "ReferenceUsage", + columns: table => new + { + ReferenceId = table.Column(nullable: false), + ApplicationId = table.Column(nullable: false), + UserId = table.Column(nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_ReferenceUsage", x => new { x.ReferenceId, x.ApplicationId, x.UserId }); + table.ForeignKey( + name: "FK_ReferenceUsage_Reference", + column: x => x.ReferenceId, + principalTable: "Reference", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + }); - migrationBuilder.CreateIndex( - name: "IX_UserId_ApplicationId", - table: "Reference", - columns: new[] { "UserId", "ApplicationId" }); - } + migrationBuilder.CreateIndex( + name: "IX_UserId_ApplicationId", + table: "Reference", + columns: ["UserId", "ApplicationId"]); + } - protected override void Down(MigrationBuilder migrationBuilder) - { - migrationBuilder.DropTable( - name: "ReferenceUsage"); + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "ReferenceUsage"); - migrationBuilder.DropTable( - name: "Reference"); - } + migrationBuilder.DropTable( + name: "Reference"); } -} +} \ No newline at end of file diff --git a/Nbic.References.Infrastructure/Repositories/DbContext/Migrations/SqlServerMigrations/SqlServerReferencesDbContextModelSnapshot.cs b/Nbic.References.Infrastructure/Repositories/DbContext/Migrations/SqlServerMigrations/SqlServerReferencesDbContextModelSnapshot.cs index 0497c7d..c77a945 100644 --- a/Nbic.References.Infrastructure/Repositories/DbContext/Migrations/SqlServerMigrations/SqlServerReferencesDbContextModelSnapshot.cs +++ b/Nbic.References.Infrastructure/Repositories/DbContext/Migrations/SqlServerMigrations/SqlServerReferencesDbContextModelSnapshot.cs @@ -5,6 +5,7 @@ using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using Nbic.References.EFCore; +using Nbic.References.Infrastructure.Repositories.DbContext; namespace Nbic.References.EFCore.Migrations.SqlServerMigrations { diff --git a/Nbic.References.Infrastructure/Repositories/DbContext/Migrations/SqliteMigrations/20200203141321_Initial.Designer.cs b/Nbic.References.Infrastructure/Repositories/DbContext/Migrations/SqliteMigrations/20200203141321_Initial.Designer.cs index f53dc83..4af6b01 100644 --- a/Nbic.References.Infrastructure/Repositories/DbContext/Migrations/SqliteMigrations/20200203141321_Initial.Designer.cs +++ b/Nbic.References.Infrastructure/Repositories/DbContext/Migrations/SqliteMigrations/20200203141321_Initial.Designer.cs @@ -1,12 +1,10 @@ // -using System; + using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; -using Microsoft.EntityFrameworkCore.Storage.ValueConversion; -using Nbic.References.EFCore; -namespace Nbic.References.EFCore.Migrations.SqliteMigrations +namespace Nbic.References.Infrastructure.Repositories.DbContext.Migrations.SqliteMigrations { [DbContext(typeof(SqliteReferencesDbContext))] [Migration("20200203141321_Initial")] diff --git a/Nbic.References.Infrastructure/Repositories/DbContext/Migrations/SqliteMigrations/20200203141321_Initial.cs b/Nbic.References.Infrastructure/Repositories/DbContext/Migrations/SqliteMigrations/20200203141321_Initial.cs index 71b2047..be7d994 100644 --- a/Nbic.References.Infrastructure/Repositories/DbContext/Migrations/SqliteMigrations/20200203141321_Initial.cs +++ b/Nbic.References.Infrastructure/Repositories/DbContext/Migrations/SqliteMigrations/20200203141321_Initial.cs @@ -1,72 +1,70 @@ -using System; -using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Migrations; -namespace Nbic.References.EFCore.Migrations.SqliteMigrations +namespace Nbic.References.Infrastructure.Repositories.DbContext.Migrations.SqliteMigrations; + +public partial class Initial : Migration { - public partial class Initial : Migration + protected override void Up(MigrationBuilder migrationBuilder) { - protected override void Up(MigrationBuilder migrationBuilder) - { - migrationBuilder.CreateTable( - name: "Reference", - columns: table => new - { - Id = table.Column(nullable: false), - ApplicationId = table.Column(nullable: true), - UserId = table.Column(nullable: false), - Author = table.Column(unicode: false, nullable: true), - Year = table.Column(unicode: false, nullable: true), - Title = table.Column(unicode: false, nullable: true), - Summary = table.Column(unicode: false, nullable: true), - Journal = table.Column(unicode: false, nullable: true), - Volume = table.Column(unicode: false, nullable: true), - Pages = table.Column(unicode: false, nullable: true), - Bibliography = table.Column(unicode: false, nullable: true), - Lastname = table.Column(unicode: false, nullable: true), - Middlename = table.Column(unicode: false, nullable: true), - Firstname = table.Column(unicode: false, nullable: true), - Url = table.Column(unicode: false, nullable: true), - Keywords = table.Column(unicode: false, nullable: true), - ReferenceString = table.Column(nullable: true), - EditDate = table.Column(type: "datetime", nullable: false, defaultValueSql: "date('now')") - }, - constraints: table => - { - table.PrimaryKey("PK_Id", x => x.Id); - }); + migrationBuilder.CreateTable( + name: "Reference", + columns: table => new + { + Id = table.Column(nullable: false), + ApplicationId = table.Column(nullable: true), + UserId = table.Column(nullable: false), + Author = table.Column(unicode: false, nullable: true), + Year = table.Column(unicode: false, nullable: true), + Title = table.Column(unicode: false, nullable: true), + Summary = table.Column(unicode: false, nullable: true), + Journal = table.Column(unicode: false, nullable: true), + Volume = table.Column(unicode: false, nullable: true), + Pages = table.Column(unicode: false, nullable: true), + Bibliography = table.Column(unicode: false, nullable: true), + Lastname = table.Column(unicode: false, nullable: true), + Middlename = table.Column(unicode: false, nullable: true), + Firstname = table.Column(unicode: false, nullable: true), + Url = table.Column(unicode: false, nullable: true), + Keywords = table.Column(unicode: false, nullable: true), + ReferenceString = table.Column(nullable: true), + EditDate = table.Column(type: "datetime", nullable: false, defaultValueSql: "date('now')") + }, + constraints: table => + { + table.PrimaryKey("PK_Id", x => x.Id); + }); - migrationBuilder.CreateTable( - name: "ReferenceUsage", - columns: table => new - { - ReferenceId = table.Column(nullable: false), - ApplicationId = table.Column(nullable: false), - UserId = table.Column(nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_ReferenceUsage", x => new { x.ReferenceId, x.ApplicationId, x.UserId }); - table.ForeignKey( - name: "FK_ReferenceUsage_Reference", - column: x => x.ReferenceId, - principalTable: "Reference", - principalColumn: "Id", - onDelete: ReferentialAction.Restrict); - }); + migrationBuilder.CreateTable( + name: "ReferenceUsage", + columns: table => new + { + ReferenceId = table.Column(nullable: false), + ApplicationId = table.Column(nullable: false), + UserId = table.Column(nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_ReferenceUsage", x => new { x.ReferenceId, x.ApplicationId, x.UserId }); + table.ForeignKey( + name: "FK_ReferenceUsage_Reference", + column: x => x.ReferenceId, + principalTable: "Reference", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + }); - migrationBuilder.CreateIndex( - name: "IX_UserId_ApplicationId", - table: "Reference", - columns: new[] { "UserId", "ApplicationId" }); - } + migrationBuilder.CreateIndex( + name: "IX_UserId_ApplicationId", + table: "Reference", + columns: ["UserId", "ApplicationId"]); + } - protected override void Down(MigrationBuilder migrationBuilder) - { - migrationBuilder.DropTable( - name: "ReferenceUsage"); + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "ReferenceUsage"); - migrationBuilder.DropTable( - name: "Reference"); - } + migrationBuilder.DropTable( + name: "Reference"); } -} +} \ No newline at end of file diff --git a/Nbic.References.Infrastructure/Repositories/DbContext/Migrations/SqliteMigrations/SqliteReferencesDbContextModelSnapshot.cs b/Nbic.References.Infrastructure/Repositories/DbContext/Migrations/SqliteMigrations/SqliteReferencesDbContextModelSnapshot.cs index be133d0..adb3b24 100644 --- a/Nbic.References.Infrastructure/Repositories/DbContext/Migrations/SqliteMigrations/SqliteReferencesDbContextModelSnapshot.cs +++ b/Nbic.References.Infrastructure/Repositories/DbContext/Migrations/SqliteMigrations/SqliteReferencesDbContextModelSnapshot.cs @@ -4,6 +4,7 @@ using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using Nbic.References.EFCore; +using Nbic.References.Infrastructure.Repositories.DbContext; namespace Nbic.References.EFCore.Migrations.SqliteMigrations { diff --git a/Nbic.References.Infrastructure/Repositories/DbContext/ReferencesDbContext.cs b/Nbic.References.Infrastructure/Repositories/DbContext/ReferencesDbContext.cs index e142329..678f7ae 100644 --- a/Nbic.References.Infrastructure/Repositories/DbContext/ReferencesDbContext.cs +++ b/Nbic.References.Infrastructure/Repositories/DbContext/ReferencesDbContext.cs @@ -1,147 +1,145 @@ using Microsoft.EntityFrameworkCore; using Nbic.References.Core.Models; -using Index = Nbic.References.Infrastructure.Services.Indexing.Index; -namespace Nbic.References.EFCore +namespace Nbic.References.Infrastructure.Repositories.DbContext; + +public partial class ReferencesDbContext : Microsoft.EntityFrameworkCore.DbContext { - public partial class ReferencesDbContext : DbContext + public ReferencesDbContext() { - public ReferencesDbContext() - { - } + } - public ReferencesDbContext(DbContextOptions options) - : base(options) - { - } + public ReferencesDbContext(DbContextOptions options) + : base(options) + { + } - public virtual DbSet Reference { get; set; } = null!; - public virtual DbSet ReferenceUsage { get; set; } = null!; + public virtual DbSet Reference { get; set; } = null!; + public virtual DbSet ReferenceUsage { get; set; } = null!; - protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) + { + if (!optionsBuilder.IsConfigured) { - if (!optionsBuilder.IsConfigured) - { - } } + } - protected override void OnModelCreating(ModelBuilder modelBuilder) - { - modelBuilder.HasAnnotation("ProductVersion", "2.2.3-servicing-35854"); + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + modelBuilder.HasAnnotation("ProductVersion", "2.2.3-servicing-35854"); - modelBuilder.Entity(entity => - { - entity.HasKey(e => e.Id) - .HasName("PK_Id"); + modelBuilder.Entity(entity => + { + entity.HasKey(e => e.Id) + .HasName("PK_Id"); - entity.ToTable("Reference"); + entity.ToTable("Reference"); - entity.HasIndex(e => new { e.UserId, e.ApplicationId }) - .HasDatabaseName("IX_UserId_ApplicationId"); + entity.HasIndex(e => new { e.UserId, e.ApplicationId }) + .HasDatabaseName("IX_UserId_ApplicationId"); - entity.Property(e => e.Id) - .HasColumnName("Id") - .ValueGeneratedNever(); + entity.Property(e => e.Id) + .HasColumnName("Id") + .ValueGeneratedNever(); - entity.Property(e => e.ApplicationId).HasColumnName("ApplicationId"); + entity.Property(e => e.ApplicationId).HasColumnName("ApplicationId"); - entity.Property(e => e.Author).IsUnicode(false); + entity.Property(e => e.Author).IsUnicode(false); - entity.Property(e => e.Bibliography).IsUnicode(false); - if (this.Database.IsSqlite()) - { - entity.Property(e => e.EditDate) - .HasColumnType("datetime") - .HasDefaultValueSql("date('now')"); - } - else - { - entity.Property(e => e.EditDate) + entity.Property(e => e.Bibliography).IsUnicode(false); + if (this.Database.IsSqlite()) + { + entity.Property(e => e.EditDate) + .HasColumnType("datetime") + .HasDefaultValueSql("date('now')"); + } + else + { + entity.Property(e => e.EditDate) .HasColumnType("datetime") .HasDefaultValueSql("GetUtcDate()"); - } + } - entity.Property(e => e.Firstname).IsUnicode(false); + entity.Property(e => e.Firstname).IsUnicode(false); - entity.Property(e => e.UserId).HasColumnName("UserId"); + entity.Property(e => e.UserId).HasColumnName("UserId"); - entity.Property(e => e.ReferenceString).HasColumnName("ReferenceString"); + entity.Property(e => e.ReferenceString).HasColumnName("ReferenceString"); - entity.Property(e => e.Journal).IsUnicode(false); + entity.Property(e => e.Journal).IsUnicode(false); - entity.Property(e => e.Keywords).IsUnicode(false); + entity.Property(e => e.Keywords).IsUnicode(false); - entity.Property(e => e.Lastname).IsUnicode(false); + entity.Property(e => e.Lastname).IsUnicode(false); - entity.Property(e => e.Middlename).IsUnicode(false); + entity.Property(e => e.Middlename).IsUnicode(false); - entity.Property(e => e.Pages).IsUnicode(false); + entity.Property(e => e.Pages).IsUnicode(false); - entity.Property(e => e.Summary).IsUnicode(false); + entity.Property(e => e.Summary).IsUnicode(false); - entity.Property(e => e.Title).IsUnicode(false); + entity.Property(e => e.Title).IsUnicode(false); - entity.Property(e => e.Url) - .HasColumnName("Url") - .IsUnicode(false); + entity.Property(e => e.Url) + .HasColumnName("Url") + .IsUnicode(false); - entity.Property(e => e.Volume).IsUnicode(false); + entity.Property(e => e.Volume).IsUnicode(false); - entity.Property(e => e.Year).IsUnicode(false); - }); + entity.Property(e => e.Year).IsUnicode(false); + }); - modelBuilder.Entity(entity => - { - entity.HasKey(e => new { e.ReferenceId, e.ApplicationId, e.UserId }); - - entity.ToTable("ReferenceUsage"); + modelBuilder.Entity(entity => + { + entity.HasKey(e => new { e.ReferenceId, e.ApplicationId, e.UserId }); - entity.Property(e => e.ReferenceId).HasColumnName("ReferenceId"); + entity.ToTable("ReferenceUsage"); - entity.Property(e => e.ApplicationId).HasColumnName("ApplicationId"); + entity.Property(e => e.ReferenceId).HasColumnName("ReferenceId"); - entity.Property(e => e.UserId).HasColumnName("UserId"); + entity.Property(e => e.ApplicationId).HasColumnName("ApplicationId"); - entity.HasOne(d => d.Reference) - .WithMany(p => p.ReferenceUsage) - .HasForeignKey(d => d.ReferenceId) - .OnDelete(DeleteBehavior.ClientSetNull) - .HasConstraintName("FK_ReferenceUsage_Reference"); - }); - } + entity.Property(e => e.UserId).HasColumnName("UserId"); + entity.HasOne(d => d.Reference) + .WithMany(p => p.ReferenceUsage) + .HasForeignKey(d => d.ReferenceId) + .OnDelete(DeleteBehavior.ClientSetNull) + .HasConstraintName("FK_ReferenceUsage_Reference"); + }); } - public class SqliteReferencesDbContext : ReferencesDbContext - { - private readonly string _dbConnectionString = "DataSource=:memory:"; +} - public SqliteReferencesDbContext(string dbConnectionString) - { - _dbConnectionString = dbConnectionString; - } - //public SqliteReferencesDbContext() - //{ - // _dbConnectionString = "Data Source=references.db"; - //} +public class SqliteReferencesDbContext : ReferencesDbContext +{ + private readonly string _dbConnectionString = "DataSource=:memory:"; - protected override void OnConfiguring(DbContextOptionsBuilder options) - => options.UseSqlite(_dbConnectionString); - } - public class SqlServerReferencesDbContext : ReferencesDbContext + public SqliteReferencesDbContext(string dbConnectionString) { - private readonly string _dbConnectionString; + _dbConnectionString = dbConnectionString; + } + //public SqliteReferencesDbContext() + //{ + // _dbConnectionString = "Data Source=references.db"; + //} - public SqlServerReferencesDbContext(string dbConnectionString) - { - _dbConnectionString = dbConnectionString; - } - //public SqlServerReferencesDbContext() - //{ - // _dbConnectionString = "Server = localhost; Database = ref2; Integrated Security = true; MultipleActiveResultSets = true"; - //} + protected override void OnConfiguring(DbContextOptionsBuilder options) + => options.UseSqlite(_dbConnectionString); +} +public class SqlServerReferencesDbContext : ReferencesDbContext +{ + private readonly string _dbConnectionString; - protected override void OnConfiguring(DbContextOptionsBuilder options) - => options.UseSqlServer(_dbConnectionString); + public SqlServerReferencesDbContext(string dbConnectionString) + { + _dbConnectionString = dbConnectionString; } -} + //public SqlServerReferencesDbContext() + //{ + // _dbConnectionString = "Server = localhost; Database = ref2; Integrated Security = true; MultipleActiveResultSets = true"; + //} + + protected override void OnConfiguring(DbContextOptionsBuilder options) + => options.UseSqlServer(_dbConnectionString); +} \ No newline at end of file diff --git a/Nbic.References.Infrastructure/Repositories/ReferenceRepository.cs b/Nbic.References.Infrastructure/Repositories/ReferenceRepository.cs index 3a4686d..9325a4a 100644 --- a/Nbic.References.Infrastructure/Repositories/ReferenceRepository.cs +++ b/Nbic.References.Infrastructure/Repositories/ReferenceRepository.cs @@ -2,7 +2,7 @@ using Nbic.References.Core.Exceptions; using Nbic.References.Core.Interfaces.Repositories; using Nbic.References.Core.Models; -using Nbic.References.EFCore; +using Nbic.References.Infrastructure.Repositories.DbContext; using Index = Nbic.References.Infrastructure.Services.Indexing.Index; namespace Nbic.References.Infrastructure.Repositories; diff --git a/Nbic.References.Infrastructure/Repositories/ReferenceUsageRepository.cs b/Nbic.References.Infrastructure/Repositories/ReferenceUsageRepository.cs index 87cff72..63e3ca9 100644 --- a/Nbic.References.Infrastructure/Repositories/ReferenceUsageRepository.cs +++ b/Nbic.References.Infrastructure/Repositories/ReferenceUsageRepository.cs @@ -1,87 +1,81 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore; using Nbic.References.Core.Exceptions; using Nbic.References.Core.Interfaces.Repositories; using Nbic.References.Core.Models; -using Nbic.References.EFCore; +using Nbic.References.Infrastructure.Repositories.DbContext; -namespace Nbic.References.Infrastructure.Repositories +namespace Nbic.References.Infrastructure.Repositories; + +public class ReferenceUsageRepository : Repository, IReferenceUsageRepository { - public class ReferenceUsageRepository : Repository, IReferenceUsageRepository + public ReferenceUsageRepository(ReferencesDbContext dbContext) : base(dbContext) { - public ReferenceUsageRepository(ReferencesDbContext dbContext) : base(dbContext) - { - } + } - public Task> GetAll(int offset, int limit) - { - return _dbContext.ReferenceUsage.OrderBy(x => x.ReferenceId) - .Skip(offset).Take(limit).ToListAsync(); - } + public Task> GetAll(int offset, int limit) + { + return _dbContext.ReferenceUsage.OrderBy(x => x.ReferenceId) + .Skip(offset).Take(limit).ToListAsync(); + } - public Task> GetFromReferenceId(Guid referenceId) - { - return _dbContext.ReferenceUsage.Where(x => x.ReferenceId == referenceId).ToListAsync(); - } + public Task> GetFromReferenceId(Guid referenceId) + { + return _dbContext.ReferenceUsage.Where(x => x.ReferenceId == referenceId).ToListAsync(); + } - public void DeleteForReference(Guid id) - { - var entity = _dbContext.Reference.SingleOrDefault(x=>x.Id == id); - if (entity == null) throw new NotFoundException("Reference", id); - var entities = _dbContext.ReferenceUsage.Where(x => x.ReferenceId == id).ToArray(); - if (entities.Length == 0) return; + public void DeleteForReference(Guid id) + { + var entity = _dbContext.Reference.SingleOrDefault(x=>x.Id == id); + if (entity == null) throw new NotFoundException("Reference", id); + var entities = _dbContext.ReferenceUsage.Where(x => x.ReferenceId == id).ToArray(); + if (entities.Length == 0) return; - _dbContext.ReferenceUsage.RemoveRange(entities); - _dbContext.SaveChanges(); - } + _dbContext.ReferenceUsage.RemoveRange(entities); + _dbContext.SaveChanges(); + } - public void DeleteUsage(Guid id, int applicationId, Guid userId) - { - var entities = _dbContext.ReferenceUsage.Where(x => x.ReferenceId == id && x.ApplicationId == applicationId && x.UserId == userId).ToArray(); - if (entities.Length == 0) throw new NotFoundException(); + public void DeleteUsage(Guid id, int applicationId, Guid userId) + { + var entities = _dbContext.ReferenceUsage.Where(x => x.ReferenceId == id && x.ApplicationId == applicationId && x.UserId == userId).ToArray(); + if (entities.Length == 0) throw new NotFoundException(); - _dbContext.ReferenceUsage.RemoveRange(entities); - _dbContext.SaveChanges(); - } + _dbContext.ReferenceUsage.RemoveRange(entities); + _dbContext.SaveChanges(); + } - public async Task Add(ReferenceUsage referenceUsage) - { - var any = _dbContext.ReferenceUsage.Any( - x => x.ReferenceId == referenceUsage.ReferenceId && x.ApplicationId == referenceUsage.ApplicationId - && x.UserId == referenceUsage.UserId); - if (any) return; + public async Task Add(ReferenceUsage referenceUsage) + { + var any = _dbContext.ReferenceUsage.Any( + x => x.ReferenceId == referenceUsage.ReferenceId && x.ApplicationId == referenceUsage.ApplicationId + && x.UserId == referenceUsage.UserId); + if (any) return; - _dbContext.ReferenceUsage.Add(referenceUsage); + _dbContext.ReferenceUsage.Add(referenceUsage); - await _dbContext.SaveChangesAsync(); - } + await _dbContext.SaveChangesAsync(); + } - public async Task AddRange(ReferenceUsage[] referenceUsages) + public async Task AddRange(IEnumerable referenceUsages) + { + var toSave = new List(); + foreach (var referenceUsage in referenceUsages) { - var toSave = new List(); - foreach (var referenceUsage in referenceUsages) - { - if (_dbContext.ReferenceUsage.Any( - x => x.ReferenceId == referenceUsage.ReferenceId && x.ApplicationId == referenceUsage.ApplicationId - && x.UserId == referenceUsage.UserId)) continue; + if (_dbContext.ReferenceUsage.Any( + x => x.ReferenceId == referenceUsage.ReferenceId && x.ApplicationId == referenceUsage.ApplicationId + && x.UserId == referenceUsage.UserId)) continue; - if (_dbContext.Reference.Any(x => x.Id == referenceUsage.ReferenceId)) - { - toSave.Add(referenceUsage); - } + if (_dbContext.Reference.Any(x => x.Id == referenceUsage.ReferenceId)) + { + toSave.Add(referenceUsage); } + } - if (!toSave.Any()) return true; + if (!toSave.Any()) return true; - _dbContext.ReferenceUsage.AddRange(toSave); + _dbContext.ReferenceUsage.AddRange(toSave); - await _dbContext.SaveChangesAsync(); + await _dbContext.SaveChangesAsync(); - return true; - } + return true; } -} +} \ No newline at end of file diff --git a/Nbic.References.Infrastructure/Repositories/Repository.cs b/Nbic.References.Infrastructure/Repositories/Repository.cs index 8fc95c8..b777da7 100644 --- a/Nbic.References.Infrastructure/Repositories/Repository.cs +++ b/Nbic.References.Infrastructure/Repositories/Repository.cs @@ -1,28 +1,27 @@ using Microsoft.EntityFrameworkCore; using Nbic.References.Core.Interfaces.Repositories; -using Nbic.References.EFCore; +using Nbic.References.Infrastructure.Repositories.DbContext; -namespace Nbic.References.Infrastructure.Repositories +namespace Nbic.References.Infrastructure.Repositories; + +public class Repository : IRepository where T : class { - public class Repository : IRepository where T : class - { - protected readonly ReferencesDbContext _dbContext; - private readonly DbSet _dbSet; + protected readonly ReferencesDbContext _dbContext; + private readonly DbSet _dbSet; - protected Repository(ReferencesDbContext dbContext) - { - _dbContext = dbContext; - _dbSet = _dbContext.Set(); - } + protected Repository(ReferencesDbContext dbContext) + { + _dbContext = dbContext; + _dbSet = _dbContext.Set(); + } - public int Count() - { - return _dbSet.Count(); - } + public int Count() + { + return _dbSet.Count(); + } - public Task CountAsync() - { - return _dbSet.CountAsync(); - } + public Task CountAsync() + { + return _dbSet.CountAsync(); } -} +} \ No newline at end of file diff --git a/Nbic.References.Infrastructure/Services/Indexing/Index.cs b/Nbic.References.Infrastructure/Services/Indexing/Index.cs index 7b23ba1..4de0d3d 100644 --- a/Nbic.References.Infrastructure/Services/Indexing/Index.cs +++ b/Nbic.References.Infrastructure/Services/Indexing/Index.cs @@ -11,21 +11,26 @@ namespace Nbic.References.Infrastructure.Services.Indexing; public class Index : IDisposable { - private const string Field_Id = "Id"; - private const string Field_String = "Reference"; + private const string FieldId = "Id"; + private const string FieldString = "Reference"; private IndexWriter _writer; private bool firstUse = true; - private HashSet _stopwords = new HashSet { "a", "an", "and", "are", "as", "at", "be", "but", "by", "for", "if", "in", "into", "is", "it", "no", "not", "of", "on", "or", "such", "that", "the", "their", "then", "there", "these", "they", "this", "to", "was", "will", "with" }; // StopAnalyzer.ENGLISH_STOP_WORDS_SET.ToArray().ToHashSet(); + private HashSet _stopwords = + [ + "a", "an", "and", "are", "as", "at", "be", "but", "by", "for", "if", "in", "into", "is", "it", "no", "not", + "of", "on", "or", "such", "that", "the", "their", "then", "there", "these", "they", "this", "to", "was", "will", + "with" + ]; // StopAnalyzer.ENGLISH_STOP_WORDS_SET.ToArray().ToHashSet(); private FSDirectory _dir; - private static object _theLock = new object(); + private static object _theLock = new(); private bool _lockWasTaken = false; public Index(bool waitForLockFile = false, bool deleteAndCreateIndex = false) { // Ensures index backwards compatibility - var AppLuceneVersion = LuceneVersion.LUCENE_48; + var appLuceneVersion = LuceneVersion.LUCENE_48; var applicationRoot = GetApplicationRoot(); if (string.IsNullOrWhiteSpace(applicationRoot)) @@ -55,11 +60,11 @@ public Index(bool waitForLockFile = false, bool deleteAndCreateIndex = false) _dir = FSDirectory.Open(indexLocation); //create an analyzer to process the text - var analyzer = new StandardAnalyzer(AppLuceneVersion); + var analyzer = new StandardAnalyzer(appLuceneVersion); //_idAnalyser = new SimpleAnalyzer(AppLuceneVersion); //create an index writer - var indexConfig = new IndexWriterConfig(AppLuceneVersion, analyzer); + var indexConfig = new IndexWriterConfig(appLuceneVersion, analyzer); if (deleteAndCreateIndex) { indexConfig.OpenMode = OpenMode.CREATE; @@ -80,16 +85,16 @@ public void AddOrUpdate(Reference reference) if (indexString.Length <= 0) return; - Document doc = new Document + var doc = new Document { - new StringField(Field_Id, reference.Id.ToString(), Field.Store.YES), + new StringField(FieldId, reference.Id.ToString(), Field.Store.YES), // StringField indexes but doesn't tokenize - new TextField(Field_String, indexString, Field.Store.YES) + new TextField(FieldString, indexString, Field.Store.YES) //new TextField("favoritePhrase", source.FavoritePhrase, Field.Store.YES) }; // var id = new Term("Id", reference.Id.ToString()); // _writer.DeleteDocuments(id); - _writer.UpdateDocument(new Term(Field_Id, reference.Id.ToString()), doc); + _writer.UpdateDocument(new Term(FieldId, reference.Id.ToString()), doc); // _writer.AddDocument(doc); //_writer.Flush(triggerMerge: true, applyAllDeletes: true); _writer.Commit(); @@ -109,16 +114,16 @@ public void AddOrUpdate(IEnumerable refs) var indexString = GetIndexString(reference); //if (indexString.Length <= 0) continue; - Document doc = new Document + var doc = new Document { - new StringField(Field_Id, reference.Id.ToString(), Field.Store.YES), + new StringField(FieldId, reference.Id.ToString(), Field.Store.YES), // StringField indexes but doesn't tokenize - new TextField(Field_String, indexString, Field.Store.YES) + new TextField(FieldString, indexString, Field.Store.YES) //new TextField("favoritePhrase", source.FavoritePhrase, Field.Store.YES) }; // var id = new Term("Id", reference.Id.ToString()); // _writer.DeleteDocuments(id); - _writer.UpdateDocument(new Term(Field_Id, reference.Id.ToString()), doc); + _writer.UpdateDocument(new Term(FieldId, reference.Id.ToString()), doc); // _writer.AddDocument(doc); @@ -160,7 +165,7 @@ public IEnumerable SearchReference(string terms, int offset, int limit) if (items.Length == 1) { - query = new TermQuery(new Term(Field_String, items[0])); + query = new TermQuery(new Term(FieldString, items[0])); } else { @@ -169,7 +174,7 @@ public IEnumerable SearchReference(string terms, int offset, int limit) { if (!_stopwords.Contains(item)) { - ((BooleanQuery)query).Add(new BooleanClause(new TermQuery(new Term(Field_String, item)), Occur.MUST)); + ((BooleanQuery)query).Add(new BooleanClause(new TermQuery(new Term(FieldString, item)), Occur.MUST)); } } @@ -185,29 +190,33 @@ public IEnumerable SearchReference(string terms, int offset, int limit) count++; if (count <= startAt) continue; var foundDoc = searcher.Doc(hit.Doc); - var guid = Guid.Parse(foundDoc.Get(Field_Id)); + var guid = Guid.Parse(foundDoc.Get(FieldId)); found.Add(guid); yield return guid; } var longTerms = items.Where(x => x.Length > 2).ToArray(); - if (longTerms.Length <= 0) yield break; - - if (longTerms.Length == 1) - { - query = new WildcardQuery(new Term(Field_String, $"{longTerms[0]}*")); - } - else + switch (longTerms.Length) { - query = new BooleanQuery(); - foreach (var item in longTerms) + case <= 0: + yield break; + case 1: + query = new WildcardQuery(new Term(FieldString, $"{longTerms[0]}*")); + break; + default: { - if (!_stopwords.Contains(item)) + query = new BooleanQuery(); + foreach (var item in longTerms) { - ((BooleanQuery)query).Add(new WildcardQuery(new Term(Field_String, $"{item}*")), Occur.MUST); + if (!_stopwords.Contains(item)) + { + ((BooleanQuery)query).Add(new WildcardQuery(new Term(FieldString, $"{item}*")), Occur.MUST); + } + } + break; } } @@ -219,7 +228,7 @@ public IEnumerable SearchReference(string terms, int offset, int limit) count++; if (count <= startAt) continue; var foundDoc = searcher.Doc(hit.Doc); - var guid = Guid.Parse(foundDoc.Get(Field_Id)); + var guid = Guid.Parse(foundDoc.Get(FieldId)); if (found.Contains(guid)) { continue; @@ -231,7 +240,7 @@ public IEnumerable SearchReference(string terms, int offset, int limit) public void Delete(Guid newGuid) { - _writer.DeleteDocuments(new Term(Field_Id, newGuid.ToString())); + _writer.DeleteDocuments(new Term(FieldId, newGuid.ToString())); //_writer.Flush(triggerMerge: true, applyAllDeletes: true); _writer.Commit(); } @@ -246,7 +255,8 @@ public void ClearIndex() //_writer.Flush(true,true); _writer.Commit(); } - public string GetApplicationRoot() + + private static string GetApplicationRoot() { var exePath = Path.GetDirectoryName(System.Reflection .Assembly.GetExecutingAssembly().Location); diff --git a/Nbic.References.Tests/AuthenticationTest.cs b/Nbic.References.Tests/AuthenticationTest.cs index 3b22ef7..49e41b3 100644 --- a/Nbic.References.Tests/AuthenticationTest.cs +++ b/Nbic.References.Tests/AuthenticationTest.cs @@ -1,64 +1,64 @@ -using System; -using System.Collections.Generic; -using System.Net; -using System.Net.Http; -using System.Text; -using IdentityModel.Client; -using Xunit; - -namespace Nbic.References.Tests -{ - public class AuthenticationTest - { - //[Fact] - //public async void CanNotDeleteNonExistingDoc() - //{ - // // discover endpoints from metadata - // var client = new HttpClient(); - // var disco = await client.GetDiscoveryDocumentAsync("https://id.test.artsdatabanken.no"); - // Assert.Equal(disco.IsError, false); - - // if (disco.IsError) - // { - // Console.WriteLine(disco.Error); - // return; - // } - - // var tokenResponse = await client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest - // { - // Address = disco.TokenEndpoint, - - // ClientId = "ReferencesApiClient", - // ClientSecret = "478f8f8d-b9b9-3bb1-219a-8bc2e3c2c949", - // Scope = "references_api" - // }); - - // Assert.Equal(tokenResponse.IsError, false); - - // if (tokenResponse.IsError) - // { - // Console.WriteLine(tokenResponse.Error); - // return; - // } - - // Console.WriteLine(tokenResponse.Json); - - // // call api - // var client2 = new HttpClient(); - // client2.SetBearerToken(tokenResponse.AccessToken); - - // var response = await client2.DeleteAsync("https://referenceapi.artsdatabanken.no/api/References/8041b97a-5d18-422b-904b-a4407cfd5a85"); - // Assert.True(response.IsSuccessStatusCode, response.StatusCode.ToString()); - // if (!response.IsSuccessStatusCode) - // { - // Console.WriteLine(response.StatusCode); - // } - // else - // { - // var content = await response.Content.ReadAsStringAsync(); - // Assert.True(content.Length > 100); - // //Console.WriteLine(JArray.Parse(content)); - // } - //} - } -} +// using System; +// using System.Collections.Generic; +// using System.Net; +// using System.Net.Http; +// using System.Text; +// using IdentityModel.Client; +// using Xunit; +// +// namespace Nbic.References.Tests +// { +// public class AuthenticationTest +// { +// //[Fact] +// //public async void CanNotDeleteNonExistingDoc() +// //{ +// // // discover endpoints from metadata +// // var client = new HttpClient(); +// // var disco = await client.GetDiscoveryDocumentAsync("https://id.test.artsdatabanken.no"); +// // Assert.Equal(disco.IsError, false); +// +// // if (disco.IsError) +// // { +// // Console.WriteLine(disco.Error); +// // return; +// // } +// +// // var tokenResponse = await client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest +// // { +// // Address = disco.TokenEndpoint, +// +// // ClientId = "ReferencesApiClient", +// // ClientSecret = "478f8f8d-b9b9-3bb1-219a-8bc2e3c2c949", +// // Scope = "references_api" +// // }); +// +// // Assert.Equal(tokenResponse.IsError, false); +// +// // if (tokenResponse.IsError) +// // { +// // Console.WriteLine(tokenResponse.Error); +// // return; +// // } +// +// // Console.WriteLine(tokenResponse.Json); +// +// // // call api +// // var client2 = new HttpClient(); +// // client2.SetBearerToken(tokenResponse.AccessToken); +// +// // var response = await client2.DeleteAsync("https://referenceapi.artsdatabanken.no/api/References/8041b97a-5d18-422b-904b-a4407cfd5a85"); +// // Assert.True(response.IsSuccessStatusCode, response.StatusCode.ToString()); +// // if (!response.IsSuccessStatusCode) +// // { +// // Console.WriteLine(response.StatusCode); +// // } +// // else +// // { +// // var content = await response.Content.ReadAsStringAsync(); +// // Assert.True(content.Length > 100); +// // //Console.WriteLine(JArray.Parse(content)); +// // } +// //} +// } +// } diff --git a/Nbic.References.Tests/IndexerTests.cs b/Nbic.References.Tests/IndexerTests.cs index 2d0b964..394f6f8 100644 --- a/Nbic.References.Tests/IndexerTests.cs +++ b/Nbic.References.Tests/IndexerTests.cs @@ -11,260 +11,243 @@ public class IndexerTests [Fact] public void CanIndexAnDocument() { - using (var index = new Index(true)) - { - var newGuid = Guid.Parse("b1df2d4b-e06a-421d-865b-03f3dfdf6913"); - index.AddOrUpdate(new Reference { Id = newGuid, Title = "Creepy" }); - var result = index.SearchReference("Creepy", 0, 10); - Assert.Single(result.ToArray()); - index.AddOrUpdate(new Reference { Id = newGuid, Title = "Snoopy Dog" }); - result = index.SearchReference("Creepy", 0, 10); - Assert.Empty(result.ToArray()); - result = index.SearchReference("Snoopy Dog", 0, 10); - Assert.Single(result.ToArray()); - index.Delete(newGuid); - result = index.SearchReference("Snoopy Dog", 0, 10); - Assert.Empty(result.ToArray()); - } + using var index = new Index(true); + var newGuid = Guid.Parse("b1df2d4b-e06a-421d-865b-03f3dfdf6913"); + index.AddOrUpdate(new Reference { Id = newGuid, Title = "Creepy" }); + var result = index.SearchReference("Creepy", 0, 10); + Assert.Single(result.ToArray()); + index.AddOrUpdate(new Reference { Id = newGuid, Title = "Snoopy Dog" }); + result = index.SearchReference("Creepy", 0, 10); + Assert.Empty(result.ToArray()); + result = index.SearchReference("Snoopy Dog", 0, 10); + Assert.Single(result.ToArray()); + index.Delete(newGuid); + result = index.SearchReference("Snoopy Dog", 0, 10); + Assert.Empty(result.ToArray()); } [Fact] public void CanFindReidarElvenReferanseDocument() { - using (var index = new Index(true, true)) + using var index = new Index(true, true); + var referanse = new Reference { - var referanse = new Reference - { - Id = Guid.Parse("208daeb0-a917-45cd-9b0f-fa21f4300d02"), - ApplicationId = 8, - UserId = new Guid("3ed89222-de9a-4df3-9e95-67f7fcac67a3"), - Author = "Elven, R.", - Year = "1980", - Title = null, - Summary = null, - Journal = null, - Volume = null, - Pages = null, - Bibliography = - "Elven, R. 1980. Association analysis of moraine vegetation at the glacier Hardangerjökulen, Finse, South Norway. - Norw. J. Bot. 25: 171-191.", - Lastname = null, - Middlename = null, - Firstname = null, - Url = null, - Keywords = "Fje Veg Ass Dyn NNNd#2", - //ImportXml = null, - EditDate = DateTime.Parse("2010-04-26T08:09:18.613") - }; - - index.AddOrUpdate(referanse); - var result = index.SearchReference("elven", 0, 10); - Assert.Single(result.ToArray()); - result = index.SearchReference("elven Association", 0, 10); - Assert.Single(result.ToArray()); - result = index.SearchReference("elven. R.", 0, 10); - Assert.Single(result.ToArray()); + Id = Guid.Parse("208daeb0-a917-45cd-9b0f-fa21f4300d02"), + ApplicationId = 8, + UserId = new Guid("3ed89222-de9a-4df3-9e95-67f7fcac67a3"), + Author = "Elven, R.", + Year = "1980", + Title = null, + Summary = null, + Journal = null, + Volume = null, + Pages = null, + Bibliography = + "Elven, R. 1980. Association analysis of moraine vegetation at the glacier Hardangerjökulen, Finse, South Norway. - Norw. J. Bot. 25: 171-191.", + Lastname = null, + Middlename = null, + Firstname = null, + Url = null, + Keywords = "Fje Veg Ass Dyn NNNd#2", + //ImportXml = null, + EditDate = DateTime.Parse("2010-04-26T08:09:18.613") + }; - } + index.AddOrUpdate(referanse); + var result = index.SearchReference("elven", 0, 10); + Assert.Single(result.ToArray()); + result = index.SearchReference("elven Association", 0, 10); + Assert.Single(result.ToArray()); + result = index.SearchReference("elven. R.", 0, 10); + Assert.Single(result.ToArray()); } [Fact] public void CanFindHoemDirectReferanseDocument() { - using (var index = new Index(true)) + using var index = new Index(true); + index.ClearIndex(); + var referanse = new Reference { - index.ClearIndex(); - var referanse = new Reference - { - Id = Guid.Parse("208daeb0-a917-45cd-9b0f-fa21f4300d01"), - ApplicationId = 8, - UserId = new Guid("3ed89222-de9a-4df3-9e95-67f7fcac67a3"), - Author = "Horem, R.", - Year = "1980", - Title = null, - Summary = null, - Journal = null, - Volume = null, - Pages = null, - Bibliography = null, - Lastname = null, - Middlename = null, - Firstname = null, - Url = null, - Keywords = "Fje Veg Ass Dyn NNNd#2", - ReferenceString = "Hoem, R. 1980. Association analysis of moraine vegetation at the glacier Hardangerjökulen, Finse, South Norway. - Norw. J. Bot. 25: 171-191.", - EditDate = DateTime.Parse("2010-04-26T08:09:18.613") - }; + Id = Guid.Parse("208daeb0-a917-45cd-9b0f-fa21f4300d01"), + ApplicationId = 8, + UserId = new Guid("3ed89222-de9a-4df3-9e95-67f7fcac67a3"), + Author = "Horem, R.", + Year = "1980", + Title = null, + Summary = null, + Journal = null, + Volume = null, + Pages = null, + Bibliography = null, + Lastname = null, + Middlename = null, + Firstname = null, + Url = null, + Keywords = "Fje Veg Ass Dyn NNNd#2", + ReferenceString = "Hoem, R. 1980. Association analysis of moraine vegetation at the glacier Hardangerjökulen, Finse, South Norway. - Norw. J. Bot. 25: 171-191.", + EditDate = DateTime.Parse("2010-04-26T08:09:18.613") + }; - index.AddOrUpdate(referanse); - var result = index.SearchReference("hoem", 0, 10); - Assert.Single(result.ToArray()); - result = index.SearchReference("hoem Association", 0, 10); - Assert.Single(result.ToArray()); - result = index.SearchReference("hoem. R.", 0, 10); - Assert.Single(result.ToArray()); - - } + index.AddOrUpdate(referanse); + var result = index.SearchReference("hoem", 0, 10); + Assert.Single(result.ToArray()); + result = index.SearchReference("hoem Association", 0, 10); + Assert.Single(result.ToArray()); + result = index.SearchReference("hoem. R.", 0, 10); + Assert.Single(result.ToArray()); } [Fact] public void CanFindAwholelotofthingsDocument() { - using (var index = new Index(true)) + using var index = new Index(true); + var referanse = new Reference { - var referanse = new Reference - { - Id = Guid.Parse("208daeb0-a917-45cd-9b0f-fa21f4300d01"), - ApplicationId = 8, - UserId = new Guid("3ed89222-de9a-4df3-9e95-67f7fcac67a3"), - Author = "Horem, R.", - Year = "1982", - Title = "A whole lot of things", - Summary = null, - Journal = null, - Volume = null, - Pages = null, - Bibliography = null, - Lastname = null, - Middlename = null, - Firstname = null, - Url = null, - Keywords = "Fje Veg Ass Dyn NNNd#2", - ReferenceString = "Hojem, R. 1980. Association analysis of moraine vegetation at the glacier Hardangerjökulen, Finse, South Norway. - Norw. J. Bot. 25: 171-191.", - EditDate = DateTime.Parse("2010-04-26T08:09:18.613") - }; - - index.AddOrUpdate(referanse); - var result = index.SearchReference("A whole lot of things", 0, 10); - Assert.Single(result.ToArray()); - result = index.SearchReference("A whole lot", 0, 10); - Assert.Single(result.ToArray()); - result = index.SearchReference("of things", 0, 10); - Assert.Single(result.ToArray()); + Id = Guid.Parse("208daeb0-a917-45cd-9b0f-fa21f4300d01"), + ApplicationId = 8, + UserId = new Guid("3ed89222-de9a-4df3-9e95-67f7fcac67a3"), + Author = "Horem, R.", + Year = "1982", + Title = "A whole lot of things", + Summary = null, + Journal = null, + Volume = null, + Pages = null, + Bibliography = null, + Lastname = null, + Middlename = null, + Firstname = null, + Url = null, + Keywords = "Fje Veg Ass Dyn NNNd#2", + ReferenceString = "Hojem, R. 1980. Association analysis of moraine vegetation at the glacier Hardangerjökulen, Finse, South Norway. - Norw. J. Bot. 25: 171-191.", + EditDate = DateTime.Parse("2010-04-26T08:09:18.613") + }; - } + index.AddOrUpdate(referanse); + var result = index.SearchReference("A whole lot of things", 0, 10); + Assert.Single(result.ToArray()); + result = index.SearchReference("A whole lot", 0, 10); + Assert.Single(result.ToArray()); + result = index.SearchReference("of things", 0, 10); + Assert.Single(result.ToArray()); } [Fact] public void CanFindSubstringsDocument() { - using (var index = new Index(true)) + using var index = new Index(true); + var referanse = new Reference { - var referanse = new Reference - { - Id = Guid.Parse("208daeb0-a917-45cd-9b0f-fa21f4300d07"), - ApplicationId = 8, - UserId = new Guid("3ed89222-de9a-4df3-9e95-67f7fcac67a3"), - Author = "Hormem, R.", - Year = "1982", - Title = "Tullball & balltull 2021", - Summary = null, - Journal = null, - Volume = null, - Pages = null, - Bibliography = null, - Lastname = null, - Middlename = null, - Firstname = null, - Url = null, - Keywords = "Fje Veg Ass Dyn NNNd#2", - ReferenceString = "Hojtem, R. 1980. Association analysis of moraine vegetation at the glacier Hardangerjökulen, Finse, South Norway. - Norw. J. Bot. 25: 171-191.", - EditDate = DateTime.Parse("2010-04-26T08:09:18.613") - }; - var referanse2 = new Reference - { - Id = Guid.Parse("208daeb0-a917-45cd-9b0f-fa21f4300d08"), - ApplicationId = 8, - UserId = new Guid("3ed89222-de9a-4df3-9e95-67f7fcac67a3"), - Author = "Hormem, R.", - Year = "1982", - Title = "Tullb & frapp 2021", - Summary = null, - Journal = null, - Volume = null, - Pages = null, - Bibliography = null, - Lastname = null, - Middlename = null, - Firstname = null, - Url = null, - Keywords = "Fje Veg Ass Dyn NNNd#2", - ReferenceString = "Hojtem, R. 1980. Association analysis of moraine vegetation at the glacier Hardangerjökulen, Finse, South Norway. - Norw. J. Bot. 25: 171-191.", - EditDate = DateTime.Parse("2010-04-26T08:09:18.613") - }; - - index.AddOrUpdate(referanse); - index.AddOrUpdate(referanse2); - var result = index.SearchReference("Tullb", 0, 10); - Assert.Equal(2, result.ToArray().Length); - result = index.SearchReference("balltu", 0, 10); - Assert.Single(result.ToArray()); - result = index.SearchReference("Tullball", 0, 10); - Assert.Single(result.ToArray()); - result = index.SearchReference("Tullb balltu", 0, 10); - Assert.Single(result.ToArray()); - result = index.SearchReference("Tullball ball", 0, 10); - Assert.Single(result.ToArray()); + Id = Guid.Parse("208daeb0-a917-45cd-9b0f-fa21f4300d07"), + ApplicationId = 8, + UserId = new Guid("3ed89222-de9a-4df3-9e95-67f7fcac67a3"), + Author = "Hormem, R.", + Year = "1982", + Title = "Tullball & balltull 2021", + Summary = null, + Journal = null, + Volume = null, + Pages = null, + Bibliography = null, + Lastname = null, + Middlename = null, + Firstname = null, + Url = null, + Keywords = "Fje Veg Ass Dyn NNNd#2", + ReferenceString = "Hojtem, R. 1980. Association analysis of moraine vegetation at the glacier Hardangerjökulen, Finse, South Norway. - Norw. J. Bot. 25: 171-191.", + EditDate = DateTime.Parse("2010-04-26T08:09:18.613") + }; + var referanse2 = new Reference + { + Id = Guid.Parse("208daeb0-a917-45cd-9b0f-fa21f4300d08"), + ApplicationId = 8, + UserId = new Guid("3ed89222-de9a-4df3-9e95-67f7fcac67a3"), + Author = "Hormem, R.", + Year = "1982", + Title = "Tullb & frapp 2021", + Summary = null, + Journal = null, + Volume = null, + Pages = null, + Bibliography = null, + Lastname = null, + Middlename = null, + Firstname = null, + Url = null, + Keywords = "Fje Veg Ass Dyn NNNd#2", + ReferenceString = "Hojtem, R. 1980. Association analysis of moraine vegetation at the glacier Hardangerjökulen, Finse, South Norway. - Norw. J. Bot. 25: 171-191.", + EditDate = DateTime.Parse("2010-04-26T08:09:18.613") + }; - } + index.AddOrUpdate(referanse); + index.AddOrUpdate(referanse2); + var result = index.SearchReference("Tullb", 0, 10); + Assert.Equal(2, result.ToArray().Length); + result = index.SearchReference("balltu", 0, 10); + Assert.Single(result.ToArray()); + result = index.SearchReference("Tullball", 0, 10); + Assert.Single(result.ToArray()); + result = index.SearchReference("Tullb balltu", 0, 10); + Assert.Single(result.ToArray()); + result = index.SearchReference("Tullball ball", 0, 10); + Assert.Single(result.ToArray()); } [Fact] public void CanFindTheRightReidarElvenReferanseDocument() { - using (var index = new Index(true)) + using var index = new Index(true); + var referanse = new Reference { - var referanse = new Reference - { - Id = Guid.Parse("208daeb0-a917-45cd-9b0f-fa21f4300d01"), - ApplicationId = 8, - UserId = new Guid("3ed89222-de9a-4df3-9e95-67f7fcac67a3"), - Author = "Elven, R.", - Year = "1980", - Title = null, - Summary = null, - Journal = null, - Volume = null, - Pages = null, - Bibliography = - "Elven, R. 1980. Association analysis of moraine vegetation at the glacier Hardangerjökulen, Finse, South Norway. - Norw. J. Bot. 25: 171-191.", - Lastname = null, - Middlename = null, - Firstname = null, - Url = null, - Keywords = "Fje Veg Ass Dyn NNNd#2", - //ImportXml = null, - EditDate = DateTime.Parse("2010-04-26T08:09:18.613") - }; - var referans2 = new Reference - { - Id = Guid.Parse("208daeb0-a917-45cd-9b0f-fa21f4300d02"), - ApplicationId = 8, - UserId = new Guid("3ed89222-de9a-4df3-9e95-67f7fcac67a3"), - Author = "Elven, R.", - Year = "1981", - Title = null, - Summary = null, - Journal = null, - Volume = null, - Pages = null, - Bibliography = - "Elven, R. 1981. Association analysis of moraine vegetation at the glacier Hardangerjökulen, Finse, South Norway. - Norw. J. Bot. 25: 171-191.", - Lastname = null, - Middlename = null, - Firstname = null, - Url = null, - Keywords = "Fje Veg Ass Dyn NNNd#2", - //ImportXml = null, - EditDate = DateTime.Parse("2010-04-26T08:09:18.613") - }; - - index.AddOrUpdate(referanse); - index.AddOrUpdate(referans2); + Id = Guid.Parse("208daeb0-a917-45cd-9b0f-fa21f4300d01"), + ApplicationId = 8, + UserId = new Guid("3ed89222-de9a-4df3-9e95-67f7fcac67a3"), + Author = "Elven, R.", + Year = "1980", + Title = null, + Summary = null, + Journal = null, + Volume = null, + Pages = null, + Bibliography = + "Elven, R. 1980. Association analysis of moraine vegetation at the glacier Hardangerjökulen, Finse, South Norway. - Norw. J. Bot. 25: 171-191.", + Lastname = null, + Middlename = null, + Firstname = null, + Url = null, + Keywords = "Fje Veg Ass Dyn NNNd#2", + //ImportXml = null, + EditDate = DateTime.Parse("2010-04-26T08:09:18.613") + }; + var referans2 = new Reference + { + Id = Guid.Parse("208daeb0-a917-45cd-9b0f-fa21f4300d02"), + ApplicationId = 8, + UserId = new Guid("3ed89222-de9a-4df3-9e95-67f7fcac67a3"), + Author = "Elven, R.", + Year = "1981", + Title = null, + Summary = null, + Journal = null, + Volume = null, + Pages = null, + Bibliography = + "Elven, R. 1981. Association analysis of moraine vegetation at the glacier Hardangerjökulen, Finse, South Norway. - Norw. J. Bot. 25: 171-191.", + Lastname = null, + Middlename = null, + Firstname = null, + Url = null, + Keywords = "Fje Veg Ass Dyn NNNd#2", + //ImportXml = null, + EditDate = DateTime.Parse("2010-04-26T08:09:18.613") + }; - var result = index.SearchReference("elven", 0, 10); - Assert.Equal(2, result.Count()); - result = index.SearchReference("elven Association", 0, 10); - Assert.Equal(2, result.Count()); - result = index.SearchReference("elven 1981", 0, 10); - Assert.Single(result.ToArray()); + index.AddOrUpdate(referanse); + index.AddOrUpdate(referans2); - } + var result = index.SearchReference("elven", 0, 10); + Assert.Equal(2, result.Count()); + result = index.SearchReference("elven Association", 0, 10); + Assert.Equal(2, result.Count()); + result = index.SearchReference("elven 1981", 0, 10); + Assert.Single(result.ToArray()); } } diff --git a/Nbic.References.Tests/Nbic.References.Tests.csproj b/Nbic.References.Tests/Nbic.References.Tests.csproj index 9639f4e..272defe 100644 --- a/Nbic.References.Tests/Nbic.References.Tests.csproj +++ b/Nbic.References.Tests/Nbic.References.Tests.csproj @@ -1,6 +1,6 @@  - net6.0 + net8.0 false @@ -9,17 +9,17 @@ - - - + + + all runtime; build; native; contentfiles; analyzers; buildtransitive - + all runtime; build; native; contentfiles; analyzers; buildtransitive - + all diff --git a/Nbic.References.Tests/ReferenceControllerTests.cs b/Nbic.References.Tests/ReferenceControllerTests.cs index dde1d30..7a066e2 100644 --- a/Nbic.References.Tests/ReferenceControllerTests.cs +++ b/Nbic.References.Tests/ReferenceControllerTests.cs @@ -7,549 +7,521 @@ using Nbic.References.Core.Models; using Nbic.References.EFCore; using Nbic.References.Infrastructure.Repositories; +using Nbic.References.Infrastructure.Repositories.DbContext; using Xunit; using Index = Nbic.References.Infrastructure.Services.Indexing.Index; -namespace Nbic.References.Tests -{ - using System.Collections.Generic; +namespace Nbic.References.Tests; + +using System.Collections.Generic; - public class ReferenceControllerTests +public class ReferenceControllerTests +{ + [Fact] + public async Task CanPostReference() { - [Fact] - public async Task CanPostReference() + GetInMemoryDb(out var connection, out var options); + using var index = new Index(true, true); + try { - GetInMemoryDb(out SqliteConnection connection, out DbContextOptions options); - using (var index = new Index(true, true)) + var id = Guid.NewGuid(); + await using (var context = new ReferencesDbContext(options)) { - try - { - var id = Guid.NewGuid(); - using (var context = new ReferencesDbContext(options)) - { - var service = GetReferencesController(context, index); - var result = await service.Post(new Reference {Id = id}).ConfigureAwait(false); - } - - // Use a separate instance of the context to verify correct data was saved to database - using (var context = new ReferencesDbContext(options)) - { - var service = GetReferencesController(context, index); - var result = await service.Get(id).ConfigureAwait(false); - Assert.Equal(id, result.Value.Id); - var count = (await service.GetCount().ConfigureAwait(false)).Value; - Assert.Equal(1, count); - var all = await service.GetAll(0, 10).ConfigureAwait(false); - Assert.Single(all.ToArray()); - } - } - finally - { - connection.Close(); - } + var service = GetReferencesController(context, index); + await service.Post(new Reference {Id = id}); } - } - private static ReferencesController GetReferencesController(ReferencesDbContext context, Index index) + // Use a separate instance of the context to verify correct data was saved to database + await using (var context = new ReferencesDbContext(options)) + { + var service = GetReferencesController(context, index); + var result = await service.Get(id); + Assert.Equal(id, result.Value.Id); + var count = (await service.GetCount()).Value; + Assert.Equal(1, count); + var all = await service.GetAll(); + Assert.Single(all.ToArray()); + } + } + finally { - return new ReferencesController(new ReferenceRepository(context, index)); + connection.Close(); } + } - [Fact] - public async Task CanPostReindexAndGetReference() + private static ReferencesController GetReferencesController(ReferencesDbContext context, Index index) + { + return new ReferencesController(new ReferenceRepository(context, index)); + } + + [Fact] + public async Task CanPostReindexAndGetReference() + { + GetInMemoryDb(out var connection, out var options); + using var index = new Index(true, true); + try { - GetInMemoryDb(out SqliteConnection connection, out DbContextOptions options); - using (var index = new Index(true, true)) + var id = Guid.NewGuid(); + await using (var context = new ReferencesDbContext(options)) { - try - { - var id = Guid.NewGuid(); - using (var context = new ReferencesDbContext(options)) - { - var service = GetReferencesController(context, index); - var result = await service.Post(new Reference {Id = id}).ConfigureAwait(false); - } - - using (var context = new ReferencesDbContext(options)) - { - var service = GetReferencesController(context, index); - var result = service.DoReindex(); - } - - // Use a separate instance of the context to verify correct data was saved to database - using (var context = new ReferencesDbContext(options)) - { - var service = GetReferencesController(context, index); - var result = await service.Get(id).ConfigureAwait(false); - Assert.Equal(id, result.Value.Id); - var count = (await service.GetCount().ConfigureAwait(false)).Value; - Assert.Equal(1, count); - var all = await service.GetAll(0, 10).ConfigureAwait(false); - Assert.Single(all.ToArray()); - } - } - finally - { - connection.Close(); - } + var service = GetReferencesController(context, index); + await service.Post(new Reference {Id = id}); } - } - [Fact] - public async Task CanDeleteReference() - { - GetInMemoryDb(out SqliteConnection connection, out DbContextOptions options); - using (var index = new Index(true, true)) + await using (var context = new ReferencesDbContext(options)) { - try - { - var id = Guid.NewGuid(); - using (var context = new ReferencesDbContext(options)) - { - var service = GetReferencesController(context, index); - var result = await service.Post(new Reference {Id = id}).ConfigureAwait(false); - } - - // Use a separate instance of the context to verify correct data was saved to database - using (var context = new ReferencesDbContext(options)) - { - var service = GetReferencesController(context, index); - var result = await service.Get(id).ConfigureAwait(false); - Assert.Equal(id, result.Value.Id); - service.Delete(id); - - var all = await service.GetAll(0, 10).ConfigureAwait(false); - Assert.Empty(all.ToArray()); - } - } - finally - { - connection.Close(); - } + var service = GetReferencesController(context, index); + service.DoReindex(); + } + + // Use a separate instance of the context to verify correct data was saved to database + await using (var context = new ReferencesDbContext(options)) + { + var service = GetReferencesController(context, index); + var result = await service.Get(id); + Assert.Equal(id, result.Value.Id); + var count = (await service.GetCount()).Value; + Assert.Equal(1, count); + var all = await service.GetAll(); + Assert.Single(all.ToArray()); } } + finally + { + connection.Close(); + } + } - [Fact] - public async Task CanNotDeleteReferenceIfUsed() + [Fact] + public async Task CanDeleteReference() + { + GetInMemoryDb(out var connection, out var options); + using var index = new Index(true, true); + try { - GetInMemoryDb(out SqliteConnection connection, out DbContextOptions options); + var id = Guid.NewGuid(); + await using (var context = new ReferencesDbContext(options)) + { + var service = GetReferencesController(context, index); + await service.Post(new Reference {Id = id}); + } - using (var index = new Index(true, true)) + // Use a separate instance of the context to verify correct data was saved to database + await using (var context = new ReferencesDbContext(options)) { - try - { - var id = Guid.NewGuid(); - using (var context = new ReferencesDbContext(options)) - { - var service = GetReferencesController(context, index); - var result = await service.Post(new Reference - { - Id = id, - ReferenceUsage = new List {new ReferenceUsage {ApplicationId = 1, UserId = new Guid()}} - }).ConfigureAwait(false); - } - - // Use a separate instance of the context to verify correct data was saved to database - using (var context = new ReferencesDbContext(options)) - { - var service = GetReferencesController(context, index); - var result = await service.Get(id).ConfigureAwait(false); - Assert.Equal(id, result.Value.Id); - - Assert.Throws(() => service.Delete(id)); - - var all = await service.GetAll(0, 10).ConfigureAwait(false); - Assert.Single(all.ToArray()); - } - } - finally - { - connection.Close(); - } + var service = GetReferencesController(context, index); + var result = await service.Get(id); + Assert.Equal(id, result.Value.Id); + service.Delete(id); + + var all = await service.GetAll(); + Assert.Empty(all.ToArray()); } } - - [Fact] - public async Task CanDeleteReferenceAfterDeletingUsages() + finally { - GetInMemoryDb(out SqliteConnection connection, out DbContextOptions options); + connection.Close(); + } + } + + [Fact] + public async Task CanNotDeleteReferenceIfUsed() + { + GetInMemoryDb(out var connection, out var options); - using (var index = new Index(true, true)) + using var index = new Index(true, true); + try + { + var id = Guid.NewGuid(); + await using (var context = new ReferencesDbContext(options)) { - try - { - var id = Guid.NewGuid(); - using (var context = new ReferencesDbContext(options)) - { - var service = GetReferencesController(context, index); - var result = await service.Post(new Reference - { - Id = id, - ReferenceUsage = new List {new ReferenceUsage {ApplicationId = 1, UserId = new Guid()}} - }).ConfigureAwait(false); - } - - // Use a separate instance of the context to verify correct data was saved to database - using (var context = new ReferencesDbContext(options)) - { - var service = GetReferencesController(context, index); - var result = await service.Get(id).ConfigureAwait(false); - Assert.Equal(id, result.Value.Id); - - Assert.Throws(() => service.Delete(id)); - - var all = await service.GetAll(0, 10).ConfigureAwait(false); - Assert.Single(all.ToArray()); - } - } - finally + var service = GetReferencesController(context, index); + await service.Post(new Reference { - connection.Close(); - } + Id = id, + ReferenceUsage = new List {new() {ApplicationId = 1, UserId = new Guid()}} + }); } - } - [Fact] - public async Task CanPostAndReadCompleteReference() + // Use a separate instance of the context to verify correct data was saved to database + await using (var context = new ReferencesDbContext(options)) + { + var service = GetReferencesController(context, index); + var result = await service.Get(id); + Assert.Equal(id, result.Value.Id); + + Assert.Throws(() => service.Delete(id)); + + var all = await service.GetAll(); + Assert.Single(all.ToArray()); + } + } + finally { - GetInMemoryDb(out SqliteConnection connection, out DbContextOptions options); + connection.Close(); + } + } - using (var index = new Index(true, true)) + [Fact] + public async Task CanDeleteReferenceAfterDeletingUsages() + { + GetInMemoryDb(out var connection, out var options); + + using var index = new Index(true, true); + try + { + var id = Guid.NewGuid(); + await using (var context = new ReferencesDbContext(options)) { - try + var service = GetReferencesController(context, index); + await service.Post(new Reference { + Id = id, + ReferenceUsage = new List {new() {ApplicationId = 1, UserId = new Guid()}} + }); + } + // Use a separate instance of the context to verify correct data was saved to database + await using (var context = new ReferencesDbContext(options)) + { + var service = GetReferencesController(context, index); + var result = await service.Get(id); + Assert.Equal(id, result.Value.Id); - Reference reference = new Reference - { - Id = Guid.NewGuid(), - ApplicationId = 1, - Author = "Theps", - Bibliography = "tri", - EditDate = DateTime.Now, - Firstname = "stein", - //ImportXml = "no", - Journal = "the", - Keywords = "natur,nett", - Lastname = "hoem", - Middlename = "Ari", - Pages = "1-3", - ReferenceUsage = new[] - { - new ReferenceUsage {UserId = new Guid("3ed89222-de9a-4df3-9e95-67f7fcac67a3"), ApplicationId = 1} - }, - Summary = "Sum", - Title = "Tiii", - Url = "http://vg.no", - UserId = new Guid("3ed89222-de9a-4df3-9e95-67f7fcac67a3"), - Volume = "1", - Year = "1901" - }; - - // Run the test against one instance of the context - using (var context = new ReferencesDbContext(options)) - { - var service = GetReferencesController(context, index); - var result = await service.Post(reference).ConfigureAwait(false); - } - - // Use a separate instance of the context to verify correct data was saved to database - using (var context = new ReferencesDbContext(options)) - { - Assert.Equal(1, context.Reference.Count()); - var it = context.Reference.Include(x => x.ReferenceUsage).First(); - Assert.Equal(it.Year, reference.Year); - Assert.Equal(it.Volume, reference.Volume); - Assert.Equal(it.ApplicationId, reference.ApplicationId); - Assert.Equal(it.Author, reference.Author); - Assert.Equal(it.Bibliography, reference.Bibliography); - Assert.Equal(it.EditDate, reference.EditDate); - Assert.Equal(it.Firstname, reference.Firstname); - Assert.Equal(it.Id, reference.Id); - //Assert.Equal(it.ImportXml, reference.ImportXml); - Assert.Equal(it.Journal, reference.Journal); - Assert.Equal(it.Lastname, reference.Lastname); - Assert.Equal(it.Middlename, reference.Middlename); - Assert.Equal(it.Pages, reference.Pages); - Assert.Single(it.ReferenceUsage.ToArray()); - Assert.Equal(it.ReferenceUsage.First().ApplicationId, - reference.ReferenceUsage.First().ApplicationId); - Assert.Equal(it.Summary, reference.Summary); - Assert.Equal(it.Title, reference.Title); - Assert.Equal(it.Url, reference.Url); - Assert.Equal(it.UserId, reference.UserId); - } - } - finally - { - connection.Close(); - } + Assert.Throws(() => service.Delete(id)); + + var all = await service.GetAll(); + Assert.Single(all.ToArray()); } } + finally + { + connection.Close(); + } + } - [Fact] - public async Task CanPostUpdateAndDeleteCompleteReference() + [Fact] + public async Task CanPostAndReadCompleteReference() + { + GetInMemoryDb(out var connection, out var options); + + using var index = new Index(true, true); + try { - GetInMemoryDb(out SqliteConnection connection, out DbContextOptions options); - using (var index = new Index(true, true)) + + var reference = new Reference { - try + Id = Guid.NewGuid(), + ApplicationId = 1, + Author = "Theps", + Bibliography = "tri", + EditDate = DateTime.Now, + Firstname = "stein", + //ImportXml = "no", + Journal = "the", + Keywords = "natur,nett", + Lastname = "hoem", + Middlename = "Ari", + Pages = "1-3", + ReferenceUsage = new[] { - var reference = new Reference - { - Id = Guid.NewGuid(), - ApplicationId = 1, - Author = "Theps", - Bibliography = "tri", - EditDate = DateTime.Now, - Firstname = "stein", - //ImportXml = "no", - Journal = "the", - Keywords = "natur,nett", - Lastname = "hoem", - Middlename = "Ari", - Pages = "1-3", - ReferenceUsage = new[] - { - new ReferenceUsage {UserId = new Guid("3ed89222-de9a-4df3-9e95-67f7fcac67a3"), ApplicationId = 1} - }, - Summary = "Sum", - Title = "Tiii", - Url = "http://vg.no", - UserId = new Guid("3ed89222-de9a-4df3-9e95-67f7fcac67a3"), - Volume = "1", - Year = "1901" - }; - - // Run the test against one instance of the context - using (var context = new ReferencesDbContext(options)) - { - var service = GetReferencesController(context, index); - await service.Post(reference).ConfigureAwait(false); - } - - var replacementReference = new Reference - { - ApplicationId = 2, - Author = "Theps2", - Bibliography = "tri2", - EditDate = DateTime.Now, - Firstname = "stein2", - ReferenceString = "no2", - Journal = "the2", - Keywords = "natur,nett2", - Lastname = "hoem2", - Middlename = "Ari2", - Pages = "1-32", - ReferenceUsage = new[] - { - new ReferenceUsage {UserId = new Guid("3ed89222-de9a-4df3-9e95-67f7fcac67a2"), ApplicationId = 2} - }, - Summary = "Sum2", - Title = "Tiii2", - Url = "http://vg.no2", - UserId = new Guid("3ed89222-de9a-4df3-9e95-67f7fcac67a2"), - Volume = "2", - Year = "1902" - }; - using (var context = new ReferencesDbContext(options)) - { - var service = GetReferencesController(context, index); - await service.Put(reference.Id, replacementReference).ConfigureAwait(false); - } - - // Use a separate instance of the context to verify correct data was saved to database - using (var context = new ReferencesDbContext(options)) - { - Assert.Equal(1, context.Reference.Count()); - var service = GetReferencesController(context, index); - var getit = await service.Get(reference.Id).ConfigureAwait(false); - var it = getit.Value; - - Assert.Equal(it.Year, replacementReference.Year); - Assert.Equal(it.Volume, replacementReference.Volume); - //Assert.Equal(it.ApplicationId, replacementReference.ApplicationId); - Assert.Equal(it.Author, replacementReference.Author); - Assert.Equal(it.Bibliography, replacementReference.Bibliography); - //Assert.Equal(it.EditDate, replacementReference.EditDate); - Assert.Equal(it.Firstname, replacementReference.Firstname); - //Assert.Equal(it.Id, replacementReference.Id); - Assert.Equal(it.ReferenceString, replacementReference.ReferenceString); - Assert.Equal(it.Journal, replacementReference.Journal); - Assert.Equal(it.Lastname, replacementReference.Lastname); - Assert.Equal(it.Middlename, replacementReference.Middlename); - Assert.Equal(it.Pages, replacementReference.Pages); - Assert.Single(it.ReferenceUsage.ToArray()); - Assert.Equal(it.ReferenceUsage.First().ApplicationId, - replacementReference.ReferenceUsage.First().ApplicationId); - Assert.Equal(it.Summary, replacementReference.Summary); - Assert.Equal(it.Title, replacementReference.Title); - Assert.Equal(it.Url, replacementReference.Url); - Assert.Equal(it.UserId, replacementReference.UserId); - } - - var replacementReference2 = new Reference - { - ApplicationId = 2, - Author = "Theps2", - Bibliography = "tri2", - EditDate = DateTime.Now, - Firstname = "stein3", - ReferenceString = "no2", - Journal = "the2", - Keywords = "natur,nett2", - Lastname = "hoem2", - Middlename = "Ari2", - Pages = "1-32", - Summary = "Sum2", - Title = "Tiii2", - Url = "http://vg.no2", - UserId = new Guid("3ed89222-de9a-4df3-9e95-67f7fcac67a2"), - Volume = "2", - Year = "1902" - }; - using (var context = new ReferencesDbContext(options)) - { - var service = GetReferencesController(context, index); - await service.Put(reference.Id, replacementReference2).ConfigureAwait(false); - } - - using (var context = new ReferencesDbContext(options)) - { - Assert.Equal(1, context.Reference.Count()); - var service = GetReferencesController(context, index); - var getit = await service.Get(reference.Id).ConfigureAwait(false); - var it = getit.Value; - - Assert.Equal(it.Year, replacementReference2.Year); - Assert.Equal(it.Volume, replacementReference2.Volume); - //Assert.Equal(it.ApplicationId, replacementReference.ApplicationId); - Assert.Equal(it.Author, replacementReference2.Author); - Assert.Equal(it.Bibliography, replacementReference2.Bibliography); - //Assert.Equal(it.EditDate, replacementReference.EditDate); - Assert.Equal(it.Firstname, replacementReference2.Firstname); - //Assert.Equal(it.Id, replacementReference.Id); - Assert.Equal(it.ReferenceString, replacementReference2.ReferenceString); - Assert.Equal(it.Journal, replacementReference2.Journal); - Assert.Equal(it.Lastname, replacementReference2.Lastname); - Assert.Equal(it.Middlename, replacementReference2.Middlename); - Assert.Equal(it.Pages, replacementReference2.Pages); - Assert.Single(it.ReferenceUsage.ToArray()); - Assert.Equal(it.ReferenceUsage.First().ApplicationId, - replacementReference.ReferenceUsage.First().ApplicationId); - Assert.Equal(it.Summary, replacementReference2.Summary); - Assert.Equal(it.Title, replacementReference2.Title); - Assert.Equal(it.Url, replacementReference2.Url); - Assert.Equal(it.UserId, replacementReference2.UserId); - } - } - finally - { - connection.Close(); - } + new ReferenceUsage {UserId = new Guid("3ed89222-de9a-4df3-9e95-67f7fcac67a3"), ApplicationId = 1} + }, + Summary = "Sum", + Title = "Tiii", + Url = "http://vg.no", + UserId = new Guid("3ed89222-de9a-4df3-9e95-67f7fcac67a3"), + Volume = "1", + Year = "1901" + }; + + // Run the test against one instance of the context + await using (var context = new ReferencesDbContext(options)) + { + var service = GetReferencesController(context, index); + await service.Post(reference); } - } - [Fact] - public void CanPostBulkReferences() + // Use a separate instance of the context to verify correct data was saved to database + await using (var context = new ReferencesDbContext(options)) + { + Assert.Equal(1, context.Reference.Count()); + var it = context.Reference.Include(x => x.ReferenceUsage).First(); + Assert.Equal(it.Year, reference.Year); + Assert.Equal(it.Volume, reference.Volume); + Assert.Equal(it.ApplicationId, reference.ApplicationId); + Assert.Equal(it.Author, reference.Author); + Assert.Equal(it.Bibliography, reference.Bibliography); + Assert.Equal(it.EditDate, reference.EditDate); + Assert.Equal(it.Firstname, reference.Firstname); + Assert.Equal(it.Id, reference.Id); + //Assert.Equal(it.ImportXml, reference.ImportXml); + Assert.Equal(it.Journal, reference.Journal); + Assert.Equal(it.Lastname, reference.Lastname); + Assert.Equal(it.Middlename, reference.Middlename); + Assert.Equal(it.Pages, reference.Pages); + Assert.Single(it.ReferenceUsage.ToArray()); + Assert.Equal(it.ReferenceUsage.First().ApplicationId, + reference.ReferenceUsage.First().ApplicationId); + Assert.Equal(it.Summary, reference.Summary); + Assert.Equal(it.Title, reference.Title); + Assert.Equal(it.Url, reference.Url); + Assert.Equal(it.UserId, reference.UserId); + } + } + finally { - GetInMemoryDb(out SqliteConnection connection, out DbContextOptions options); + connection.Close(); + } + } + + [Fact] + public async Task CanPostUpdateAndDeleteCompleteReference() + { + GetInMemoryDb(out var connection, out var options); - using (var index = new Index(true, true)) + using var index = new Index(true, true); + try + { + var reference = new Reference { - try + Id = Guid.NewGuid(), + ApplicationId = 1, + Author = "Theps", + Bibliography = "tri", + EditDate = DateTime.Now, + Firstname = "stein", + //ImportXml = "no", + Journal = "the", + Keywords = "natur,nett", + Lastname = "hoem", + Middlename = "Ari", + Pages = "1-3", + ReferenceUsage = new[] { + new ReferenceUsage {UserId = new Guid("3ed89222-de9a-4df3-9e95-67f7fcac67a3"), ApplicationId = 1} + }, + Summary = "Sum", + Title = "Tiii", + Url = "http://vg.no", + UserId = new Guid("3ed89222-de9a-4df3-9e95-67f7fcac67a3"), + Volume = "1", + Year = "1901" + }; + + // Run the test against one instance of the context + await using (var context = new ReferencesDbContext(options)) + { + var service = GetReferencesController(context, index); + await service.Post(reference); + } - // Run the test against one instance of the context - using (var context = new ReferencesDbContext(options)) - { - var service = GetReferencesController(context, index); - var result = service.PostMany(new[] - {new Reference {Summary = "Ref1"}, new Reference {Summary = "Ref2"}}); - } - - // Use a separate instance of the context to verify correct data was saved to database - using (var context = new ReferencesDbContext(options)) - { - Assert.Equal(1, context.Reference.Where(x => x.Summary == "Ref1").Count()); - Assert.Equal(1, context.Reference.Where(x => x.Summary == "Ref2").Count()); - } - } - finally + var replacementReference = new Reference + { + ApplicationId = 2, + Author = "Theps2", + Bibliography = "tri2", + EditDate = DateTime.Now, + Firstname = "stein2", + ReferenceString = "no2", + Journal = "the2", + Keywords = "natur,nett2", + Lastname = "hoem2", + Middlename = "Ari2", + Pages = "1-32", + ReferenceUsage = new[] { - connection.Close(); - } + new ReferenceUsage {UserId = new Guid("3ed89222-de9a-4df3-9e95-67f7fcac67a2"), ApplicationId = 2} + }, + Summary = "Sum2", + Title = "Tiii2", + Url = "http://vg.no2", + UserId = new Guid("3ed89222-de9a-4df3-9e95-67f7fcac67a2"), + Volume = "2", + Year = "1902" + }; + await using (var context = new ReferencesDbContext(options)) + { + var service = GetReferencesController(context, index); + await service.Put(reference.Id, replacementReference); } - } - [Fact] - public async Task CanNotBulkPostReferencesWithIdenticalId() - { - GetInMemoryDb(out SqliteConnection connection, out DbContextOptions options); + // Use a separate instance of the context to verify correct data was saved to database + await using (var context = new ReferencesDbContext(options)) + { + Assert.Equal(1, context.Reference.Count()); + var service = GetReferencesController(context, index); + var getit = await service.Get(reference.Id); + var it = getit.Value; + + Assert.Equal(it.Year, replacementReference.Year); + Assert.Equal(it.Volume, replacementReference.Volume); + //Assert.Equal(it.ApplicationId, replacementReference.ApplicationId); + Assert.Equal(it.Author, replacementReference.Author); + Assert.Equal(it.Bibliography, replacementReference.Bibliography); + //Assert.Equal(it.EditDate, replacementReference.EditDate); + Assert.Equal(it.Firstname, replacementReference.Firstname); + //Assert.Equal(it.Id, replacementReference.Id); + Assert.Equal(it.ReferenceString, replacementReference.ReferenceString); + Assert.Equal(it.Journal, replacementReference.Journal); + Assert.Equal(it.Lastname, replacementReference.Lastname); + Assert.Equal(it.Middlename, replacementReference.Middlename); + Assert.Equal(it.Pages, replacementReference.Pages); + Assert.Single(it.ReferenceUsage.ToArray()); + Assert.Equal(it.ReferenceUsage.First().ApplicationId, + replacementReference.ReferenceUsage.First().ApplicationId); + Assert.Equal(it.Summary, replacementReference.Summary); + Assert.Equal(it.Title, replacementReference.Title); + Assert.Equal(it.Url, replacementReference.Url); + Assert.Equal(it.UserId, replacementReference.UserId); + } - using (var index = new Index(true, true)) + var replacementReference2 = new Reference { - try - { - using (var context = new ReferencesDbContext(options)) - { - var id = Guid.NewGuid(); - var service = GetReferencesController(context, index); - await Assert.ThrowsAsync(() => service.PostMany(new[] - { - new Reference {Id = id, Summary = "Ref1"}, new Reference {Id = id, Summary = "Ref2"} - })); - } - } - finally - { - connection.Close(); - } + ApplicationId = 2, + Author = "Theps2", + Bibliography = "tri2", + EditDate = DateTime.Now, + Firstname = "stein3", + ReferenceString = "no2", + Journal = "the2", + Keywords = "natur,nett2", + Lastname = "hoem2", + Middlename = "Ari2", + Pages = "1-32", + Summary = "Sum2", + Title = "Tiii2", + Url = "http://vg.no2", + UserId = new Guid("3ed89222-de9a-4df3-9e95-67f7fcac67a2"), + Volume = "2", + Year = "1902" + }; + await using (var context = new ReferencesDbContext(options)) + { + var service = GetReferencesController(context, index); + await service.Put(reference.Id, replacementReference2); } + + await using (var context = new ReferencesDbContext(options)) + { + Assert.Equal(1, context.Reference.Count()); + var service = GetReferencesController(context, index); + var getit = await service.Get(reference.Id); + var it = getit.Value; + + Assert.Equal(it.Year, replacementReference2.Year); + Assert.Equal(it.Volume, replacementReference2.Volume); + //Assert.Equal(it.ApplicationId, replacementReference.ApplicationId); + Assert.Equal(it.Author, replacementReference2.Author); + Assert.Equal(it.Bibliography, replacementReference2.Bibliography); + //Assert.Equal(it.EditDate, replacementReference.EditDate); + Assert.Equal(it.Firstname, replacementReference2.Firstname); + //Assert.Equal(it.Id, replacementReference.Id); + Assert.Equal(it.ReferenceString, replacementReference2.ReferenceString); + Assert.Equal(it.Journal, replacementReference2.Journal); + Assert.Equal(it.Lastname, replacementReference2.Lastname); + Assert.Equal(it.Middlename, replacementReference2.Middlename); + Assert.Equal(it.Pages, replacementReference2.Pages); + Assert.Single(it.ReferenceUsage.ToArray()); + Assert.Equal(it.ReferenceUsage.First().ApplicationId, + replacementReference.ReferenceUsage.First().ApplicationId); + Assert.Equal(it.Summary, replacementReference2.Summary); + Assert.Equal(it.Title, replacementReference2.Title); + Assert.Equal(it.Url, replacementReference2.Url); + Assert.Equal(it.UserId, replacementReference2.UserId); + } + } + finally + { + connection.Close(); } + } + + [Fact] + public async void CanPostBulkReferences() + { + GetInMemoryDb(out var connection, out var options); - [Fact] - public async void CanNotPostReferencesWithIdenticalId() + using var index = new Index(true, true); + try { - GetInMemoryDb(out SqliteConnection connection, out DbContextOptions options); - using (var index = new Index(true, true)) + // Run the test against one instance of the context + await using (var context = new ReferencesDbContext(options)) { - try - { - using (var context = new ReferencesDbContext(options)) - { - var id = Guid.NewGuid(); - var service = GetReferencesController(context, index); - await service.Post(new Reference {Id = id}).ConfigureAwait(false); - await Assert - .ThrowsAsync(() => - service.Post(new Reference {Id = id, Summary = "Ref1"})).ConfigureAwait(false); - } - } - finally - { - connection.Close(); - } + var service = GetReferencesController(context, index); + await service.PostMany([new Reference {Summary = "Ref1"}, new Reference {Summary = "Ref2"}]); + } + + // Use a separate instance of the context to verify correct data was saved to database + await using (var context = new ReferencesDbContext(options)) + { + Assert.Equal(1, context.Reference.Count(x => x.Summary == "Ref1")); + Assert.Equal(1, context.Reference.Count(x => x.Summary == "Ref2")); } } + finally + { + connection.Close(); + } + } - private static void GetInMemoryDb(out SqliteConnection connection, out DbContextOptions options) + [Fact] + public async Task CanNotBulkPostReferencesWithIdenticalId() + { + GetInMemoryDb(out var connection, out var options); + + using var index = new Index(true, true); + try + { + await using var context = new ReferencesDbContext(options); + var id = Guid.NewGuid(); + var service = GetReferencesController(context, index); + await Assert.ThrowsAsync(() => service.PostMany([ + new Reference {Id = id, Summary = "Ref1"}, new Reference {Id = id, Summary = "Ref2"} + ])); + } + finally { - // In-memory database only exists while the connection is open - connection = new SqliteConnection("DataSource=:memory:"); - connection.Open(); - options = new DbContextOptionsBuilder() - .UseSqlite(connection) - .Options; + connection.Close(); + } + } + [Fact] + public async void CanNotPostReferencesWithIdenticalId() + { + GetInMemoryDb(out var connection, out var options); - // Create the schema in the database - using (var context = new ReferencesDbContext(options)) - { - context.Database.EnsureCreated(); - } + using var index = new Index(true, true); + try + { + await using var context = new ReferencesDbContext(options); + var id = Guid.NewGuid(); + var service = GetReferencesController(context, index); + await service.Post(new Reference {Id = id}); + await Assert + .ThrowsAsync(() => + service.Post(new Reference {Id = id, Summary = "Ref1"})); } + finally + { + connection.Close(); + } + } + + private static void GetInMemoryDb(out SqliteConnection connection, out DbContextOptions options) + { + // In-memory database only exists while the connection is open + connection = new SqliteConnection("DataSource=:memory:"); + connection.Open(); + options = new DbContextOptionsBuilder() + .UseSqlite(connection) + .Options; + + + // Create the schema in the database + using var context = new ReferencesDbContext(options); + context.Database.EnsureCreated(); } -} +} \ No newline at end of file diff --git a/Nbic.References.Tests/ReferenceUsageControllerTests.cs b/Nbic.References.Tests/ReferenceUsageControllerTests.cs index f1d24d3..7366e6f 100644 --- a/Nbic.References.Tests/ReferenceUsageControllerTests.cs +++ b/Nbic.References.Tests/ReferenceUsageControllerTests.cs @@ -6,6 +6,7 @@ using Nbic.References.Core.Models; using Nbic.References.EFCore; using Nbic.References.Infrastructure.Repositories; +using Nbic.References.Infrastructure.Repositories.DbContext; using Xunit; using Index = Nbic.References.Infrastructure.Services.Indexing.Index; @@ -30,164 +31,156 @@ private static ReferenceUsageController GetReferencesUsageController(ReferencesD [Fact] public async Task CanPostReferenceAndGetReferenceUsages() { - GetInMemoryDb(out SqliteConnection connection, out DbContextOptions options); - using (var index = new Index(true, true)) + GetInMemoryDb(out var connection, out var options); + using var index = new Index(true, true); + try { - try + var id = Guid.NewGuid(); + await using (var context = new ReferencesDbContext(options)) { - var id = Guid.NewGuid(); - using (var context = new ReferencesDbContext(options)) + var service = GetReferencesController(context, index); + await service.Post(new Reference { - var service = GetReferencesController(context, index); - await service.Post(new Reference + Id = id, + ReferenceUsage = new List { - Id = id, - ReferenceUsage = new List - { - new ReferenceUsage {ApplicationId = 1, UserId = new Guid("3ed89222-de9a-4df3-9e95-67f7fcac67a3")} - } - }).ConfigureAwait(false); - } - - // Use a separate instance of the context to verify correct data was saved to database - using (var context = new ReferencesDbContext(options)) - { - var usageService = GetReferencesUsageController(context); - - var count = (await usageService.GetCount().ConfigureAwait(false)).Value; - Assert.Equal(1, count); - var all = await usageService.GetAll(0, 10).ConfigureAwait(false); - Assert.Single(all); - var them = await usageService.Get(id).ConfigureAwait(false); - Assert.Single(them); - } + new() {ApplicationId = 1, UserId = new Guid("3ed89222-de9a-4df3-9e95-67f7fcac67a3")} + } + }); } - finally + + // Use a separate instance of the context to verify correct data was saved to database + await using (var context = new ReferencesDbContext(options)) { - connection.Close(); + var usageService = GetReferencesUsageController(context); + + var count = (await usageService.GetCount()).Value; + Assert.Equal(1, count); + var all = await usageService.GetAll(); + Assert.Single(all); + var them = await usageService.Get(id); + Assert.Single(them); } } + finally + { + connection.Close(); + } } [Fact] public async Task CanDeleteReferenceIfUsageReferencesIsDeletedFirst() { - GetInMemoryDb(out SqliteConnection connection, out DbContextOptions options); - using (var index = new Index(true, true)) + GetInMemoryDb(out var connection, out var options); + using var index = new Index(true, true); + try { - - try + var id = Guid.NewGuid(); + await using (var context = new ReferencesDbContext(options)) { - var id = Guid.NewGuid(); - using (var context = new ReferencesDbContext(options)) + var service = GetReferencesController(context, index); + await service.Post(new Reference { - var service = GetReferencesController(context, index); - await service.Post(new Reference + Id = id, + ReferenceUsage = new List { - Id = id, - ReferenceUsage = new List - { - new ReferenceUsage {ApplicationId = 1, UserId = new Guid("3ed89222-de9a-4df3-9e95-67f7fcac67a3")} - } - }).ConfigureAwait(false); - } - - // Use a separate instance of the context to verify correct data was saved to database - using (var context = new ReferencesDbContext(options)) - { - var service = GetReferencesController(context, index); - var usageService = GetReferencesUsageController(context); - usageService.DeleteAllUsages(id); - var all = await usageService.GetAll(0, 10).ConfigureAwait(false); - Assert.Empty(all); - var result = await service.Get(id).ConfigureAwait(false); - Assert.Equal(id, result.Value.Id); - - // now delete reference - service.Delete(id); - // and should not be found - var result2 = await service.Get(id).ConfigureAwait(false); - Assert.IsType(result2.Result); - } + new() {ApplicationId = 1, UserId = new Guid("3ed89222-de9a-4df3-9e95-67f7fcac67a3")} + } + }); } - finally + + // Use a separate instance of the context to verify correct data was saved to database + await using (var context = new ReferencesDbContext(options)) { - connection.Close(); + var service = GetReferencesController(context, index); + var usageService = GetReferencesUsageController(context); + usageService.DeleteAllUsages(id); + var all = await usageService.GetAll(); + Assert.Empty(all); + var result = await service.Get(id); + Assert.Equal(id, result.Value.Id); + + // now delete reference + service.Delete(id); + // and should not be found + var result2 = await service.Get(id); + Assert.IsType(result2.Result); } } + finally + { + connection.Close(); + } } [Fact] public async Task CanDeleteSingleReferenceUsage() { - GetInMemoryDb(out SqliteConnection connection, out DbContextOptions options); - using (var index = new Index(true, true)) + GetInMemoryDb(out var connection, out var options); + using var index = new Index(true, true); + try { - - try + var id = Guid.NewGuid(); + await using (var context = new ReferencesDbContext(options)) { - var id = Guid.NewGuid(); - using (var context = new ReferencesDbContext(options)) + var service = GetReferencesController(context, index); + await service.Post(new Reference { - var service = GetReferencesController(context, index); - await service.Post(new Reference + Id = id, + ReferenceUsage = new List { - Id = id, - ReferenceUsage = new List - { - new ReferenceUsage {ApplicationId = 1, UserId = new Guid("3ed89222-de9a-4df3-9e95-67f7fcac67a3")}, - new ReferenceUsage {ApplicationId = 2, UserId = new Guid("3ed89222-de9a-4df3-9e95-67f7fcac67a3")} - } - }).ConfigureAwait(false); - } - - // Use a separate instance of the context to verify correct data was saved to database - using (var context = new ReferencesDbContext(options)) - { - var service = GetReferencesController(context, index); - var usageService = GetReferencesUsageController(context); - usageService.DeleteUsage(id, 1, new Guid("3ed89222-de9a-4df3-9e95-67f7fcac67a3")); - var all = await usageService.GetAll(0, 10).ConfigureAwait(false); - Assert.Single(all); - var result = await service.Get(id).ConfigureAwait(false); - Assert.Equal(id, result.Value.Id); - - // and should not be found - var result2 = await service.Get(id).ConfigureAwait(false); - Assert.Single(result2.Value.ReferenceUsage); - } + new() {ApplicationId = 1, UserId = new Guid("3ed89222-de9a-4df3-9e95-67f7fcac67a3")}, + new() {ApplicationId = 2, UserId = new Guid("3ed89222-de9a-4df3-9e95-67f7fcac67a3")} + } + }); } - finally + + // Use a separate instance of the context to verify correct data was saved to database + await using (var context = new ReferencesDbContext(options)) { - connection.Close(); + var service = GetReferencesController(context, index); + var usageService = GetReferencesUsageController(context); + usageService.DeleteUsage(id, 1, new Guid("3ed89222-de9a-4df3-9e95-67f7fcac67a3")); + var all = await usageService.GetAll(); + Assert.Single(all); + var result = await service.Get(id); + Assert.Equal(id, result.Value.Id); + + // and should not be found + var result2 = await service.Get(id); + Assert.Single(result2.Value.ReferenceUsage); } } + finally + { + connection.Close(); + } } [Fact] public async Task CanAddSingleReferenceUsage() { - GetInMemoryDb(out SqliteConnection connection, out DbContextOptions options); + GetInMemoryDb(out var connection, out var options); using var index = new Index(true, true); try { var id = Guid.NewGuid(); - using (var context = new ReferencesDbContext(options)) + await using (var context = new ReferencesDbContext(options)) { var service = GetReferencesController(context, index); - await service.Post(new Reference { Id = id, ReferenceUsage = new List { new ReferenceUsage { ApplicationId = 1, UserId = new Guid("3ed89222-de9a-4df3-9e95-67f7fcac67a3") }, new ReferenceUsage { ApplicationId = 2, UserId = new Guid("3ed89222-de9a-4df3-9e95-67f7fcac67a3") } } }).ConfigureAwait(false); + await service.Post(new Reference { Id = id, ReferenceUsage = new List { new() { ApplicationId = 1, UserId = new Guid("3ed89222-de9a-4df3-9e95-67f7fcac67a3") }, new() { ApplicationId = 2, UserId = new Guid("3ed89222-de9a-4df3-9e95-67f7fcac67a3") } } }); } // Use a separate instance of the context to verify correct data was saved to database - using (var context = new ReferencesDbContext(options)) + await using (var context = new ReferencesDbContext(options)) { var service = GetReferencesController(context, index); var usageService = GetReferencesUsageController(context); - await usageService.Post(new ReferenceUsage { ApplicationId = 3, ReferenceId = id, UserId = new Guid("3ed89222-de9a-4df3-9e95-67f7fcac67a3") }).ConfigureAwait(false); - var all = await usageService.GetAll(0, 10).ConfigureAwait(false); + await usageService.Post(new ReferenceUsage { ApplicationId = 3, ReferenceId = id, UserId = new Guid("3ed89222-de9a-4df3-9e95-67f7fcac67a3") }); + var all = await usageService.GetAll(); Assert.Equal(3, all.Count); - var result = await service.Get(id).ConfigureAwait(false); + var result = await service.Get(id); Assert.Equal(id, result.Value.Id); Assert.Equal(3, result.Value.ReferenceUsage.Count); } @@ -201,192 +194,183 @@ public async Task CanAddSingleReferenceUsage() [Fact] public async Task CanAddDoubleReferenceUsage() { - GetInMemoryDb(out SqliteConnection connection, out DbContextOptions options); + GetInMemoryDb(out var connection, out var options); - using (var index = new Index(true, true)) + using var index = new Index(true, true); + try { - try + var id = Guid.NewGuid(); + var id2 = Guid.NewGuid(); + await using (var context = new ReferencesDbContext(options)) { - var id = Guid.NewGuid(); - var id2 = Guid.NewGuid(); - using (var context = new ReferencesDbContext(options)) + var service = GetReferencesController(context, index); + await service.Post(new Reference { - var service = GetReferencesController(context, index); - await service.Post(new Reference - { - Id = id, - ReferenceUsage = new List - { - new ReferenceUsage {ApplicationId = 1, UserId = new Guid("3ed89222-de9a-4df3-9e95-67f7fcac67a3")}, - new ReferenceUsage {ApplicationId = 2, UserId = new Guid("3ed89222-de9a-4df3-9e95-67f7fcac67a3")} - } - }).ConfigureAwait(false); - await service.Post(new Reference + Id = id, + ReferenceUsage = new List { - Id = id2, - ReferenceUsage = new List - { - new ReferenceUsage {ApplicationId = 1, UserId = new Guid("3ed89222-de9a-4df3-9e95-67f7fcac67a3")}, - new ReferenceUsage {ApplicationId = 2, UserId = new Guid("3ed89222-de9a-4df3-9e95-67f7fcac67a3")} - } - }).ConfigureAwait(false); - } - - // Use a separate instance of the context to verify correct data was saved to database - using (var context = new ReferencesDbContext(options)) + new() {ApplicationId = 1, UserId = new Guid("3ed89222-de9a-4df3-9e95-67f7fcac67a3")}, + new() {ApplicationId = 2, UserId = new Guid("3ed89222-de9a-4df3-9e95-67f7fcac67a3")} + } + }); + await service.Post(new Reference { - var service = GetReferencesController(context, index); - var usageService = GetReferencesUsageController(context); - await usageService.Post(new ReferenceUsage[] + Id = id2, + ReferenceUsage = new List { - new ReferenceUsage - { - ApplicationId = 3, ReferenceId = id, - UserId = new Guid("3ed89222-de9a-4df3-9e95-67f7fcac67a3") - }, - new ReferenceUsage - { - ApplicationId = 3, ReferenceId = id2, - UserId = new Guid("3ed89222-de9a-4df3-9e95-67f7fcac67a3") - } - }).ConfigureAwait(false); - var all = await usageService.GetAll(0, 10).ConfigureAwait(false); - Assert.Equal(6, all.Count); - var result = await service.Get(id).ConfigureAwait(false); - Assert.Equal(id, result.Value.Id); - Assert.Equal(3, result.Value.ReferenceUsage.Count); - var result2 = await service.Get(id2).ConfigureAwait(false); - Assert.Equal(id2, result2.Value.Id); - Assert.Equal(3, result2.Value.ReferenceUsage.Count); - } + new() {ApplicationId = 1, UserId = new Guid("3ed89222-de9a-4df3-9e95-67f7fcac67a3")}, + new() {ApplicationId = 2, UserId = new Guid("3ed89222-de9a-4df3-9e95-67f7fcac67a3")} + } + }); } - finally + + // Use a separate instance of the context to verify correct data was saved to database + await using (var context = new ReferencesDbContext(options)) { - connection.Close(); + var service = GetReferencesController(context, index); + var usageService = GetReferencesUsageController(context); + await usageService.Post([ + new() + { + ApplicationId = 3, ReferenceId = id, + UserId = new Guid("3ed89222-de9a-4df3-9e95-67f7fcac67a3") + }, + new() + { + ApplicationId = 3, ReferenceId = id2, + UserId = new Guid("3ed89222-de9a-4df3-9e95-67f7fcac67a3") + } + ]); + var all = await usageService.GetAll(); + Assert.Equal(6, all.Count); + var result = await service.Get(id); + Assert.Equal(id, result.Value.Id); + Assert.Equal(3, result.Value.ReferenceUsage.Count); + var result2 = await service.Get(id2); + Assert.Equal(id2, result2.Value.Id); + Assert.Equal(3, result2.Value.ReferenceUsage.Count); } } + finally + { + connection.Close(); + } } [Fact] public async Task AddReferenceUsageToNotExistingReferenceShouldNotFail() { - GetInMemoryDb(out SqliteConnection connection, out DbContextOptions options); + GetInMemoryDb(out var connection, out var options); - using (var index = new Index(true, true)) + using var index = new Index(true, true); + try { - try + var id = Guid.NewGuid(); + var id2 = Guid.NewGuid(); + var id3 = Guid.NewGuid(); + await using (var context = new ReferencesDbContext(options)) { - var id = Guid.NewGuid(); - var id2 = Guid.NewGuid(); - var id3 = Guid.NewGuid(); - using (var context = new ReferencesDbContext(options)) + var service = GetReferencesController(context, index); + await service.Post(new Reference { - var service = GetReferencesController(context, index); - await service.Post(new Reference + Id = id, + ReferenceUsage = new List { - Id = id, - ReferenceUsage = new List - { - new ReferenceUsage {ApplicationId = 1, UserId = new Guid("3ed89222-de9a-4df3-9e95-67f7fcac67a3")}, - new ReferenceUsage {ApplicationId = 2, UserId = new Guid("3ed89222-de9a-4df3-9e95-67f7fcac67a3")} - } - }).ConfigureAwait(false); - await service.Post(new Reference - { - Id = id2, - ReferenceUsage = new List - { - new ReferenceUsage {ApplicationId = 1, UserId = new Guid("3ed89222-de9a-4df3-9e95-67f7fcac67a3")}, - new ReferenceUsage {ApplicationId = 2, UserId = new Guid("3ed89222-de9a-4df3-9e95-67f7fcac67a3")} - } - }).ConfigureAwait(false); - } - - // Use a separate instance of the context to verify correct data was saved to database - using (var context = new ReferencesDbContext(options)) + new() {ApplicationId = 1, UserId = new Guid("3ed89222-de9a-4df3-9e95-67f7fcac67a3")}, + new() {ApplicationId = 2, UserId = new Guid("3ed89222-de9a-4df3-9e95-67f7fcac67a3")} + } + }); + await service.Post(new Reference { - var service = GetReferencesController(context, index); - var usageService = GetReferencesUsageController(context); - await usageService.Post(new ReferenceUsage[] + Id = id2, + ReferenceUsage = new List { - new ReferenceUsage - { - ApplicationId = 3, ReferenceId = id, - UserId = new Guid("3ed89222-de9a-4df3-9e95-67f7fcac67a3") - }, - new ReferenceUsage - { - ApplicationId = 3, ReferenceId = id2, - UserId = new Guid("3ed89222-de9a-4df3-9e95-67f7fcac67a3") - }, - new ReferenceUsage - { - ApplicationId = 3, ReferenceId = id3, - UserId = new Guid("3ed89222-de9a-4df3-9e95-87f7fcac67a3") - } - }).ConfigureAwait(false); - var all = await usageService.GetAll(0, 10).ConfigureAwait(false); - Assert.Equal(6, all.Count); - var result = await service.Get(id).ConfigureAwait(false); - Assert.Equal(id, result.Value.Id); - Assert.Equal(3, result.Value.ReferenceUsage.Count); - var result2 = await service.Get(id2).ConfigureAwait(false); - Assert.Equal(id2, result2.Value.Id); - Assert.Equal(3, result2.Value.ReferenceUsage.Count); - } + new() {ApplicationId = 1, UserId = new Guid("3ed89222-de9a-4df3-9e95-67f7fcac67a3")}, + new() {ApplicationId = 2, UserId = new Guid("3ed89222-de9a-4df3-9e95-67f7fcac67a3")} + } + }); } - finally + + // Use a separate instance of the context to verify correct data was saved to database + await using (var context = new ReferencesDbContext(options)) { - connection.Close(); + var service = GetReferencesController(context, index); + var usageService = GetReferencesUsageController(context); + await usageService.Post([ + new() + { + ApplicationId = 3, ReferenceId = id, + UserId = new Guid("3ed89222-de9a-4df3-9e95-67f7fcac67a3") + }, + new() + { + ApplicationId = 3, ReferenceId = id2, + UserId = new Guid("3ed89222-de9a-4df3-9e95-67f7fcac67a3") + }, + new() + { + ApplicationId = 3, ReferenceId = id3, + UserId = new Guid("3ed89222-de9a-4df3-9e95-87f7fcac67a3") + } + ]); + var all = await usageService.GetAll(); + Assert.Equal(6, all.Count); + var result = await service.Get(id); + Assert.Equal(id, result.Value.Id); + Assert.Equal(3, result.Value.ReferenceUsage.Count); + var result2 = await service.Get(id2); + Assert.Equal(id2, result2.Value.Id); + Assert.Equal(3, result2.Value.ReferenceUsage.Count); } } + finally + { + connection.Close(); + } } [Fact] public async Task CanAddSingleDuplicateReferenceUsage() { - GetInMemoryDb(out SqliteConnection connection, out DbContextOptions options); - using (var index = new Index(true, true)) + GetInMemoryDb(out var connection, out var options); + using var index = new Index(true, true); + try { - - try + var id = Guid.NewGuid(); + await using (var context = new ReferencesDbContext(options)) { - var id = Guid.NewGuid(); - using (var context = new ReferencesDbContext(options)) - { - var service = GetReferencesController(context, index); - await service.Post(new Reference - { - Id = id, - ReferenceUsage = new List - { - new ReferenceUsage {ApplicationId = 1, UserId = new Guid("3ed89222-de9a-4df3-9e95-67f7fcac67a3")}, - new ReferenceUsage {ApplicationId = 2, UserId = new Guid("3ed89222-de9a-4df3-9e95-67f7fcac67a3")} - } - }).ConfigureAwait(false); - } - - // Use a separate instance of the context to verify correct data was saved to database - using (var context = new ReferencesDbContext(options)) + var service = GetReferencesController(context, index); + await service.Post(new Reference { - var service = GetReferencesController(context, index); - var usageService = GetReferencesUsageController(context); - await usageService.Post(new ReferenceUsage + Id = id, + ReferenceUsage = new List { - ApplicationId = 1, - ReferenceId = id, - UserId = new Guid("3ed89222-de9a-4df3-9e95-67f7fcac67a3") - }).ConfigureAwait(false); - var all = await usageService.GetAll(0, 10).ConfigureAwait(false); - Assert.Equal(2, all.Count); - var result = await service.Get(id).ConfigureAwait(false); - Assert.Equal(id, result.Value.Id); - Assert.Equal(2, result.Value.ReferenceUsage.Count); - } + new() {ApplicationId = 1, UserId = new Guid("3ed89222-de9a-4df3-9e95-67f7fcac67a3")}, + new() {ApplicationId = 2, UserId = new Guid("3ed89222-de9a-4df3-9e95-67f7fcac67a3")} + } + }); } - finally + + // Use a separate instance of the context to verify correct data was saved to database + await using (var context = new ReferencesDbContext(options)) { - connection.Close(); + var service = GetReferencesController(context, index); + var usageService = GetReferencesUsageController(context); + await usageService.Post(new ReferenceUsage + { + ApplicationId = 1, + ReferenceId = id, + UserId = new Guid("3ed89222-de9a-4df3-9e95-67f7fcac67a3") + }); + var all = await usageService.GetAll(); + Assert.Equal(2, all.Count); + var result = await service.Get(id); + Assert.Equal(id, result.Value.Id); + Assert.Equal(2, result.Value.ReferenceUsage.Count); } } + finally + { + connection.Close(); + } } private static void GetInMemoryDb(out SqliteConnection connection, out DbContextOptions options) @@ -399,9 +383,7 @@ private static void GetInMemoryDb(out SqliteConnection connection, out DbContext .Options; // Create the schema in the database - using (var context = new ReferencesDbContext(options)) - { - context.Database.EnsureCreated(); - } + using var context = new ReferencesDbContext(options); + context.Database.EnsureCreated(); } } diff --git a/Nbic.References.sln b/Nbic.References.sln index 9f54e1b..fdfbab6 100644 --- a/Nbic.References.sln +++ b/Nbic.References.sln @@ -7,10 +7,11 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Nbic.References", "Nbic.Ref EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution", "Solution", "{69A2E534-0B87-456E-B931-E0C42F48BED5}" ProjectSection(SolutionItems) = preProject - removed.travis.yml = removed.travis.yml - removed-deploy.sh = removed-deploy.sh .github\workflows\dotnetcore.yml = .github\workflows\dotnetcore.yml README.md = README.md + .github\workflows\codeql-analysis.yml = .github\workflows\codeql-analysis.yml + .github\workflows\metrics.yml = .github\workflows\metrics.yml + .github\dependabot.yml = .github\dependabot.yml EndProjectSection EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Nbic.References.Tests", "Nbic.References.Tests\Nbic.References.Tests.csproj", "{9DD48F8F-28B8-4C33-9C4C-339C0B360028}" diff --git a/Nbic.References/Controllers/ReferenceUsageController.cs b/Nbic.References/Controllers/ReferenceUsageController.cs index 8c1260a..dd30884 100644 --- a/Nbic.References/Controllers/ReferenceUsageController.cs +++ b/Nbic.References/Controllers/ReferenceUsageController.cs @@ -1,110 +1,106 @@ using System; using System.Collections.Generic; -using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Swashbuckle.AspNetCore.Annotations; -namespace Nbic.References.Controllers +namespace Nbic.References.Controllers; + +using Microsoft.AspNetCore.Authorization; + +[Route("api/[controller]")] +[ApiController] +[SwaggerTag("Read, add or delete ReferencesUsages")] +public class ReferenceUsageController : ControllerBase { - using Microsoft.AspNetCore.Authorization; + private readonly IReferenceUsageRepository _referenceUsageRepository; - using EFCore; + public ReferenceUsageController(IReferenceUsageRepository referenceUsageRepository) + { + _referenceUsageRepository = referenceUsageRepository; + } - [Route("api/[controller]")] - [ApiController] - [SwaggerTag("Read, add or delete ReferencesUsages")] - public class ReferenceUsageController : ControllerBase + [HttpGet] + public async Task> GetAll(int offset = 0, int limit = 10) { - private readonly IReferenceUsageRepository _referenceUsageRepository; + return await _referenceUsageRepository.GetAll(offset, limit); + } + [HttpGet] + [Route("Reference/{id:guid}")] + public async Task> Get(Guid id) + { + return await _referenceUsageRepository.GetFromReferenceId(id); + } - public ReferenceUsageController(IReferenceUsageRepository referenceUsageRepository) - { - _referenceUsageRepository = referenceUsageRepository; - } + [HttpGet] + [Route("Count")] + public async Task> GetCount() + { + return await _referenceUsageRepository.CountAsync(); + } - [HttpGet] - public async Task> GetAll(int offset = 0, int limit = 10) + /// + /// Delete Usage for Reference + /// + /// Reference Id + /// + [Authorize("WriteAccess")] + [HttpDelete("{id:guid}")] + [ProducesResponseType(404)] + public Microsoft.AspNetCore.Mvc.ActionResult DeleteAllUsages(Guid id) + { + try { - return await _referenceUsageRepository.GetAll(offset, limit); + _referenceUsageRepository.DeleteForReference(id); } - [HttpGet] - [Route("Reference/{id}")] - public async Task> Get(Guid id) + catch (NotFoundException e) { - return await _referenceUsageRepository.GetFromReferenceId(id); + return NotFound(e); } + + return Ok(); + } - [HttpGet] - [Route("Count")] - public async Task> GetCount() + [Authorize("WriteAccess")] + [HttpDelete("{id:guid},{applicationId:int},{userId:guid}")] + public Microsoft.AspNetCore.Mvc.ActionResult DeleteUsage(Guid id, int applicationId, Guid userId) + { + try { - return await _referenceUsageRepository.CountAsync(); + _referenceUsageRepository.DeleteUsage(id, applicationId,userId); } - - /// - /// Delete Usage for Reference - /// - /// Reference Id - /// - [Authorize("WriteAccess")] - [HttpDelete("{id}")] - [ProducesResponseType(404)] - public Microsoft.AspNetCore.Mvc.ActionResult DeleteAllUsages(Guid id) + catch (NotFoundException e) { - try - { - _referenceUsageRepository.DeleteForReference(id); - } - catch (NotFoundException e) - { - return NotFound(e); - } - - return Ok(); + return NotFound(e); } - - [Authorize("WriteAccess")] - [HttpDelete("{id},{applicationId},{userId}")] - public Microsoft.AspNetCore.Mvc.ActionResult DeleteUsage(Guid id, int applicationId, Guid userId) - { - try - { - _referenceUsageRepository.DeleteUsage(id, applicationId,userId); - } - catch (NotFoundException e) - { - return NotFound(e); - } - return Ok(); + return Ok(); - } + } - [Authorize("WriteAccess")] - [HttpPost] - public async Task> Post([FromBody] ReferenceUsage value) + [Authorize("WriteAccess")] + [HttpPost] + public async Task> Post([FromBody] ReferenceUsage value) + { + if (value == null) { - if (value == null) - { - return BadRequest("No data posted"); - } + return BadRequest("No data posted"); + } - await _referenceUsageRepository.Add(value); + await _referenceUsageRepository.Add(value); - return value; - } + return value; + } - [Authorize("WriteAccess")] - [HttpPost("bulk")] - public async Task> Post(ReferenceUsage[] value) + [Authorize("WriteAccess")] + [HttpPost("bulk")] + public async Task> Post(ReferenceUsage[] value) + { + if (value == null) { - if (value == null) - { - return BadRequest("No data posted"); - } - - return await _referenceUsageRepository.AddRange(value); + return BadRequest("No data posted"); } + + return await _referenceUsageRepository.AddRange(value); } } \ No newline at end of file diff --git a/Nbic.References/Controllers/ReferencesController.cs b/Nbic.References/Controllers/ReferencesController.cs index ff96ba2..5893690 100644 --- a/Nbic.References/Controllers/ReferencesController.cs +++ b/Nbic.References/Controllers/ReferencesController.cs @@ -5,141 +5,140 @@ using Microsoft.AspNetCore.Mvc; using Swashbuckle.AspNetCore.Annotations; -namespace Nbic.References.Controllers +namespace Nbic.References.Controllers; + +[Route("api/[controller]")] +[ApiController] +[SwaggerTag("Create, read, update and delete References")] +public class ReferencesController : ControllerBase { - [Route("api/[controller]")] - [ApiController] - [SwaggerTag("Create, read, update and delete References")] - public class ReferencesController : ControllerBase + private readonly IReferencesRepository _referencesRepository; + + public ReferencesController(IReferencesRepository referencesRepository) { - private readonly IReferencesRepository _referencesRepository; + _referencesRepository = referencesRepository; + } - public ReferencesController(IReferencesRepository referencesRepository) - { - _referencesRepository = referencesRepository; - } + [HttpGet] + public async Task> GetAll(int offset = 0, int limit = 10, string search = null) + { + return await _referencesRepository.Search(search, offset, limit); + } + + [HttpGet] + [Route("Count")] + public async Task> GetCount() + { + return await _referencesRepository.CountAsync(); // _referencesDbContext.Reference.CountAsync().ConfigureAwait(false); + } + + [HttpGet] + [Authorize("WriteAccess")] + [Route("Reindex")] + public ActionResult DoReindex() + { + _referencesRepository.ReIndex(); + return true; + } + + [HttpGet("{id:guid}")] + public async Task> Get(Guid id) + { + var reference = await _referencesRepository.Get(id); + if (reference == null) return NotFound(); + + return reference; + } - [HttpGet] - public async Task> GetAll(int offset = 0, int limit = 10, string search = null) + [Authorize("WriteAccess")] + [HttpPost] + public async Task> Post([FromBody] Reference value) + { + if (value == null) { - return await _referencesRepository.Search(search, offset, limit); + return BadRequest("No data posted"); } - [HttpGet] - [Route("Count")] - public async Task> GetCount() + Reference newReference; + try { - return await _referencesRepository.CountAsync(); // _referencesDbContext.Reference.CountAsync().ConfigureAwait(false); + newReference = await _referencesRepository.Add(value); } - - [HttpGet] - [Authorize("WriteAccess")] - [Route("Reindex")] - public ActionResult DoReindex() + catch (BadRequestException e) { - _referencesRepository.ReIndex(); - return true; + return BadRequest(e); } - [HttpGet("{id}")] - public async Task> Get(Guid id) + return newReference; + } + + [Authorize("WriteAccess")] + [HttpPost] + [Route("Bulk")] + public async Task PostMany([FromBody] Reference[] values) + { + if (values == null || values.Length == 0) { - var reference = await _referencesRepository.Get(id); - if (reference == null) return NotFound(); - - return reference; + return BadRequest("No data posted"); } - - [Authorize("WriteAccess")] - [HttpPost] - public async Task> Post([FromBody] Reference value) + try { - if (value == null) - { - return BadRequest("No data posted"); - } - - Reference newReference; - try - { - newReference = await _referencesRepository.Add(value); - } - catch (BadRequestException e) - { - return BadRequest(e); - } - - return newReference; + await _referencesRepository.AddRange(values); } - - [Authorize("WriteAccess")] - [HttpPost] - [Route("Bulk")] - public async Task PostMany([FromBody] Reference[] values) + catch (BadRequestException e) { - if (values == null || values.Length == 0) - { - return BadRequest("No data posted"); - } - try - { - await _referencesRepository.AddRange(values); - } - catch (BadRequestException e) - { - return BadRequest(e); - } - - return Ok(); + return BadRequest(e); } + + return Ok(); + } - [Authorize("WriteAccess")] - [HttpPut("{id}")] - public async Task Put(Guid id, [FromBody] Reference value) + [Authorize("WriteAccess")] + [HttpPut("{id:guid}")] + public async Task Put(Guid id, [FromBody] Reference value) + { + if (value == null) { - if (value == null) - { - return BadRequest("No reference to put"); - } + return BadRequest("No reference to put"); + } - if (value.Id == Guid.Empty) - { - value.Id = id; - } + if (value.Id == Guid.Empty) + { + value.Id = id; + } - if (value.Id != id) - { - return BadRequest("Id on reference set and different..."); - } + if (value.Id != id) + { + return BadRequest("Id on reference set and different..."); + } - try - { - await _referencesRepository.Update(value); - } - catch (NotFoundException e) - { - return NotFound(e); - } - - return Ok(); + try + { + await _referencesRepository.Update(value); + } + catch (NotFoundException e) + { + return NotFound(e); } + + return Ok(); + } - [Authorize("WriteAccess")] - [HttpDelete("{id}")] - [System.Diagnostics.CodeAnalysis.SuppressMessage("Globalization", "CA1303:Do not pass literals as localized parameters", Justification = "")] - public ActionResult Delete(Guid id) + [Authorize("WriteAccess")] + [HttpDelete("{id:guid}")] + [System.Diagnostics.CodeAnalysis.SuppressMessage("Globalization", "CA1303:Do not pass literals as localized parameters", Justification = "")] + public ActionResult Delete(Guid id) + { + try + { + _referencesRepository.Delete(id); + } + catch (NotFoundException e) { - try - { - _referencesRepository.Delete(id); - } - catch (NotFoundException e) - { - return NotFound(e); - } + return NotFound(e); + } - return Ok(); + return Ok(); - } } -} +} \ No newline at end of file diff --git a/Nbic.References/Dockerfile b/Nbic.References/Dockerfile index 6f6e887..36dd0a4 100644 --- a/Nbic.References/Dockerfile +++ b/Nbic.References/Dockerfile @@ -1,6 +1,6 @@ #See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging. -FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base +FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS base WORKDIR /app # temp fix ols ssl on sql server RUN sed -i 's/DEFAULT@SECLEVEL=2/DEFAULT@SECLEVEL=1/g' /etc/ssl/openssl.cnf @@ -17,7 +17,7 @@ ENV SwaggerClientId="implicit" ENV DbProvider=Sqlite ENV DbConnectionString="Data Source=references.db" -FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build +FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build WORKDIR /src COPY ["Nbic.References/Nbic.References.csproj", "Nbic.References/"] COPY ["Nbic.References.Core/Nbic.References.Core.csproj", "Nbic.References.Core/"] diff --git a/Nbic.References/Nbic.References.csproj b/Nbic.References/Nbic.References.csproj index d94eedf..966cdef 100644 --- a/Nbic.References/Nbic.References.csproj +++ b/Nbic.References/Nbic.References.csproj @@ -1,6 +1,6 @@  - net6.0 + net8.0 InProcess Linux d1a9df1e-a712-4a31-80a5-eb5557a1f6ee @@ -8,21 +8,21 @@ - + all runtime; build; native; contentfiles; analyzers; buildtransitive - + all runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - - - + + + + + + + all diff --git a/Nbic.References/Program.cs b/Nbic.References/Program.cs index de2e30a..b1f31e8 100644 --- a/Nbic.References/Program.cs +++ b/Nbic.References/Program.cs @@ -1,20 +1,19 @@ using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Hosting; -namespace Nbic.References +namespace Nbic.References; + +public static class Program { - public static class Program + public static void Main(string[] args) { - public static void Main(string[] args) - { - CreateHostBuilder(args).Build().Run(); - } - - public static IHostBuilder CreateHostBuilder(string[] args) => - Host.CreateDefaultBuilder(args) - .ConfigureWebHostDefaults(webBuilder => - { - webBuilder.UseStartup(); - }); + CreateHostBuilder(args).Build().Run(); } -} + + public static IHostBuilder CreateHostBuilder(string[] args) => + Host.CreateDefaultBuilder(args) + .ConfigureWebHostDefaults(webBuilder => + { + webBuilder.UseStartup(); + }); +} \ No newline at end of file diff --git a/Nbic.References/Startup.cs b/Nbic.References/Startup.cs index f1eb457..1c5fc22 100644 --- a/Nbic.References/Startup.cs +++ b/Nbic.References/Startup.cs @@ -2,331 +2,328 @@ // ReSharper disable StyleCop.SA1600 using Nbic.References.Infrastructure.Repositories; +using Nbic.References.Infrastructure.Repositories.DbContext; using Nbic.References.Infrastructure.Services.Indexing; -namespace Nbic.References +namespace Nbic.References; + +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Linq; +using System.Threading.Tasks; + +using Microsoft.AspNetCore.Authentication.JwtBearer; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Data.Sqlite; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using Microsoft.OpenApi.Models; +using Microsoft.IdentityModel.Logging; +using RobotsTxt; + +using Swagger; + +using Index = Index; + +public class Startup { - using System; - using System.Collections.Generic; - using System.Diagnostics.CodeAnalysis; - using System.IO; - using System.Linq; - using System.Threading.Tasks; - - using Microsoft.AspNetCore.Authentication.JwtBearer; - using Microsoft.AspNetCore.Builder; - using Microsoft.AspNetCore.Hosting; - using Microsoft.Data.Sqlite; - using Microsoft.EntityFrameworkCore; - using Microsoft.Extensions.Configuration; - using Microsoft.Extensions.DependencyInjection; - using Microsoft.Extensions.Hosting; - using Microsoft.Extensions.Logging; - using Microsoft.OpenApi.Models; - using Microsoft.IdentityModel.Logging; - - using EFCore; - - using RobotsTxt; - - using Swagger; - - using Index = Index; - - public class Startup - { - private readonly string apiName; - private readonly string authAuthority; - private readonly string authAuthorityEndPoint; - private readonly string connectionString; - private readonly string provider; - private readonly string writeAccessRole; - private readonly string swaggerClientId; + private readonly string apiName; + private readonly string authAuthority; + private readonly string authAuthorityEndPoint; + private readonly string connectionString; + private readonly string provider; + private readonly string writeAccessRole; + private readonly string swaggerClientId; - private ILogger logger; + private ILogger logger; - public Startup(IConfiguration configuration) - { - Configuration = configuration; + public Startup(IConfiguration configuration) + { + Configuration = configuration; - // configuration - authAuthority = Configuration.GetValue("AuthAuthority", "https://demo.identityserver.com"); - authAuthorityEndPoint = Configuration.GetValue( - "AuthAuthorityEndPoint", - "https://demo.identityserver.com/connect/authorize"); - apiName = Configuration.GetValue("ApiName", "api"); + // configuration + authAuthority = Configuration.GetValue("AuthAuthority", "https://demo.identityserver.com"); + authAuthorityEndPoint = Configuration.GetValue( + "AuthAuthorityEndPoint", + "https://demo.identityserver.com/connect/authorize"); + apiName = Configuration.GetValue("ApiName", "api"); - provider = Configuration.GetValue("DbProvider", "Sqlite"); - connectionString = Configuration.GetValue("DbConnectionString", "DataSource=:memory:"); + provider = Configuration.GetValue("DbProvider", "Sqlite"); + connectionString = Configuration.GetValue("DbConnectionString", "DataSource=:memory:"); - writeAccessRole = Configuration.GetValue("WriteAccessRole", "my_write_access_role"); - swaggerClientId = Configuration.GetValue("SwaggerClientId", "implicit"); - } + writeAccessRole = Configuration.GetValue("WriteAccessRole", "my_write_access_role"); + swaggerClientId = Configuration.GetValue("SwaggerClientId", "implicit"); + } - public IConfiguration Configuration { get; } + public IConfiguration Configuration { get; } - // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. - [SuppressMessage("Globalization", "CA1303:Do not pass literals as localized parameters", Justification = "")] - public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger log) + // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. + [SuppressMessage("Globalization", "CA1303:Do not pass literals as localized parameters", Justification = "")] + public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger log) + { + logger = log; + app.UseResponseCompression(); + if (env.IsDevelopment()) { - logger = log; - app.UseResponseCompression(); - if (env.IsDevelopment()) - { - app.UseDeveloperExceptionPage(); - log.LogInformation("In Development environment"); + app.UseDeveloperExceptionPage(); + log.LogInformation("In Development environment"); - IdentityModelEventSource.ShowPII = true; - } + IdentityModelEventSource.ShowPII = true; + } - app.UseHttpsRedirection(); - app.UseStaticFiles(); - app.UseRobotsTxt(); - app.UseRouting(); + app.UseHttpsRedirection(); + app.UseStaticFiles(); + app.UseRobotsTxt(); + app.UseRouting(); - AddSwaggerMiddleware(app); + AddSwaggerMiddleware(app); - app.UseCors("AllowAll"); + app.UseCors("AllowAll"); - app.UseAuthentication(); - app.UseAuthorization(); + app.UseAuthentication(); + app.UseAuthorization(); - app.UseEndpoints(endpoints => - { - endpoints.MapControllers(); - }); - } - - // This method gets called by the runtime. Use this method to add services to the container. - [SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope", Justification = "")] - public void ConfigureServices(IServiceCollection services) + app.UseEndpoints(endpoints => { - services.AddResponseCompression(); - services.AddControllers(options => options.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = true); + endpoints.MapControllers(); + }); + } - // services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0); - AddIdentityServerAuthentication(services); - AddSwaggerGenerator(services); - switch (provider) - { - case "Sqlite": - AddSqliteContext(services); - break; - case "SqlServer": - AddSqlServerContext(services); - break; - } + // This method gets called by the runtime. Use this method to add services to the container. + [SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope", Justification = "")] + public void ConfigureServices(IServiceCollection services) + { + services.AddResponseCompression(); + services.AddControllers(options => options.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = true); - services.AddSingleton(new Index()); - services.AddScoped(); - services.AddScoped(); + // services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0); + AddIdentityServerAuthentication(services); + AddSwaggerGenerator(services); + switch (provider) + { + case "Sqlite": + AddSqliteContext(services); + break; + case "SqlServer": + AddSqlServerContext(services); + break; + } - services.AddCors( - options => + services.AddSingleton(new Index()); + services.AddScoped(); + services.AddScoped(); + + services.AddCors( + options => + { + options.AddPolicy( + "AllowAll", + builder => { - options.AddPolicy( - "AllowAll", - builder => - { - builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod() - .WithExposedHeaders("WWW-Authenticate"); - }); + builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod() + .WithExposedHeaders("WWW-Authenticate"); }); + }); - services.AddStaticRobotsTxt(builder => builder.DenyAll()); - } + services.AddStaticRobotsTxt(builder => builder.DenyAll()); + } - private void AddIdentityServerAuthentication(IServiceCollection services) - { - var roleClaim = "role"; - var roleClaimValue = writeAccessRole; + private void AddIdentityServerAuthentication(IServiceCollection services) + { + var roleClaim = "role"; + var roleClaimValue = writeAccessRole; - // Users defined at https://demo.identityserver.com has no roles. - // Using the Issuer-claim (iss) as a substitute to allow authorization with Swagger when testing - if (authAuthority == "https://demo.identityserver.com") - { - roleClaim = "iss"; - roleClaimValue = "https://demo.identityserver.com"; - } + // Users defined at https://demo.identityserver.com has no roles. + // Using the Issuer-claim (iss) as a substitute to allow authorization with Swagger when testing + if (authAuthority == "https://demo.identityserver.com") + { + roleClaim = "iss"; + roleClaimValue = "https://demo.identityserver.com"; + } - services.AddAuthorization(options => - options.AddPolicy("WriteAccess", policy => policy.RequireClaim(roleClaim, roleClaimValue))); + services.AddAuthorization(options => + options.AddPolicy("WriteAccess", policy => policy.RequireClaim(roleClaim, roleClaimValue))); - services.AddCors(); + services.AddCors(); - services.AddAuthentication("token") - .AddJwtBearer("Bearer", options => - { - options.Authority = authAuthority; - options.RequireHttpsMetadata = false; + services.AddAuthentication("token") + .AddJwtBearer("Bearer", options => + { + options.Authority = authAuthority; + options.RequireHttpsMetadata = false; - options.Audience = apiName; - //options.TokenValidationParameters.ValidAudiences = options.TokenValidationParameters.ValidAudiences.Append("fab4api"); - } - ) - .AddIdentityServerAuthentication( + options.Audience = apiName; + //options.TokenValidationParameters.ValidAudiences = options.TokenValidationParameters.ValidAudiences.Append("fab4api"); + } + ) + .AddIdentityServerAuthentication( "token", options => - { - options.Authority = authAuthority; - options.RequireHttpsMetadata = false; - - options.ApiName = apiName; - options.JwtBearerEvents = new JwtBearerEvents - { - OnMessageReceived = e => - { - // _logger.LogTrace("JWT: message received"); - return Task.CompletedTask; - }, - OnTokenValidated = e => - { - // _logger.LogTrace("JWT: token validated"); - return Task.CompletedTask; - }, - OnAuthenticationFailed = e => - { - // _logger.LogTrace("JWT: authentication failed"); - return Task.CompletedTask; - }, - OnChallenge = e => - { - // _logger.LogTrace("JWT: challenge"); - return Task.CompletedTask; - } - }; - }); - - Microsoft.IdentityModel.Logging.IdentityModelEventSource.ShowPII = true; - } - - [SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope", Justification = "")] - [SuppressMessage("Globalization", "CA1303:Do not pass literals as localized parameters", Justification = "")] - private void AddSqliteContext(IServiceCollection services) - { - Console.WriteLine("Adding SqliteContext"); - if (connectionString == "DataSource=:memory:") - { - Console.WriteLine($"SqliteContext - ConnectionString:{connectionString}"); - var context = new SqliteReferencesDbContext(connectionString); - context.Database.OpenConnection(); - context.Database.Migrate(); - services.AddSingleton(context); // in memory version need this - Console.WriteLine("Added InMemoryDatabase"); - } - else - { - // if database is empty - initiate - if (!Directory.Exists("Data")) Directory.CreateDirectory("Data"); - var dbConnectionString = connectionString.Contains('/', StringComparison.InvariantCulture) - ? connectionString - : connectionString.Replace( - "Data Source=", - "Data Source=./Data/", - StringComparison.InvariantCulture); - Console.WriteLine($"SqliteContext - ConnectionString:{dbConnectionString}"); - using (var context = new SqliteReferencesDbContext(dbConnectionString)) { - try - { - var any = context.Reference.Any(); - } - catch (SqliteException ex) + options.Authority = authAuthority; + options.RequireHttpsMetadata = false; + + options.ApiName = apiName; + options.JwtBearerEvents = new JwtBearerEvents { - if (ex.Message.Contains("SQLite Error 1: 'no such table", StringComparison.CurrentCulture)) + OnMessageReceived = e => { - context.Database.Migrate(); - Console.WriteLine($"Empty Schema - initial create - after exception {ex.Message}"); - } - else + // _logger.LogTrace("JWT: message received"); + return Task.CompletedTask; + }, + OnTokenValidated = e => + { + // _logger.LogTrace("JWT: token validated"); + return Task.CompletedTask; + }, + OnAuthenticationFailed = e => + { + // _logger.LogTrace("JWT: authentication failed"); + return Task.CompletedTask; + }, + OnChallenge = e => { - throw; + // _logger.LogTrace("JWT: challenge"); + return Task.CompletedTask; } - } + }; + }); - Console.WriteLine("Added FileDatabase"); - } + Microsoft.IdentityModel.Logging.IdentityModelEventSource.ShowPII = true; + } - services.AddDbContext(options => options.UseSqlite(dbConnectionString)); - Console.WriteLine("Added SqliteContext"); - } + [SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope", Justification = "")] + [SuppressMessage("Globalization", "CA1303:Do not pass literals as localized parameters", Justification = "")] + private void AddSqliteContext(IServiceCollection services) + { + Console.WriteLine("Adding SqliteContext"); + if (connectionString == "DataSource=:memory:") + { + Console.WriteLine($"SqliteContext - ConnectionString:{connectionString}"); + var context = new SqliteReferencesDbContext(connectionString); + context.Database.OpenConnection(); + context.Database.Migrate(); + services.AddSingleton(context); // in memory version need this + Console.WriteLine("Added InMemoryDatabase"); } - - [SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "")] - [SuppressMessage("Globalization", "CA1303:Do not pass literals as localized parameters", Justification = "")] - private void AddSqlServerContext(IServiceCollection services) + else { - Console.WriteLine("Adding SqlServerContext"); - using (var context = new SqlServerReferencesDbContext(connectionString)) + // if database is empty - initiate + if (!Directory.Exists("Data")) Directory.CreateDirectory("Data"); + var dbConnectionString = connectionString.Contains('/', StringComparison.InvariantCulture) + ? connectionString + : connectionString.Replace( + "Data Source=", + "Data Source=./Data/", + StringComparison.InvariantCulture); + Console.WriteLine($"SqliteContext - ConnectionString:{dbConnectionString}"); + using (var context = new SqliteReferencesDbContext(dbConnectionString)) { try { var any = context.Reference.Any(); } - catch (Exception ex) + catch (SqliteException ex) { - Console.WriteLine($"Empty Schema - initial create - after error {ex.Message}"); - context.Database.Migrate(); + if (ex.Message.Contains("SQLite Error 1: 'no such table", StringComparison.CurrentCulture)) + { + context.Database.Migrate(); + Console.WriteLine($"Empty Schema - initial create - after exception {ex.Message}"); + } + else + { + throw; + } } + + Console.WriteLine("Added FileDatabase"); } - services.AddDbContext(options => options.UseSqlServer(connectionString)); - Console.WriteLine("Added SqlServerContext"); + services.AddDbContext(options => options.UseSqlite(dbConnectionString)); + Console.WriteLine("Added SqliteContext"); } + } - private void AddSwaggerGenerator(IServiceCollection services) + [SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "")] + [SuppressMessage("Globalization", "CA1303:Do not pass literals as localized parameters", Justification = "")] + private void AddSqlServerContext(IServiceCollection services) + { + Console.WriteLine("Adding SqlServerContext"); + using (var context = new SqlServerReferencesDbContext(connectionString)) { - services.AddSwaggerGen( - c => - { - c.SwaggerDoc( - "v1", - new OpenApiInfo { Title = "Nbic References API via Swagger", Version = "v1" }); - - c.AddSecurityDefinition( - "oauth2", - new OpenApiSecurityScheme - { - Type = SecuritySchemeType.OAuth2, - Flows = new OpenApiOAuthFlows - { - Implicit = new OpenApiOAuthFlow - { - AuthorizationUrl = - new Uri( - authAuthorityEndPoint, - UriKind.Absolute), - Scopes = new Dictionary - { - { apiName, "Access Api" } - - // { "readAccess", "Access read operations" }, - // { "writeAccess", "Access write operations" } - } - } - } - }); - c.OperationFilter(); - c.EnableAnnotations(); - }); + try + { + var any = context.Reference.Any(); + } + catch (Exception ex) + { + Console.WriteLine($"Empty Schema - initial create - after error {ex.Message}"); + context.Database.Migrate(); + } } - private void AddSwaggerMiddleware(IApplicationBuilder app) - { - app.UseSwagger(); - app.UseSwaggerUI( - c => + services.AddDbContext(options => options.UseSqlServer(connectionString)); + Console.WriteLine("Added SqlServerContext"); + } + + private void AddSwaggerGenerator(IServiceCollection services) + { + services.AddSwaggerGen( + c => + { + c.SwaggerDoc( + "v1", + new OpenApiInfo { Title = "Nbic References API via Swagger", Version = "v1" }); + + c.AddSecurityDefinition( + "oauth2", + new OpenApiSecurityScheme { - c.SwaggerEndpoint("/swagger/v1/swagger.json", "Nbic References API V1"); - c.OAuthClientId(swaggerClientId); - c.OAuthAppName(apiName); - c.OAuthScopeSeparator(" "); - - // c.OAuthAdditionalQueryStringParams(new { foo = "bar" }); - c.OAuthUseBasicAuthenticationWithAccessCodeGrant(); - c.RoutePrefix = string.Empty; + Type = SecuritySchemeType.OAuth2, + Flows = new OpenApiOAuthFlows + { + Implicit = new OpenApiOAuthFlow + { + AuthorizationUrl = + new Uri( + authAuthorityEndPoint, + UriKind.Absolute), + Scopes = new Dictionary + { + { apiName, "Access Api" } + + // { "readAccess", "Access read operations" }, + // { "writeAccess", "Access write operations" } + } + } + } }); - } + c.OperationFilter(); + c.EnableAnnotations(); + }); + } + + private void AddSwaggerMiddleware(IApplicationBuilder app) + { + app.UseSwagger(); + app.UseSwaggerUI( + c => + { + c.SwaggerEndpoint("/swagger/v1/swagger.json", "Nbic References API V1"); + c.OAuthClientId(swaggerClientId); + c.OAuthAppName(apiName); + c.OAuthScopeSeparator(" "); + + // c.OAuthAdditionalQueryStringParams(new { foo = "bar" }); + c.OAuthUseBasicAuthenticationWithAccessCodeGrant(); + c.RoutePrefix = string.Empty; + }); } } \ No newline at end of file diff --git a/Nbic.References/Swagger/SecurityRequirementsOperationFilter.cs b/Nbic.References/Swagger/SecurityRequirementsOperationFilter.cs index 196aca3..62fa3ad 100644 --- a/Nbic.References/Swagger/SecurityRequirementsOperationFilter.cs +++ b/Nbic.References/Swagger/SecurityRequirementsOperationFilter.cs @@ -1,43 +1,41 @@ using System.Collections.Generic; using System.Linq; -using Microsoft.AspNetCore.Authorization; using Microsoft.OpenApi.Models; using Swashbuckle.AspNetCore.SwaggerGen; -namespace Nbic.References.Swagger +namespace Nbic.References.Swagger; + +/// +/// Help swagger discover api operations that require authentication +/// +public class SecurityRequirementsOperationFilter : IOperationFilter { - /// - /// Help swagger discover api operations that require authentication - /// - public class SecurityRequirementsOperationFilter : IOperationFilter + [System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1062:Validate arguments of public methods", Justification = "")] + public void Apply(OpenApiOperation operation, OperationFilterContext context) { - [System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1062:Validate arguments of public methods", Justification = "")] - public void Apply(OpenApiOperation operation, OperationFilterContext context) - { - // Policy names map to scopes - var requiredScopes = context.MethodInfo - .GetCustomAttributes(true) - .OfType() - .Select(attr => attr.Policy) - .Distinct().ToList(); + // Policy names map to scopes + var requiredScopes = context.MethodInfo + .GetCustomAttributes(true) + .OfType() + .Select(attr => attr.Policy) + .Distinct().ToList(); - if (!requiredScopes.Any()) return; + if (requiredScopes.Count == 0) return; - operation.Responses.Add("401", new OpenApiResponse { Description = "Unauthorized" }); - operation.Responses.Add("403", new OpenApiResponse { Description = "Forbidden" }); + operation.Responses.Add("401", new() { Description = "Unauthorized" }); + operation.Responses.Add("403", new() { Description = "Forbidden" }); - var oAuthScheme = new OpenApiSecurityScheme - { - Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "oauth2" } - }; + var oAuthScheme = new OpenApiSecurityScheme + { + Reference = new() { Type = ReferenceType.SecurityScheme, Id = "oauth2" } + }; - operation.Security = new List + operation.Security = new List + { + new() { - new OpenApiSecurityRequirement - { - [ oAuthScheme ] = requiredScopes - } - }; - } + [ oAuthScheme ] = requiredScopes + } + }; } } \ No newline at end of file