Exploring the Future Potential of AI-Enabled Smartphone Processors
ASP.NET MVC 5 and SignalR 2
1. ASP.NET MVC 5 and SignalR 2
Jaliya Udagedara
MVP – Visual Studio and Development Technologies
2. Line Up
• What is SignalR
• Transports
• Supported Platforms
• Connections and Hubs
• Demo
• Hubs API Guide
• Server (C#)
• Client (JavaScript)
• Understanding Lifetime Events
• Security
• Performance
• What’s Next: ASP.NET Core SignalR
3. What is SignalR
• Library for adding REAL-TIME web functionality to applications
• Candidates for SignalR,
• User needs to do a refresh to see new data
• Page implements long polling to retrieve new data etc.
• Possible applications?
4. Transports
• HTML 5 Transports
• WebSocket
• Server Sent Events (AKA EventSource)
• Comet Transports (long-held HTTP requests)
• Forever Frame
• Ajax Long Polling
5. Transports contd.
• SignalR starts as HTTP, then if possible promoting to WebSockets
• Transport Selection Process
• If the browser is IE 8 or earlier
then Long Polling
• If JSONP is configured
then Long Polling
• If Cross Domain AND Client Supports WebSockets AND Server Supports WebSockets
then WebSockets
Else
then Long Polling
• If JSONP is NOT configured AND NOT Cross Domain AND Client Supports WebSockets
AND Server Supports WebSockets
then WebSockets
Else
then Long Polling
6. Transports contd.
• Transport Selection Process contd.
• If Client or Server does NOT support WebSockets
If Server Side Events is NOT Available
If Forever Frame is NOT Available
then Long Polling
Else
then Forever Frame
Else
then Server Side Events
Else
WebSockets
7. Transports contd.
• Specifying a Transport
// fallback order from left to right
connection.start(
{
transport: ['webSockets’, 'longPolling’]
});
// string constants: webSockets, serverSentEvents, foreverFrame, longPolling
8. Supported Platforms
• Server System Requirements
• Windows Server 2008 r2, Windows 7 or above
• .NET Framework 4.5 or above
• WebSockets
• Windows Server 2012, Windows 8 or above
• IIS 8 or IIS 8 Express
• WebSocket must be enabled in IIS
• Client System Requirements
• Web Browsers
• Windows Desktop and Silverlight Applications
• Windows Store and Windows Phone Applications
• Visit the documentation
9. Connections and Hubs
• The SignalR API contains two models for communicating between
clients and servers
• Persistent Connections
• Hubs
• Choosing a communication model
• Most applications should use the Hubs
• More advance, then Persistent Connections
• Today, we will be moving ahead with Hubs
10. Demo
• Create a Server Application
• Install SignalR
• Map SignalR to app builder pipeline
• Add a Hub
• Creating a Client Application
• Install SignalR Client (JS, .NET, Java etc.) and add references
• Start the connection
• Start Cracking
11. Hubs API Guide: Server (C#)
• Adding SignalR to app builder pipeline
• app.MapSignalR()
• Overloads
• Can configure URL
• Enable CORS
• Enable detailed error messages
• Disable automatically generated JavaScript proxy files
• Make sure that the SignalR route is added before the other routes
12. Hubs API Guide: Server (C#) contd.
• Object Lifetime
• Transient
• How to maintain state
• Static variable on the Hub class
• Different class
• Database
• Defining Methods
• Defining Overloads
13. Hubs API Guide: Server (C#) contd.
• Call client methods from the Hub class
• Selecting which clients will receive the RPC
• All
• Caller
• Others
• Client(connectionId)
• Clients(ConnectionIds)
• AllExcept(connectionId1, connectionId2)
• Group(groupName)
• Group(groupName, connectionId1, connectionId2)
contd.
14. Hubs API Guide: Server (C#) contd.
• Selecting which clients will receive the RPC contd.
• OthersInGroup(groupName)
• User(userid)
• Groups(groupIds)
• Client(userName)
• Users(new string[] { "myUser", "myUser2" })
• Groups
• A group can have any number of clients, and a client can be a member of any
number of groups
15. Hubs API Guide: Server (C#) contd.
• Connection lifetime events
• OnConnected
• OnReconnected
• OnDisconnected
• Passing state between Client and Server
• Client Side (JavaScript)
• myHub.state.userName = “John Smith";
• Hub
• string userName = Clients.Caller.userName;
16. Hubs API Guide: Client (JavaScript)
• Generated Proxy
• {endpoint}/hubs => signalr/hubs
• Dynamically generated JavaScript code, not to a physical file
• Can create a physical file if you prefer to
• You can still communicate with SignalR Service without a Proxy
17. Hubs API Guide: Client (JavaScript) contd.
• Establishing a connection
• Create a connection proxy
var myHub = $.connection.myHub;
• Register event handlers for methods that can be called from the server
myHub.client.addMessageToPage = function() { … }
• Start connection
$.connection.hub.start().done(function(){
// will get called after OnConnected on Server
})
20. Security
• Authorize hub or method
• [Authorize]
• [Authorize(Roles = "Admin,Manager")]
• [Authorize(Users = "user1,user2")]
• [Authorize(RequireOutgoing=false)]
• Existing Authentication Mechanism
• Connection Token (Connection ID and Username)
• CSRF (Cross-Site Request Forgery)
• CSRF mitigations taken by SignalR
• Disable cross domain requests
• Pass connection token in query string, not cookie
• Verify connection token
21. Performance
• Scale Up vs Scale Out
• Scale Out
• Azure Service Bus
• Redis
• SQL Server
• Backplane
22. What’s Next: ASP.NET Core SignalR
• Reimagined as ASP.NET Core Sockets
• Removed:
• No more jQuery dependency
• No more auto-reconnect with message replay
• No more Hub-state
• No more multi hub endpoints
• No more single-model scale-out
• No more multi server ping-pong (now require sticky connections)
23. What’s Next: ASP.NET Core SignalR contd.
• Introduced:
• Binary data support
• Host agnostic (Non HTTP Transports)
• All new connection level “Endpoints” API
• Multiple protocols/formats support, JSON, Protobuf, Custom etc.
• Support “pure” WebSocket clients
• Return results from client methods invocation
• TypeScript client
• Flexible scale-out extensibility
What is real-time?
Ability for the Server to push content to connected clients instantly, rather than having the client to request new data
Possible Applications
Dashboards
Monitoring Applications
Collaborative Applications
Real-time Gaming
WebSocket
Duplex
Persistent communication
TCP
Server Sent Events
All browsers except Internet Explorer
Forever Frame
Internet Explorer Only
Hidden iFrame
Two Way but separate connections
Ajax long polling
Long AJAX Request
Timeout
Reconnect
JSONP (JSON with Padding) is a method commonly used to bypass the cross-domain policies in web browsers.
If JSONP is configured => jsonp parameter is set to true when the connection is started
Cross-Origin Resource Sharing (CORS)
Negotiating a transport takes a certain amount of time and client/server resources.
If the client capabilities are known, then a transport can be specified when the client connection is started.
Persistent Connections
Low Level
Hubs
High Level
Explain: Make sure that the SignalR route is added before the other routes : Why?
Object Lifetime
SignalR creates a new instance of your Hub class each time it needs to handle a Hub operation such as when a client connects, disconnects, or makes a method call to the server
Defining Methods
Hub names, method names are Camel-cased by default in JavaScript clients
Can use HubName and HubMethodName attributes to override
Defining Overloads
On Server side, changing parameter types is fine, but on JavaScript side that will throw an error.
So when overloading, number of parameters should be different
All // All connected clients.
Caller // Only the calling client.
Others // All clients except the calling client.
Client(connectionId) // A specific client identified by connection ID.
Clients(ConnectionIds) // All clients and groups in a list of connection IDs.
AllExcept(connectionId1, connectionId2) // All connected clients except the specified clients, identified by connection ID.
Group(groupName) // All connected clients in a specified group.
Group(groupName, connectionId1, connectionId2) // All connected clients in a specified group except the specified clients, identified by connection ID.
OthersInGroup(groupName) // All connected clients in a specified group except the calling client.
User(userid) // A specific user, identified by userId. IPrincipal.Identity.Name
Groups(groupIds) // A list of groups.
Client(username) // A user by name.
Users(new string[] { "myUser", "myUser2" }) // A list of user names (introduced in SignalR 2.1).
A possible sequence of events for a given client is,
OnConnected, OnReconnected, OnDisconnected
OnConnected, OnDisconnected.
You won't see the sequence OnConnected, OnDisconnected, OnReconnected
Passing state between Client and Server
Clients.Caller property is not populated for the connection lifetime event handler methods OnConnected, OnDisconnected, and OnReconnected
What the proxy does for you is simplify the syntax of the code you use to connect, write methods that the server calls, and call methods on the server.
Should have atleast 1 event handler, Otherwise OnConnection will not trigger
starting: Raised before any data is sent over the connection.
received: Raised when any data is received on the connection. Provides the received data.
connectionSlow: Raised when the client detects a slow or frequently dropping connection.
reconnecting: Raised when the underlying transport begins reconnecting.
reconnected: Raised when the underlying transport has reconnected.
stateChanged: Raised when the connection state changes. Provides the old state and the new state (Connecting, Connected, Reconnecting, or Disconnected).
disconnected: Raised when the connection has disconnected.
https://docs.microsoft.com/en-us/aspnet/signalr/overview/guide-to-the-api/handling-connection-lifetime-events
Disconnection Scenarios
Transport disconnection scenarios
Connection loss in SignalR, Transport or Physical connection
Client disconnection scenarios
Navigates to a new page or refreshes the page
Closes a browser window or tab
Server disconnection scenarios
Reboot
Crash
App domain recycle
[Authorize]
[Authorize(Roles = "Admin,Manager")]
[Authorize(Users = "user1,user2")]
[Authorize(RequireOutgoing=false)]
Only authenticated users can invoke the hub, no restriction on receiving
The RequireOutgoing property can only be applied to the entire hub, not on individuals methods within the hub.
Each server instance connects to the backplane through the bus. When a message is sent, it goes to the backplane, and the backplane sends it to every server. When a server gets a message from the backplane, it puts the message in its local cache. The server then delivers messages to clients from its local cache.
Limitations
Server broadcast : Works Well
Client-to-client (e.g., chat): In this scenario, the backplane might be a bottleneck if the number of messages scales with the number of clients; that is, if the rate of messages grows proportionally as more clients join.
High-frequency real-time (e.g., real-time games): A backplane is not recommended for this scenario.
No more auto-reconnect with message replay
SignalR was developed keeping Long polling in mind.
When the connection drops, SignalR stores the messages, this should be a Application Concern
No more single-model scale-out
Server broadcast : Works Well
Client-to-client (e.g., chat): In this scenario, the backplane might be a bottleneck if the number of messages scales with the number of clients; that is, if the rate of messages grows proportionally as more clients join.
No more multi server ping-pong (now require sticky connections)
Sticky connections - All your requests will be directed to the same physical server
Host agnostic (Non HTTP Transports)
TCP Clients
All new connection level “Endpoints” API
No more Persistent Connections
Multiple protocols/formats support, JSON, Protobuf, Custom etc.
Protobuf: Protocol Buffers - Google's data interchange format
Support “pure” WebSocket clients
Not bound to Microsoft created libraries
Your own code