Upgrade to Pro — share decks privately, control downloads, hide ads and more …

End-to-End-Anwendungen mit ASP.NET Web API & An...

End-to-End-Anwendungen mit ASP.NET Web API & Angular 2

Zu jeder Server-Implementierung gehören auch Clients, na klar! In dieser Session zeigt Ihnen Christian Weyer wie man mit einem Single Page Application Framework wie Angular 2 und TypeScript als Programmiersprache echte Anwendungen für den Web Browser, für den Desktop und nahezu beliebige mobile Plattformen effizient realisieren kann. Dazu gehört eine passende Zielarchitektur mit Web APIs sowie Push Services für die bidirektionale Kommunikation. Umgesetzt wird diese im Backend mit C# und ASP.NET Web API und SignalR, zwei erprobte und robuste Technologien aus dem bekannten .NET-Universum. Und Action!

Christian Weyer

November 23, 2016
Tweet

More Decks by Christian Weyer

Other Decks in Programming

Transcript

  1. End-to-End-Anwendungen mit ASP.NET Web API, SignalR & Angular 2 In

    Action Christian Weyer @christianweyer Principal Consultant & CTO
  2. End-to-End-Anwendungen mit ASP.NET Web API, SignalR & Angular 2 In

    Action Thinktecture AG - http://thinktecture.com § Microsoft MVP for ASP.NET § Google GDE for Web Technologies § Focus on cross-platform solutions – end-to-end § [email protected] § @christianweyer Christian Weyer 2
  3. End-to-End-Anwendungen mit ASP.NET Web API, SignalR & Angular 2 In

    Action Cross-Platform == Reach Mobile-First != Mobile-only 5
  4. End-to-End-Anwendungen mit ASP.NET Web API, SignalR & Angular 2 In

    Action § Web / REST APIs § Node.js: Express or Restify § Java: Jersey § .NET: ASP.NET Web API § Push Services § Platform level § APNS, FCM, WNS § Application level § Node.js: socket.io § Java: Atmospehere § .NET: ASP.NET SignalR Target architecture: Services, everywhere 6
  5. End-to-End-Anwendungen mit ASP.NET Web API, SignalR & Angular 2 In

    Action § Client-side single page applications (SPA) § Features § Consequently component-based § Metadata-driven § Tooling ecosystem § Focus on proven pattern and separation of concerns § Components, views, view models § Services and dependency injection Angular 2 9
  6. End-to-End-Anwendungen mit ASP.NET Web API, SignalR & Angular 2 In

    Action § Modules § Components § Directives § Services § Router Angular 2 – Central Artifacts 10
  7. End-to-End-Anwendungen mit ASP.NET Web API, SignalR & Angular 2 In

    Action Components in TypeScript 11 @Component({ selector: 'my-app', template: '<h1>My Angular 2 App</h1>' }) export class AppComponent { }
  8. End-to-End-Anwendungen mit ASP.NET Web API, SignalR & Angular 2 In

    Action Component ‚Controller‘ 12 export class AppComponent implements OnInit { constructor() { } ... }
  9. End-to-End-Anwendungen mit ASP.NET Web API, SignalR & Angular 2 In

    Action § Directives add behavior to a DOM element • Component can consist of directives § A component is a directive with a view Component vs. Directive 13 @Directive({ selector: '[x-large]' }) export class XLargeDirective { constructor(public el: ElementRef) { this.el.nativeElement.style.fontSize = 'x-large'; } } <span x-large>Extra Large Text</span>
  10. End-to-End-Anwendungen mit ASP.NET Web API, SignalR & Angular 2 In

    Action Services 14 export class MyService { constructor() { } public GetMyData() {…} }
  11. End-to-End-Anwendungen mit ASP.NET Web API, SignalR & Angular 2 In

    Action Dependency Injection 15 @Injectable() export class MyService { constructor(private _otherService: OtherService) { } public GetMyData() { this._otherService.doSomething(); } }
  12. End-to-End-Anwendungen mit ASP.NET Web API, SignalR & Angular 2 In

    Action § Modularity system § Every Angular app has at least one module • Root module, conventionally named AppModule § Most apps have many more feature modules Modules @NgModule({ imports: [ BrowserModule ], providers: [ Logger ], declarations: [ AppComponent ], exports: [ AppComponent ], bootstrap: [ AppComponent ] }) export class AppModule { } 16
  13. End-to-End-Anwendungen mit ASP.NET Web API, SignalR & Angular 2 In

    Action Bootstrapping an Application – ng 2 17 @Component({ selector: 'my-app', viewTemplate: '<div>This app is called {{ title }}</div>' }) // needs to be in AppModule class AppComponent { this.title = 'My super app'; } import ... from 'angular'; import {AppModule} from 'appModule'; platformBrowserDynamic().bootstrapModule(AppModule); <html> <body> <my-app></my-app> </body> import ... from 'angular'; import {AppModuleNgFactory} from 'appModuleNgFactory'; platformBrowser().bootstrapModuleFactory(AppModuleNgFactory); AOT
  14. End-to-End-Anwendungen mit ASP.NET Web API, SignalR & Angular 2 In

    Action § Routing configuration Routing 18 export const APP_ROUTING: ModuleWithProviders = RouterModule.forRoot(appRootRoutes); export const GAMES_ROUTING: ModuleWithProviders = RouterModule.forChild(gameRoutes); const appRootRoutes: Routes = [ { path: 'login', component: LoginComponent, name: 'Login' }, { path: 'list', component: DataList, name: 'List' } ]; const gameRoutes: Routes = [ { path: 'games', component: GamesRootComponent, children: [{ path: 'all', component: GameListComponent }] } ];
  15. End-to-End-Anwendungen mit ASP.NET Web API, SignalR & Angular 2 In

    Action § Module imports Routing @NgModule({ imports: [ BrowserModule, APP_ROUTING ], providers: [ Logger ], declarations: [ AppComponent ], exports: [ AppComponent ], bootstrap: [ AppComponent ] }) export class AppModule { } 19
  16. End-to-End-Anwendungen mit ASP.NET Web API, SignalR & Angular 2 In

    Action § Routing placeholder in view Routing <div class="content-wrapper" style="min-height: 100%;"> <section class="content scrolling-module"> <router-outlet></router-outlet> </section> </div> 20
  17. End-to-End-Anwendungen mit ASP.NET Web API, SignalR & Angular 2 In

    Action § Data flows into a component via inputs § Data flows out of a component via outputs Data Flow & Component Public API 21
  18. End-to-End-Anwendungen mit ASP.NET Web API, SignalR & Angular 2 In

    Action § In Angular 2 no need to call $scope.$apply § Magic resides inside special library named zone.js • Overrides all standard browser APIs that are considered asynchronous • Injects its own implementation & uses it to monitor start and completion of any asynchronous activity § Async • Events: user events like click, change, input, submit • XMLHttpRequests: e.g. fetching data from REST API • Timers: setTimeout(), setInterval() Change Detection with Zones 22
  19. End-to-End-Anwendungen mit ASP.NET Web API, SignalR & Angular 2 In

    Action § Angular heavily builds on observables • Observable object represents a push-based collection • Leverages RxJS § Angular 2 has a native HTTP service • Can use any HTTP functionality like the Fetch API in modern browsers • Returns observable streams Observables & HTTP 23
  20. End-to-End-Anwendungen mit ASP.NET Web API, SignalR & Angular 2 In

    Action § Event bindings § Property bindings § Local variables Template Syntax 24
  21. End-to-End-Anwendungen mit ASP.NET Web API, SignalR & Angular 2 In

    Action Template Syntax 25 @Component({ selector: 'name-change', templateUrl: 'name-change.html' }) export class NameChange { constructor() { this.name = ''; } changeName(newName) { this.name = newName; } } <div> My name is {{ name }} </div> <div> <input #newname type="text"> <button (click)="changeName(newname.value)" [disabled]="newname.value == 'CW'"> Change Name </button> </div>
  22. End-to-End-Anwendungen mit ASP.NET Web API, SignalR & Angular 2 In

    Action § One-time bindings by default • Simplification and performance § Two-way binding is syntactic sugar • ng-model uses combination of property and event binding Two-Way Bindings 26
  23. End-to-End-Anwendungen mit ASP.NET Web API, SignalR & Angular 2 In

    Action Two-Way Binding Explained 27 <input [value]="name"> <p>Hello {{name}}</p> <input [value]="name" (input)="name = $event.target.value"> <p>Hello {{name}}</p> <input [ng-model]="name" (ng-model)="name = $event"> <p>Hello {{name}}</p> <input [(ng-model)]="name"> <p>Hello {{name}}</p>
  24. End-to-End-Anwendungen mit ASP.NET Web API, SignalR & Angular 2 In

    Action § In real projects we have a build process § Tools like gulp.js make life easier • Transpilation • Concatenation • Minification • and so on… § Angular 2 is agnostic to actual underlying build process § Angular CLI tool: https://cli.angular.io/ • Based on Webpack Build Process 28
  25. End-to-End-Anwendungen mit ASP.NET Web API, SignalR & Angular 2 In

    Action § View encapsulation § Forms in depth § Animations § AOT § Universal Angular § … and more ... More Topics 29
  26. End-to-End-Anwendungen mit ASP.NET Web API, SignalR & Angular 2 In

    Action § Toolkit and framework for building native application shells for our web apps § Make ‘app apps’ from ‘web apps’ J § Uses native web view components to host the original web app locally § Provides framework and APIs via plugins to interact with underlying native platforms § CLI tools for automating project creation & build § We always need the native SDKs (e.g. iOS, Android, Windows) § Access to native platforms via plugins Mobile apps with Cordova 31 JS HTML CSS Native wrapper Deploy to devices
  27. End-to-End-Anwendungen mit ASP.NET Web API, SignalR & Angular 2 In

    Action § Create real desktop applications from HTML5 code base § Similar to Cordova’s base idea: from web app to app app § Target Windows desktop, macOS, and Linux § Marriage of Chromium and Node.js § Independent of installed browsers on target machines § Does not need native SDKs to build final artifact § Access to native platform features § Electron API § Node modules ecosystem § Auto-updating and platform deployment available Desktop applications with Electron 32
  28. End-to-End-Anwendungen mit ASP.NET Web API, SignalR & Angular 2 In

    Action § ASP.NET Web API technology stack • Based on OWIN § Derive from ApiController § Implement your actions • Actions map to HTTP methods • Prefix method name with desired HTTP method – e.g. PostComment • Use [HttpGet/Post/Put/Delete] if you prefer a different name • Supports async with Task<T> § Actions expose explicit DTO data, HttpResponseMessage or JsonValue / dynamic Implementing a Web API 34
  29. End-to-End-Anwendungen mit ASP.NET Web API, SignalR & Angular 2 In

    Action § Several hosting options, e.g. • ASP.NET Web Application (IIS) • Self-host server option (console application, Windows service, etc.) § HttpConfiguration defines behavior § OWIN as base for hosting Web API, SignalR etc. Hosting 35
  30. End-to-End-Anwendungen mit ASP.NET Web API, SignalR & Angular 2 In

    Action § Maps a URL space to your Web API controllers • {controller} + “Controller” § Can be tailored using actions, default values and route constraints • Like more RPC-ish behavior § Alternative: attribute-based routing • Defines routes with .NET attributes Routing 36
  31. End-to-End-Anwendungen mit ASP.NET Web API, SignalR & Angular 2 In

    Action § “First class experience” for using HTTP • exposing HTTP as an application protocol in its full glory and not hiding it § Use of HttpRequestMessage and HttpResponseMessage • way of giving direct access to the HTTP protocol, without parsing and encoding complexity § Use IHttpActionResult • Better testability; pre-defined action results Working with HTTP 37
  32. End-to-End-Anwendungen mit ASP.NET Web API, SignalR & Angular 2 In

    Action § Model binding can “shred” the request and bind it to individual parameters § Values are taken from the URL (route variables, query parameters) or from the body § MediaTypeFormatters are used to deserialize the request body based on the content type • XML, JSON, form-url-encoded supported out of the box § Request data is validated as it is bound to the parameters Model Binding & Formatters 38
  33. End-to-End-Anwendungen mit ASP.NET Web API, SignalR & Angular 2 In

    Action § Response format is determined based on HTTP content negotiation § Request Accept header expresses desired format(s) § Server selects a format for the response based on the request and the available MediaTypeFormatters § Help/documentation page optionally available at /help § Use Swagger for open documentation standard Content Negotiation 39
  34. End-to-End-Anwendungen mit ASP.NET Web API, SignalR & Angular 2 In

    Action § ‘Push Services’ are really not an official pattern • Aka Observer pattern § Model a service that • accepts incoming connections from callers • is able to push data down to callers • abstracts from communication nitty-gritty details § Realize Publish-Subscribe semantics • Based on standard web technologies with reach in mind • With maximum reach into any device, platform Push Services Pattern 41 Push Service Consumer Send data External event (Database) External event (Message queue) External event (Other actor) Notify [data]
  35. End-to-End-Anwendungen mit ASP.NET Web API, SignalR & Angular 2 In

    Action § Periodic Polling § Long Polling • HTTP Streaming / Comet Technical Approaches for Push 42
  36. End-to-End-Anwendungen mit ASP.NET Web API, SignalR & Angular 2 In

    Action § Poll, but don’t respond untill there’s data § Server holds on to the HTTP request until there is data to return § (Re-)Poll after data received or after the connection times out § Consumes server threads & connection resources Long Polling 43 Server Client
  37. End-to-End-Anwendungen mit ASP.NET Web API, SignalR & Angular 2 In

    Action § Periodic Polling § Long Polling § Forever Frame § Server-Sent Events (SSE) § Web Sockets • Only with Windows 8/Server 2012 • Network considerations § Alright, let’s just write code for any technology & technique! • For any server and any client platform? Technical Approaches for Push 44
  38. End-to-End-Anwendungen mit ASP.NET Web API, SignalR & Angular 2 In

    Action § SignalR is • a server-side framework to write push services • a set of client libraries to make push service communication easy to use on any platform • optimized for asynchronous processing § Abstracts from the different techniques to implement pushing data • Mental model is a persistent connection • Volatile, non-durable § ‘Signal’, anyone? • Sending data to a signal. E.g. represented by a connection ID § Part of the ASP.NET brand, but not tied into ASP.NET runtime and APIs ASP.NET SignalR as a Solution 45
  39. End-to-End-Anwendungen mit ASP.NET Web API, SignalR & Angular 2 In

    Action § Extensible framework & pipeline • Based on interfaces & DI § Two programming models • Persistent connections • Hubs § Hubs offer a pre-defined application-level protocol in an RPC-ish style • Easy-to-get-going means for 80/20 situations ASP.NET SignalR Development 46
  40. End-to-End-Anwendungen mit ASP.NET Web API, SignalR & Angular 2 In

    Action § Hubs are classes to implement push services in SignalR • Abstraction on top of persistent connection • Convention-over-configuration § Hubs provide a higher level RPC framework • Perfect for different types of messages to send between server and client § Hub conventions • Public methods are callable from the outside • Send messages to clients by invoking client-side methods § Simple steps to get going • Write hub class • Add route in host process • Done Hubs Concept 47
  41. End-to-End-Anwendungen mit ASP.NET Web API, SignalR & Angular 2 In

    Action § Hub name reflected into external API • [HubName] can alias name § Return simple type, complex type or Task § Complex objects and arrays of objects automatically serialized/deserialized to/from JSON • Default is JSON.NET § Context holds connection- and request-specific information • ConnectionId • Request • Headers • RequestCookies • QueryString • User Programming Model 48
  42. End-to-End-Anwendungen mit ASP.NET Web API, SignalR & Angular 2 In

    Action § Clients property as dispatching point to send messages to clients § Holds dynamic properties and methods § Target method with parameters is dynamically ‘injected’ into code path, serialized, and embedded into response Pushing Data: Clients 49 public void SendMessage(string message) { var msg = string.Format("{0}: {1}", Context.ConnectionId, message); Clients.All.newMessage(msg); }
  43. End-to-End-Anwendungen mit ASP.NET Web API, SignalR & Angular 2 In

    Action § Consumers can be classic client applications or other services/hubs § SignalR provides a variety of client libraries § Microsoft SignalR team • .NET 4.0+ • WinRT • Windows Phone 8 • Silverlight 5 • jQuery • C++ § Community • iOS native • iOS, Android via Xamarin Hub Consumers 50
  44. End-to-End-Anwendungen mit ASP.NET Web API, SignalR & Angular 2 In

    Action § HTML5-based applications often use jQuery § JSON-based wire protocol makes it easy to integrate with JavaScript § SignalR jQuery plugin offers two approaches • Proxy-based with generated proxy • Without proxy but ‘late binding’ jQuery Client 51
  45. End-to-End-Anwendungen mit ASP.NET Web API, SignalR & Angular 2 In

    Action § Late binding approach § Simple steps to get going • Create hubConnection • Derived from $.connection • Get dynamic proxy • Wire up events based on method/event handler name via on • Start & invoke methods based on method name via invoke § Same connection-related event handlers § Cross-domain support same as with static proxy jQuery without Proxy File 52 var connection = $.hubConnection(); var proxy = connection.createHubProxy('chat'); proxy.on('newMessage', onNewMessage); connection.start(); proxy.invoke('sendMessage', $('#message').val());
  46. End-to-End-Anwendungen mit ASP.NET Web API, SignalR & Angular 2 In

    Action § Client NuGet package contains binaries for all supported .NET flavors § Mental model resembles proxy-less JavaScript approach § Simple steps to get going • Create HubConnection • Create hub proxy via CreateHubProxy • Wire up event handlers via On • Start connection with Start • Call methods via Invoke .NET Client 53 var hubConnection = new HubConnection("http://localhost/services"); var chat = hubConnection.CreateHubProxy("chat"); chat.On<string>("newMessage", …); hubConnection.Start().Wait(); …
  47. End-to-End-Anwendungen mit ASP.NET Web API, SignalR & Angular 2 In

    Action § Hosting sits on top of OWIN • IAppBuilder API § Simple steps to get going • Define startup class with IAppBuilder method signature • Map hubs onto IAppBuilder (routing) Hosting 54
  48. End-to-End-Anwendungen mit ASP.NET Web API, SignalR & Angular 2 In

    Action § Demo application § https://github.com/thinktecture/apisummit-2016-angular2-webapi § Contact § [email protected] § @christianweyer Thank you! 55
  49. End-to-End-Anwendungen mit ASP.NET Web API, SignalR & Angular 2 In

    Action § Christian Weyer über leichtgewichtige Architekturen und Angular 2 § https://entwickler.de/online/web/service-architektur-angular-2-302663.html Xamarin, Angular oder Cordova? Erstmal die passende Service-Architektur! 56