SlideShare une entreprise Scribd logo
1  sur  25
ASP.NET MVC 5 and SignalR 2
Jaliya Udagedara
MVP – Visual Studio and Development Technologies
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
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?
Transports
• HTML 5 Transports
• WebSocket
• Server Sent Events (AKA EventSource)
• Comet Transports (long-held HTTP requests)
• Forever Frame
• Ajax Long Polling
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
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
Transports contd.
• Specifying a Transport
// fallback order from left to right
connection.start(
{
transport: ['webSockets’, 'longPolling’]
});
// string constants: webSockets, serverSentEvents, foreverFrame, longPolling
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
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
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
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
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
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.
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
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;
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
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
})
Hubs API Guide: Client (JavaScript) contd.
• Connection Lifetime Events
• starting
• received
• connectionSlow
• reconnecting
• reconnected
• stateChanged
• disconnected
Understanding Lifetime Events
• Connection Types
• SignalR connection
• Transport connection
• Physical connection
• Disconnection Scenarios
• Transport disconnection scenarios
• Client disconnection scenarios
• Server disconnection scenarios
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
Performance
• Scale Up vs Scale Out
• Scale Out
• Azure Service Bus
• Redis
• SQL Server
• Backplane
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)
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
Resources
• SignalR 2 Documentation
• Sample Code
Q & A

Contenu connexe

Tendances

Tendances (20)

Connector API Apps
Connector API AppsConnector API Apps
Connector API Apps
 
SPS calgary 2017 introduction to azure functions microsoft flow
SPS calgary 2017 introduction to azure functions microsoft flowSPS calgary 2017 introduction to azure functions microsoft flow
SPS calgary 2017 introduction to azure functions microsoft flow
 
First Look at Azure Logic Apps (BAUG)
First Look at Azure Logic Apps (BAUG)First Look at Azure Logic Apps (BAUG)
First Look at Azure Logic Apps (BAUG)
 
Azure functions
Azure functionsAzure functions
Azure functions
 
Serverless patterns v2 public
Serverless patterns v2 publicServerless patterns v2 public
Serverless patterns v2 public
 
Debugging your Way through .NET with Visual Studio 2015
Debugging your Way through .NET with Visual Studio 2015Debugging your Way through .NET with Visual Studio 2015
Debugging your Way through .NET with Visual Studio 2015
 
Serverless patterns v3 public
Serverless patterns v3 publicServerless patterns v3 public
Serverless patterns v3 public
 
What is IBM Bluemix , Une nouvelle façon de coder , dans le cloud
What is IBM Bluemix , Une nouvelle façon de coder , dans le cloudWhat is IBM Bluemix , Une nouvelle façon de coder , dans le cloud
What is IBM Bluemix , Une nouvelle façon de coder , dans le cloud
 
O365Con18 - Working with PowerShell, VS Code and GitHub - Thomas Vochten
O365Con18 - Working with PowerShell, VS Code and GitHub - Thomas VochtenO365Con18 - Working with PowerShell, VS Code and GitHub - Thomas Vochten
O365Con18 - Working with PowerShell, VS Code and GitHub - Thomas Vochten
 
SenchaCon 2016: Developing and Delivering Quality Code, Frequently - Neil Manvar
SenchaCon 2016: Developing and Delivering Quality Code, Frequently - Neil ManvarSenchaCon 2016: Developing and Delivering Quality Code, Frequently - Neil Manvar
SenchaCon 2016: Developing and Delivering Quality Code, Frequently - Neil Manvar
 
O365Con18 - Implementing Automated UI Testing for SharePoint Solutions - Elio...
O365Con18 - Implementing Automated UI Testing for SharePoint Solutions - Elio...O365Con18 - Implementing Automated UI Testing for SharePoint Solutions - Elio...
O365Con18 - Implementing Automated UI Testing for SharePoint Solutions - Elio...
 
Using PowerShell DSC with AWS Cloud and CloudFormation
Using PowerShell DSC with AWS Cloud and CloudFormationUsing PowerShell DSC with AWS Cloud and CloudFormation
Using PowerShell DSC with AWS Cloud and CloudFormation
 
