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

"It's alive!": Real-time applications with ASP.NET SignalR and AngularJS

"It's alive!": Real-time applications with ASP.NET SignalR and AngularJS

Everybody and his mother is talking about real-time data in applications on all kinds of devices. Christian Weyer will show the Open Source framework ASP.NET SignalR to build these kinds of systems. As a .NET developer you will feel very familiar on the server with building persistent connections and hubs in a services-like manner - with ASP.NET 5 this even runs on Linux! In addition, Christian will prove by using AngularJS on the client that it really works across Windows, MacOS X and mobile platforms. And usually you do not really have to care about the technical details of HTTP, Long Polling, WebSockets or whatever. Yay, your applications are really alive!

Christian Weyer

May 12, 2015
Tweet

More Decks by Christian Weyer

Other Decks in Programming

Transcript

  1. Christian Weyer • 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) ASP.NET Web API / vNext Advisory Board Member ASPInsider, AzureInsider • Google GDE for AngularJS • http://blogs.thinktecture.com/cweyer [email protected] @christianweyer 2
  2. Outline • Web-based real-time communication • ASP.NET SignalR • Hubs

    • Clients (with AngularJS) • Hosting • Summary 3
  3. Real time: Problem space • It is all about the

    users • Users want data – Now & instant – Up-to-date – Delivered to any device, over any connection • Increasing number of web sites & web applications offer ‚real time‘ data – Live searches/updates – Stock streamers, auctions – Live scores, betting, interactive games – Collaborative apps • In general: Real-time feedback, real-time notifications 4
  4. Real time: Developers’ world • Developers look for ways to

    provide real time data – But not only for web applications – What about mobile devices & apps? – What about traditional desktop applications? – What about server-to-server? • Web-based push communication beyond the web is a need • We got accustomed to a service-oriented design – Think in service facades – Facades provide entry points into our logic & data access • Think, design & implement Push Services 5
  5. 6

  6. Push Services pattern • ‘Push Services’ are really not an

    official pattern – Maybe ‘Observer’ • Model an application 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 Service Consumer Subscribe External event (Database) External event (Message queue) External event (Other actor) Notify [data] 7
  7. HTTP is the protocol • When talking about web communication

    technologies we talk about HTTP – HTTP is warrantor for ubiquity & reach • HTTP is inherently request-response, n’est pas? • Still we need to realize Push Services with what HTTP gives us 8
  8. Long polling 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 Server Client 10
  9. Technical approaches for push • 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 yet today • Alright, let’s just write code for any technology & technique! – Erm… really? For any server and any client platform? 11
  10. ASP.NET SignalR as a solution • 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 12
  11. ASP.NET SignalR development • 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 13
  12. Hubs concept • 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 1. Write hub class 2. Map hub routes in host process 3. Done 14
  13. Programming model • 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 15
  14. Hubs protocol • Base endpoint is /signalr • Optional: get

    JS metadata from /signalr/hubs • Basically two protocol steps (details vary by transport) – /negotiate: which transport do you support? – /connect: OK, here is my persistent connection • ‘Best’ transport negotiation – Web Sockets  SSE  Forever frame  Long polling • Pre-defined payload • Any data is JSON encoded C: Cursor M: Messages H: Hub name M: Method name A: Method args T: Timeout D: Disconnect 16
  15. Pushing data • 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 protocol response public void SendMessage(string message) { var msg = string.Format("{0}: {1}", Context.ConnectionId, message); Clients.All.newMessage(msg); } 17
  16. Hub lifecycle • Hub connections have a lifecycle – Override

    async pipeline event handlers • Sending data from outside a hub – Retrieve hub context (via dependency resolver) private void SendMonitorData(string eventType, string connection) { var context = GlobalHost.ConnectionManager.GetHubContext<MonitorHub>(); context.Clients.All.newEvent(eventType, connection); } public override Task OnConnected() { … } public override Task OnDisconnected() { … } public override Task OnReconnected() { … } 18
  17. SignalR & Web API integration • Use Web API as

    inbound API – E.g. to use authentication/authorization • Use SignalR as outbound API – To push data to consumers – Only IHubContext features available • Hub-able ApiController – Aka HubApiController<THub> 19
  18. Hub consumers • Consumers can be classic client applications or

    other services/hubs • SignalR provides a variety of client libraries • Microsoft SignalR team – .NET 4.5 – Portable Library – jQuery – Java – C++ • Community – iOS native – iOS via Mono – Android via Mono 20
  19. JavaScript/jQuery client • HTML5-based applications often use jQuery – SignalR

    not available yet as plain JS implementation • 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’ 21
  20. jQuery with proxy • Automatic proxy code via /signalr/hubs –

    Script generated based on hubs declaration in .NET – ‘Contract’ - if you will… • Simple steps to get going 1. Get reference to hub 2. Wire up events 3. Start hub connection 4. Call method 5. Done • Hubs become properties on $.connection – E.g. $.connection.chatHub – Hub name camel cased 22
  21. jQuery with proxy - II • $.connection.hub.start can take transport

    configuration – Auto, or any of the supported persistent connection transports • [hub].server.abc – Call methods on the server hub • [hub].client.xyz – Define client-side methods to be invoked by server hub var chat; chat = $.connection.chat; chat.client.newMessage = onNewMessage; var chat; chat = $.connection.chat; $.connection.hub.start({ transport: 'longPolling'}); chat.server.joinRoom('private'); 23
  22. jQuery without proxy file • We can also use a

    late binding approach • Simple steps to get going 1. Create hubConnection 2. Get dynamic proxy 3. Wire up events based on method/event handler name via on 4. Start & invoke methods based on method name via invoke • Same connection-related event handlers • Cross-domain support same as with static proxy var connection = $.hubConnection(); var proxy = connection.createHubProxy('chat'); proxy.on('newMessage', onNewMessage); connection.start(); proxy.invoke('sendMessage', $('#message').val()); 24
  23. AngularJS client • Use jQuery proxy-file-less client • Create hub

    proxy in Angular service or factory – Handle start and reconnecting • Broadcast SignalR events via AngularJS events on scope • Inject and use hub service in controllers – Do your data binding dance • Do not instantiate hub proxy in controllers – Will cause memory leaks 25 service.init = function (scope) { hubProxy.on("newCpuValue", function (data) { scope.$broadcast("newCpuValue", data); }); connection.start().done(function () {}); }
  24. .NET client • Mental model resembles proxy-less JavaScript approach •

    Simple steps to get going 1. Create HubConnection 2. Create hub proxy via CreateHubProxy 3. Wire up event handlers via On 4. Start connection with Start 5. Call methods via Invoke var hubConnection = new HubConnection( "http://localhost/services"); var chat = hubConnection.CreateHubProxy("chat"); chat.On<string>("newMessage", …); await hubConnection.Start(); 26
  25. ASP.NET hosting • SignalR ASP.NET hosting sits on top of

    OWIN • Map hubs to create routes – Referenced assemblies are scanned for Hub implementations public class Startup { public void Configuration(IAppBuilder app) { app.MapSignalR(); } } 27
  26. Self hosting • Self hosting sits on top of OWIN

    – IAppBuilder API • Simple steps to get going 1. Define startup class with IAppBuilder method signature 2. Map hubs onto IAppBuilder (route) 3. No automatic scanning of referenced assemblies • Startup class used in WebApplication.Start to spin up server – HTTP or HTTPS base URL • Runs on Mono today! 28
  27. Summary • SignalR enables near real-time push on application level

    – Server-side implementation in .NET – Various client-side libraries for cross-platform usage • SignalR runs on Linux today with Mono – Will run on Linux tomorrow with Mono and CoreCLR • AngularJS is a great means to integrate SignalR push functionality in client applications – Can be used in browser, mobile apps, on the desktop – Use Angular services to encapsulate SignalR API 29
  28. Resources • http://blogs.thinktecture.com/cweyer • [email protected] • @christianweyer • ASP.NET SignalR

    – http://www.asp.net/signalr • AngularJS – http://www.angularjs.org 31
  29. Demos • Push from Database to Browser – https://github.com/ChristianWeyer/ef-change-notify •

    Simple Chat (jQuery, Windows Forms) – https://github.com/ChristianWeyer/SignalR-SimpleChat-NOUG • Self-hosted System Monitor with AngularJS client – https://github.com/thinktecture/AngularJSSignalRDashboard 33
  30. 34 A big thank you to our partners Gold Partners

    Silver & Social Partners Platinum Partners