Posts

Showing posts from May, 2020

Authorisation

Roles User can be added to one or more roles.  When the user is authenticated, these role memberships can be included in the authentication token. Claims Terminology to describe what the user has claims to (i.e. who they are and what privileges they have). JWT Tokens As well as containing the claims to be who they are, role memberships can be passed as claims so that the client application can expose / restrict areas of the application as that are applicable. Policies These are the rule sets that determine whether a service can be accessed (authorisation).  Roles and other logic can be used to determine a policy.

Bits and bobs

EF Global Filters These can be set up in OnModelCreating so that the default case is that the deleted items are not returned.  This can be overriden for specific queries using IgnoreQueryFilters. builder.Entity<Thing>().HasQueryFilter(p => p.Deleted); Displaying text over an Image For this we need to set the container div style to  position: relative and then the text to position: absolute.  Then set the bottom so that it appears in the corrrect place.

Publishing

Publishing to IIS Run >dotnet publish --configuration Release A . NET Core Hosting Bundle is required to publish to IIS. Download the bundle. TODO -  There seems to be a problem with the API connecting to the database and perfroming the login call.  I need to look further into this. Publishing to Azure Set up a Web App with Database in Azure. Correct the database connection string name Add firewall rule to access db from own machine. In VS Code, install the extension Azure App Services Enabled Hsts and Https Publish to Files from publish directory. Use developer exception page until happy.

Setting up for Deployment

Building Angular App into Kestrel wit the API Change output path in angular.json to "outputPath": "../DatingApi.API/wwwroot" Set up an ignore rule so we don't commit this folder. To expose the SPA we need to add the following two lines to our Startup.cs app.UseDefaultFiles(); app.UsesStaticFiles(); When refreshing, need to pass routing responsibility onto Angular.  Otherwise we get a page not found error. This is done by adding a new FallbackController which is an MVC controller (base class Controller rather than ControllerBase), that does the following: return PhysicalFile(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "index.html), "text/HTML"); And then in the startup endpoints, add: endpoints.MapFallbackToController("Index", "Fallback"); Creating a Production Build  - Ahead of Time (AOT) Using the --prod option on ng build does a lot of the things that you'd have to configur...

Troubleshooting notes

HTTP.Post gotcha on ASP.NET MVC Core API V3 If you don't provide all of the route parameters on the CreatedAtRoute an error is returned which suggests the routing could not find the controller.  What has actually happened is that the post has completed, but cannot return via the routing.

Pagination

On Server Side: Once you have an IQueryable<T> which has your stored command it it (i.e. the where and ordey by clauses) use .Skip and .Take to get the pages.  Pass in: pageNumber  pageSize Pass out: Items - so they can be displayed CurrentPage ItemsPerPage TotalItems - so this can be displayeded TotalPages - so this can provide other pages to load On Client Side Use PaginationModule from ngx-bootstrap.  This will provide navigation around the pages. When loading a new page, set only the TotalItems and TotalPages to prevent triggering a seconp page load.

Web API - Action Filters

Been looking at action filters which can be applied as declarative  attributes on a controller or even across the whole app.  This could be used for cross cutting concerns such as logging and auditing. [ServiceFilter(typeof(MyLogger))] Where MyLogger need to implement IAsyncActionFilter and have been registered as a service in StartUp

Reactive Forms

Reactive Forms as opposed to template forms. If you want responsive validation as you fill in the form, Reactive forms are the way to go.  Infact, template forms should only really be used for very simple forms with just text controls. Features: Built in validators Custom validators FormBuilder Invalid Feedack This is the text in red that appears under the controls if there are validation errors.  This needs to be ngIf guarded manually as does the 'is-invalid' class which gives the control a red border  The touched property on the control can be checked to stop the errors appearing before the user has started using the control. Datepicker To get a uniform experience across browsers, it best to use the ngx-bootstrap datepicker control. Time Ago Pipe pipe package  to provide the time ago.  This doesn't work for Angular 9, so currently can only be used with Angular 8. There is an  open issue  and raised on  stack overflow  ...

Editing in the app

CanDeactivate guard This is used to prevent accidental loss of edits when accidentally routing to another page. However, I'm wondering if the 'dialog boxes' could be intergrated into the page, so that they aren't effected by pop up blockers. Also they would work better on mobile devices. Over-mapping with mapper Mapper allows entity from the repo to have a subset of fields updated from the dto.  This is quite nice.  For cases where multiple users can edit a record, would need to do some form of check for updates. Host Listener This can be used to listen for browser events such as closing a browser tab and cancel to avoid losing edits. ClaimsPrincipal The User (ClaimsPrincipal) is checked so that only the token authenticated user can update the profile relating to that user.  Need to learn more about claims. Cloudinary  - which is used to host pictures and to the picture transformations. File upload component  - which is used to visually suppo...