SenchaCon 2016: The Changing Landscape of JavaScript Testing - Joel Watson an...
SenchaCon 2016: The Changing Landscape of JavaScript Testing - Joel Watson an...SenchaCon 2016: The Changing Landscape of JavaScript Testing - Joel Watson an...
SenchaCon 2016: The Changing Landscape of JavaScript Testing - Joel Watson an...
 
Techorama migrate to sharepoint framework
Techorama migrate to sharepoint frameworkTechorama migrate to sharepoint framework
Techorama migrate to sharepoint framework
 
Tfs Build vNext (Jelle Druyts)
Tfs Build vNext (Jelle Druyts)Tfs Build vNext (Jelle Druyts)
Tfs Build vNext (Jelle Druyts)
 
SPS vancouver is it possible to do devops with SharePoint Framework
SPS vancouver is it possible to do devops with SharePoint FrameworkSPS vancouver is it possible to do devops with SharePoint Framework
SPS vancouver is it possible to do devops with SharePoint Framework
 
Get Started with ASP.NET Core Training, Tutorial - Beginner to Advance
Get Started with ASP.NET Core Training, Tutorial - Beginner to AdvanceGet Started with ASP.NET Core Training, Tutorial - Beginner to Advance
Get Started with ASP.NET Core Training, Tutorial - Beginner to Advance
 
Developing Infrastructure Code for CI & CD
Developing Infrastructure Code for CI & CDDeveloping Infrastructure Code for CI & CD
Developing Infrastructure Code for CI & CD
 
Serverless Summit - Quiz
Serverless Summit - QuizServerless Summit - Quiz
Serverless Summit - Quiz
 
Azure Integration DTAP Series, How to go from Development to Production – Par...
Azure Integration DTAP Series, How to go from Development to Production – Par...Azure Integration DTAP Series, How to go from Development to Production – Par...
Azure Integration DTAP Series, How to go from Development to Production – Par...
 

Similaire à ASP.NET MVC 5 and SignalR 2

Real time Communication with Signalr (Android Client)
Real time Communication with Signalr (Android Client)Real time Communication with Signalr (Android Client)
Real time Communication with Signalr (Android Client)
Deepak Gupta
 
SignalR Dublin ALT.NET
SignalR Dublin ALT.NETSignalR Dublin ALT.NET
SignalR Dublin ALT.NET
Dorin Manoli
 

Similaire à ASP.NET MVC 5 and SignalR 2 (20)

Introduction to SignalR
Introduction to SignalRIntroduction to SignalR
Introduction to SignalR
 
Real-time web applications using SharePoint, SignalR and Azure Service Bus
Real-time web applications using SharePoint, SignalR and Azure Service BusReal-time web applications using SharePoint, SignalR and Azure Service Bus
Real-time web applications using SharePoint, SignalR and Azure Service Bus
 
Real time Communication with Signalr (Android Client)
Real time Communication with Signalr (Android Client)Real time Communication with Signalr (Android Client)
Real time Communication with Signalr (Android Client)
 
signalr
signalrsignalr
signalr
 
Realtime web experience with signal r
Realtime web experience with signal rRealtime web experience with signal r
Realtime web experience with signal r
 
Windows 8 Metro apps and the outside world
Windows 8 Metro apps and the outside worldWindows 8 Metro apps and the outside world
Windows 8 Metro apps and the outside world
 
Windows 8 Apps and the Outside World
Windows 8 Apps and the Outside WorldWindows 8 Apps and the Outside World
Windows 8 Apps and the Outside World
 
SignalR Dublin ALT.NET
SignalR Dublin ALT.NETSignalR Dublin ALT.NET
SignalR Dublin ALT.NET
 
Building Real Time Applications with ASP.NET SignalR 2.0 by Rachel Appel
Building Real Time Applications with ASP.NET SignalR 2.0 by Rachel AppelBuilding Real Time Applications with ASP.NET SignalR 2.0 by Rachel Appel
Building Real Time Applications with ASP.NET SignalR 2.0 by Rachel Appel
 
