SlideShare a Scribd company logo
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
Mobile &
ITCamp 2012 sponsors                                                       Development




@   itcampro   # itcamp12   Premium conference on Microsoft technologies
Mobile &
Agenda                                                                     Development




• ASP.Net Web API
• SignalR
• WebSocket




@   itcampro   # itcamp12   Premium conference on Microsoft technologies
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
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
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
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
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
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
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
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
Mobile &
RESTful APIs example                                                               Development




Action                       HTTP verb           Relative URI
Get a list of all products   GET                 /api/products
Get a product by ID          GET                 /api/products/id
Get a product by category    GET                 /api/products?category=category
Create a new product         POST                /api/products
Update a product             PUT                 /api/products/id
Delete a product             DELETE              /api/products/id




@   itcampro       # itcamp12       Premium conference on Microsoft technologies
Mobile &
jQuery example                                                                  Development


jQuery 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
Mobile &
ASP.Net Web API routing                                                                Development


routes.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
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
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
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
WEB API DEMO


@   itcampro   # itcamp12   Premium conference on Microsoft technologies
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
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
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
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
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
Mobile &
IConnection API                                                            Development




• Task Broadcast(object value)
• Task Send(string signal, object value)




@   itcampro   # itcamp12   Premium conference on Microsoft technologies
Mobile &
External broadcasts                                                        Development




var 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
Mobile &
Hub (server)                                                                  Development


public 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
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
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
Mobile &
External broadcasts                                                        Development


var context =
GlobalHost.ConnectionManager.
GetHubContext<MyHub>();

context.Clients.say(message);




@   itcampro   # itcamp12   Premium conference on Microsoft technologies
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
SIGNALR DEMO


@   itcampro   # itcamp12   Premium conference on Microsoft technologies
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
Mobile &
Handshake                                                                      Development

Request:

GET /mychat HTTP/1.1
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==
Sec-WebSocket-Protocol: chat
Sec-WebSocket-Version: 13
Origin: http://example.com

Response:

HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: HSmrc0sMlYUkAGmm5OPpG2HaGWk=
Sec-WebSocket-Protocol: chat




@   itcampro   # itcamp12       Premium conference on Microsoft technologies
Mobile &
Javascript                                                                 Development


• Url: ws://yourhost/etc
     – wss: when used with SSL/TLS

