- •Contents at a Glance
- •Introduction
- •Who should read this book
- •Assumptions
- •Who should not read this book
- •Organization of this book
- •Finding your best starting point in this book
- •Conventions and features in this book
- •System requirements
- •Code samples
- •Notes on the version
- •Installing the code samples
- •Using the code samples
- •Acknowledgments
- •Errata & book support
- •We want to hear from you
- •Stay in touch
- •HTTP operations
- •Polling: The answer?
- •Push: The server takes the initiative
- •WebSockets
- •Server-Sent Events (API Event Source)
- •Push today
- •The world needs more than just push
- •What does SignalR offer?
- •Two levels of abstraction
- •Supported platforms
- •OWIN and Katana: The new kids on the block
- •Installing SignalR
- •Implementation on the server side
- •Mapping and configuring persistent connections
- •Events of a persistent connection
- •Sending messages to clients
- •Asynchronous event processing
- •Connection groups
- •The OWIN startup class
- •Implementation on the client side
- •Initiating the connection by using the JavaScript client
- •Support for older browsers
- •Support for cross-domain connections
- •Sending messages
- •Receiving messages
- •Sending additional information to the server
- •Other events available at the client
- •Transport negotiation
- •Adjusting SignalR configuration parameters
- •Complete example: Tracking visitors
- •Project creation and setup
- •Implementation on the client side
- •Implementation on the server side
- •Server implementation
- •Hub registration and configuration
- •Creating hubs
- •Receiving messages
- •Sending messages to clients
- •Sending messages to specific users
- •State maintenance
- •Accessing information about the request context
- •Notification of connections and disconnections
- •Managing groups
- •Maintaining state at the server
- •Client implementation
- •JavaScript clients
- •Generating the proxy
- •Manual generation of JavaScript proxies
- •Establishing the connection
- •Sending messages to the server
- •Sending additional information
- •Receiving messages sent from the server
- •Logging
- •State maintenance
- •Implementing the client without a proxy
- •Complete example: Shared drawing board
- •Project creation and setup
- •Implementation on the client side
- •Implementation on the server side
- •Access from other threads
- •External access using persistent connections
- •Complete example: Monitoring connections at the server
- •Project creation and setup
- •Implementing the website
- •System for tracing requests (server side)
- •System for tracing requests (client side)
- •External access using hubs
- •Complete example: Progress bar
- •Project creation and setup
- •Implementation on the client side
- •Implementation on the server side
- •Multiplatform SignalR servers
- •SignalR hosting in non-web applications
- •SignalR hosting in platforms other than Windows
- •Multiplatform SignalR clients
- •Accessing services from .NET non-web clients
- •Consumption of services from other platforms
- •Growing pains
- •Scalability in SignalR
- •Scaling on backplanes
- •Windows Azure Service Bus
- •SQL Server
- •Redis
- •Custom backplanes
- •Improving performance in SignalR services
- •Server configuration
- •Monitoring performance
- •Authorization in SignalR
- •Access control in persistent connections
- •Access control in hubs
- •Client authentication
- •An extensible framework
- •Dependency Injection
- •Manual dependency injection
- •Releasing dependencies
- •Inversion of Control containers
- •Unit testing with SignalR
- •Unit testing of hubs
- •Unit testing persistent connections
- •Intercepting messages in hubs
- •Integration with other frameworks
- •Knockout
- •AngularJS
- •Index
- •About the author
FIGURE 6-3 System for tracing connections in operation.
Project creation and setup
For the purpose of creating the application that we will develop over the following pages, it is necessary to first create a project of the “ASP.NET Web Application” type from Visual Studio 2013 and then select the “Empty” template to create a completely empty project1. The version of the .NET Framework used must be at least 4.5.
After we have created it, we must install the following package using NuGet:
PM> install-package Microsoft.AspNet.SignalR
1 In Visual Studio 2012, we can achieve the same goal by creating a project from the template “ASP.NET Empty Web Application.”
Persistent connections and hubs from other threads Chapter 6 |
107 |
www.it-ebooks.info
Implementing the website
Page markup (default.aspx)
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="ConnectionSpy.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server">
<title><%: Title %></title>
<script src="Scripts/jquery-1.6.4.min.js"></script> </head>
<body>
<h1><%: Title %></h1>
<form id="form1" runat="server"> <div>
<p>This is the content of the <%: Title %></p> <h3>Navigation links</h3>
<asp:PlaceHolder runat="server" ID="placeHolder"> </asp:PlaceHolder>
</div>
<a href="Spy.html" target="_blank"> Spy requests (new window)
</a>
</form>
</body>
</html>
Code-behind (default.aspx.cs)
using System; using System.Text;
using System.Web.UI; namespace ConnectionSpy
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
int id;
this.Title = int.TryParse(Request["id"], out id) ? "Page " + id
: "Home page";
var html = new StringBuilder(); html.AppendLine("<ul>");
for (int i = 1; i < 11; i++)
{
var text = "Page " + i; var link = string.Format(
"<li><a href='Default.aspx?id={0}'>{1}</a></li>", i, text
);
108 Chapter 6 Persistent connections and hubs from other threads
www.it-ebooks.info
html.AppendFormat(link);
}
html.AppendLine("</ul>");
placeHolder.Controls.Add(
new LiteralControl(html.ToString())
);
}
}
}
System for tracing requests (server side)
Persistent connection (ConnectionSpy.cs)
using Microsoft.AspNet.SignalR
public class ConnectionSpy: PersistentConnection
{
}
Note that the body of the persistent connection is empty. We will not need to take control in it when the SignalR clients connect to it, nor will we need to send messages to clients from here; this will be done from the application global class, as we shall see in the “Application global class (Global.asax.cs)” code.
Startup code (Startup.cs)
using Owin;
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR<ConnectionSpy>("/spy");
}
}
Application global class (Global.asax.cs)
using System; using System.Web;
using Microsoft.AspNet.SignalR;
public class Global : HttpApplication
{
private static IPersistentConnectionContext connSpy = GlobalHost.ConnectionManager.GetConnectionContext<ConnectionSpy>();
protected void Application_BeginRequest(object sender, EventArgs e)
{
var context = ((HttpApplication)sender).Context; var message = string.Format(
Persistent connections and hubs from other threads Chapter 6 |
109 |
www.it-ebooks.info
"{0}: Requested '{1}' from IP {2} using {3}", DateTime.Now.ToShortTimeString(), context.Request.Url.ToString(), context.Request.UserHostAddress, context.Request.Browser.Type
);
connSpy.Connection.Broadcast(message);
}
}
We could also have implemented this same process as OWIN middleware, instead of doing it in the application global class. In that case, the module would be the following:
using System;
using System.Threading.Tasks; using Microsoft.AspNet.SignalR; using Microsoft.Owin;
public class SpyMiddleware : OwinMiddleware
{
private static IPersistentConnectionContext connSpy = GlobalHost.ConnectionManager.GetConnectionContext<ConnectionSpy>();
public SpyMiddleware(OwinMiddleware next): base(next) { }
public override Task Invoke(IOwinContext context)
{
var message = string.Format(
"{0}: Requested '{1}' from IP {2} using {3}", DateTime.Now.ToShortTimeString(), context.Request.Uri.ToString(), context.Request.Host, context.Request.Headers["USER-AGENT"]
);
return Next.Invoke(context)
.ContinueWith(c => connSpy.Connection.Broadcast(message));
}
}
And to enter this module in the request processing pipeline, we would have to modify the configuration code:
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR<ConnectionSpy>("/spy");
app.Use<SpyMiddleware>();
}
}
110 Chapter 6 Persistent connections and hubs from other threads
www.it-ebooks.info