Realtime web experience with signalR
Realtime web experience with signalRRealtime web experience with signalR
Realtime web experience with signalR
 
Asynchrone Echtzeitanwendungen für SharePoint mit SignalR und knockout.js
Asynchrone Echtzeitanwendungen für SharePoint mit SignalR und knockout.jsAsynchrone Echtzeitanwendungen für SharePoint mit SignalR und knockout.js
Asynchrone Echtzeitanwendungen für SharePoint mit SignalR und knockout.js
 
Nick Raienko ''Service-oriented GraphQL''
Nick Raienko ''Service-oriented GraphQL''Nick Raienko ''Service-oriented GraphQL''
Nick Raienko ''Service-oriented GraphQL''
 
Azure signalr service
Azure signalr serviceAzure signalr service
Azure signalr service
 
Real time web apps
Real time web appsReal time web apps
Real time web apps
 
AWS Lambda in C#
AWS Lambda in C#AWS Lambda in C#
AWS Lambda in C#
 
SRV418 Deep Dive on Accelerating Content, APIs, and Applications with Amazon ...
SRV418 Deep Dive on Accelerating Content, APIs, and Applications with Amazon ...SRV418 Deep Dive on Accelerating Content, APIs, and Applications with Amazon ...
SRV418 Deep Dive on Accelerating Content, APIs, and Applications with Amazon ...
 
IT2255 Web Essentials - Unit V Servlets and Database Connectivity
IT2255 Web Essentials - Unit V Servlets and Database ConnectivityIT2255 Web Essentials - Unit V Servlets and Database Connectivity
IT2255 Web Essentials - Unit V Servlets and Database Connectivity
 
Real-time Communications with SignalR
Real-time Communications with SignalRReal-time Communications with SignalR
Real-time Communications with SignalR
 
Progressive Web Apps
Progressive Web AppsProgressive Web Apps
Progressive Web Apps
 
Tokyo Azure Meetup #7 - Introduction to Serverless Architectures with Azure F...
Tokyo Azure Meetup #7 - Introduction to Serverless Architectures with Azure F...Tokyo Azure Meetup #7 - Introduction to Serverless Architectures with Azure F...
Tokyo Azure Meetup #7 - Introduction to Serverless Architectures with Azure F...
 

Plus de Jaliya Udagedara

Getting Started Developing Universal Windows Platform (UWP) Apps
Getting Started Developing Universal Windows Platform (UWP) AppsGetting Started Developing Universal Windows Platform (UWP) Apps
Getting Started Developing Universal Windows Platform (UWP) Apps
Jaliya Udagedara
 
Windows Phone Application Development
Windows Phone Application DevelopmentWindows Phone Application Development
Windows Phone Application Development
Jaliya Udagedara
 
Universal Apps for Windows Devices
Universal Apps for Windows DevicesUniversal Apps for Windows Devices
Universal Apps for Windows Devices
Jaliya Udagedara
 
Lambda Expressions in C# From Beginner To Expert - Jaliya Udagedara
Lambda Expressions in C# From Beginner To Expert - Jaliya UdagedaraLambda Expressions in C# From Beginner To Expert - Jaliya Udagedara
Lambda Expressions in C# From Beginner To Expert - Jaliya Udagedara
Jaliya Udagedara
 
Lap Around Entity Framework
Lap Around Entity FrameworkLap Around Entity Framework
Lap Around Entity Framework
Jaliya Udagedara
 
Lap Around Entity Framework
Lap Around Entity FrameworkLap Around Entity Framework
Lap Around Entity Framework
Jaliya Udagedara
 
Windows communication foundation (part2) jaliya udagedara
Windows communication foundation (part2) jaliya udagedaraWindows communication foundation (part2) jaliya udagedara
Windows communication foundation (part2) jaliya udagedara
Jaliya Udagedara
 

Plus de Jaliya Udagedara (18)

