Building modern web sites with ASP .Net Web API, WebSockets and RSignal

13,547 views

Published on

My session at ITCamp.ro 2012:

Web site development is an ever changing landscape. Thanks to the latest web browser technologies it's possible to create highly responsive single page applications, requiring a new approach to design and development on the server side. During this session we'll see ho to use .Net technologies to get the best out of the new Web API, WebSockets and the excellent RSignal framework.

Published in: Technology
0 Comments
4 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
13,547
On SlideShare
0
From Embeds
0
Number of Embeds
1,728
Actions
Shares
0
Downloads
84
Comments
0
Likes
4
Embeds 0
No embeds

No notes for slide

Building modern web sites with ASP .Net Web API, WebSockets and RSignal

  1. 1. Building modern web sites with ASP .Net Web API, WebSockets and RSignal Alessandro Pilotti MVP ASP.Net / IIS Windows Azure Insider @alexpilotti@ itcampro # itcamp12 Premium conference on Microsoft technologies
  2. 2. Mobile &ITCamp 2012 sponsors Development@ itcampro # itcamp12 Premium conference on Microsoft technologies
  3. 3. Mobile &Agenda Development• ASP.Net Web API• SignalR• WebSocket@ itcampro # itcamp12 Premium conference on Microsoft technologies
  4. 4. Mobile &What’s the deal? Development• The web app designer’s holy grail: – Reach the usability level of a desktop app• The web app designer’s curse: – Lack of standard API on the browser’s side• Until recently the only way out was a RIA framework: – Flash / Silverlight@ itcampro # itcamp12 Premium conference on Microsoft technologies
  5. 5. Mobile &HTML5 Development• HTML5 is changing the game• Great set of new browser features: – Application cache – Web storage – WebSockets – WebWorkers – Geolocation – Drag&Drop – Multiple file uploads – Inline SVG – History management – … and that Video thing@ itcampro # itcamp12 Premium conference on Microsoft technologies
  6. 6. Mobile &Javascript? Development• Javascript is getting a huge boost – There’s more than meets the eye – Its prototyping nature and flexibility is great • The rest sucks • An enormous amount of frameworks are available today, e.g: – JQuery / JQuery UI – Knockout.js – Backbone.js – Underscore.js – History.js – …And a gazillion more@ itcampro # itcamp12 Premium conference on Microsoft technologies
  7. 7. Mobile &SPA Development• Single Page Applications – A single HTML is loaded in the browser – History (aka back button) is managed via Javascript – Templates are used to load and render in the DOM content on demand • Some Ajax might be useful for that – Offline usage • Application cache • Web storage@ itcampro # itcamp12 Premium conference on Microsoft technologies
  8. 8. Mobile &And how do we access Data? Development• Web pages communicate with the server via asynchronous calls – XmlHttpRequest (as in ajax) – JSON serialization • Way faster than XML • Originally decoded with “eval” • Modern browsers provide native encoding / deconding – JSON.parse(…) / JSON.stringify(…) – Even faster! – RESTful APIs – WebSockets • Where supported@ itcampro # itcamp12 Premium conference on Microsoft technologies
  9. 9. Mobile &Great advantages Development• Faster web sites• Lower traffic• Clear separation – UI – Services / BL• Enhanced testability – Unit tests for the server API – MVVM in Javascript (e.g. Knockout.js)• Enhanced portability – E.g. Mobile UI@ itcampro # itcamp12 Premium conference on Microsoft technologies
  10. 10. Mobile &ASP.Net Web API Development• ASP.Net Web API – Comes with MVC4 – Provides a new RESTful Web API framework – ODATA support – Very easy – Great IoC support – EF integration (DbDataController<T>) – Can be also installed on MVC3 or Web Forms • Install-Package AspNetWebApi• All the ASP.Net Stack is open source!! – http://aspnetwebstack.codeplex.com/• Alternative: WCF – RESTful support – More control • Complicated bindings configuration@ itcampro # itcamp12 Premium conference on Microsoft technologies
  11. 11. Mobile &RESTful APIs Development• Use of HTTP verbs: – GET – POST – PUT – DELETE• Great for CRUD operations• Errors use HTTP semantics – E.g. not found => 404• Uses custom routing• A lot less bloated than SOAP@ itcampro # itcamp12 Premium conference on Microsoft technologies
  12. 12. Mobile &RESTful APIs example DevelopmentAction HTTP verb Relative URIGet a list of all products GET /api/productsGet a product by ID GET /api/products/idGet a product by category GET /api/products?category=categoryCreate a new product POST /api/productsUpdate a product PUT /api/products/idDelete a product DELETE /api/products/id@ itcampro # itcamp12 Premium conference on Microsoft technologies
  13. 13. Mobile &jQuery example DevelopmentjQuery does all the dirty job, the result is neat and clean:$.getJSON( "api/products", function(data) { $.each(data, function(index, value) { $("#products").append(<li> + value.Name + </li>); }); });@ itcampro # itcamp12 Premium conference on Microsoft technologies
  14. 14. Mobile &ASP.Net Web API routing Developmentroutes.MapHttpRoute( name: "API Default", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional });• Avoids conflicts with MVC routing• Naming Convention – GetAllProducts, DeleteProduct, etc• Explicit action attributes: – [HttpGet], [HttpPost], [HttpPut], [HttpDelete], [NonAction]• User "api/{controller}/{action}/{id}” for RPC style routing – Needs explicit verb attributes@ itcampro # itcamp12 Premium conference on Microsoft technologies
  15. 15. Mobile &HttpMessageHandler Development• ASP.Net Web API is based on a pipeline• Inherit from DelegatingHandler to create your handlers – E.g. check an API key• Add with: – config.MessageHandlers.Add(new ApiKeyHandler());@ itcampro # itcamp12 Premium conference on Microsoft technologies
  16. 16. Mobile &ODATA + Web API Development• Open Data Protocol – A web protocol for querying and updating data• Enable ODATA queries on your Web API – Just return an IQueriable<T>• Examples – http://localhost:1702/api/Products?$filter=Enabled%2 0eq%20true – http://localhost:1702/api/Products?$orderby=Name% 20desc – http://localhost:1702/api/Products?$filter=startswith( Name,’whatever)@ itcampro # itcamp12 Premium conference on Microsoft technologies
  17. 17. Mobile &CURL Development• Great tool for troubleshooting• curl -i -H "Accept: application/json" http://localhost:1823/api/Products• curl -i -H "Content-Type: application/json" -H "Accept: application/json" -X POST -d @data.json http://localhost:1823/api/Product@ itcampro # itcamp12 Premium conference on Microsoft technologies
  18. 18. WEB API DEMO@ itcampro # itcamp12 Premium conference on Microsoft technologies
  19. 19. Mobile &SignalR Development• A framework that provides some magic for: – Persistent connections • LongPolling • WebSockets • Examples: chat, stock ticker updates – Dynamic proxy generation for Javascript code • Hubs – JSON serialization• Asynchronous model• Supports self hosting• Unrelated to MVC or Web Forms• Install-package SignalR – Or: https://github.com/SignalR/SignalR@ itcampro # itcamp12 Premium conference on Microsoft technologies
  20. 20. Mobile &Long Polling Development A way to simulate push data connections 1. The client connects via HTTP 2. The server waits for available data 3. The server sends the response 4. Back to step one@ itcampro # itcamp12 Premium conference on Microsoft technologies
  21. 21. Mobile &Persistent connections (server) Development public class MyConnection : PersistentConnection { protected override Task OnReceivedAsync(IRequest request, string connectionId, string data) { // Broadcast data to all clients return Connection.Broadcast(data); } }Routing setup in global.asax:RouteTable.Routes.MapConnection<MyConnection>("echo", "echo/{*operation}");@ itcampro # itcamp12 Premium conference on Microsoft technologies
  22. 22. Mobile &Persistent connections (client) Development $(function () { var connection = $.connection(/echo); connection.received(function (data) { $(#messages).append(<li> + data + </li>); }); connection.start(); $("#broadcast").click(function () { connection.send($(#msg).val()); }); });@ itcampro # itcamp12 Premium conference on Microsoft technologies
  23. 23. Mobile &PersistentConnection API Development• Task OnConnectedAsync(IRequest request, string connectionId)• Task OnReconnectedAsync(IRequest request, IEnumerable groups, string connectionId)• Task OnReceivedAsync(IRequest request, string connectionId, string data)• Task OnDisconnectAsync(string connectionId)• Task OnErrorAsync(Exception error)@ itcampro # itcamp12 Premium conference on Microsoft technologies
  24. 24. Mobile &IConnection API Development• Task Broadcast(object value)• Task Send(string signal, object value)@ itcampro # itcamp12 Premium conference on Microsoft technologies
  25. 25. Mobile &External broadcasts Developmentvar context =GlobalHost.ConnectionManager.GetConnectionContext<MyEndPoint>();context.Connection.Broadcast(message);• Useful to send messages starting from a server action@ itcampro # itcamp12 Premium conference on Microsoft technologies
  26. 26. Mobile &Hub (server) Developmentpublic class Chat : Hub { public void Send(string message) { // Call the addMessage method on all clients Clients.addMessage(message); } }• Methods can have any name, the client resolves the names via proxy• Clients is a dynamic object – addMessage is defined in Javascript!!@ itcampro # itcamp12 Premium conference on Microsoft technologies
  27. 27. Mobile &Hub (client) Development var chat = $.connection.chat; // Declare a function on the chat hub so the server can invoke it chat.addMessage = function(message) { $(#messages).append(<li> + message + </li>); }; $("#broadcast").click(function () { // Call the chat method on the server chat.send($(#msg).val()) .done(function() { console.log(Success!); }) .fail(function(e) { console.warn(e); }); }); // Start the connection $.connection.hub.start();@ itcampro # itcamp12 Premium conference on Microsoft technologies
  28. 28. Mobile &Look Mama, no global.asax routes Development• SignalR’s AspNetBootStrapper defines – [assembly: PreApplicationStartMethod(typeof(AspNetBootstrapper), "Initialize")] – Initialize calls: RouteTable.Routes.MapHubs(); • Mapping the /signalr route• No need for: – Explicit global.asax route mapping – Web.config settings@ itcampro # itcamp12 Premium conference on Microsoft technologies
  29. 29. Mobile &External broadcasts Developmentvar context =GlobalHost.ConnectionManager.GetHubContext<MyHub>();context.Clients.say(message);@ itcampro # itcamp12 Premium conference on Microsoft technologies
  30. 30. Mobile &IIS setup for high loads Development• appcmd.exe set config /section:serverRuntime /appConcurrentRequestLimit:100000• In %windir%Microsoft.NETFrameworkv4.0.30319 aspnet.config – maxConcurrentRequestsPerCPU="20000”• In %windir%Microsoft.NETFrameworkv4.0.30319 Configmachine.config – <processModel autoConfig="false" requestQueueLimit="250000" /> technologies@ itcampro # itcamp12 Premium conference on Microsoft
  31. 31. SIGNALR DEMO@ itcampro # itcamp12 Premium conference on Microsoft technologies
  32. 32. Mobile &WebSockets Development• TCP/IP communication style model – Handshake resembles HTTP• Interoperable• Standard W3C (still in draft) – Older browsers support old versions• Bidirectional communications• Supports cross domain access!@ itcampro # itcamp12 Premium conference on Microsoft technologies
  33. 33. Mobile &Handshake DevelopmentRequest:GET /mychat HTTP/1.1Host: server.example.comUpgrade: websocketConnection: UpgradeSec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==Sec-WebSocket-Protocol: chatSec-WebSocket-Version: 13Origin: http://example.comResponse:HTTP/1.1 101 Switching ProtocolsUpgrade: websocketConnection: UpgradeSec-WebSocket-Accept: HSmrc0sMlYUkAGmm5OPpG2HaGWk=Sec-WebSocket-Protocol: chat@ itcampro # itcamp12 Premium conference on Microsoft technologies
  34. 34. Mobile &Javascript Development• Url: ws://yourhost/etc – wss: when used with SSL/TLSvar socket = newWebSocket(ws://game.example.com:12010/updates);socket.onopen = function () { setInterval(function() { if (socket.bufferedAmount == 0) socket.send(getUpdateData()); }, 50);};@ itcampro # itcamp12 Premium conference on Microsoft technologies
  35. 35. Mobile &Minimum requirements Development• IE 10• Chrome 4• Firefox 4• Safari 5• Opera 11• Server: IIS 8@ itcampro # itcamp12 Premium conference on Microsoft technologies
  36. 36. Mobile &Proxy support Development• Proxies tipically don’t recognize WebSocket traffic• By using SSL/TLS the problem is mitigated – Client uses HTTP CONNECT in this case@ itcampro # itcamp12 Premium conference on Microsoft technologies
  37. 37. Mobile &IIS 8 – enable WebSockets feature Development@ itcampro # itcamp12 Premium conference on Microsoft technologies
  38. 38. Mobile &WCF 4.5 – HTTP Activation Development@ itcampro # itcamp12 Premium conference on Microsoft technologies
  39. 39. Mobile &WCF 4.5 Development@ itcampro # itcamp12 Premium conference on Microsoft technologies
  40. 40. Mobile &In ASP.Net – updated support Development• Install-Package Microsoft.WebSocketsRouteTable.Routes.Add(new ServiceRoute("connect", new WebSocketServiceHostFactory(), typeof(GameService)));public class GameService : WebSocketService { private static GameServer server = new GameServer(); private GameConnection connection; public override void OnOpen() { string nickname = QueryParameters["nickname"]; int gameSize = int.Parse(QueryParameters["gamesize"]); connection = server.JoinGame(this, nickname, gameSize); } public override void OnMessage(string message) { connection.ProcessCommand(message); } protected override void OnClose() { if(connection != null) connection.Disconnect(); } }}@ itcampro # itcamp12 Premium conference on Microsoft technologies
  41. 41. WEBSOCKETS DEMO@ itcampro # itcamp12 Premium conference on Microsoft technologies
  42. 42. Q&A@ itcampro # itcamp12 Premium conference on Microsoft technologies

×