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

Leichtgewichtige Architekturen mit ASP.NET Web API und SignalR - “Die Architektur”

Leichtgewichtige Architekturen mit ASP.NET Web API und SignalR - “Die Architektur”

Der Traum von einer einzigen Codebasis für alle Clientplattformen: Er lebt immer noch. In dieser Session zeigt Ihnen Christian Weyer, wie weit dieser Traum mit HTML5/JavaScript und aktuellen Cross-Plattform-Werkzeugen Wirklichkeit werden kann. Auf Basis moderner UI/UX-Konzepte lassen sich Oberflächen für Desktops, Tablets und Smartphones entwerfen – mit einer Codebasis. Mischt man diesen Ansatz mit Tools wie Cordova und Electron, so kann man mit Single-Page-Applications-(SPA-)Frameworks wie Angular 2 echte Anwendungen für alle relevanten Plattformen und Devicegrößen bauen, Mobile und Desktop: Windows, Linux, Mac OS, iOS, Android und Co. – und natürlich den Browser. Kommen Sie vorbei und sehen Sie all dies in Action!

Christian Weyer

February 21, 2017
Tweet

More Decks by Christian Weyer

Other Decks in Programming

Transcript

  1. Leichtgewichtige Architekturen mit ASP.NET Web API und SignalR “Die Architektur”

    Christian Weyer @christianweyer Principal Consultant & CTO
  2. Special Day Modern Business Applications Thema Sprecher Datum, Uhrzeit Raum

    Leichtgewichtige Architekturen mit ASP.NET Web API und SignalR Die Architektur Christian Weyer DI, 21. Februar 2017, 10.00 bis 11.15 PLATINUM BALLSAAL II TypeScript für .NET-Entwickler Die Sprache Christian Wenz DI, 21. Februar 2017, 11.30 bis 12.45 PLATINUM BALLSAAL II Angular 2: Komponentenbasierte HTML5- Anwendungen Die Plattform Manuel Rauber DI, 21. Februar 2017, 14.15 bis 15.30 PLATINUM BALLSAAL II CSS Flexbox: Oberflächenlayout der Zukunft Die Oberfläche Timo Korinth DI, 21. Februar 2017, 16.15 bis 17.30 PLATINUM BALLSAAL II Mobile und Desktop: Echte Anwendungen mit Cordova, Electron und Angular 2 Die Betriebsumgebung Thorsten Hans DI, 21. Februar 2017, 18.30 bis 19.45 PLATINUM BALLSAAL II
  3. Leichtgewichtige Architekturen mit ASP.NET Web API und SignalR Die Architektur

    § Co-founder, co-owner and principal consultant at Thinktecture AG § Focus on • Mobile & web-based application architectures • Interoperability, cross-device • Pragmatic end-to-end solutions § Microsoft MVP for ASP.NET (Architecture) ASPInsider, AzureInsider § Google GDE for Web Technologies § [email protected] § @christianweyer Christian Weyer 3
  4. Leichtgewichtige Architekturen mit ASP.NET Web API und SignalR Die Architektur

    § How to move our Windows Forms or WPF or UWP app to mobile devices and to the browser? Central Question J 4
  5. Leichtgewichtige Architekturen mit ASP.NET Web API und SignalR Die Architektur

    § Enterprise § ISV § Web § … any difference today?  Services Architecture for… 5
  6. Leichtgewichtige Architekturen mit ASP.NET Web API und SignalR Die Architektur

    § .NET clients § Silverlight clients § Pure HTML(5) § JavaScript & jQuery § Android (Java) § iOS (Objective-C) § Embedded (C/C++) § Java § Any client, any device, actually Ubiquituous Access 10
  7. Leichtgewichtige Architekturen mit ASP.NET Web API und SignalR Die Architektur

    § „SOAP“ / WS-* • transport protocol independent • „secure, reliable and transacted“ (WS-*) • sophisticated and complex protocol stack • interoperability may become difficult • „the best RPC so far“ § Web/HTTP („REST“, anyone?) • fully embrace HTTP • least common denominator technologies • less functionality (KISS?) • reach and interoperability said to be better • „easier to use“ Architectural Approaches to Service Orientation 15
  8. Leichtgewichtige Architekturen mit ASP.NET Web API und SignalR Die Architektur

    § Application protocol § URIs § Verbs § Headers § Content types § Content negotiation § Status codes HTTP – the Application Protocol 17
  9. Leichtgewichtige Architekturen mit ASP.NET Web API und SignalR Die Architektur

    § Need a first class HTTP programming model § Easily map resources to URIs and implement the uniform interface § Rich support for formats and HTTP content negotiation § Separate out cross cutting concerns § Lightweight, Internet scale § Realize REST-ful or RPC-ish architectures • Being pragmatic, not idealistic Web API Framework Requirements 18
  10. Leichtgewichtige Architekturen mit ASP.NET Web API und SignalR Die Architektur

    § 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 19
  11. Leichtgewichtige Architekturen mit ASP.NET Web API und SignalR Die Architektur

    § 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. § HttpClient is a cross-.NET HTTP client API § JavaScript: jQuery’s $.ajax, or $http in AngularJS Hosting & Clients 20
  12. Leichtgewichtige Architekturen mit ASP.NET Web API und SignalR Die Architektur

    § 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 21
  13. Leichtgewichtige Architekturen mit ASP.NET Web API und SignalR Die Architektur

    § “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 22
  14. Leichtgewichtige Architekturen mit ASP.NET Web API und SignalR Die Architektur

    § 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 23
  15. Leichtgewichtige Architekturen mit ASP.NET Web API und SignalR Die Architektur

    § 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 24
  16. Leichtgewichtige Architekturen mit ASP.NET Web API und SignalR Die Architektur

    § ‘Push Services’ are really not an official pattern • Observer pattern, anyone? § 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 Push Service Consumer Send data External event (Database) External event (Message queue) External event (Other actor) Notify [data] 26
  17. Leichtgewichtige Architekturen mit ASP.NET Web API und SignalR Die Architektur

    § Periodic Polling § Long Polling • HTTP Streaming / Comet Technical Approaches to Push 27
  18. Leichtgewichtige Architekturen mit ASP.NET Web API und SignalR Die Architektur

    § 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 Server Client 28
  19. Leichtgewichtige Architekturen mit ASP.NET Web API und SignalR Die Architektur

    § Periodic Polling § Long Polling • HTTP Streaming / Comet § Forever Frame § Server-Sent Events (SSE) § Web Sockets § Easy: Web Sockets are the way to go! • Only with Windows 8/Server 2012 • Network considerations • Maybe some time, but not today § Alright, let’s just write code for any technology & technique! • Erm… really? For any server and any client platform? Technical Approaches to Push 29
  20. Leichtgewichtige Architekturen mit ASP.NET Web API und SignalR Die Architektur

    § 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 30
  21. Leichtgewichtige Architekturen mit ASP.NET Web API und SignalR Die Architektur

    § 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 31
  22. Leichtgewichtige Architekturen mit ASP.NET Web API und SignalR Die Architektur

    § 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 32
  23. Leichtgewichtige Architekturen mit ASP.NET Web API und SignalR Die Architektur

    § 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 § Context holds connection- and request-specific information • ConnectionId • Request • Headers • RequestCookies • QueryString • User Hubs Programming Model 33
  24. Leichtgewichtige Architekturen mit ASP.NET Web API und SignalR Die Architektur

    § 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 public void SendMessage(string message) { var msg = string.Format("{0}: {1}", Context.ConnectionId, message); Clients.All.newMessage(msg); } 34
  25. Leichtgewichtige Architekturen mit ASP.NET Web API und SignalR Die Architektur

    § Consumers can be classic client applications or other services/hubs § SignalR provides a variety of client libraries § Microsoft SignalR team • .NET 4.0+ • Windows Phone 8 • Silverlight 5 • jQuery • C++ § Community • iOS native • iOS via Mono • Android via Mono Hub Consumers 35
  26. Leichtgewichtige Architekturen mit ASP.NET Web API und SignalR Die Architektur

    § 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’ JavaScript Client 36
  27. Leichtgewichtige Architekturen mit ASP.NET Web API und SignalR Die Architektur

    § 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 JavaScript without Proxy File var connection = $.hubConnection(); var proxy = connection.createHubProxy('chat'); proxy.on('newMessage', onNewMessage); connection.start(); proxy.invoke('sendMessage', $('#message').val()); 37
  28. Leichtgewichtige Architekturen mit ASP.NET Web API und SignalR Die Architektur

    § 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 var hubConnection = new HubConnection("http://localhost/services"); var chat = hubConnection.CreateHubProxy("chat"); chat.On<string>("newMessage", …); hubConnection.Start().Wait(); … 38
  29. Leichtgewichtige Architekturen mit ASP.NET Web API und SignalR Die Architektur

    § Hosting sits on top of OWIN • IAppBuilder API § Simple steps to get going • Define startup class with IAppBuilder method signature • Map hubs onto IAppBuilder (route) § In Self-Host: Startup class used in WebApplication.Start to spin up server • HTTP or HTTPS base URL Hosting 39
  30. Leichtgewichtige Architekturen mit ASP.NET Web API und SignalR Die Architektur

    § Flexible lightweight architectures • Based on the Web § Web APIs for exposing services with reach • ASP.NET Web API as lean technology stack § Push Services for implementing bi-directional communication • ASP.NET SignalR as enabling framework § Good base for a number of different application architectures • Web-based, native, desktop, mobile ASP.NET Web API & SignalR - & ASP.NET Core MVC 41
  31. Leichtgewichtige Architekturen mit ASP.NET Web API und SignalR Die Architektur

    § [email protected] § http://www.thinktecture.com § Thinktecture’s GitHub Repositories • https://github.com/thinktecture § Christian Weyer’s GitHub Repositories • https://github.com/ChristianWeyer § WebApiSignalRAngularDemo • https://github.com/ChristianWeyer/WebApiSignalRAngularDemo Resources 42