From 92dcf4b3ffa91cfd7812e93dcfa3b8c646d9ca47 Mon Sep 17 00:00:00 2001 From: navule Date: Tue, 30 Nov 2021 19:10:34 +0530 Subject: [PATCH 1/3] minimal web api aspnet core 6 CRUD on PostgreSQL --- .../20211130132934_firstmigration.Designer.cs | 47 +++ Migrations/20211130132934_firstmigration.cs | 33 ++ Migrations/NoteDbModelSnapshot.cs | 45 +++ NotesMinimalAPI.csproj | 20 + NotesMinimalAPI/.gitignore | 350 ------------------ NotesMinimalAPI/NotesMinimalAPI.csproj | 13 - NotesMinimalAPI/Program.cs | 19 - .../Properties/launchSettings.json | 31 -- Program.cs | 90 +++++ README.md | 1 + ...pment.json => appsettings.Development.json | 0 .../appsettings.json => appsettings.json | 3 + 12 files changed, 239 insertions(+), 413 deletions(-) create mode 100644 Migrations/20211130132934_firstmigration.Designer.cs create mode 100644 Migrations/20211130132934_firstmigration.cs create mode 100644 Migrations/NoteDbModelSnapshot.cs create mode 100644 NotesMinimalAPI.csproj delete mode 100644 NotesMinimalAPI/.gitignore delete mode 100644 NotesMinimalAPI/NotesMinimalAPI.csproj delete mode 100644 NotesMinimalAPI/Program.cs delete mode 100644 NotesMinimalAPI/Properties/launchSettings.json create mode 100644 Program.cs rename NotesMinimalAPI/appsettings.Development.json => appsettings.Development.json (100%) rename NotesMinimalAPI/appsettings.json => appsettings.json (70%) diff --git a/Migrations/20211130132934_firstmigration.Designer.cs b/Migrations/20211130132934_firstmigration.Designer.cs new file mode 100644 index 0000000..44383f6 --- /dev/null +++ b/Migrations/20211130132934_firstmigration.Designer.cs @@ -0,0 +1,47 @@ +// +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace NotesMinimalAPI.Migrations +{ + [DbContext(typeof(NoteDb))] + [Migration("20211130132934_firstmigration")] + partial class firstmigration + { + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "6.0.0") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("Note", b => + { + b.Property("id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("id")); + + b.Property("done") + .HasColumnType("boolean"); + + b.Property("text") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("id"); + + b.ToTable("Notes"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/Migrations/20211130132934_firstmigration.cs b/Migrations/20211130132934_firstmigration.cs new file mode 100644 index 0000000..4862bca --- /dev/null +++ b/Migrations/20211130132934_firstmigration.cs @@ -0,0 +1,33 @@ +using Microsoft.EntityFrameworkCore.Migrations; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace NotesMinimalAPI.Migrations +{ + public partial class firstmigration : Migration + { + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "Notes", + columns: table => new + { + id = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + text = table.Column(type: "text", nullable: false), + done = table.Column(type: "boolean", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Notes", x => x.id); + }); + } + + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "Notes"); + } + } +} diff --git a/Migrations/NoteDbModelSnapshot.cs b/Migrations/NoteDbModelSnapshot.cs new file mode 100644 index 0000000..353fa77 --- /dev/null +++ b/Migrations/NoteDbModelSnapshot.cs @@ -0,0 +1,45 @@ +// +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace NotesMinimalAPI.Migrations +{ + [DbContext(typeof(NoteDb))] + partial class NoteDbModelSnapshot : ModelSnapshot + { + protected override void BuildModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "6.0.0") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("Note", b => + { + b.Property("id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("id")); + + b.Property("done") + .HasColumnType("boolean"); + + b.Property("text") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("id"); + + b.ToTable("Notes"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/NotesMinimalAPI.csproj b/NotesMinimalAPI.csproj new file mode 100644 index 0000000..1b81006 --- /dev/null +++ b/NotesMinimalAPI.csproj @@ -0,0 +1,20 @@ + + + + net6.0 + enable + enable + + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + + diff --git a/NotesMinimalAPI/.gitignore b/NotesMinimalAPI/.gitignore deleted file mode 100644 index dfcfd56..0000000 --- a/NotesMinimalAPI/.gitignore +++ /dev/null @@ -1,350 +0,0 @@ -## Ignore Visual Studio temporary files, build results, and -## files generated by popular Visual Studio add-ons. -## -## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore - -# User-specific files -*.rsuser -*.suo -*.user -*.userosscache -*.sln.docstates - -# User-specific files (MonoDevelop/Xamarin Studio) -*.userprefs - -# Mono auto generated files -mono_crash.* - -# Build results -[Dd]ebug/ -[Dd]ebugPublic/ -[Rr]elease/ -[Rr]eleases/ -x64/ -x86/ -[Aa][Rr][Mm]/ -[Aa][Rr][Mm]64/ -bld/ -[Bb]in/ -[Oo]bj/ -[Ll]og/ -[Ll]ogs/ - -# Visual Studio 2015/2017 cache/options directory -.vs/ -# Uncomment if you have tasks that create the project's static files in wwwroot -#wwwroot/ - -# Visual Studio 2017 auto generated files -Generated\ Files/ - -# MSTest test Results -[Tt]est[Rr]esult*/ -[Bb]uild[Ll]og.* - -# NUnit -*.VisualState.xml -TestResult.xml -nunit-*.xml - -# Build Results of an ATL Project -[Dd]ebugPS/ -[Rr]eleasePS/ -dlldata.c - -# Benchmark Results -BenchmarkDotNet.Artifacts/ - -# .NET Core -project.lock.json -project.fragment.lock.json -artifacts/ - -# StyleCop -StyleCopReport.xml - -# Files built by Visual Studio -*_i.c -*_p.c -*_h.h -*.ilk -*.meta -*.obj -*.iobj -*.pch -*.pdb -*.ipdb -*.pgc -*.pgd -*.rsp -*.sbr -*.tlb -*.tli -*.tlh -*.tmp -*.tmp_proj -*_wpftmp.csproj -*.log -*.vspscc -*.vssscc -.builds -*.pidb -*.svclog -*.scc - -# Chutzpah Test files -_Chutzpah* - -# Visual C++ cache files -ipch/ -*.aps -*.ncb -*.opendb -*.opensdf -*.sdf -*.cachefile -*.VC.db -*.VC.VC.opendb - -# Visual Studio profiler -*.psess -*.vsp -*.vspx -*.sap - -# Visual Studio Trace Files -*.e2e - -# TFS 2012 Local Workspace -$tf/ - -# Guidance Automation Toolkit -*.gpState - -# ReSharper is a .NET coding add-in -_ReSharper*/ -*.[Rr]e[Ss]harper -*.DotSettings.user - -# TeamCity is a build add-in -_TeamCity* - -# DotCover is a Code Coverage Tool -*.dotCover - -# AxoCover is a Code Coverage Tool -.axoCover/* -!.axoCover/settings.json - -# Visual Studio code coverage results -*.coverage -*.coveragexml - -# NCrunch -_NCrunch_* -.*crunch*.local.xml -nCrunchTemp_* - -# MightyMoose -*.mm.* -AutoTest.Net/ - -# Web workbench (sass) -.sass-cache/ - -# Installshield output folder -[Ee]xpress/ - -# DocProject is a documentation generator add-in -DocProject/buildhelp/ -DocProject/Help/*.HxT -DocProject/Help/*.HxC -DocProject/Help/*.hhc -DocProject/Help/*.hhk -DocProject/Help/*.hhp -DocProject/Help/Html2 -DocProject/Help/html - -# Click-Once directory -publish/ - -# Publish Web Output -*.[Pp]ublish.xml -*.azurePubxml -# Note: Comment the next line if you want to checkin your web deploy settings, -# but database connection strings (with potential passwords) will be unencrypted -*.pubxml -*.publishproj - -# Microsoft Azure Web App publish settings. Comment the next line if you want to -# checkin your Azure Web App publish settings, but sensitive information contained -# in these scripts will be unencrypted -PublishScripts/ - -# NuGet Packages -*.nupkg -# NuGet Symbol Packages -*.snupkg -# The packages folder can be ignored because of Package Restore -**/[Pp]ackages/* -# except build/, which is used as an MSBuild target. -!**/[Pp]ackages/build/ -# Uncomment if necessary however generally it will be regenerated when needed -#!**/[Pp]ackages/repositories.config -# NuGet v3's project.json files produces more ignorable files -*.nuget.props -*.nuget.targets - -# Microsoft Azure Build Output -csx/ -*.build.csdef - -# Microsoft Azure Emulator -ecf/ -rcf/ - -# Windows Store app package directories and files -AppPackages/ -BundleArtifacts/ -Package.StoreAssociation.xml -_pkginfo.txt -*.appx -*.appxbundle -*.appxupload - -# Visual Studio cache files -# files ending in .cache can be ignored -*.[Cc]ache -# but keep track of directories ending in .cache -!?*.[Cc]ache/ - -# Others -ClientBin/ -~$* -*~ -*.dbmdl -*.dbproj.schemaview -*.jfm -*.pfx -*.publishsettings -orleans.codegen.cs - -# Including strong name files can present a security risk -# (https://github.com/github/gitignore/pull/2483#issue-259490424) -#*.snk - -# Since there are multiple workflows, uncomment next line to ignore bower_components -# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) -#bower_components/ - -# RIA/Silverlight projects -Generated_Code/ - -# Backup & report files from converting an old project file -# to a newer Visual Studio version. Backup files are not needed, -# because we have git ;-) -_UpgradeReport_Files/ -Backup*/ -UpgradeLog*.XML -UpgradeLog*.htm -ServiceFabricBackup/ -*.rptproj.bak - -# SQL Server files -*.mdf -*.ldf -*.ndf - -# Business Intelligence projects -*.rdl.data -*.bim.layout -*.bim_*.settings -*.rptproj.rsuser -*- [Bb]ackup.rdl -*- [Bb]ackup ([0-9]).rdl -*- [Bb]ackup ([0-9][0-9]).rdl - -# Microsoft Fakes -FakesAssemblies/ - -# GhostDoc plugin setting file -*.GhostDoc.xml - -# Node.js Tools for Visual Studio -.ntvs_analysis.dat -node_modules/ - -# Visual Studio 6 build log -*.plg - -# Visual Studio 6 workspace options file -*.opt - -# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) -*.vbw - -# Visual Studio LightSwitch build output -**/*.HTMLClient/GeneratedArtifacts -**/*.DesktopClient/GeneratedArtifacts -**/*.DesktopClient/ModelManifest.xml -**/*.Server/GeneratedArtifacts -**/*.Server/ModelManifest.xml -_Pvt_Extensions - -# Paket dependency manager -.paket/paket.exe -paket-files/ - -# FAKE - F# Make -.fake/ - -# CodeRush personal settings -.cr/personal - -# Python Tools for Visual Studio (PTVS) -__pycache__/ -*.pyc - -# Cake - Uncomment if you are using it -# tools/** -# !tools/packages.config - -# Tabs Studio -*.tss - -# Telerik's JustMock configuration file -*.jmconfig - -# BizTalk build output -*.btp.cs -*.btm.cs -*.odx.cs -*.xsd.cs - -# OpenCover UI analysis results -OpenCover/ - -# Azure Stream Analytics local run output -ASALocalRun/ - -# MSBuild Binary and Structured Log -*.binlog - -# NVidia Nsight GPU debugger configuration file -*.nvuser - -# MFractors (Xamarin productivity tool) working folder -.mfractor/ - -# Local History for Visual Studio -.localhistory/ - -# BeatPulse healthcheck temp database -healthchecksdb - -# Backup folder for Package Reference Convert tool in Visual Studio 2017 -MigrationBackup/ - -# Ionide (cross platform F# VS Code tools) working folder -.ionide/ diff --git a/NotesMinimalAPI/NotesMinimalAPI.csproj b/NotesMinimalAPI/NotesMinimalAPI.csproj deleted file mode 100644 index 60bf9ea..0000000 --- a/NotesMinimalAPI/NotesMinimalAPI.csproj +++ /dev/null @@ -1,13 +0,0 @@ - - - - net6.0 - enable - enable - - - - - - - diff --git a/NotesMinimalAPI/Program.cs b/NotesMinimalAPI/Program.cs deleted file mode 100644 index ef9a790..0000000 --- a/NotesMinimalAPI/Program.cs +++ /dev/null @@ -1,19 +0,0 @@ -var builder = WebApplication.CreateBuilder(args); - -// Add services to the container. -// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle -builder.Services.AddEndpointsApiExplorer(); -builder.Services.AddSwaggerGen(); - -var app = builder.Build(); - -// Configure the HTTP request pipeline. -if (app.Environment.IsDevelopment()) -{ - app.UseSwagger(); - app.UseSwaggerUI(); -} - -app.MapGet("/", () => "Welcome to Notes API!"); - -app.Run(); \ No newline at end of file diff --git a/NotesMinimalAPI/Properties/launchSettings.json b/NotesMinimalAPI/Properties/launchSettings.json deleted file mode 100644 index 91c1bf4..0000000 --- a/NotesMinimalAPI/Properties/launchSettings.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "$schema": "https://json.schemastore.org/launchsettings.json", - "iisSettings": { - "windowsAuthentication": false, - "anonymousAuthentication": true, - "iisExpress": { - "applicationUrl": "http://localhost:38047", - "sslPort": 44378 - } - }, - "profiles": { - "NotesMinimalAPI": { - "commandName": "Project", - "dotnetRunMessages": true, - "launchBrowser": true, - "launchUrl": "swagger", - "applicationUrl": "https://localhost:7009;http://localhost:5267", - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - } - }, - "IIS Express": { - "commandName": "IISExpress", - "launchBrowser": true, - "launchUrl": "swagger", - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - } - } - } -} diff --git a/Program.cs b/Program.cs new file mode 100644 index 0000000..6f17c48 --- /dev/null +++ b/Program.cs @@ -0,0 +1,90 @@ +using Microsoft.EntityFrameworkCore; // place this line at the beginning of file. +var builder = WebApplication.CreateBuilder(args); + +// Add services to the container. +// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle +builder.Services.AddEndpointsApiExplorer(); +builder.Services.AddSwaggerGen(); + +// Connect to PostgreSQL Database +var connectionString = builder.Configuration.GetConnectionString("DefaultConnection"); +builder.Services.AddDbContext(options => + options.UseNpgsql(connectionString)); + +builder.Services.AddDatabaseDeveloperPageExceptionFilter(); + + +var app = builder.Build(); + +// Configure the HTTP request pipeline. +if (app.Environment.IsDevelopment()) +{ + app.UseSwagger(); + app.UseSwaggerUI(); +} + +app.MapGet("/", () => "Welcome to Notes API!"); + +// Create Note +app.MapPost("/notes/", async(Note n, NoteDb db)=> { + db.Notes.Add(n); + await db.SaveChangesAsync(); + + return Results.Created($"/notes/{n.id}", n); +}); + +// Read Note by id +app.MapGet("/notes/{id:int}", async(int id, NoteDb db)=> +{ + return await db.Notes.FindAsync(id) + is Note n + ? Results.Ok(n) + : Results.NotFound(); +}); + +// Read all Notes +app.MapGet("/notes", async (NoteDb db) => await db.Notes.ToListAsync()); + +// Update a Note by id +app.MapPut("/notes/{id:int}", async(int id, Note n, NoteDb db)=> +{ + if (n.id != id) + { + return Results.BadRequest(); + } + + var note = await db.Notes.FindAsync(id); + + if (note is null) return Results.NotFound(); + + //found, so update with incoming note n. + note.text = n.text; + note.done = n.done; + await db.SaveChangesAsync(); + return Results.Ok(note); +}); + +// Delete a Note by id +app.MapDelete("/notes/{id:int}", async(int id, NoteDb db)=>{ + + var note = await db.Notes.FindAsync(id); + if (note is not null){ + db.Notes.Remove(note); + await db.SaveChangesAsync(); + } + return Results.NoContent(); +}); + +await app.RunAsync(); + +record Note(int id){ + public string text {get;set;} = default!; + public bool done {get;set;} = default!; +} + +class NoteDb: DbContext { + public NoteDb(DbContextOptions options): base(options) { + + } + public DbSet Notes => Set(); +} \ No newline at end of file diff --git a/README.md b/README.md index 9dba4ec..ee18edc 100644 --- a/README.md +++ b/README.md @@ -10,4 +10,5 @@ Navule Pavan Kumar Rao [🤵](https://bit.ly/3d17tZP) | Code | Article | | --- | --- | | [NotesMinimalAPI](https://github.com/windson/minimal-web-api-tutorials/tree/main/NotesMinimalAPI) | [Getting started with Minimal web API using ASP.NET Core for .NET 6.0 (LTS)](https://bit.ly/3E3UqnZ) | +| | [Minimal web API with CRUD on PostgreSQL: A RESTful Microservice implementation in ASP.NET Core for .NET](https://www.tutlinks.com/minimal-web-api-with-crud-on-postgresql-dotnet-6/)| diff --git a/NotesMinimalAPI/appsettings.Development.json b/appsettings.Development.json similarity index 100% rename from NotesMinimalAPI/appsettings.Development.json rename to appsettings.Development.json diff --git a/NotesMinimalAPI/appsettings.json b/appsettings.json similarity index 70% rename from NotesMinimalAPI/appsettings.json rename to appsettings.json index bab9b2d..2424782 100644 --- a/NotesMinimalAPI/appsettings.json +++ b/appsettings.json @@ -1,4 +1,7 @@ { + "ConnectionStrings": { + "DefaultConnection": "Server=localhost;Port=5432;Database=notesdb;User Id=postgres;Password=secret" + }, "Kestrel": { "Endpoints": { "Https": { From 42cdb285ead7a9f732d6fb5aacb25d34b38911aa Mon Sep 17 00:00:00 2001 From: navule Date: Tue, 30 Nov 2021 19:11:56 +0530 Subject: [PATCH 2/3] minimal web api aspnet core 6 CRUD on PostgreSQL --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ee18edc..6ba0969 100644 --- a/README.md +++ b/README.md @@ -10,5 +10,5 @@ Navule Pavan Kumar Rao [🤵](https://bit.ly/3d17tZP) | Code | Article | | --- | --- | | [NotesMinimalAPI](https://github.com/windson/minimal-web-api-tutorials/tree/main/NotesMinimalAPI) | [Getting started with Minimal web API using ASP.NET Core for .NET 6.0 (LTS)](https://bit.ly/3E3UqnZ) | -| | [Minimal web API with CRUD on PostgreSQL: A RESTful Microservice implementation in ASP.NET Core for .NET](https://www.tutlinks.com/minimal-web-api-with-crud-on-postgresql-dotnet-6/)| +| [CRUD on PostgreSQL](https://github.com/windson/minimal-web-api-tutorials/tree/minimal-web-api-crud-postgresql-net6) | [Minimal web API with CRUD on PostgreSQL: A RESTful Microservice implementation in ASP.NET Core for .NET](https://www.tutlinks.com/minimal-web-api-with-crud-on-postgresql-dotnet-6/)| From ab777c82d80c345bf0b00783e371bc76d1c3c2de Mon Sep 17 00:00:00 2001 From: navule Date: Tue, 30 Nov 2021 19:12:33 +0530 Subject: [PATCH 3/3] minimal web api aspnet core 6 CRUD on PostgreSQL --- README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README.md b/README.md index 6ba0969..0159ca2 100644 --- a/README.md +++ b/README.md @@ -11,4 +11,3 @@ Navule Pavan Kumar Rao [🤵](https://bit.ly/3d17tZP) | --- | --- | | [NotesMinimalAPI](https://github.com/windson/minimal-web-api-tutorials/tree/main/NotesMinimalAPI) | [Getting started with Minimal web API using ASP.NET Core for .NET 6.0 (LTS)](https://bit.ly/3E3UqnZ) | | [CRUD on PostgreSQL](https://github.com/windson/minimal-web-api-tutorials/tree/minimal-web-api-crud-postgresql-net6) | [Minimal web API with CRUD on PostgreSQL: A RESTful Microservice implementation in ASP.NET Core for .NET](https://www.tutlinks.com/minimal-web-api-with-crud-on-postgresql-dotnet-6/)| -