Note for Angular.io (Angular 2)

Architecture overview

The basic building blocks of Angular 2 applications

Modules

Angular has its modularity system called Angular modules or NgModules.

Every Angular app has at least one module, the root module, conventionally named AppModule.

maybe root module be the only module in the small application, or many more feature modules in most apps.

Angular module is a class with an @NgModule decorator.

NgModule properties
|—-> declarations: [‘view classes, eg. components, directives and pipes’].
|—-> exports: the subset of declarations that should be visible and usable in the component templates of the modules.
|—-> imports: other modules whose exported classes are needed by component templates declared in this module.
|—-> providers: services
|—-> bootstrap: the main application view, called the root component, that hosts all other app views.

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
@NgModule({
imports: [ BrowserModule ],
providers: [ Logger ],
declarations: [ AppComponent ],
exports: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }

Launch an application by bootstrapping its root module. During development you’re likely to bootstrap the AppModule in a main.ts file like this one.

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app.module';

platformBrowserDynamic().bootstrapModule(AppModule);

Angular libraries

Angular ships as a collection of JavaScript modules. You can think of them as library modules.

Each Angular library name begins with the @angular prefix.

You install them with the npm package manager and import parts of them with JavaScript import statements.

Components

A component controls a patch of screen called a view.

You define a component’s application logic - what it does to support the view - inside a class.

The class interacts with the view through an API of properties and methods.

export class HeroListComponent implements OnInit {
heroes: Hero[];
selectedHero: Hero;

constructor(private service: HeroService) { }

ngOnInit() {
this.heroes = this.service.getHeroes();
}

selectHero(hero: Hero) { this.selectedHero = hero; }
}

Templates

You define a component’s view with its companion template.

<h2>Hero List</h2>
<p><i>Pick a hero from the list</i></p>
<ul>
<li *ngFor="let hero of heroes" (click)="selectHero(hero)">
{{hero.name}}
</li>
</ul>
<hero-detail *ngIf="selectedHero" [hero]="selectedHero"></hero-detail>

Metadata

Metadata tells Angular how to process a class.

Attaching metadata to the class to tell Angular that a class is a component.

In TypeScript, you attach metadata by using a decorator.

@Component({
selector: 'hero-list',
templateUrl: 'app/hero-list.component.html',
providers: [ HeroService ]
})
export class HeroListComponent implements OnInit {
/* . . . */
}

@Component properties:
|—-> selector: CSS selector.
|—-> templateUrl: address of this component’s HTML template.
|—-> directives: array of the components or directives that this template requires.
|—-> providers: array of dependency injection providersfor the services that the component requires.

Data binding

Angular supports data binding,

databinding

4 forms of data binding syntax.

<li>{{hero.name}}</li>
<hero-detail [hero]="selectedHero"></hero-detail>
<li (click)="selectHero(hero)"></li>
  • The interpolation display the component’s hero.name property value within the <li> tags.
  • The [hero] property binding passes the value of selectedHero from the parent HeroListComponent to the hero property of the child HeroDetailComponent.
  • The (click) event binding calls the component’s selelctHero method when the user clicks a hero’s name.
<input [(ngModel)]="hero.name">
  • Two-way data binding
    Combines property and event binding in a single notation, using the ngModel.

Angular processes all data bindings once per JavaScript event cycle, from the root of the application component tree through all child components.

component-databinding

parent-child-binding

Directives

Angular templates are dynamic.
When Angular renders them, it transforms the DOM according to the instructions given by directives.

@Directive

A component is a directive-with-a-template;
A @Component decorator is actually a @Directive decorator extended with template-oriented features.

While a component is technically a directive, components are so distinctive and central to Angular applications that
this architectual overview separates components from directives.

structural directive attribute directive

Structural directives alter layout by adding, removing, and replacing elements in DOM.

<li *ngFor="let hero of heroes"></li>
<hero-detail *ngIf="selectedHero"></hero-detail>

Attribute directives alter the appearance or behavior of an existing element.
In templates they look like regular HTML attributes, hence the name.

E.g. ngModel
ngModel modifies the behavior of an existing element (typically an ) by setting its display value property and responding to change events.

<input [(ngModel)]="hero.name">

Angular has a few more directives that either alter the layout structure (for example, ngSwitch) or modify aspects of DOM elements and components (for example, ngStyle and ngClass).

Then create your own directives.

Services

Service is a broad category encompassing any value, function, or feature that your application needs.

A service is typically a class with a narrow, well-defined purpose.

export class Logger {
log(msg: any) { console.log(msg); }
error(msg: any) { console.error(msg); }
warn(msg: any) { console.warn(msg); }
}
export class HeroService {
private heros: Hero[] = [];

constructor(
private backend: BackendService,
private logger: Logger
) {}


getHeroes() {
this.backend.getAll(Hero).then((heroes: Hero[]) => {
this.logger.log(`Fetched ${heroes.length} heroes.`);
this.heroes.push(...heroes); // fill cache
});

return this.heroes;
}
}

Dependency Injection

Dependency injection is a way to supply a new instance of a class with the fully-formed dependencies it requires.
Most dependencies are services.
Angular uses dependency injection to provide new components with the services they need.

constructor(private service: HeroService) {}

When Angular creates a component, it first asks an injector for the services that the component requires.

An injector maintains a container of service instances that it has previously created.
if a requested service instance is not in the container, the injector makes one and adds it to the container before returning the service to angular.
When all requested services have been resolved and returned, Angular can call the component’s constructor with those services as arguments.
This is dependency injection.

If the injector doesn’t have a HeroService, how does it know how to make one ?

In brief, you must have previously registered a provider of the HeroService with the injector.

  • Register providers in modules.

Add providers to the root module so that the same instance of a service is avaiable everywhere.

providers: [
BackendService,
HeroService,
Logger
],

  • Register providers in component.
@Component({
selector: 'hero-list',
templateUrl: 'app/hero-list.component.html',
providers: [HeroService]
})

Registering at a component level means you get a new instance of the service with each new instance of that component.

  • Dependency injection is wired into the Angular framework and used everywhere.

  • The injector is the main mechanism.

    • An injector maintains a container of service instances that it created.
    • An injector can create a new service instance from a provider.
  • A provider is a recipe for creating a service.

  • Register providers with injectors.

More

Here is a brief, alphabetical list of other important Angular features and services. Most of them are covered in this documentation (or soon will be).

  • Animations: Animate component behavior without deep knowledge of animation techniques or CSS with Angular’s animation library.

  • Change detection: The change detection documentation will cover how Angular decides that a component property value has changed, when to update the screen, and how it uses zones to intercept asynchronous activity and run its change detection strategies.

  • Events: The events documentation will cover how to use components and services to raise events with mechanisms for publishing and subscribing to events.

  • Forms: Support complex data entry scenarios with HTML-based validation and dirty checking.

  • HTTP: Communicate with a server to get data, save data, and invoke server-side actions with an HTTP client.

  • Lifecycle hooks: Tap into key moments in the lifetime of a component, from its creation to its destruction, by implementing the lifecycle hook interfaces.

  • Pipes: Use pipes in your templates to improve the user experience by transforming values for display. Consider this currency pipe expression:

price | currency:'USD':true

It displays a price of “42.33” as $42.33.

  • Router: Navigate from page to page within the client application and never leave the browser.

  • Testing: Run unit tests with Angular’s testing library on your application parts as they interact with the Angular framework.

ws=D: $t IF ".$*." == ".." (cd D:\1Stop-Project\TradingParterManagement) ELSE (cd $*) $t subl .

Client Server
—> syn=1 seq=x —>
<— ack=x+1 seq=y <—
—> ack=y+1 seq=z —>

Summary:

Equivalent to HTTP status 100. System.Net.HttpStatusCode.Continue indicates
that the client can continue with its request.

Continue = 100,

Summary:

Equivalent to HTTP status 101. System.Net.HttpStatusCode.SwitchingProtocols
indicates that the protocol version or protocol is being changed.

SwitchingProtocols = 101,

Summary:

Equivalent to HTTP status 200. System.Net.HttpStatusCode.OK indicates that
the request succeeded and that the requested information is in the response.
This is the most common status code to receive.

OK = 200,

Summary:

Equivalent to HTTP status 201. System.Net.HttpStatusCode.Created indicates
that the request resulted in a new resource created before the response was
sent.

Created = 201,

Summary:

Equivalent to HTTP status 202. System.Net.HttpStatusCode.Accepted indicates
that the request has been accepted for further processing.

Accepted = 202,

Summary:

Equivalent to HTTP status 203. System.Net.HttpStatusCode.NonAuthoritativeInformation
indicates that the returned metainformation is from a cached copy instead
of the origin server and therefore may be incorrect.

NonAuthoritativeInformation = 203,

Summary:

Equivalent to HTTP status 204. System.Net.HttpStatusCode.NoContent indicates
that the request has been successfully processed and that the response is
intentionally blank.

NoContent = 204,

Summary:

Equivalent to HTTP status 205. System.Net.HttpStatusCode.ResetContent indicates
that the client should reset (not reload) the current resource.

ResetContent = 205,

Summary:

Equivalent to HTTP status 206. System.Net.HttpStatusCode.PartialContent indicates
that the response is a partial response as requested by a GET request that
includes a byte range.

PartialContent = 206,

Summary:

Equivalent to HTTP status 300. System.Net.HttpStatusCode.MultipleChoices
indicates that the requested information has multiple representations. The
default action is to treat this status as a redirect and follow the contents
of the Location header associated with this response.

MultipleChoices = 300,

Summary:

Equivalent to HTTP status 300. System.Net.HttpStatusCode.Ambiguous indicates
that the requested information has multiple representations. The default
action is to treat this status as a redirect and follow the contents of the
Location header associated with this response.

Ambiguous = 300,

Summary:

Equivalent to HTTP status 301. System.Net.HttpStatusCode.MovedPermanently
indicates that the requested information has been moved to the URI specified
in the Location header. The default action when this status is received is
to follow the Location header associated with the response.

MovedPermanently = 301,

Summary:

Equivalent to HTTP status 301. System.Net.HttpStatusCode.Moved indicates
that the requested information has been moved to the URI specified in the
Location header. The default action when this status is received is to follow
the Location header associated with the response. When the original request
method was POST, the redirected request will use the GET method.

Moved = 301,

Summary:

Equivalent to HTTP status 302. System.Net.HttpStatusCode.Found indicates
that the requested information is located at the URI specified in the Location
header. The default action when this status is received is to follow the
Location header associated with the response. When the original request method
was POST, the redirected request will use the GET method.

Found = 302,

Summary:

Equivalent to HTTP status 302. System.Net.HttpStatusCode.Redirect indicates
that the requested information is located at the URI specified in the Location
header. The default action when this status is received is to follow the
Location header associated with the response. When the original request method
was POST, the redirected request will use the GET method.

Redirect = 302,

Summary:

Equivalent to HTTP status 303. System.Net.HttpStatusCode.SeeOther automatically
redirects the client to the URI specified in the Location header as the result
of a POST. The request to the resource specified by the Location header will
be made with a GET.

SeeOther = 303,

Summary:

Equivalent to HTTP status 303. System.Net.HttpStatusCode.RedirectMethod automatically
redirects the client to the URI specified in the Location header as the result
of a POST. The request to the resource specified by the Location header will
be made with a GET.

RedirectMethod = 303,

Summary:

Equivalent to HTTP status 304. System.Net.HttpStatusCode.NotModified indicates
that the client's cached copy is up to date. The contents of the resource
are not transferred.

NotModified = 304,

Summary:

Equivalent to HTTP status 305. System.Net.HttpStatusCode.UseProxy indicates
that the request should use the proxy server at the URI specified in the
Location header.

UseProxy = 305,

Summary:

Equivalent to HTTP status 306. System.Net.HttpStatusCode.Unused is a proposed
extension to the HTTP/1.1 specification that is not fully specified.

Unused = 306,

Summary:

Equivalent to HTTP status 307. System.Net.HttpStatusCode.RedirectKeepVerb
indicates that the request information is located at the URI specified in
the Location header. The default action when this status is received is to
follow the Location header associated with the response. When the original
request method was POST, the redirected request will also use the POST method.

RedirectKeepVerb = 307,

Summary:

Equivalent to HTTP status 307. System.Net.HttpStatusCode.TemporaryRedirect
indicates that the request information is located at the URI specified in
the Location header. The default action when this status is received is to
follow the Location header associated with the response. When the original
request method was POST, the redirected request will also use the POST method.

TemporaryRedirect = 307,

Summary:

Equivalent to HTTP status 400. System.Net.HttpStatusCode.BadRequest indicates
that the request could not be understood by the server. System.Net.HttpStatusCode.BadRequest
is sent when no other error is applicable, or if the exact error is unknown
or does not have its own error code.

BadRequest = 400,

Summary:

Equivalent to HTTP status 401. System.Net.HttpStatusCode.Unauthorized indicates
that the requested resource requires authentication. The WWW-Authenticate
header contains the details of how to perform the authentication.

Unauthorized = 401,

Summary:

Equivalent to HTTP status 402. System.Net.HttpStatusCode.PaymentRequired
is reserved for future use.

PaymentRequired = 402,

Summary:

Equivalent to HTTP status 403. System.Net.HttpStatusCode.Forbidden indicates
that the server refuses to fulfill the request.

Forbidden = 403,

Summary:

Equivalent to HTTP status 404. System.Net.HttpStatusCode.NotFound indicates
that the requested resource does not exist on the server.

NotFound = 404,

Summary:

Equivalent to HTTP status 405. System.Net.HttpStatusCode.MethodNotAllowed
indicates that the request method (POST or GET) is not allowed on the requested
resource.

MethodNotAllowed = 405,

Summary:

Equivalent to HTTP status 406. System.Net.HttpStatusCode.NotAcceptable indicates
that the client has indicated with Accept headers that it will not accept
any of the available representations of the resource.

NotAcceptable = 406,

Summary:

Equivalent to HTTP status 407. System.Net.HttpStatusCode.ProxyAuthenticationRequired
indicates that the requested proxy requires authentication. The Proxy-authenticate
header contains the details of how to perform the authentication.

ProxyAuthenticationRequired = 407,

Summary:

Equivalent to HTTP status 408. System.Net.HttpStatusCode.RequestTimeout indicates
that the client did not send a request within the time the server was expecting
the request.

RequestTimeout = 408,

Summary:

Equivalent to HTTP status 409. System.Net.HttpStatusCode.Conflict indicates
that the request could not be carried out because of a conflict on the server.

Conflict = 409,

Summary:

Equivalent to HTTP status 410. System.Net.HttpStatusCode.Gone indicates that
the requested resource is no longer available.

Gone = 410,

Summary:

Equivalent to HTTP status 411. System.Net.HttpStatusCode.LengthRequired indicates
that the required Content-length header is missing.

LengthRequired = 411,

Summary:

Equivalent to HTTP status 412. System.Net.HttpStatusCode.PreconditionFailed
indicates that a condition set for this request failed, and the request cannot
be carried out. Conditions are set with conditional request headers like
If-Match, If-None-Match, or If-Unmodified-Since.

PreconditionFailed = 412,

Summary:

Equivalent to HTTP status 413. System.Net.HttpStatusCode.RequestEntityTooLarge
indicates that the request is too large for the server to process.

RequestEntityTooLarge = 413,

Summary:

Equivalent to HTTP status 414. System.Net.HttpStatusCode.RequestUriTooLong
indicates that the URI is too long.

RequestUriTooLong = 414,

Summary:

Equivalent to HTTP status 415. System.Net.HttpStatusCode.UnsupportedMediaType
indicates that the request is an unsupported type.

UnsupportedMediaType = 415,

Summary:

Equivalent to HTTP status 416. System.Net.HttpStatusCode.RequestedRangeNotSatisfiable
indicates that the range of data requested from the resource cannot be returned,
either because the beginning of the range is before the beginning of the
resource, or the end of the range is after the end of the resource.

RequestedRangeNotSatisfiable = 416,

Summary:

Equivalent to HTTP status 417. System.Net.HttpStatusCode.ExpectationFailed
indicates that an expectation given in an Expect header could not be met
by the server.

ExpectationFailed = 417,

Summary:

Equivalent to HTTP status 426. System.Net.HttpStatusCode.UpgradeRequired
indicates that the client should switch to a different protocol such as TLS/1.0.

UpgradeRequired = 426,

Summary:

Equivalent to HTTP status 500. System.Net.HttpStatusCode.InternalServerError
indicates that a generic error has occurred on the server.

InternalServerError = 500,

Summary:

Equivalent to HTTP status 501. System.Net.HttpStatusCode.NotImplemented indicates
that the server does not support the requested function.

NotImplemented = 501,

Summary:

Equivalent to HTTP status 502. System.Net.HttpStatusCode.BadGateway indicates
that an intermediate proxy server received a bad response from another proxy
or the origin server.

BadGateway = 502,

Summary:

Equivalent to HTTP status 503. System.Net.HttpStatusCode.ServiceUnavailable
indicates that the server is temporarily unavailable, usually due to high
load or maintenance.

ServiceUnavailable = 503,

Summary:

Equivalent to HTTP status 504. System.Net.HttpStatusCode.GatewayTimeout indicates
that an intermediate proxy server timed out while waiting for a response
from another proxy or the origin server.

GatewayTimeout = 504,

Summary:

Equivalent to HTTP status 505. System.Net.HttpStatusCode.HttpVersionNotSupported
indicates that the requested HTTP version is not supported by the server.

HttpVersionNotSupported = 505,

Auto Property Initializers

public class Developer
{
public bool DrinksCoffee {get;set;} = true;
}

Dictionary Initializers

var devSkills = new Dictionary<string, bool>();

devSkills["C#"] = true;
devSkills["HTML"] = true;

var devSkills = new Dictionary<string, bool>() {
["C#"] = true,
["VB.NET"] = true,
["HTML"] = true
};
```

### String Interpolation

```csharp
string test = "test1" + "with " + test2 + " finished.";
string test2 = string.Fromat("{0} {1}, {2} @ {3}", test1, test3, test4, test5);

var testCsharp6 = $"{firstName} {middleName} {lastName} , {jobTitle} @ {Company}";

Null Conditional Operator

public string[] GenerateCoffeeOrder(Coffee[] favCoffee)
{
var order = favCoffee?.Select(x => $"{x.Name} - {x.Size}").ToArray();

return order;
}

\?.\

  • “?” If the variable is null, then return null.
  • Otherwise execute whatever is after the “.”

Name of Expression

public string[] GenerateCoffeeOrder(Coffee[] favCoffee)
{
if (favCoffee == null)
{
throw new ArgumentNullException("favCoffee");
}

var order = favCoffee.Select(x => $"{x.Name} - {x.Size}").ToArray();

return order;
}

public string[] GenerateCoffeeOrder(Coffee[] coffeeOrders)
{
if (coffeeOrders == null)
{
throw new ArgumentNullException(nameof(coffeeOrders));
}

var order = coffeeOrders.Select(x => $"{x.Name} - {x.Size}").ToArray();

return order;
}

Expression Bodied Functions & Properties

public class Coffee {
public string Name {get;set;}
public string Size {get;set;}
public string OrderDescription => $"{Name} - {Size}";
}

Exception Filters

catch (SqlException ex) when (ex.ErrorCode == -2)
{
return "Timeout Error";
}
catch (SqlException ex) when (ex.ErrorCode == 1205)
{
return "Deadlock occurred";
}
catch (SqlException)
{
return "Unknown";
}

catch (SqlException ex) when (HttpContext.Current.Identity.Name == "Boss Man" || DateTime.Now.DayOfWeek == DayOfWeek.Saturday || DateTime.Now.DayOfWeek == DayOfWeek.Sunday) {
// Do nothing
}

Static Using

public double GetArea(double radius)
{

return Math.PI * Math.Pow(radius, 2);
}

public double GetArea(double radius
{
return PI * Pow(radius, 2)
;

}

Await in Catch and Finally Blocks

Extension Add in Collection Initializers

Youtube:

Enhanced .NET Unit Testing | David Gardiner

AutoFixture

https://github.com/AutoFixture/AutoFixture/

Approval Tests

Shouldly

dotMemory Unit

NBench