From e369f7d565f0351474121b800a292ddcaee1308c Mon Sep 17 00:00:00 2001 From: Marcello Lamonaca Date: Fri, 30 Apr 2021 19:21:53 +0200 Subject: [PATCH 01/17] Add notes for blazor components --- .NET/ASP.NET/Blazor.md | 102 ++++++++++++++++++++++++++++++++++++----- 1 file changed, 91 insertions(+), 11 deletions(-) diff --git a/.NET/ASP.NET/Blazor.md b/.NET/ASP.NET/Blazor.md index b216a44..295b32b 100644 --- a/.NET/ASP.NET/Blazor.md +++ b/.NET/ASP.NET/Blazor.md @@ -31,8 +31,7 @@ Project | |- favicon.ico | |-Pages -| |- Page.cshtml -| |- Page.cshtml.cs +| |- _Host.cshtml --> fallback page | |- Component.razor | |- Index.razor | |- ... @@ -86,7 +85,7 @@ Project ```cs - + // for component routing @@ -97,24 +96,105 @@ Project ``` -## Components (`.razor`) +### `MainLayout.razor` (Blazor Server/WASM) ```cs -@page "/route" +@inherits LayoutComponentBase - +
+ - // insert component into page +
+
+
+ +
+ @Body +
+
+
+``` + +### `_Host.cshtml` (Blazor Server) + +```html +@page "/" +@namespace BlazorServerDemo.Pages +@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers +@{ + Layout = null; +} + + + + + + + BlazorServerDemo + + + + + + + + +
+ + An error has occurred. This application may no longer respond until reloaded. + + + An unhandled exception has occurred. See browser dev tools for details. + + Reload + 🗙 +
+ + + + +``` + +## Components (`.razor`) + +[Blazor Components](https://docs.microsoft.com/en-us/aspnet/core/blazor/components/) + +```cs +@page "/route/{RouteParameter?}" // make component accessible from a URL (optional) + +@namespace // set the component namespace +@using // using statement +@inherits BaseType // inheritance +@attribute [Attribute] // apply an attribute +@inject Type objectName // dependency injection + +// html of the page here + + // access component w/o @using + // insert component into page, passing attributes + + @ChildContent // segment of UI content + @code { // component model (Properties, Methods, ...) - [Parameter] // use prop as HTML attribute - purblic Type Property { get; set; } = defaultValue; + [Parameter] // capture attribute + public Type Property { get; set; } = defaultValue; + + [Parameter] // capture route parameters + public type RouteParameter { get; set;} + + [Parameter] // segment of UI content + public RenderFragment ChildContent { get; set;} + + private void CallbackMethod() { } } ``` - +[Call .NET from Javascript](https://docs.microsoft.com/en-us/aspnet/core/blazor/call-dotnet-from-javascript) From a789e7e6c44d60762d7a58226f9ce86470d10bb0 Mon Sep 17 00:00:00 2001 From: Marcello Lamonaca Date: Sat, 1 May 2021 12:39:58 +0200 Subject: [PATCH 02/17] Add blazor PWA notes --- .NET/ASP.NET/Blazor.md | 63 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) diff --git a/.NET/ASP.NET/Blazor.md b/.NET/ASP.NET/Blazor.md index 295b32b..709e0ea 100644 --- a/.NET/ASP.NET/Blazor.md +++ b/.NET/ASP.NET/Blazor.md @@ -81,6 +81,69 @@ Project |- Program.cs --> App entrypoint ``` +### Blazor PWA Project Structure + +```txt +Project +|-Properties +| |- launchSettings.json +| +|-wwwroot --> static files +| |-css +| | |- site.css +| | |- bootstrap +| | +| |- index.html +| |- favicon.ico +| |- manifest.json +| |- service-worker.js +| |- icon-512.png +| +|-Pages +| |- Component.razor +| |- Index.razor +| |- ... +| +|-Shared +| |- MainLayout.razor +| |- MainLayout.razor.css +| |- ... +| +|- _Imports.razor --> @using imports +|- App.razor --> component root of the app +| +|- appsettings.json --> application settings +|- Program.cs --> App entrypoint +``` + +### `manifest.json`, `service-worker.js` (Blazor PWA) + +[PWA](https://web.dev/progressive-web-apps/) +[PWA MDN Docs](https://developer.mozilla.org/en-US/docs/Web/Progressive_web_apps) +[PWA Manifest](https://developer.mozilla.org/en-US/docs/Web/Manifest) +[Service Worker API](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API) + +```json +// manifest.json +{ + "name": "", + "short_name": "", + "start_url": "./", + "display": "standalone", + "background_color": "#ffffff", + "theme_color": "#03173d", + "icons": [ + { + "src": "icon-512.png", + "type": "image/png", + "sizes": "512x512" + } + ] +} +``` + +## Common Blazor Files + ### `App.razor` ```cs From 8bfb001be173108a4f6a7ae405e0d7b50a2cc6ae Mon Sep 17 00:00:00 2001 From: Marcello Lamonaca Date: Wed, 5 May 2021 10:15:09 +0200 Subject: [PATCH 03/17] Fix notes language [ITA => ENG] --- Java/Java.md | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/Java/Java.md b/Java/Java.md index 8bd871f..7c6229b 100644 --- a/Java/Java.md +++ b/Java/Java.md @@ -77,15 +77,15 @@ fmt.format(number); // apply format to a number, returns a String ```java import java.util.Scanner; //package import -Scanner nome_oggetto_scanner = new Scanner(System.in); //Scanner obj init -nome_oggetto_scanner.useDelimiter("delimitatore"); //delimiter setting -nome_oggetto_scanner.close() //closing of Scanner, releases memory +Scanner scanner = new Scanner(System.in); //Scanner obj init +scanner.useDelimiter("delimitatore"); //delimiter setting +scanner.close() //closing of Scanner, releases memory -int variabile_int_1 = nome_oggetto_scanner.nextInt(); //takes integer number -String string_1 = nome_oggetto_scanner.nextLine(); //takes line of text (\n ends line) -String string_1 = nome_oggetto_scanner.next(); //takes text (spacec ends word) -double variabile_double_1 = nome_oggetto_scanner.nextDouble(); //takes double decimal number -boolean variabile_bool = nome_oggetto_scanner.netxBoolean(); //takes boolean value +int variabile_int_1 = scanner.nextInt(); //takes integer number +String string_1 = scanner.nextLine(); //takes line of text (\n ends line) +String string_1 = scanner.next(); //takes text (spacec ends word) +double variabile_double_1 = scanner.nextDouble(); //takes double decimal number +boolean variabile_bool = scanner.netxBoolean(); //takes boolean value //(TRUE, FALSE, true, false, True, False) ``` @@ -531,17 +531,17 @@ static Type methodName (Type[]...[] ArrayName) { ```java static Type[]...[] methodName (parameters) { - Type[]...[] arrayName = new Type[dimension1]...[dimensionN]; + Type[]...[] array = new Type[dimension1]...[dimensionN]; //array valorization - return nomeArray; + return array; } ``` ### Array Length of multi-dimensional arrays ```java -nomeArray.length //row lenght -nomeArray[rowIndex].length //column length +array.length //row lenght +array[rowIndex].length //column length ``` ### Irregular Table Visualization @@ -678,7 +678,7 @@ void methodName (parameters) { ### Class Definition ```java -public class NomeClasse { +public class ClassName { //instance variables declaration //instantiation block From cd1fa67960f6af1671064bb93aef86532d1697e4 Mon Sep 17 00:00:00 2001 From: Marcello Lamonaca Date: Sat, 8 May 2021 11:46:09 +0200 Subject: [PATCH 04/17] Add notes on DbContext Nullability --- .NET/Database/EntityFramework.md | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/.NET/Database/EntityFramework.md b/.NET/Database/EntityFramework.md index 9308482..a946b87 100644 --- a/.NET/Database/EntityFramework.md +++ b/.NET/Database/EntityFramework.md @@ -30,7 +30,8 @@ namespace .Model NuGet Packages to install: - `Microsoft.EntityFrameworkCore` -- `Microsoft.EntityFrameworkCore.Tools` to use migrations +- `Microsoft.EntityFrameworkCore.Tools` to use migrations in Visual Studio +- `Microsoft.EntityFrameworkCore.Tools.DotNet` to use migrations in `dotnet` cli (`dotnet-ef`) - `Microsoft.EntityFrameworkCore.Design` *or* `Microsoft.EntityFrameworkCore..Design` needed for tools to work (bundled w\ tools) - `Microsoft.EntityFrameworkCore.` @@ -39,15 +40,6 @@ using Microsoft.EntityFrameworkCore; namespace .Model { - class Context : DbContext - { - public Context(DbContextOptions options) : base(options) - { - } - } - - // or - class Context : DbContext { private const string _connectionString = "Server=;Database=;UID=;Pwd="; @@ -58,8 +50,15 @@ namespace .Model optionsBuilder.UseSqlServer(_connectionString); // specify connection } + // or + + public Context(DbContextOptions options) : base(options) + { + } + //DBSet represents the collection of all entities in the context (or that can be queried from the database) of a given type public DbSet Entities { get; set; } + public DbSet Entities => Set(); // with nullable reference types } } ``` From 8b5e7252080e6d699fa7510462ea0f23158d265b Mon Sep 17 00:00:00 2001 From: Marcello Lamonaca Date: Sat, 8 May 2021 12:43:30 +0200 Subject: [PATCH 05/17] Fix CRUD notes --- .NET/Database/EntityFramework.md | 103 ++++--------------------------- 1 file changed, 13 insertions(+), 90 deletions(-) diff --git a/.NET/Database/EntityFramework.md b/.NET/Database/EntityFramework.md index a946b87..0124ab2 100644 --- a/.NET/Database/EntityFramework.md +++ b/.NET/Database/EntityFramework.md @@ -88,31 +88,10 @@ dotnet ef database update ### Create ```cs -public static bool InsertOne(Entity entity) -{ - int rows = 0; +context.Add(entity); +context.AddRange(entities); - using(var context = new Context()) - { - context.Add(entity); - context.SaveChanges(); - } - - return rows == 1; -} - -public static bool InsertMany(IEnumerable entities) -{ - int rows = 0; - - using(var context = new Context()) - { - context.AddRange(entities); - context.SaveChanges(); - } - - return rows == entities.Count(); -} +context.SaveChanges(); ``` ### Read @@ -120,83 +99,27 @@ public static bool InsertMany(IEnumerable entities) [Referenced Object Not Loading Fix](https://stackoverflow.com/a/5385288) ```cs -public static List SelectAll() -{ - using(var context = new Context()) - { - return context.Entities.ToList(); - } -} +context.Entities.ToList(); +context.Entities.Find(id); -static Entity SelectOneById(int id) -{ - using(var context = new Context()) - { - return context.Entities.Find(id); - - // force read of foreign key identifying referenced obj - return context.Entities.Include(c => c.ForeignObject).Find(id); - - } -} +// force read of foreign key identifying referenced obj +context.Entities.Include(c => c.ForeignObject).Find(id); ``` ### Update ```cs -public static bool UpdateOne(Entity entity) -{ - int rows = 0; +context.Entities.Update(entity); +context.UpdateRange(entities); - using(var context = new Context()) - { - context.Entities.Update(entity); - context.SaveChanges(); - } - - return rows == 1; -} - -public static bool UpdateMany(IEnumerable entities) -{ - int rows = 0; - - using(var context = new Context()) - { - context.UpdateRange(entities); - context.SaveChanges(); - } - - return rows == entities.Count(); -} +context.SaveChanges(); ``` ### Delete ```cs -public static bool DeleteOne(Entity entity) -{ - int rows = 0; +context.Entities.Remove(entity); +context.RemoveRange(entities); - using(var context = new Context()) - { - context.Entities.Remove(entity); - context.SaveChanges(); - } - - return rows == 1; -} - -public static bool DeleteMany(IEnumerable entities) -{ - int rows = 0; - - using(var context = new Context()) - { - context.RemoveRange(entities); - context.SaveChanges(); - } - - return rows == entities.Count(); -} +context.SaveChanges(); ``` From b2cd8364313f6dde30c7057a95488b1c06430ce3 Mon Sep 17 00:00:00 2001 From: Marcello Lamonaca Date: Tue, 11 May 2021 11:19:32 +0200 Subject: [PATCH 06/17] Add dynamic object keys notes --- JavaScript/JavaScript.md | 1 + 1 file changed, 1 insertion(+) diff --git a/JavaScript/JavaScript.md b/JavaScript/JavaScript.md index a224aaa..5c7c11a 100644 --- a/JavaScript/JavaScript.md +++ b/JavaScript/JavaScript.md @@ -560,6 +560,7 @@ let variable = value; let obj = { property: value, variable, // same as variable: variable + [property]: value // dynamic prop name object: { ... From 965a1936b462ca91eae87597b8a4a2f082657c6e Mon Sep 17 00:00:00 2001 From: Marcello Lamonaca Date: Tue, 18 May 2021 12:05:45 +0200 Subject: [PATCH 07/17] Add notes on CSS units --- CSS/CSS.md | 70 ++++++++++++++++++++++++++++++++++++++---------------- 1 file changed, 49 insertions(+), 21 deletions(-) diff --git a/CSS/CSS.md b/CSS/CSS.md index 8674707..d283367 100644 --- a/CSS/CSS.md +++ b/CSS/CSS.md @@ -350,6 +350,34 @@ a::after/before { `selector::selection {...}` identifies part of the document that has been selected, or highlighted, by a user’s actions. `selector::-moz-selection {...}` Mozilla prefixed fragment pseudo-element has been added to ensure the best support for all browser. +## Units + +### Absolute Length units + +| Unit | Name | Equivalent to | +| ---- | ------------------- | -------------------- | +| cm | centimeters | 1cm = 38px = 25/64in | +| mm | Millimeters | 1mm = 1/10th of 1cm | +| Q | Quarter-millimeters | 1Q = 1/40th of 1cm | +| in | Inches | 1in = 2.54cm = 96px | +| pc | Picas | 1pc = 1/6th of 1in | +| pt | Points | 1pt = 1/72th of 1in | +| px | Pixels | 1px = 1/96th of 1in | + +### Relative Length Units + +| Unit | Relative to | +| ---- | ------------------------------------------------------------------- | +| rem | Font size of the root element. | +| em | Font size of the parent or the element itself | +| ex | x-height of the element's font. | +| ch | The advance measure (width) of the glyph "0" of the element's font. | +| lh | Line height of the element. | +| vw | 1% of the viewport's width. | +| vh | 1% of the viewport's height. | +| vmin | 1% of the viewport's smaller dimension. | +| vmax | 1% of the viewport's larger dimension. | + ## Element Properties ### Color @@ -566,28 +594,28 @@ selector { ### Absolute Lengths -Symbol | Unit --------|----------------------------- -`cm` | centimeters -`mm` | millimeters -`in` | inch (1 in = 96px = 2.54 cm) -`px` | pixel (1 px = 1/96 of 1 in) -`pt` | points (1 pt = 1/72 of 1 in) -`pc` | picas (1 pc = 12 pt) +| Symbol | Unit | +| ------ | ---------------------------- | +| `cm` | centimeters | +| `mm` | millimeters | +| `in` | inch (1 in = 96px = 2.54 cm) | +| `px` | pixel (1 px = 1/96 of 1 in) | +| `pt` | points (1 pt = 1/72 of 1 in) | +| `pc` | picas (1 pc = 12 pt) | ### Relative Lengths -Symbol | Unit --------|------------------------------------------------------------------------------------------ -`em` | Relative to the font-size of the element (2em means 2 times the size of the current font) -`ex` | Relative to the x-height of the current font (rarely used) -`ch` | Relative to width of the "0" (zero) -`rem` | Relative to font-size of the root element -`vw` | Relative to 1% of the width of the viewport* -`vh` | Relative to 1% of the height of the viewport* -`vmin` | Relative to 1% of viewport's* smaller dimension -`vmax` | Relative to 1% of viewport's* larger dimension -`%` | Relative to the parent element +| Symbol | Unit | +| ------ | ----------------------------------------------------------------------------------------- | +| `em` | Relative to the font-size of the element (2em means 2 times the size of the current font) | +| `ex` | Relative to the x-height of the current font (rarely used) | +| `ch` | Relative to width of the "0" (zero) | +| `rem` | Relative to font-size of the root element | +| `vw` | Relative to 1% of the width of the viewport* | +| `vh` | Relative to 1% of the height of the viewport* | +| `vmin` | Relative to 1% of viewport's* smaller dimension | +| `vmax` | Relative to 1% of viewport's* larger dimension | +| `%` | Relative to the parent element | ## CSS Cascading @@ -822,7 +850,7 @@ There are several methods to 'hide' elements: `opacity: 0` hides the element, still takes up space in the layout, events work | Rule | Collapse | Events | Tab Order | -|----------------------|----------|--------|-----------| +| -------------------- | -------- | ------ | --------- | | `display: none` | Yes | No | No | | `visibility: hidden` | No | No | No | | `opacity: 0` | No | Yes | Yes | @@ -1124,7 +1152,7 @@ The HTML code is not changed, only the CSS style. A media query is a logical expression: true or false; if a media query is true, the related rules are applied to the target device. | Type | Used For | -|----------|----------------------------------------------| +| -------- | -------------------------------------------- | | `all` | all media type devices | | `print` | printers | | `screen` | computer screens, tablets, smart-phones, etc | From 66829521b835fa481c56beae62067436e66a4068 Mon Sep 17 00:00:00 2001 From: Marcello Lamonaca Date: Thu, 20 May 2021 12:21:48 +0200 Subject: [PATCH 08/17] Add notes on git reset --- Git/git.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Git/git.md b/Git/git.md index 7ae522f..8e9bf13 100644 --- a/Git/git.md +++ b/Git/git.md @@ -214,7 +214,7 @@ It’s generally recommended creating annotated tags so it's possible to have al `git reset `: undo all commits after specified commit, preserving changes locally `git checkout `: discard changes `git checkout -- `: discard changes, no output to screen -`git reset --hard`: discard all changes since last commit +`git reset --soft `: revert to specific commit but keep changes and staged files `git reset --hard `: discard all history and changes back to specified commit `git rebase -i HEAD~`: modify (reword, edit, drop, squash, merge, ...) *n* commits From 2528d00f7c901ee36ccbd5b1b91c5306d2ee35c4 Mon Sep 17 00:00:00 2001 From: Marcello Lamonaca Date: Fri, 21 May 2021 19:23:10 +0200 Subject: [PATCH 09/17] Improve REST API Notes --- .NET/ASP.NET/REST API.md | 302 ++++++--------------------------------- 1 file changed, 40 insertions(+), 262 deletions(-) diff --git a/.NET/ASP.NET/REST API.md b/.NET/ASP.NET/REST API.md index 47d0c12..a96e6f5 100644 --- a/.NET/ASP.NET/REST API.md +++ b/.NET/ASP.NET/REST API.md @@ -1,181 +1,5 @@ # ASP .NET REST API -## Startup class - -- Called by `Program.cs` - -```cs -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Hosting; - -namespace -{ - public class Startup - { - public Startup(IConfiguration configuration) - { - Configuration = configuration; - } - - public IConfiguration Configuration { get; } - - // This method gets called by the runtime. Use this method to add services to the container. - public void ConfigureServices(IServiceCollection services) - { - services.AddControllers(); // controllers w/o views - //or - sevices.AddControllersWithViews(); // MVC Controllers - } - - // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. - public void Configure(IApplicationBuilder app, IWebHostEnvironment env) - { - if (env.IsDevelopment()) - { - app.UseDeveloperExceptionPage(); - } - - app.UseHttpsRedirection(); - - app.UseRouting(); - - app.UseAuthorization(); - - app.UseEndpoints(endpoints => - { - endpoints.MapControllers(); - }); - } - } -} -``` - -## DB Context (EF to access DB) - -NuGet Packages to install: - -- `Microsoft.EntityFrameworkCore` -- `Microsoft.EntityFrameworkCore.Tools` -- `Microsoft.EntityFrameworkCore.Design` *or* `Microsoft.EntityFrameworkCore..Design` -- `Microsoft.EntityFrameworkCore.` - -In `AppDbContext.cs`: - -```cs -using .Model; -using Microsoft.EntityFrameworkCore; - -namespace .Repo -{ - public class AppDbContext : DbContext - { - public AppDbContext(DbContextOptions options) : base(options) - { - - } - //DBSet represents the collection of all entities in the context, or that can be queried from the database, of a given type - public DbSet entities { get; set; } - } -} -``` - -In `appsettings.json`: - -```json -{ - "Logging": { - "LogLevel": { - "Default": "Information", - "Microsoft": "Warning", - "Microsoft.Hosting.Lifetime": "Information" - } - }, - "AllowedHosts": "*", - "ConnectionStrings": { - "CommanderConnection" : "Server=;Database=;UID=;Pwd=" - } -} -``` - -In `Startup.cs`: - -```cs -// This method gets called by the runtime. Use this method to add services to the container. -public void ConfigureServices(IServiceCollection services) -{ - // SqlServer is the db used in this example - services.AddDbContext(option => option.UseSqlServer(Configuration.GetConnectionString("CommanderConnection"))); - services.AddControllers(); -} -``` - -### Migrations - -- Mirroring of model in the DB. -- Will create & update DB Schema if necessary - -In Packge Manager Shell: - -```ps1 -add-migrations -update-database # use the migrations to modify the db -``` - -## Repository - -In `IEntityRepo`: - -```cs -using .Model; -using System.Collections.Generic; - -namespace .Repository -{ - public interface IEntityRepo - { - IEnumerable SelectAll(); - Entity SelectOneById(int id); - - ... - } -} -``` - -In `EntityRepo`: - -```cs -using .Model; -using System.Collections.Generic; - -namespace .Repo -{ - public class EntityRepo : IEntityRepo - { - private readonly AppDbContext _context; - - public EntityRepo(AppDbContext context) - { - _context = context; - } - - public IEnumerable SelectAll() - { - return _context.Entities.ToList(); // linq query (ToList()) becomes sql query - } - - public Entity SelectOneById(int id) - { - return _context.Entities.FirstOrDefault(p => p.Id == id); - } - - ... - } -} -``` - ## Data Transfer Objects (DTOs) A **DTO** is an object that defines how the data will be sent and recieved over the network (usually as JSON). @@ -183,38 +7,28 @@ Without a DTO the JSON response (or reqest) could contain irrilevant, wrong or u Moreover, by decoupling the JSON response from the actual data model, it's possible to change the latter without breaking the API. DTOs must be mapped to the internal methods. -Required NuGet Packages: - -- AutoMapper.Extensions.Microsoft.DependencyInjection - -In `StartUp.cs`: - -```cs -using AutoMapper; - -// ... - -public void ConfigureServices(IServiceCollection services) -{ - // other services - - services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); // set automapper service -} -``` - -In `EntityDTO.cs`: +In `EntityDTO.cs`: ```cs namespace .DTOs { - // define the data to be serialized in JSON (can differ from model) - public class EntityCrudOpDTO // e.g: EntityReadDTO, ... + // define the data to be serialized in JSON (differs from model) + public class EntityDTO { // only properties to be serialized } } ``` +### DTO mapping with Automapper + +Required NuGet Packages: + +- `AutoMapper` +- `AutoMapper.Extensions.Microsoft.DependencyInjection` + +A good way to organize mapping configurations is with *profiles*. + In `EntitiesProfile.cs`: ```cs @@ -228,34 +42,31 @@ namespace .Profiles { public EntitiesProfile() { - CreateMap(); // map entity to it's DTO + CreateMap(); // map entity to it's DTO } } } ``` -## Controller (No View) - -Uses [Dependency Injection](https://en.wikipedia.org/wiki/Dependency_injection) to recieve a suitable implementation of `IEntityRepo`, - -### Service Lifetimes - -- `AddSignleton`: same for every request -- `AddScoped`: created once per client -- `Transient`: new instance created every time - -In `Startup.cs`: +In `StartUp.cs`: ```cs -// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { - services.AddControllers(); - services.AddScoped(); // map the interface to its implementation, needed for dependency injection + // other services + + // let AutoMapper know in what assemblies are the profiles defined + services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); + + // or create a MapperConfiguration + services.AddAutoMapper(cfg => { + cfg.CreateMap(); + cfg.AddProfile(); + }) } ``` -### Request Mappings +### Controller with DTOs ```cs using .Model; @@ -269,68 +80,35 @@ namespace .Controllers [ApiController] public class EntitiesController : ControllerBase // MVC controller w/o view { - private readonly ICommandRepo _repo; + // service or repo (DAL) injection + private readonly IMapper _mapper; // AutoMapper class - public EntitiesController(IEntityRepo repository, IMapper mapper) // injection og the dependency - { - _repo = repository; - _mapper = mapper - } - [HttpGet] // GET api/endpoint - public ActionResult> SelectAllEntities() + public ActionResult SelectAllEntities() { - var results = _repo.SelectAll(); + ... - return Ok(_mapper.Map(results)); // return an action result OK (200) with the results - } - - // default binding source: [FromRoute] - [HttpGet("{id}")] // GET api/endpoint/{id} - public ActionResult SelectOneEntityById(int id) - { - var result = _repo.SelectOneById(id); - - if(result != null) - { - return Ok(_mapper.Map(result)); // transfrom entity to it's DTO - } - - return NotFound(); // ActionResult NOT FOUND (404) + return Ok(_mapper.Map(entity)); } } } ``` -## Controller (With View) +## Simple API Controller ```cs -using .Model; -using Microsoft.AspNetCore.Mvc; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; - -namespace .Controllers +[Route("api/endpoint")] +[ApiController] +public class EntitiesController : ControllerBase { - [Route("api/endpoint")] - [ApiController] - public class EntitiesController : Controller + // service or repo (DAL) injection + + [HttpGet] + public ActionResult SelectAll() { - private readonly AppDbContext _db; - - public EntitiesController(AppDbContext db) - { - _db = db; - } - - [HttpGet] - public IActionResult SelectAll() - { - return Json(new { data = _db.Entities.ToList() }); // json view - } + ... + return Ok(entity); } } ``` From c30e9d807c8d518baa753e0efed025790666ace9 Mon Sep 17 00:00:00 2001 From: Marcello Lamonaca Date: Thu, 20 May 2021 12:21:48 +0200 Subject: [PATCH 10/17] Add notes on git reset --- Git/git.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Git/git.md b/Git/git.md index 8e9bf13..eb21d74 100644 --- a/Git/git.md +++ b/Git/git.md @@ -85,7 +85,7 @@ def load_reference(name_or_id): ### Create Repository -`git init []`: initialize a brand new Git repository and begins tracking +`git init []`: initialize a brand new Git repository and begins tracking `.gitignore`: specify intentionally untracked files to ignore ### Config @@ -188,28 +188,28 @@ It’s generally recommended creating annotated tags so it's possible to have al ### Branching And Merging -`git branch`: shows branches +`git branch`: shows branches `git branch -v`: show branch + last commit `git branch `: create new branch `git checkout -b `: create a branch and switches to it, same as `git branch ; git checkout ` `git branch`: show list of all existing branches (* indicates current) `git checkout `: change current branch (update HEAD) and update working directory -`git branch -d `: delete specified branch +`git branch -d `: delete specified branch `git branch -m `: rename a branch without affecting the branch’s history `git merge `: merges into current branch `git merge --continue`: continue previous merge after solving a merge conflinct `git mergetool`: use a fancy tool to help resolve merge conflicts -`git rebase`: rebase set of patches onto a new base +`git rebase`: rebase set of patches onto a new base `git rebase -i`: interactive rebasing `gitk`: show graph of history (git for windows only) ### Undo & [Rewriting History](https://www.themoderncoder.com/rewriting-git-history/) -`git commit --amend`: replace last commit by creating a new one (can add files or rewrite commit message) -`git commit --amend --no-edit`: replace last commit by creating a new one (can add files or rewrite commit message) +`git commit --amend`: replace last commit by creating a new one (can add files or rewrite commit message) +`git commit --amend --no-edit`: replace last commit by creating a new one (can add files or rewrite commit message) `git reset HEAD `: unstage a file `git reset `: undo all commits after specified commit, preserving changes locally `git checkout `: discard changes From 395825ce8e0ab005c4bf2a75f5a92d54536f93cd Mon Sep 17 00:00:00 2001 From: Marcello Lamonaca Date: Fri, 28 May 2021 12:49:03 +0200 Subject: [PATCH 11/17] Add Svelte notes (#3) --- JavaScript/Svelte/Svelte.md | 205 ++++++++++++++++++++++++++++++++++++ 1 file changed, 205 insertions(+) create mode 100644 JavaScript/Svelte/Svelte.md diff --git a/JavaScript/Svelte/Svelte.md b/JavaScript/Svelte/Svelte.md new file mode 100644 index 0000000..e261dc4 --- /dev/null +++ b/JavaScript/Svelte/Svelte.md @@ -0,0 +1,205 @@ +# [Svelte](https://svelte.dev/docs) + +```sh +npx degit sveltejs/template + +# set project to use typescript +npm install --save-dev @tsconfig/svelte typescript svelte-preprocess svelte-check +node scripts/setupTypeScript.js +``` + +## App Entrypoint + +```js +import App from "./App.svelte"; // import the component + +const app = new App({ + target: document.body, + props: { + // props passed to the App component + }, +}); + +export default app; +``` + +## Components (`.svelte`) + +### Basic Structure + +```html + + + + + + + + + +
{variable}
+ + + +``` + +### If-Else + +```js +{#if } + // markup here +{:else if } + // markup here +{:else} + // markup here +{/if} +``` + +### Loops + +```js +{#each array as item, index} // index is optional + // markup here +{/each} + +{#each array as item (key)} // usse key to determine changes + // markup here +{/each} +``` + +### Await Blocks + +```js +{#await promise} +

...waiting

+{:then number} +

The number is {number}

+{:catch error} +

{error.message}

+{/await} +``` + +### Event Handling + +The full list of modifiers: + +- `preventDefault` — calls `event.preventDefault()` before running the handler. Useful for client-side form handling, for example. +- `stopPropagation` — calls `event.stopPropagation()`, preventing the event reaching the next element +- `passive` — improves scrolling performance on touch/wheel events (Svelte will add it automatically where it's safe to do so) +- `nonpassive` — explicitly set `passive: false` +- `capture` — fires the handler during the capture phase instead of the bubbling phase +- `once` — remove the handler after the first time it runs +- `self` — only trigger handler if `event.target` is the element itself + +```js + + +