In which layer should the AppDBContext be put in? - c#

I am doing my first webAPI with .net and I am trying to implement the Clean Architecture in my project. But I do not know where should I put my AppDBContext. Here is my code.
using Microsoft.EntityFrameworkCore;
namespace ReactNoteAPI.Data
{
public class AppDBContext : DbContext
{
public DbSet<Note> Notes { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(#"Server=(localdb)\MSSQLLocalDB;Database=Notes;Trusted_Connection=True;");
}
}
}

echo# off
dotnet new mvc -o fqSSDb
cd fqSSDb
cls
echo dotnet add package Microsoft.EntityFrameworkCore.Sqlite
dotnet add package Microsoft.EntityFrameworkCore.Sqlite
REM echo "add package Microsoft.EntityFrameworkCore.SqlServer"
REM dotnet add package Microsoft.EntityFrameworkCore.SqlServer
cls
echo "dotnet add package Microsoft.VisualStudio.Web.CodeGeneration.Design"
dotnet add package Microsoft.VisualStudio.Web.CodeGeneration.Design
cls
echo "dotnet add package Microsoft.EntityFrameworkCore.SqlServer.Design"
dotnet add package Microsoft.EntityFrameworkCore.SqlServer.Design
cls
echo "dotnet add package Microsoft.EntityFrameworkCore.Tools"
dotnet add package Microsoft.EntityFrameworkCore.Tools
cls
echo "dotnet tool install --global dotnet-aspnet-codegenerator"
dotnet tool install --global dotnet-aspnet-codegenerator
cls
echo "Finally..."
dotnet ef dbcontext scaffold "Server=(localdb)\mssqllocaldb;Database=fqSSDb;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -o fqSSDb -c "fqSSDbContext" -d --context-namespace fqSSDb --context-dir fqSSDb
REM https://docs.microsoft.com/en-us/aspnet/core/fundamentals/tools/dotnet-aspnet-codegenerator?view=aspnetcore-6.0
REM Uninstall aspnet-codegenerator
REM It may be necessary to uninstall the aspnet-codegenerator to resolve problems. For example, if you installed a preview version of aspnet-codegenerator, uninstall it before installing the released version.
REM The following commands uninstall the dotnet-aspnet-codegenerator tool and installs the latest stable version:
REM Now easily you can generate CRUD code by applying the following command :
dotnet aspnet-codegenerator controller -name fqRequestController -m fqRequest -dc fqRequestDbContext --relativeFolderPath Controllers --useDefaultLayout --referenceScriptLibraries
REM note: but before run that command make sure you have made the necessary changes at your
REM - appsettings.json
REM - "ConnectionStrings": {"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=fqSSDb;Trusted_Connection=True;MultipleActiveResultSets=true"}
REM - startup.cs file
REM var fqssdbConnectionString = builder.Configuration.GetConnectionString("fqSSDbConnection");
REM builder.Services.AddDbContext<FqSSDbContext>(options => options.UseSqlServer(fqssdbConnectionString));

Related

Docker skip project on build

I have dockerfile with this config
FROM mcr.microsoft.com/dotnet/sdk:6.0 as builder
WORKDIR /app
COPY . .
RUN apt-get update;apt-get install curl; apt-get -y install zip
RUN curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
RUN unzip awscliv2.zip
RUN ./aws/install
ENV PATH="${PATH}:/root/.dotnet/tools"
#RUN dotnet tool install -g AWS.CodeArtifact.NuGet.CredentialProvider
#
#RUN dotnet codeartifact-creds install
#
#RUN aws codeartifact login --tool dotnet --domain monspire --domain-owner 986853728599 --repository monspire
RUN dotnet restore
RUN dotnet publish -c Release TooSee.Web.Host.csproj
# create the runnable container...
FROM mcr.microsoft.com/dotnet/sdk:6.0
# install dependencies
RUN apt-get update \
&& apt-get install -y --allow-unauthenticated \
libc6-dev \
libgdiplus \
libx11-dev \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /app
COPY --from=builder /app/src/TooSee.Web.Host/bin/Debug/net6.0/publish/ .
ARG ENVIRONMENT
ENV ENVIRONMENT=${ENVIRONMENT}
EXPOSE 80
CMD ["dotnet", "TooSee.Web.Host.dll"]
And try to run it via docker build -t tooseeapi .
But for reasons it skipped .Core project
Here is log
=> ERROR [builder 9/9] RUN dotnet publish -c Release TooSee.Web.Host.csproj 6.9s
[builder 9/9] RUN dotnet publish -c Release TooSee.Web.Host.csproj:
#15 0.750 Microsoft (R) Build Engine version 17.2.0+41abc5629 for .NET
#15 0.750 Copyright (C) Microsoft Corporation. All rights reserved.
#15 0.750
#15 2.054 Determining projects to restore...
#15 2.057 Skipping project "/TooSee.Web.Core/TooSee.Web.Core.csproj" because it was not found.
#15 2.060 Skipping project "/TooSee.Web.Core/TooSee.Web.Core.csproj" because it was not found.
#15 2.385 All projects are up-to-date for restore.
#15 3.150 /usr/share/dotnet/sdk/6.0.302/Microsoft.Common.CurrentVersion.targets(2066,5): warning : The referenced project '../TooSee.Web.Core/TooSee.Web.Core.csproj' does not exist. [/app/TooSee.Web.Host.csproj]
Dockerfile is under this path - C:\Users\nemes\Documents\GitHub\tooseeapi\src\TooSee.Web.Host
And .Core is here
C:\Users\nemes\Documents\GitHub\tooseeapi\src\TooSee.Web.Core
But if I run dotnet publish -c Release TooSee.Web.Host.csproj I got no errors
Why it's skipped and how I can fix this?
you have to keep your docker file at this location
C:\Users\nemes\Documents\GitHub\tooseeapi\src
and copy both project files separately. something like
COPY ["TooSee.Web.Host/TooSee.Web.Host.csproj", "./"]
COPY ["TooSee.Web.Core/TooSee.Web.Core.csproj", "./"]

How to run unit test coverage report using coverlet inside a container?

I'm using mcr.microsoft.com/dotnet/core/sdk:2.2 image to run unit tests inside a container. It is failing to generate coverage report by throwing following error.
error : One or more errors occurred.
(Could not find file '/tmp/xunit.runner.visualstudio.dotnetcore.testadapter
Dockerfile:
FROM mcr.microsoft.com/dotnet/core/sdk:2.2
WORKDIR /app
COPY . /app
CMD [ "bash", "./build.sh" ]
build.sh
#!bin/bash
export PATH="$PATH:/root/.dotnet/tools"
echo "Installing Tools"
dotnet tool install --global coverlet.console
echo "Adding Package"
dotnet add <.csproj> package coverlet.msbuild
echo "Running Tests"
dotnet test <.csproj> /p:CollectCoverage=true /p:CoverletOutputFormat=opencover /p:CoverletOutput='./coverage/'
Problem with the 2.6.0 version of coverlet.
Hardcoding version solves the problem.
echo "Adding Package"
dotnet add <.csproj> package coverlet.msbuild --version 2.5.1

'dotnet build' command not finding NuGet packages (they exist)

I'm trying to build my .NET Core 2.1 application from the command-line on my Jenkins server.
It builds fine on my local machine (Windows 10, Visual Studio 2017 Enterprise), and if I manually build it on the server Jenkins is running on (manually checkout Git repository and running dotnet build). It's only when I'm doing it through Jenkins in a Docker container that it fails.
The error:
/usr/share/dotnet/sdk/2.1.403/Sdks/Microsoft.NET.Sdk/targets/Microsoft.PackageDependencyResolution.targets(198,5): error NETSDK1064: Package Microsoft.CodeQuality.Analyzers, version 2.6.2 was not found. It might have been deleted since NuGet restore. Otherwise, NuGet restore might have only partially completed, which might have been due to maximum path length restrictions. [/var/lib/jenkins/jobs/pr-builder/jobs/cgi-api/branches/PR-18/workspace/API/API.csproj]
The package exists in ~/.nuget/packages/.
I'm aware my Jenkinsfile is a bit weird at the moment, but that has to do with me trying to make this all work. It seems dotnet restore is working fine, but dotnet build is somehow not locating these files.
I've tried specifying the package directory (through the environment variable, with dotnet restore --sources and dotnet build --sources.
I attached pretty much anything I could think of at the moment, but if I forgot something please tell. I'm pretty lost at the moment.
My Jenkinsfile:
pipeline {
agent {
docker {
image 'microsoft/dotnet:2.1-sdk'
}
}
environment {
HOME = '.'
NUGET_PACKAGES = './.nuget/packages/'
}
stages {
stage('pre-build') {
steps {
// logging tooling versions
sh 'dotnet --info'
sh 'find ~/.nuget/packages/microsoft.codequality.analyzers/ -type f'
sh 'dotnet nuget locals all --list'
sh 'dotnet restore'
// sh 'dotnet clean'
}
}
stage('build') {
steps {
// sh 'dotnet restore --force --no-cache'
// sh 'ls ./packages/'
// sh 'find ./packages/microsoft.codequality.analyzers/ -type f'
sh 'dotnet build --no-restore'
}
}
stage('test') {
steps {
sh 'no test project configured'
// sh 'dotnet test'
}
}
}
}
My .csproj
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp2.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<Folder Include="wwwroot\" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Microsoft.CodeAnalysis.FxCopAnalyzers" Version="2.6.2">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>
</ItemGroup>
<PropertyGroup>
<CodeAnalysisRuleSet></CodeAnalysisRuleSet>
<Features>IOperation</Features>
</PropertyGroup>
</Project>
Some build details:
$ docker --version
Docker version 18.06.1-ce, build e68fc7a
Inside docker container:
$ dotnet --info
.NET Core SDK (reflecting any global.json):
Version: 2.1.403
Commit: 04e15494b6
Runtime Environment:
OS Name: debian
OS Version: 9
OS Platform: Linux
RID: debian.9-arm
Base Path: /usr/share/dotnet/sdk/2.1.403/
Host (useful for support):
Version: 2.1.5
Commit: 290303f510
.NET Core SDKs installed:
2.1.403 [/usr/share/dotnet/sdk]
.NET Core runtimes installed:
Microsoft.AspNetCore.All 2.1.5 [/usr/share/dotnet/shared/Microsoft.AspNetCore.All]
Microsoft.AspNetCore.App 2.1.5 [/usr/share/dotnet/shared/Microsoft.AspNetCore.App]
Microsoft.NETCore.App 2.1.5 [/usr/share/dotnet/shared/Microsoft.NETCore.App]
$ find ./.nuget/packages/microsoft.codequality.analyzers/ -type f
./.nuget/packages/microsoft.codequality.analyzers/2.6.2/analyzers/dotnet/vb/Microsoft.CodeQuality.VisualBasic.Analyzers.dll
./.nuget/packages/microsoft.codequality.analyzers/2.6.2/analyzers/dotnet/vb/Microsoft.CodeQuality.Analyzers.dll
./.nuget/packages/microsoft.codequality.analyzers/2.6.2/analyzers/dotnet/cs/Microsoft.CodeQuality.Analyzers.dll
./.nuget/packages/microsoft.codequality.analyzers/2.6.2/analyzers/dotnet/cs/Microsoft.CodeQuality.CSharp.Analyzers.dll
./.nuget/packages/microsoft.codequality.analyzers/2.6.2/.signature.p7s
./.nuget/packages/microsoft.codequality.analyzers/2.6.2/ThirdPartyNotices.rtf
./.nuget/packages/microsoft.codequality.analyzers/2.6.2/build/Microsoft.CodeQuality.CSharp.Analyzers.props
./.nuget/packages/microsoft.codequality.analyzers/2.6.2/build/Microsoft.CodeQuality.VisualBasic.Analyzers.props
./.nuget/packages/microsoft.codequality.analyzers/2.6.2/build/Microsoft.CodeQuality.Analyzers.props
./.nuget/packages/microsoft.codequality.analyzers/2.6.2/rulesets/DesignRulesEnabled.ruleset
./.nuget/packages/microsoft.codequality.analyzers/2.6.2/rulesets/DocumentationRulesDefault.ruleset
./.nuget/packages/microsoft.codequality.analyzers/2.6.2/rulesets/PerformanceRulesDefault.ruleset
./.nuget/packages/microsoft.codequality.analyzers/2.6.2/rulesets/UsageRulesDefault.ruleset
./.nuget/packages/microsoft.codequality.analyzers/2.6.2/rulesets/ReliabilityRulesDefault.ruleset
./.nuget/packages/microsoft.codequality.analyzers/2.6.2/rulesets/MaintainabilityRulesDefault.ruleset
./.nuget/packages/microsoft.codequality.analyzers/2.6.2/rulesets/SecurityRulesDefault.ruleset
./.nuget/packages/microsoft.codequality.analyzers/2.6.2/rulesets/PerformanceRulesEnabled.ruleset
./.nuget/packages/microsoft.codequality.analyzers/2.6.2/rulesets/MaintainabilityRulesEnabled.ruleset
./.nuget/packages/microsoft.codequality.analyzers/2.6.2/rulesets/UsageRulesEnabled.ruleset
./.nuget/packages/microsoft.codequality.analyzers/2.6.2/rulesets/DocumentationRulesEnabled.ruleset
./.nuget/packages/microsoft.codequality.analyzers/2.6.2/rulesets/ReliabilityRulesEnabled.ruleset
./.nuget/packages/microsoft.codequality.analyzers/2.6.2/rulesets/AllRulesEnabled.ruleset
./.nuget/packages/microsoft.codequality.analyzers/2.6.2/rulesets/NamingRulesEnabled.ruleset
./.nuget/packages/microsoft.codequality.analyzers/2.6.2/rulesets/AllRulesDisabled.ruleset
./.nuget/packages/microsoft.codequality.analyzers/2.6.2/rulesets/SecurityRulesEnabled.ruleset
./.nuget/packages/microsoft.codequality.analyzers/2.6.2/rulesets/DesignRulesDefault.ruleset
./.nuget/packages/microsoft.codequality.analyzers/2.6.2/rulesets/NamingRulesDefault.ruleset
./.nuget/packages/microsoft.codequality.analyzers/2.6.2/rulesets/AllRulesDefault.ruleset
./.nuget/packages/microsoft.codequality.analyzers/2.6.2/microsoft.codequality.analyzers.2.6.2.nupkg.sha512
./.nuget/packages/microsoft.codequality.analyzers/2.6.2/microsoft.codequality.analyzers.2.6.2.nupkg
./.nuget/packages/microsoft.codequality.analyzers/2.6.2/microsoft.codequality.analyzers.nuspec
./.nuget/packages/microsoft.codequality.analyzers/2.6.2/tools/uninstall.ps1
./.nuget/packages/microsoft.codequality.analyzers/2.6.2/tools/install.ps1
$ dotnet nuget locals all --list
info : http-cache: ./.local/share/NuGet/v3-cache
info : global-packages: ./.nuget/packages/
info : temp: /tmp/NuGetScratch
info : plugins-cache: ./.local/share/NuGet/plugins-cache
$ dotnet restore
Restoring packages for /var/lib/jenkins/jobs/pr-builder/jobs/cgi-api/branches/PR-18/workspace/API/API.csproj...
Restore completed in 13.5 sec for /var/lib/jenkins/jobs/pr-builder/jobs/cgi-api/branches/PR-18/workspace/API/API.csproj.
$ dotnet build --no-restore
Microsoft (R) Build Engine version 15.8.169+g1ccb72aefa for .NET Core
Copyright (C) Microsoft Corporation. All rights reserved.
/usr/share/dotnet/sdk/2.1.403/Sdks/Microsoft.NET.Sdk/targets/Microsoft.PackageDependencyResolution.targets(198,5): error NETSDK1064: Package Microsoft.CodeQuality.Analyzers, version 2.6.2 was not found. It might have been deleted since NuGet restore. Otherwise, NuGet restore might have only partially completed, which might have been due to maximum path length restrictions. [/var/lib/jenkins/jobs/pr-builder/jobs/cgi-api/branches/PR-18/workspace/API/API.csproj]
Build FAILED.
/usr/share/dotnet/sdk/2.1.403/Sdks/Microsoft.NET.Sdk/targets/Microsoft.PackageDependencyResolution.targets(198,5): error NETSDK1064: Package Microsoft.CodeQuality.Analyzers, version 2.6.2 was not found. It might have been deleted since NuGet restore. Otherwise, NuGet restore might have only partially completed, which might have been due to maximum path length restrictions. [/var/lib/jenkins/jobs/pr-builder/jobs/cgi-api/branches/PR-18/workspace/API/API.csproj]
0 Warning(s)
1 Error(s)
I've resolved the issue by specifying where dotnet build should look for the NuGet packages. It that within the image it doesn't look at the right location (although I'm not sure where it is looking either...)
I've specified the location with the --packages option. This option is listed in the dotnet restore documentation, but not in the dotnet build ones, even though it is available there as well (and you need it there, specifically).
You can specify it as follows:
dotnet restore --packages <path>
and
dotnet build --packages <path>
It works with the --no-restore option as well, if you need that.
My final Jenkinsfile looks as follows:
pipeline {
agent {
docker {
image 'microsoft/dotnet:2.1-sdk'
}
}
environment {
HOME = '.'
}
stages {
stage('pre-build') {
steps {
// logging tooling versions
sh 'dotnet --info'
sh 'dotnet nuget locals all --list'
sh 'dotnet clean'
}
}
stage('build') {
steps {
sh 'dotnet build --packages ./.nuget/packages'
}
}
stage('test') {
steps {
sh 'echo no test project configured'
// sh 'dotnet test'
}
}
}
}
I ran into a similar issue solved by clearing global packages and cache with dotnet nuget locals all --clear as explained here.

How to perform migrations in the package manager?

I installed FluentMigration to manage my SQL files.
In the package management I execute the following commands:
PM> dotnet add package FluentMigrator
PM> dotnet add package FluentMigrator.Runner
Migration
[Migration(201805041513)]
public class _201805041513_CriacaoTabelaPessoa : ForwardOnlyMigration
{
public override void Up()
{
Create.Table("Pessoa")
.InSchema("angularCore")
.WithColumn("Id").AsInt32().Identity()
.WithColumn("Nome").AsString(80)
.WithColumn("SobreNome").AsString(50)
.WithColumn("Email").AsString(50)
.WithColumn("IdTpoPessoa").AsInt16()
.WithColumn("IdEndereco").AsInt16();
}
}
Out-of-process (for some corporate requirements)
PM> dotnet tool install -g FluentMigrator.DotNet.Cli
Error:
No executable found corresponding to the "dotnet-tool" command
Documentation
Edit
Run in
PM> dotnet tool install -g FluentMigrator.DotNet.Cli
PM> dotnet fm migrate -p sqlite -c "Data Source=test.db" -a ".\bin\Debug\netcoreapp2.1\test.dll"
Generate teste.db
In the old versions you run the migrations directly in the database, I
did not understand how to update my database, ie create the Person
table through the generated test.db file?
I was able to get this to work without any issues. Here is what I did:
First I installed .NET Core 2.1-Preview 2. After installing I verified the version:
dotnet --version
2.1.300-preview2-008533
I then created the project
mkdir testfm
cd testfm
dotnet new console
Installed the nuget packages
dotnet add package FluentMigrator
dotnet add package FluentMigrator.Runner
dotnet add package FluentMigrator.Runner.SQLite
dotnet add package Microsoft.Data.Sqlite
Installed the CLI tool
dotnet tool install -g FluentMigrator.DotNet.Cli
Created a Migration Class called Migration1.cs
using FluentMigrator;
namespace test
{
[Migration(201805041513)]
public class _201805041513_CriacaoTabelaPessoa : ForwardOnlyMigration
{
public override void Up()
{
Create.Table("Pessoa")
.InSchema("angularCore")
.WithColumn("Id").AsInt32().Identity()
.WithColumn("Nome").AsString(80)
.WithColumn("SobreNome").AsString(50)
.WithColumn("Email").AsString(50)
.WithColumn("IdTpoPessoa").AsInt16()
.WithColumn("IdEndereco").AsInt16();
}
}
}
Compiled the project
dotnet build
Ran the migration from the root project directory
dotnet fm migrate -p sqlite -c "Data Source=test.db" -a
".\bin\Debug\netcoreapp2.1\test.dll"
I then Received the following messages.
I then confirmed the table was created by viewing the SqlLite DB
To run this same migration on a Sql Server 2016 you would run:
dotnet fm migrate -p SqlServer2016 -c
"server=SQLSERVERINSTANCE;uid=testfm;pwd=test;Trusted_Connection=yes;database=FluentMigrator"
-a ".\bin\Debug\netcoreapp2.1\test.dll"

Any way to run dotnet-ef from a published app

I'm constructing a docker container from a Dotnet Core 2.0 WebApp that was packaged with dotnet publish, but publishing this way doesn't copy the extensions in Microsoft.EntityFrameworkCore.Tools.DotNet that enable the dotnet-ef command.
Specifically, I want to run dotnet ef commands in the container, but I get this error:
No executable found matching command "dotnet-ef"
My .csproj file contains this, so dotnet-ef works fine on the host:
<DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.0" />
Is there a way to run migrations from a dotnet app that's been packaged with dotnet publish?
Based on #bricelam's suggestion and Ben Day's blog entry, this works for dotnet 2.x on Linux:
$ dotnet exec \
--depsfile Api.deps.json \
/usr/share/dotnet/sdk/NuGetFallbackFolder/microsoft.entityframeworkcore.tools.dotnet/2.0.2/tools/netcoreapp2.0/ef.dll \
database update \
--assembly ./MyDllWithMigrations.dll \
--startup-assembly Api.dll \
--project-dir . \
--verbose
(This is based on the microsoft/aspnetcore-build base image.)

Categories

Resources