Serverless Computing With Azure Functions
Serverless Computing With Azure FunctionsServerless Computing With Azure Functions
Serverless Computing With Azure Functions
 
Getting Started Developing Universal Windows Platform (UWP) Apps
Getting Started Developing Universal Windows Platform (UWP) AppsGetting Started Developing Universal Windows Platform (UWP) Apps
Getting Started Developing Universal Windows Platform (UWP) Apps
 
Introduction to Universal Apps-Jaliya Udagedara
Introduction to Universal Apps-Jaliya UdagedaraIntroduction to Universal Apps-Jaliya Udagedara
Introduction to Universal Apps-Jaliya Udagedara
 
Building Universal Apps for Windows and Windows Phone
Building Universal Apps for Windows and Windows PhoneBuilding Universal Apps for Windows and Windows Phone
Building Universal Apps for Windows and Windows Phone
 
Introduction to Universal Apps
Introduction to Universal AppsIntroduction to Universal Apps
Introduction to Universal Apps
 
Let's Explore C# 6
Let's Explore C# 6Let's Explore C# 6
Let's Explore C# 6
 
Windows Runtime Apps
Windows Runtime AppsWindows Runtime Apps
Windows Runtime Apps
 
Windows Runtime Apps
Windows Runtime AppsWindows Runtime Apps
Windows Runtime Apps
 
Universal Apps for Windows Devices
Universal Apps for Windows DevicesUniversal Apps for Windows Devices
Universal Apps for Windows Devices
 
Debugging C# Applications
Debugging C# ApplicationsDebugging C# Applications
Debugging C# Applications
 
Windows Phone Application Development
Windows Phone Application DevelopmentWindows Phone Application Development
Windows Phone Application Development
 
Universal Apps for Windows Devices
Universal Apps for Windows DevicesUniversal Apps for Windows Devices
Universal Apps for Windows Devices
 
Lambda Expressions in C# From Beginner To Expert - Jaliya Udagedara
Lambda Expressions in C# From Beginner To Expert - Jaliya UdagedaraLambda Expressions in C# From Beginner To Expert - Jaliya Udagedara
Lambda Expressions in C# From Beginner To Expert - Jaliya Udagedara
 
Lap Around Entity Framework
Lap Around Entity FrameworkLap Around Entity Framework
Lap Around Entity Framework
 
Lap Around Entity Framework
Lap Around Entity FrameworkLap Around Entity Framework
Lap Around Entity Framework
 
Generics In and Out
Generics In and OutGenerics In and Out
Generics In and Out
 
Windows communication foundation (part2) jaliya udagedara
Windows communication foundation (part2) jaliya udagedaraWindows communication foundation (part2) jaliya udagedara
Windows communication foundation (part2) jaliya udagedara
 
Windows communication foundation (part1) jaliya udagedara
Windows communication foundation (part1)    jaliya udagedaraWindows communication foundation (part1)    jaliya udagedara
Windows communication foundation (part1) jaliya udagedara
 

Dernier

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Dernier (20)

Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
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 })
  • 18. Hubs API Guide: Client (JavaScript) contd. • Connection Lifetime Events • starting • received • connectionSlow • reconnecting • reconnected • stateChanged • disconnected
  • 19. Understanding Lifetime Events • Connection Types • SignalR connection • Transport connection • Physical connection • Disconnection Scenarios • Transport disconnection scenarios • Client disconnection scenarios • Server disconnection scenarios
  • 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
  • 24. Resources • SignalR 2 Documentation • Sample Code
  • 25. Q & A

Notes de l'éditeur

  1. 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
  2. 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
  3. 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)
  4. 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.
  5. Persistent Connections Low Level Hubs High Level
  6. Explain: Make sure that the SignalR route is added before the other routes : Why?
  7. 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
  8. 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.
  9. 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).
  10. 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
  11. 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.
  12. Should have atleast 1 event handler, Otherwise OnConnection will not trigger
  13. 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.
  14. 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
  15. [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.
  16. 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.
  17. 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 
  18. 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