var socket = new
WebSocket('ws://game.example.com:12010/update
s');
socket.onopen = function () {
   setInterval(function() {
     if (socket.bufferedAmount == 0)
       socket.send(getUpdateData());
   }, 50);
};
@   itcampro   # itcamp12   Premium conference on Microsoft technologies
Mobile &
Minimum requirements                                                       Development


•   IE 10
•   Chrome 4
•   Firefox 4
•   Safari 5
•   Opera 11

• Server: IIS 8



@   itcampro   # itcamp12   Premium conference on Microsoft technologies
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
Mobile &
IIS 8 – enable WebSockets feature                                          Development




@   itcampro   # itcamp12   Premium conference on Microsoft technologies
Mobile &
WCF 4.5 – HTTP Activation                                                  Development




@   itcampro   # itcamp12   Premium conference on Microsoft technologies
Mobile &
WCF 4.5                                                                    Development




@   itcampro   # itcamp12   Premium conference on Microsoft technologies
Mobile &
In ASP.Net – updated support                                                                        Development

•   Install-Package Microsoft.WebSockets
RouteTable.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
WEBSOCKETS DEMO


@   itcampro   # itcamp12   Premium conference on Microsoft technologies
Q&A


@   itcampro   # itcamp12   Premium conference on Microsoft technologies

More Related Content

PDF
Consuming ASP.NET Web API with WebSockets
Maayan Glikser
 
PDF
Node.js to the rescue
Marko Heijnen
 
KEY
ClubAJAX Basics - Server Communication
Mike Wilcox
 
PDF
Webservices: connecting Joomla! with other programs.
Herman Peeren
 
KEY
Flash And Dom
Mike Wilcox
 
PDF
A Day of REST
Scott Taylor
 
PDF
Beginning MEAN Stack
Rob Davarnia
 
PDF
Improve WordPress performance with caching and deferred execution of code
Danilo Ercoli
 
Consuming ASP.NET Web API with WebSockets
Maayan Glikser
 
Node.js to the rescue
Marko Heijnen
 
ClubAJAX Basics - Server Communication
Mike Wilcox
 
Webservices: connecting Joomla! with other programs.
Herman Peeren
 
Flash And Dom
Mike Wilcox
 
A Day of REST
Scott Taylor
 
Beginning MEAN Stack
Rob Davarnia
 
Improve WordPress performance with caching and deferred execution of code
Danilo Ercoli
 

What's hot (20)

PDF
WordPress Development Tools and Best Practices
Danilo Ercoli
 
PDF
Mobile Hybrid Development with WordPress
Danilo Ercoli
 
PDF
Sails.js Intro
Nicholas Jansma
 
PPTX
Making Watir and Cucumber an efficient tool for Web UI Automation
Ruslan Strazhnyk
 
PPTX
REST and ASP.NET Web API (Tunisia)
Jef Claes
 
PPS
J web socket
Hiroshi Ochi
 
PPTX
Large scale web socket system with AWS and Web socket
Le Kien Truc
 
PPTX
Codegen2021 blazor mobile
Jose Javier Columbie
 
PDF
Integrating Alfresco @ Scale (via event-driven micro-services)
J V
 
PDF
MEAN Stack WeNode Barcelona Workshop
Valeri Karpov
 
PPTX
Web assembly with PWA
Shashank Sharma
 
PDF
A 20 minute introduction to AngularJS for XPage developers
Mark Leusink
 
PDF
BeEF_EUSecWest-2012_Michele-Orru
Michele Orru
 
PPTX
ASP.NET Core 1.0
Ido Flatow
 
PDF
WEB SOCKET 應用
Jerromy Lee
 
PDF
PLAT-8 Spring Web Scripts and Spring Surf
Alfresco Software
 
PDF
React server side rendering performance
Nick Dreckshage
 
PPTX
Host, deploy & scale Blazor Server Apps
Jose Javier Columbie
 
KEY
Thats Not Flash?
Mike Wilcox
 
PPTX
Alfresco 5.0 Technology Review
Zia Consulting
 
WordPress Development Tools and Best Practices
Danilo Ercoli
 
Mobile Hybrid Development with WordPress
Danilo Ercoli
 
Sails.js Intro
Nicholas Jansma
 
Making Watir and Cucumber an efficient tool for Web UI Automation
Ruslan Strazhnyk
 
REST and ASP.NET Web API (Tunisia)
Jef Claes
 
J web socket
Hiroshi Ochi
 
Large scale web socket system with AWS and Web socket
Le Kien Truc
 
Codegen2021 blazor mobile
Jose Javier Columbie
 
Integrating Alfresco @ Scale (via event-driven micro-services)
J V
 
MEAN Stack WeNode Barcelona Workshop
Valeri Karpov
 
Web assembly with PWA
Shashank Sharma
 
A 20 minute introduction to AngularJS for XPage developers
Mark Leusink
 
BeEF_EUSecWest-2012_Michele-Orru
Michele Orru
 
ASP.NET Core 1.0
Ido Flatow
 
WEB SOCKET 應用
Jerromy Lee
 
PLAT-8 Spring Web Scripts and Spring Surf
Alfresco Software
 
React server side rendering performance
Nick Dreckshage
 
Host, deploy & scale Blazor Server Apps
Jose Javier Columbie
 
Thats Not Flash?
Mike Wilcox
 
Alfresco 5.0 Technology Review
Zia Consulting
 
Ad

Viewers also liked (8)

PPTX
Introdução ao ASP .NET Web API
Vinicius Mussak
 
PPTX
Online Shopping based on ASP .NET
Pragnya Dash
 
PPTX
HTML Basic, CSS Basic, JavaScript basic.
Beqa Chacha
 
PDF
JavaScript Programming
Sehwan Noh
 
PDF
Online Shopping System PPT
somarka
 
PPT
Flow of communication
Vibhor Agarwal
 
PPTX
Online Shopping Full Project Presentation (20 slides)
Krishna Mohan Shakya
 
PDF
Online shopping
gajapandiyan
 
Introdução ao ASP .NET Web API
Vinicius Mussak
 
Online Shopping based on ASP .NET
Pragnya Dash
 
HTML Basic, CSS Basic, JavaScript basic.
Beqa Chacha
 
JavaScript Programming
Sehwan Noh
 
Online Shopping System PPT
somarka
 
Flow of communication
Vibhor Agarwal
 
Online Shopping Full Project Presentation (20 slides)
Krishna Mohan Shakya
 
Online shopping
gajapandiyan
 
Ad

Similar to Building modern web sites with ASP .Net Web API, WebSockets and RSignal (20)

PDF
Mihai Tataran - Building Windows 8 Applications with HTML5 and JS
ITCamp
 
PPT
Building intranet applications with ASP.NET AJAX and jQuery
Alek Davis
 
PPTX
Serverless Single Page Apps with React and Redux at ItCamp 2017
Melania Andrisan (Danciu)
 
PPTX
Mihai tataran developing modern web applications
ITCamp
 
PPT
Building intranet applications with ASP.NET AJAX and jQuery
Alek Davis
 
PPTX
Social Photos - My presentation at Microsoft Tech Day
TechMaster Vietnam
 
PDF
App engine cloud_comp_expo_nyc
Chris Schalk
 
PPTX
The next step from Microsoft - Vnext (Srdjan Poznic)
Geekstone
 
PDF
"BlackBerry Webworks : Apps for The Smartphone and Tablet"
Software Park Thailand
 
PDF
ITCamp 2013 - Lorant Domokos - Chasing the one codebase, multiple platforms d...
ITCamp
 
PDF
Curriculum vitae of nguyen hai quy
Hai Quy Nguyen
 
PDF
ITCamp 2013 - Raffaele Rialdi - Windows Runtime (WinRT) deep dive
ITCamp
 
PDF
IBM Think Session 8598 Domino and JavaScript Development MasterClass
Paul Withers
 
PDF
전문가 토크릴레이 1탄 html5 전망 (전종홍 박사)
zinyus
 
PDF
전문가토크릴레이 1탄 html5 전망 (전종홍 박사)
Saltlux zinyus
 
PDF
ITCamp 2012 - Adam Granicz - Web development with WebSharper in F#
ITCamp
 
PDF
Exploring pwa for shopware
Sander Mangel
 
PDF
What's this jQuery? Where it came from, and how it will drive innovation
Marakana Inc.
 
PDF
C# Client to Cloud
Stuart Lodge
 
PPSX
Web development concepts using microsoft technologies
Hosam Kamel
 
Mihai Tataran - Building Windows 8 Applications with HTML5 and JS
ITCamp
 
Building intranet applications with ASP.NET AJAX and jQuery
Alek Davis
 
Serverless Single Page Apps with React and Redux at ItCamp 2017
Melania Andrisan (Danciu)
 
Mihai tataran developing modern web applications
ITCamp
 
Building intranet applications with ASP.NET AJAX and jQuery
Alek Davis
 
Social Photos - My presentation at Microsoft Tech Day
TechMaster Vietnam
 
App engine cloud_comp_expo_nyc
Chris Schalk
 
The next step from Microsoft - Vnext (Srdjan Poznic)
Geekstone
 
"BlackBerry Webworks : Apps for The Smartphone and Tablet"
Software Park Thailand
 
ITCamp 2013 - Lorant Domokos - Chasing the one codebase, multiple platforms d...
ITCamp
 
Curriculum vitae of nguyen hai quy
Hai Quy Nguyen
 
ITCamp 2013 - Raffaele Rialdi - Windows Runtime (WinRT) deep dive
ITCamp
 
IBM Think Session 8598 Domino and JavaScript Development MasterClass
Paul Withers
 
전문가 토크릴레이 1탄 html5 전망 (전종홍 박사)
zinyus
 
전문가토크릴레이 1탄 html5 전망 (전종홍 박사)
Saltlux zinyus
 
ITCamp 2012 - Adam Granicz - Web development with WebSharper in F#
ITCamp
 
Exploring pwa for shopware
Sander Mangel
 
What's this jQuery? Where it came from, and how it will drive innovation
Marakana Inc.
 
C# Client to Cloud
Stuart Lodge
 
Web development concepts using microsoft technologies
Hosam Kamel
 

More from Alessandro Pilotti (15)

PPTX
OpenStack and Windows - What's new in Ocata
Alessandro Pilotti
 
PPTX
Strategies for migrating workloads from VMware to OpenStack
Alessandro Pilotti
 
PPTX
Puppet + Windows Nano Server
Alessandro Pilotti
 
PPTX
OpenStack + Nano Server + Hyper-V + S2D
Alessandro Pilotti
 
PPTX
Building a Microsoft cloud with open technologies
Alessandro Pilotti
 
PPTX
OpenStack Summit 2013 Hong Kong - OpenStack and Windows
Alessandro Pilotti
 
PPTX
Interoperable OpenStack guest provisioning with Cloudbase-Init
Alessandro Pilotti
 
PPTX
OpenStack and Windows
Alessandro Pilotti
 
PPTX
An HTML5 client to connect to the Hyper-V console
Alessandro Pilotti
 
PPTX
Hyper-V OpenStack Nova Compute
Alessandro Pilotti
 
PPTX
Drupal, Memcache and Solr on Windows
Alessandro Pilotti
 
PPTX
PHP and FastCGI Performance Optimizations
Alessandro Pilotti
 
PPTX
Managing Drupal on Windows with Drush
Alessandro Pilotti
 
PPTX
Building drupal web farms with IIS - part 1
Alessandro Pilotti
 
PPTX
Windows Loves drupal
Alessandro Pilotti
 
OpenStack and Windows - What's new in Ocata
Alessandro Pilotti
 
Strategies for migrating workloads from VMware to OpenStack
Alessandro Pilotti
 
Puppet + Windows Nano Server
Alessandro Pilotti
 
OpenStack + Nano Server + Hyper-V + S2D
Alessandro Pilotti
 
Building a Microsoft cloud with open technologies
Alessandro Pilotti
 
OpenStack Summit 2013 Hong Kong - OpenStack and Windows
Alessandro Pilotti
 
Interoperable OpenStack guest provisioning with Cloudbase-Init
Alessandro Pilotti
 
OpenStack and Windows
Alessandro Pilotti
 
An HTML5 client to connect to the Hyper-V console
Alessandro Pilotti
 
Hyper-V OpenStack Nova Compute
Alessandro Pilotti
 
Drupal, Memcache and Solr on Windows
Alessandro Pilotti
 
PHP and FastCGI Performance Optimizations
Alessandro Pilotti
 
Managing Drupal on Windows with Drush
Alessandro Pilotti
 
Building drupal web farms with IIS - part 1
Alessandro Pilotti
 
Windows Loves drupal
Alessandro Pilotti
 

Recently uploaded (20)

PDF
A Day in the Life of Location Data - Turning Where into How.pdf
Precisely
 
PDF
Using Anchore and DefectDojo to Stand Up Your DevSecOps Function
Anchore
 
PDF
REPORT: Heating appliances market in Poland 2024
SPIUG
 
PDF
Automating ArcGIS Content Discovery with FME: A Real World Use Case
Safe Software
 
PDF
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
Artjoker Software Development Company
 
PDF
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
PDF
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
PDF
CIFDAQ's Market Wrap : Bears Back in Control?
CIFDAQ
 
PPTX
Applied-Statistics-Mastering-Data-Driven-Decisions.pptx
parmaryashparmaryash
 
PDF
Architecture of the Future (09152021)
EdwardMeyman
 
PDF
Software Development Company | KodekX
KodekX
 
PDF
NewMind AI Weekly Chronicles - July'25 - Week IV
NewMind AI
 
PDF
A Strategic Analysis of the MVNO Wave in Emerging Markets.pdf
IPLOOK Networks
 
PDF
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 
PDF
Software Development Methodologies in 2025
KodekX
 
PDF
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
PDF
How-Cloud-Computing-Impacts-Businesses-in-2025-and-Beyond.pdf
Artjoker Software Development Company
 
PDF
Beyond Automation: The Role of IoT Sensor Integration in Next-Gen Industries
Rejig Digital
 
PDF
Tea4chat - another LLM Project by Kerem Atam
a0m0rajab1
 
PDF
Brief History of Internet - Early Days of Internet
sutharharshit158
 
A Day in the Life of Location Data - Turning Where into How.pdf
Precisely
 
Using Anchore and DefectDojo to Stand Up Your DevSecOps Function
Anchore
 
REPORT: Heating appliances market in Poland 2024
SPIUG
 
Automating ArcGIS Content Discovery with FME: A Real World Use Case
Safe Software
 
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
Artjoker Software Development Company
 
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
CIFDAQ's Market Wrap : Bears Back in Control?
CIFDAQ
 
Applied-Statistics-Mastering-Data-Driven-Decisions.pptx
parmaryashparmaryash
 
Architecture of the Future (09152021)
EdwardMeyman
 
Software Development Company | KodekX
KodekX
 
NewMind AI Weekly Chronicles - July'25 - Week IV
NewMind AI
 
A Strategic Analysis of the MVNO Wave in Emerging Markets.pdf
IPLOOK Networks
 
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 
Software Development Methodologies in 2025
KodekX
 
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
How-Cloud-Computing-Impacts-Businesses-in-2025-and-Beyond.pdf
Artjoker Software Development Company
 
Beyond Automation: The Role of IoT Sensor Integration in Next-Gen Industries
Rejig Digital
 
Tea4chat - another LLM Project by Kerem Atam
a0m0rajab1
 
Brief History of Internet - Early Days of Internet
sutharharshit158
 

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

  • 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. Mobile & ITCamp 2012 sponsors Development @ itcampro # itcamp12 Premium conference on Microsoft technologies
  • 3. Mobile & Agenda Development • ASP.Net Web API • SignalR • WebSocket @ itcampro # itcamp12 Premium conference on Microsoft technologies
  • 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. 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. 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. 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. 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. 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. 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. 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. Mobile & RESTful APIs example Development Action HTTP verb Relative URI Get a list of all products GET /api/products Get a product by ID GET /api/products/id Get a product by category GET /api/products?category=category Create a new product POST /api/products Update a product PUT /api/products/id Delete a product DELETE /api/products/id @ itcampro # itcamp12 Premium conference on Microsoft technologies
  • 13. Mobile & jQuery example Development jQuery 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. Mobile & ASP.Net Web API routing Development routes.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. 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. 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. 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. WEB API DEMO @ itcampro # itcamp12 Premium conference on Microsoft technologies
  • 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. 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. 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. 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. 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. Mobile & IConnection API Development • Task Broadcast(object value) • Task Send(string signal, object value) @ itcampro # itcamp12 Premium conference on Microsoft technologies
  • 25. Mobile & External broadcasts Development var 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. Mobile & Hub (server) Development public 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. 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. 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. Mobile & External broadcasts Development var context = GlobalHost.ConnectionManager. GetHubContext<MyHub>(); context.Clients.say(message); @ itcampro # itcamp12 Premium conference on Microsoft technologies
  • 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. SIGNALR DEMO @ itcampro # itcamp12 Premium conference on Microsoft technologies
  • 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. Mobile & Handshake Development Request: GET /mychat HTTP/1.1 Host: server.example.com Upgrade: websocket Connection: Upgrade Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw== Sec-WebSocket-Protocol: chat Sec-WebSocket-Version: 13 Origin: http://example.com Response: HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: HSmrc0sMlYUkAGmm5OPpG2HaGWk= Sec-WebSocket-Protocol: chat @ itcampro # itcamp12 Premium conference on Microsoft technologies
  • 34. Mobile & Javascript Development • Url: ws://yourhost/etc – wss: when used with SSL/TLS var socket = new WebSocket('ws://game.example.com:12010/update s'); socket.onopen = function () { setInterval(function() { if (socket.bufferedAmount == 0) socket.send(getUpdateData()); }, 50); }; @ itcampro # itcamp12 Premium conference on Microsoft technologies
  • 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. 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. Mobile & IIS 8 – enable WebSockets feature Development @ itcampro # itcamp12 Premium conference on Microsoft technologies
  • 38. Mobile & WCF 4.5 – HTTP Activation Development @ itcampro # itcamp12 Premium conference on Microsoft technologies
  • 39. Mobile & WCF 4.5 Development @ itcampro # itcamp12 Premium conference on Microsoft technologies
  • 40. Mobile & In ASP.Net – updated support Development • Install-Package Microsoft.WebSockets RouteTable.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. WEBSOCKETS DEMO @ itcampro # itcamp12 Premium conference on Microsoft technologies
  • 42. Q&A @ itcampro # itcamp12 Premium conference on Microsoft technologies