Angular user interfaces

Token Getter This http interceptor is used to 'automatically add the token to the whitelisted domains.  This saves having to add this in each service and also fixes the issue where it's not available straight after login. Route Resolvers These allow us to get the data for a component before we route to the component.  This avoids the need for having to use elvis operators everywhere in our component html. Boostrap Cards  Really nice way of displaying a list of items.  Might use this for the boat selection screen. Gallery  NGX Gallery 9  was used to show the photos. V9 worked without having to make the workaround fix that had to be done for V8. Styles I feel that I really need to get into what is achievable with Bootstrap.  I probably need a more in depth course on this alone so I can get an idea what a finished (polished) UI should look like as I tend to be happy with unfinished looks.

Back to the API

Data seeding  A quick way of getting some test data into the database is to use data setting form JSON.  A JSON generator  can be used to generated some data that can easily be seeded into the database via EF.  The new way of doing this is to run migrations in Program.cs and then seed the data.  This would need to be a development only step rather than n production. Automapper Using automapper to convert between Dtos and Models.  This is something that I'm quite familiar with.  Would just need to check the performance.

Angular routing

Routes Maps the path to the controllers.  Also ensure that the full path is updated in the browser. Route Guards These can be used to run logic to decide whether a component can be routed to.  This prevents users from trying to get access to pages that they are not authorised to access by entering the path in the address bar. To create the guard >ng g guard auth --skipTests

Angular third party components

Third Party Components Alertify JS  notification toasters Angular JWT  library for handling tokens NGX Boostrap  Angular Bootstrap component library Bootswatch  themes

Angular SPI Notes

Local Storage to hold the token to persist the token, local storage is used. Parent-Child Bindings @Input - to pass values from parent to child @Output - to make values from the child available to the parent (event callback) Typescript tips Shorthand for an if statement  >!!variable  is equivalent to if variable == null then false else true  (like ?? in C#) Error Handling Server side - Globally handle exceptions and return as 500 errors.  This saves having to add try catches around every controller method. Client side - Write an error.interceptor that can bee added as a provider.  This will intercept the http request and emits error notifications.  

Web API Notes

IoC Singleton - Gives the same instance or each request - this can cause concurrency issues Transient - Gives a new instance on each request Scoped - Gives a new instance on each thread Controller base classes ControllerBase  without view support, used for APIs for SPIs Controller with view support, used for MVC architecture Controller attributes [ApiController] - This gives a few things including automatic FromBody mappings and model validation. Security - Hash and Salt Passwords are stored as a hash, but because matching passwords have the same hash, a salt is used when hashing.  The salt needs to be stored too, but makes the password hash unique. Security - Token Authentication JWT (JSON Web Token) passed back after successful login verification This this then used for subsequent requests. The token has a time window in which it can be used. This site  can be used to look at the public part of the token.  Tokens should not contain sen...

Completing the walking skeleton

Angular Notes package.json is the master package file.  node_modules can be recreated from this.  No need to put node_modules into source control node packages (from npm) can be installed either locally for a project or globally for any project.  The local one will win out if you need a specific version. How the Angular project bootstraps - app,module.ts - decorated with @NgModule boostraps angular component(s).  app.component.ts - decorated with @Component this is the root component for the app app.component.html - root level html - standard html with {{}} interpolation main.ts - this bootstraps the app module index.html - this is the SPA and it has <app-root></app-root> in it.  Webpack adds in the javascript files that are needed to implement the app angular.json - window into the webpacking.  configures the above Angular Extensions Angular Files - Quickly scaffold angular file templates Angular Language Service -...

Understanding the technologies - Angular 8 and ASP.NET Web API Core 3

Course Notes Yesterday, I followed some of the preview lessons and have taken the following points: Instead of using a Visual Studio template to create an integrated Angular and WebAPI project, I'm going to the follow the advice on the course to create these separately.  I'll use dotnet CLI to create the web API project and Angular CLI (ng) to create the separate Angular project. The following needed to be installed as prerequisites: .NET Core SDK V3.0 - This is required to create the WEB API project To check all that are installed - >dotnet --info To check the default version - >dotnet --version I already had V3.1 of the SDK installed so needed to switch back to the earlier version : NodeJS V12.16.3 - This is required to serve and run the Angular App NPM V6.14.5 - This is used to add libraries for for the Angular App (like nuget) I'm also going to be using VS Code rather than Visual Studio Community as my IDE.   I want to see how this work in ...