ASP.net Signalr Hubs API Guide - .Net Client (c#) _ the ASP

14
8/10/2015 ASP.NET SignalR Hubs API Guide .NET Client (C#) | The ASP.NET Site http://www.asp.net/signalr/overview/guidetotheapi/hubsapiguidenetclient 1/14 This document provides an introduction to using the Hubs API for SignalR version 2 in .NET clients, such as Windows Store ﴾WinRT﴿, WPF, Silverlight, and console applications. The SignalR Hubs API enables you to make remote procedure calls ﴾RPCs﴿ from a server to connected clients and from clients to the server. In server code, you define methods that can be called by clients, and you call methods that run on the client. In client code, you define methods that can be called from the server, and you call methods that run on the server. SignalR takes care of all of the client‐to‐server plumbing for you. SignalR also offers a lower‐level API called Persistent Connections. For an introduction to SignalR, Hubs, and Persistent Connections, or for a tutorial that shows how to build a complete SignalR application, see SignalR ‐ Getting Started ﴾/signalr/overview/signalr‐20/getting‐started‐with‐signalr‐20﴿ . Software versions used in this topic Previous versions of this topic Questions and comments Overview This document contains the following sections: Client Setup ﴾#clientsetup﴿ How to establish a connection ﴾#establishconnection﴿ Cross‐domain connections from Silverlight clients ﴾#slcrossdomain﴿ How to configure the connection ﴾#configureconnection﴿ How to set the maximum number of concurrent connections in WPF clients ﴾#maxconnections﴿ How to specify query string parameters ﴾#querystring﴿ How to specify the transport method ﴾#transport﴿ How to specify HTTP headers ﴾#httpheaders﴿ How to specify client certificates ﴾#clientcertificate﴿ How to create the Hub proxy ﴾#proxy﴿ How to define methods on the client that the server can call ﴾#callclient﴿ Methods without parameters ﴾#clientmethodswithoutparms﴿ Methods with parameters, specifying parameter types ﴾#clientmethodswithparmtypes﴿ Methods with parameters, specifying dynamic objects for the parameters ﴾#clientmethodswithdynamparms﴿ How to remove a handler ﴾#removehandler﴿ By Tom Dykstra and Patrick Fletcher | June 10, 2014 | Level 100 : Beginner ASP.NET SignalR Hubs API Guide ‐ .NET Client ﴾C#﴿

description

ASP.NET SignalR Hubs API Guide - .NET Client (C#)

Transcript of ASP.net Signalr Hubs API Guide - .Net Client (c#) _ the ASP

Page 1: ASP.net Signalr Hubs API Guide - .Net Client (c#) _ the ASP

8/10/2015 ASP.NET SignalR Hubs API Guide ­ .NET Client (C#) | The ASP.NET Site

http://www.asp.net/signalr/overview/guide­to­the­api/hubs­api­guide­net­client 1/14

This document provides an introduction to using the Hubs API for SignalR version 2 in .NET clients, such asWindows Store ﴾WinRT﴿, WPF, Silverlight, and console applications.

The SignalR Hubs API enables you to make remote procedure calls ﴾RPCs﴿ from a server to connected clientsand from clients to the server. In server code, you define methods that can be called by clients, and you callmethods that run on the client. In client code, you define methods that can be called from the server, and youcall methods that run on the server. SignalR takes care of all of the client‐to‐server plumbing for you.

SignalR also offers a lower‐level API called Persistent Connections. For an introduction to SignalR, Hubs, andPersistent Connections, or for a tutorial that shows how to build a complete SignalR application, see SignalR ‐Getting Started ﴾/signalr/overview/signalr‐20/getting‐started‐with‐signalr‐20﴿ .

Software versions used in this topicPrevious versions of this topicQuestions and comments

OverviewThis document contains the following sections:

Client Setup ﴾#clientsetup﴿

How to establish a connection ﴾#establishconnection﴿

Cross‐domain connections from Silverlight clients ﴾#slcrossdomain﴿

How to configure the connection ﴾#configureconnection﴿

How to set the maximum number of concurrent connections in WPF clients ﴾#maxconnections﴿

How to specify query string parameters ﴾#querystring﴿

How to specify the transport method ﴾#transport﴿

How to specify HTTP headers ﴾#httpheaders﴿

How to specify client certificates ﴾#clientcertificate﴿

How to create the Hub proxy ﴾#proxy﴿

How to define methods on the client that the server can call ﴾#callclient﴿

Methods without parameters ﴾#clientmethodswithoutparms﴿

Methods with parameters, specifying parameter types ﴾#clientmethodswithparmtypes﴿

Methods with parameters, specifying dynamic objects for the parameters﴾#clientmethodswithdynamparms﴿

How to remove a handler ﴾#removehandler﴿

By Tom Dykstra and Patrick Fletcher | June 10, 2014 | Level 100 : Beginner

ASP.NET SignalR Hubs API Guide ‐ .NET Client﴾C#﴿

Page 2: ASP.net Signalr Hubs API Guide - .Net Client (c#) _ the ASP

8/10/2015 ASP.NET SignalR Hubs API Guide ­ .NET Client (C#) | The ASP.NET Site

http://www.asp.net/signalr/overview/guide­to­the­api/hubs­api­guide­net­client 2/14

How to call server methods from the client ﴾#callserver﴿

How to handle connection lifetime events ﴾#connectionlifetime﴿

How to handle errors ﴾#handleerrors﴿

How to enable client‐side logging ﴾#logging﴿

WPF, Silverlight, and console application code samples for client methods that the server can call ﴾#wpfsl﴿

For a sample .NET client projects, see the following resources:

gustavo‐armenta / SignalR‐Samples ﴾https://github.com/gustavo‐armenta/SignalR‐Samples﴿ on GitHub.com﴾WinRT, Silverlight, console app examples﴿.

DamianEdwards / SignalR‐MoveShapeDemo / MoveShape.Desktop﴾https://github.com/DamianEdwards/SignalR‐MoveShapeDemo/tree/master/MoveShape/MoveShape.Desktop﴿ onGitHub.com ﴾WPF example﴿.

SignalR / Microsoft.AspNet.SignalR.Client.Samples﴾https://github.com/SignalR/SignalR/tree/master/samples/Microsoft.AspNet.SignalR.Client.Samples﴿ onGitHub.com ﴾Console app example﴿.

For documentation on how to program the server or JavaScript clients, see the following resources:

SignalR Hubs API Guide ‐ Server ﴾/signalr/overview/signalr‐20/hubs‐api/hubs‐api‐guide‐server﴿

SignalR Hubs API Guide ‐ JavaScript Client ﴾/signalr/overview/signalr‐20/hubs‐api/hubs‐api‐guide‐javascript‐client﴿

Links to API Reference topics are to the .NET 4.5 version of the API. If you're using .NET 4, see the .NET 4 version ofthe API topics ﴾http://msdn.microsoft.com/en‐us/library/jj891075﴾v=vs.100﴿.aspx﴿ .

Client setupInstall the Microsoft.AspNet.SignalR.Client ﴾http://nuget.org/packages/Microsoft.AspNet.SignalR.Client﴿ NuGetpackage ﴾not the Microsoft.AspNet.SignalR ﴾http://nuget.org/packages/microsoft.aspnet.signalr﴿ package﴿. Thispackage supports WinRT, Silverlight, WPF, console application, and Windows Phone clients, for both .NET 4 and .NET4.5.

If the version of SignalR that you have on the client is different from the version that you have on the server, SignalRis often able to adapt to the difference. For example, a server running SignalR version 2 will support clients that have1.1.x installed as well as clients that have version 2 installed. If the difference between the version on the server andthe version on the client is too great, or if the client is newer than the server, SignalR throws anInvalidOperationException exception when the client tries to establish a connection. The error message is "Youare using a version of the client that isn't compatible with the server. Client version X.X,server version X.X".

How to establish a connectionBefore you can establish a connection, you have to create a HubConnection object and create a proxy. To establishthe connection, call the Start method on the HubConnection object.

var hubConnection = new HubConnection("http://www.contoso.com/");IHubProxy stockTickerHubProxy = hubConnection.CreateHubProxy("StockTickerHub");stockTickerHubProxy.On<Stock>("UpdateStockPrice", stock => Console.WriteLine("Stock update 

Page 3: ASP.net Signalr Hubs API Guide - .Net Client (c#) _ the ASP

8/10/2015 ASP.NET SignalR Hubs API Guide ­ .NET Client (C#) | The ASP.NET Site

http://www.asp.net/signalr/overview/guide­to­the­api/hubs­api­guide­net­client 3/14

for {0} new price {1}", stock.Symbol, stock.Price));await hubConnection.Start();

The sample code uses the default "/signalr" URL to connect to your SignalR service. For information about how tospecify a different base URL, see ASP.NET SignalR Hubs API Guide ‐ Server ‐ The /signalr URL﴾/signalr/overview/signalr‐20/hubs‐api/hubs‐api‐guide‐server#signalrurl﴿ .

The Start method executes asynchronously. To make sure that subsequent lines of code don't execute until after theconnection is established, use await in an ASP.NET 4.5 asynchronous method or .Wait() in a synchronous method.Don't use .Wait() in a WinRT client.

 await connection.Start();

 connection.Start().Wait();

The HubConnection class is thread‐safe. 

Cross‐domain connections from Silverlight clientsFor information about how to enable cross‐domain connections from Silverlight clients, see Making a ServiceAvailable Across Domain Boundaries ﴾http://msdn.microsoft.com/en‐us/library/cc197955﴾v=vs.95﴿.aspx﴿ .

How to configure the connectionBefore you establish a connection, you can specify any of the following options:

Concurrent connections limit.

Query string parameters.

The transport method.

HTTP headers.

Client certificates.

How to set the maximum number of concurrent connections in WPF clientsIn WPF clients, you might have to increase the maximum number of concurrent connections from its default value of2. The recommended value is 10.

Note: For JavaScript clients you have to register at least one event handler before calling theStart method to establish the connection. This is not necessary for .NET clients. For JavaScriptclients, the generated proxy code automatically creates proxies for all Hubs that exist on theserver, and registering a handler is how you indicate which Hubs your client intends to use. Butfor a .NET client you create Hub proxies manually, so SignalR assumes that you will be using anyHub that you create a proxy for.

Page 4: ASP.net Signalr Hubs API Guide - .Net Client (c#) _ the ASP

8/10/2015 ASP.NET SignalR Hubs API Guide ­ .NET Client (C#) | The ASP.NET Site

http://www.asp.net/signalr/overview/guide­to­the­api/hubs­api­guide­net­client 4/14

var hubConnection = new HubConnection("http://www.contoso.com/");IHubProxy stockTickerHubProxy = hubConnection.CreateHubProxy("StockTickerHub");stockTickerHubProxy.On<Stock>("UpdateStockPrice", stock => Console.WriteLine("Stock update for {0} new price {1}", stock.Symbol, stock.Price));ServicePointManager.DefaultConnectionLimit = 10;await hubConnection.Start();

For more information, see ServicePointManager.DefaultConnectionLimit ﴾http://msdn.microsoft.com/en‐us/library/system.net.servicepointmanager.defaultconnectionlimit.aspx﴿ .

How to specify query string parametersIf you want to send data to the server when the client connects, you can add query string parameters to theconnection object. The following example shows how to set a query string parameter in client code. 

var querystringData = new Dictionary<string, string>();querystringData.Add("contosochatversion", "1.0");var connection = new HubConnection("http://contoso.com/", querystringData);

The following example shows how to read a query string parameter in server code.

public class StockTickerHub : Hub{    public override Task OnConnected()    {        var version = Context.QueryString["contosochatversion"];        if (version != "1.0")        {            Clients.Caller.notifyWrongVersion();        }        return base.OnConnected();    }}

How to specify the transport methodAs part of the process of connecting, a SignalR client normally negotiates with the server to determine the besttransport that is supported by both server and client. If you already know which transport you want to use, you canbypass this negotiation process. To specify the transport method, pass in a transport object to the Start method. Thefollowing example shows how to specify the transport method in client code.

var hubConnection = new HubConnection("http://www.contoso.com/");IHubProxy stockTickerHubProxy = hubConnection.CreateHubProxy("StockTickerHub");stockTickerHubProxy.On<Stock>("UpdateStockPrice", stock => Console.WriteLine("Stock update for {0} new price {1}", stock.Symbol, stock.Price));await hubConnection.Start(new LongPollingTransport());

Page 5: ASP.net Signalr Hubs API Guide - .Net Client (c#) _ the ASP

8/10/2015 ASP.NET SignalR Hubs API Guide ­ .NET Client (C#) | The ASP.NET Site

http://www.asp.net/signalr/overview/guide­to­the­api/hubs­api­guide­net­client 5/14

The Microsoft.AspNet.SignalR.Client.Transports ﴾http://msdn.microsoft.com/en‐us/library/jj918090﴾v=vs.111﴿.aspx﴿namespace includes the following classes that you can use to specify the transport.

LongPollingTransport ﴾http://msdn.microsoft.com/en‐us/library/microsoft.aspnet.signalr.client.transports.longpollingtransport﴾v=vs.111﴿.aspx﴿

ServerSentEventsTransport ﴾http://msdn.microsoft.com/en‐us/library/microsoft.aspnet.signalr.client.transports.serversenteventstransport﴾v=vs.111﴿.aspx﴿

WebSocketTransport ﴾http://msdn.microsoft.com/en‐us/library/microsoft.aspnet.signalr.client.transports.websockettransport﴾v=vs.111﴿.aspx﴿ ﴾Available only when bothserver and client use .NET 4.5.﴿

AutoTransport ﴾http://msdn.microsoft.com/en‐us/library/microsoft.aspnet.signalr.client.transports.autotransport﴾v=vs.111﴿.aspx﴿ ﴾Automatically chooses the besttransport that is supported by both the client and the server. This is the default transport. Passing this in to theStart method has the same effect as not passing in anything.﴿

The ForeverFrame transport is not included in this list because it is used only by browsers.

For information about how to check the transport method in server code, see ASP.NET SignalR Hubs API Guide ‐Server ‐ How to get information about the client from the Context property ﴾/signalr/overview/signalr‐20/hubs‐api/hubs‐api‐guide‐server#contextproperty﴿ . For more information about transports and fallbacks, see Introductionto SignalR ‐ Transports and Fallbacks ﴾/signalr/overview/signalr‐20/getting‐started‐with‐signalr‐20/introduction‐to‐signalr#transports﴿ .

How to specify HTTP headersTo set HTTP headers, use the Headers property on the connection object. The following example shows how to addan HTTP header.

hubConnection = new hubConnection("http://www.contoso.com/");connection.Headers.Add("headername", "headervalue");IHubProxy stockTickerHubProxy = hubConnection.CreateHubProxy("StockTickerHub");stockTickerHubProxy.On<Stock>("UpdateStockPrice", stock => Console.WriteLine("Stock update for {0} new price {1}", stock.Symbol, stock.Price));await connection.Start();

How to specify client certificatesTo add client certificates, use the AddClientCertificate method on the connection object.

hubConnection = new hubConnection("http://www.contoso.com/");hubConnection.AddClientCertificate(X509Certificate.CreateFromCertFile("MyCert.cer"));IHubProxy stockTickerHubProxy = hubConnection.CreateHubProxy("StockTickerHub");stockTickerHubProxy.On<Stock>("UpdateStockPrice", stock => Console.WriteLine("Stock update for {0} new price {1}", stock.Symbol, stock.Price));await connection.Start();

How to create the Hub proxy

Page 6: ASP.net Signalr Hubs API Guide - .Net Client (c#) _ the ASP

8/10/2015 ASP.NET SignalR Hubs API Guide ­ .NET Client (C#) | The ASP.NET Site

http://www.asp.net/signalr/overview/guide­to­the­api/hubs­api­guide­net­client 6/14

In order to define methods on the client that a Hub can call from the server, and to invoke methods on a Hub at theserver, create a proxy for the Hub by calling CreateHubProxy on the connection object. The string you pass in toCreateHubProxy is the name of your Hub class, or the name specified by the HubName attribute if one was used onthe server. Name matching is case‐insensitive.

Hub class on server

public class StockTickerHub : Hub

Create client proxy for the Hub class

var hubConnection = new HubConnection("http://www.contoso.com/");IHubProxy stockTickerHubProxy = hubConnection.CreateHubProxy("StockTickerHub");stockTickerHubProxy.On<Stock>("UpdateStockPrice", stock => Console.WriteLine("Stock update for {0} new price {1}", stock.Symbol, stock.Price));await hubConnection.Start();

If you decorate your Hub class with a HubName attribute, use that name.

Hub class on server

[HubName("stockTicker")]public class StockTickerHub : Hub

Create client proxy for the Hub class

var hubConnection = new HubConnection("http://www.contoso.com/");IHubProxy stockTickerHubProxy = hubConnection.CreateHubProxy("stockTicker");stockTickerHubProxy.On<Stock>("UpdateStockPrice", stock =>     Console.WriteLine("Stock update for {0} new price {1}", stock.Symbol, stock.Price));await hubConnection.Start();

The proxy object is thread‐safe. In fact, if you call HubConnection.CreateHubProxy multiple times with the samehubName, you get the same cached IHubProxy object. 

How to define methods on the client that the server can callTo define a method that the server can call, use the proxy's On method to register an event handler.

Method name matching is case‐insensitive. For example, Clients.All.UpdateStockPrice on the server willexecute updateStockPrice, updatestockprice, or UpdateStockPrice on the client.

Different client platforms have different requirements for how you write method code to update the UI. The examplesshown are for WinRT ﴾Windows Store .NET﴿ clients. WPF, Silverlight, and console application examples are provided ina separate section later in this topic ﴾#wpfsl﴿ .

Page 7: ASP.net Signalr Hubs API Guide - .Net Client (c#) _ the ASP

8/10/2015 ASP.NET SignalR Hubs API Guide ­ .NET Client (C#) | The ASP.NET Site

http://www.asp.net/signalr/overview/guide­to­the­api/hubs­api­guide­net­client 7/14

Methods without parametersIf the method you're handling does not have parameters, use the non‐generic overload of the On method:

Server code calling client method without parameters

public class StockTickerHub : Hub{    public void NotifyAllClients()    {         Clients.All.Notify();    }}

WinRT Client code for method called from server without parameters ﴾see WPF and Silverlight examples laterin this topic ﴾#wpfsl﴿ ﴿

var hubConnection = new HubConnection("http://www.contoso.com/");IHubProxy stockTickerHubProxy = hubConnection.CreateHubProxy("StockTickerHub");stockTickerHub.On("notify", () =>    // Context is a reference to SynchronizationContext.Current    Context.Post(delegate    {        textBox.Text += "Notified!\n";    }, null));await hubConnection.Start();

Methods with parameters, specifying the parameter typesIf the method you're handling has parameters, specify the types of the parameters as the generic types of the Onmethod. There are generic overloads of the On method to enable you to specify up to 8 parameters ﴾4 on WindowsPhone 7﴿. In the following example, one parameter is sent to the UpdateStockPrice method.

Server code calling client method with a  parameter

public void BroadcastStockPrice(Stock stock){    context.Clients.Others.UpdateStockPrice(stock);}

The Stock class used for the parameter

public class Stock{    public string Symbol { get; set; }    public decimal Price { get; set; }

Page 8: ASP.net Signalr Hubs API Guide - .Net Client (c#) _ the ASP

8/10/2015 ASP.NET SignalR Hubs API Guide ­ .NET Client (C#) | The ASP.NET Site

http://www.asp.net/signalr/overview/guide­to­the­api/hubs­api­guide­net­client 8/14

}

WinRT Client code for a method called from server with a parameter ﴾see WPF and Silverlight examples laterin this topic ﴾#wpfsl﴿ ﴿

stockTickerHubProxy.On<Stock>("UpdateStockPrice", stock =>     // Context is a reference to SynchronizationContext.Current    Context.Post(delegate    {        textBox.Text += string.Format("Stock update for {0} new price {1}\n", stock.Symbol, stock.Price);    }, null));

Methods with parameters, specifying dynamic objects for the parametersAs an alternative to specifying parameters as generic types of the On method, you can specify parameters as dynamicobjects:

Server code calling client method with a  parameter

public void BroadcastStockPrice(Stock stock){    context.Clients.Others.UpdateStockPrice(stock);}

The Stock class used for the parameter

public class Stock{    public string Symbol { get; set; }    public decimal Price { get; set; }}

WinRT Client code for a method called from server with a parameter, using a dynamic object for theparameter ﴾see WPF and Silverlight examples later in this topic ﴾#wpfsl﴿ ﴿

stockTickerHubProxy.On("UpdateStockPrice", stock =>     // Context is a reference to SynchronizationContext.Current    Context.Post(delegate    {        textBox.Text += string.Format("Stock update for {0} new price {1}\n", stock.Symbol, stock.Price);    }, null));

Page 9: ASP.net Signalr Hubs API Guide - .Net Client (c#) _ the ASP

8/10/2015 ASP.NET SignalR Hubs API Guide ­ .NET Client (C#) | The ASP.NET Site

http://www.asp.net/signalr/overview/guide­to­the­api/hubs­api­guide­net­client 9/14

How to remove a handlerTo remove a handler, call its Dispose method.

Client code for a method called from server

var updateStockPriceHandler = stockTickerHubProxy.On<Stock>("UpdateStockPrice", stock =>     Context.Post(delegate    {        textBox.Text += string.Format("Stock update for {0} new price {1}\n", stock.Symbol, stock.Price);    }, null));

Client code to remove the handler

updateStockPriceHandler.Dispose(); 

How to call server methods from the clientTo call a method on the server, use the Invoke method on the Hub proxy.

If the server method has no return value, use the non‐generic overload of the Invoke method.

Server code for a method that has no return value

public class StockTickerHub : Hub{    public void JoinGroup(string groupName)    {        Groups.Add(Context.ConnectionId, groupName);     }}

Client code calling a method that has no return value

stockTickerHubProxy.Invoke("JoinGroup", "SignalRChatRoom");

If the server method has a return value, specify the return type as the generic type of the Invoke method.

Server code for a method that has a return value and takes a complex type parameter

public IEnumerable<Stock> AddStock(Stock stock){    _stockTicker.AddStock(stock);

Page 10: ASP.net Signalr Hubs API Guide - .Net Client (c#) _ the ASP

8/10/2015 ASP.NET SignalR Hubs API Guide ­ .NET Client (C#) | The ASP.NET Site

http://www.asp.net/signalr/overview/guide­to­the­api/hubs­api­guide­net­client 10/14

    return _stockTicker.GetAllStocks();}

The Stock class used for the parameter and return value

public class Stock{    public string Symbol { get; set; }    public decimal Price { get; set; }}

Client code calling a method that has a return value and takes a complex type parameter, in an ASP.NET 4.5async method

var stocks = await stockTickerHub.Invoke<IEnumerable<Stock>>("AddStock", new Stock() { Symbol = "MSFT" });foreach (Stock stock in stocks){    textBox.Text += string.Format("Symbol: {0} price: {1}\n", stock.Symbol, stock.Price);}

Client code calling a method that has a return value and takes a complex type parameter, in a synchronousmethod

var stocks = stockTickerHub.Invoke<IEnumerable<Stock>>("AddStock", new Stock() { Symbol = "MSFT" }).Result;foreach (Stock stock in stocks){    textBox.Text += string.Format("Symbol: {0} price: {1}\n", stock.Symbol, stock.Price);}

The Invoke method executes asynchronously and returns a Task object. If you don't specify await or .Wait(), thenext line of code will execute before the method that you invoke has finished executing.

How to handle connection lifetime eventsSignalR provides the following connection lifetime events that you can handle:

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. Forinformation about connection state values see ConnectionState Enumeration ﴾http://msdn.microsoft.com/en‐

Page 11: ASP.net Signalr Hubs API Guide - .Net Client (c#) _ the ASP

8/10/2015 ASP.NET SignalR Hubs API Guide ­ .NET Client (C#) | The ASP.NET Site

http://www.asp.net/signalr/overview/guide­to­the­api/hubs­api­guide­net­client 11/14

us/library/microsoft.aspnet.signalr.client.connectionstate﴾v=vs.111﴿.aspx﴿ .

Closed: Raised when the connection has disconnected.

For example, if you want to display warning messages for errors that are not fatal but cause intermittent connectionproblems, such as slowness or frequent dropping of the connection, handle the ConnectionSlow event.

hubConnection.ConnectionSlow += () => Console.WriteLine("Connection problems.");

For more information, see Understanding and Handling Connection Lifetime Events in SignalR﴾/signalr/overview/signalr‐20/hubs‐api/handling‐connection‐lifetime‐events﴿ .

How to handle errorsIf you don't explicitly enable detailed error messages on the server, the exception object that SignalR returns after anerror contains minimal information about the error. For example, if a call to newContosoChatMessage fails, the errormessage in the error object contains "There was an error invoking Hub method'contosoChatHub.newContosoChatMessage'." Sending detailed error messages to clients in production is notrecommended for security reasons, but if you want to enable detailed error messages for troubleshooting purposes,use the following code on the server.

var hubConfiguration = new HubConfiguration (http://msdn.microsoft.com/en‐us/library/microsoft.aspnet.signalr.hubconfiguration(v=vs.111).aspx) ();hubConfiguration.EnableDetailedErrors = true;App.MapSignalR(hubConfiguration);

To handle errors that SignalR raises, you can add a handler for the Error event on the connection object.

hubConnection.Error += ex => Console.WriteLine("SignalR error: {0}", ex.Message);

To handle errors from method invocations, wrap the code in a try‐catch block. 

try{    IEnumerable<Stock> stocks = await stockTickerHub.Invoke<IEnumerable<Stock>>("GetAllStocks");    foreach (Stock stock in stocks)    {        Console.WriteLine("Symbol: {0} price: {1}", stock.Symbol, stock.Price);    }}catch (Exception ex){    Console.WriteLine("Error invoking GetAllStocks: {0}", ex.Message);}

Page 12: ASP.net Signalr Hubs API Guide - .Net Client (c#) _ the ASP

8/10/2015 ASP.NET SignalR Hubs API Guide ­ .NET Client (C#) | The ASP.NET Site

http://www.asp.net/signalr/overview/guide­to­the­api/hubs­api­guide­net­client 12/14

How to enable client‐side loggingTo enable client‐side logging, set the TraceLevel and TraceWriter properties on the connection object.

var hubConnection = new HubConnection("http://www.contoso.com/");hubConnection.TraceLevel = TraceLevels.All;hubConnection.TraceWriter = Console.Out;IHubProxy stockTickerHubProxy = hubConnection.CreateHubProxy("StockTickerHub");stockTickerHubProxy.On<Stock>("UpdateStockPrice", stock => Console.WriteLine("Stock update for {0} new price {1}", stock.Symbol, stock.Price));await hubConnection.Start();

WPF, Silverlight, and console application code samples for client methodsthat the server can callThe code samples shown earlier for defining client methods that the server can call apply to WinRT clients. Thefollowing samples show the equivalent code for WPF, Silverlight, and console application clients.

Methods without parametersWPF client code for method called from server without parameters

stockTickerHub.On<Stock>("notify", () =>    Dispatcher.InvokeAsync(() =>        {            SignalRTextBlock.Text += string.Format("Notified!");        }));

Silverlight client code for method called from server without parameters

stockTickerHub.On<Stock>("notify", () =>    // Context is a reference to SynchronizationContext.Current    Context.Post(delegate    {        textBox.Text += "Notified!";    }, null));

Console application client code for method called from server without parameters

stockTickerHubProxyProxy.On("Notify", () => Console.WriteLine("Notified!"));

Methods with parameters, specifying the parameter typesWPF client code for a method called from server with a parameter

Page 13: ASP.net Signalr Hubs API Guide - .Net Client (c#) _ the ASP

8/10/2015 ASP.NET SignalR Hubs API Guide ­ .NET Client (C#) | The ASP.NET Site

http://www.asp.net/signalr/overview/guide­to­the­api/hubs­api­guide­net­client 13/14

stockTickerHubProxy.On<Stock>("UpdateStockPrice", stock =>     Dispatcher.InvokeAsync(() =>        {            textBox.Text += string.Format("Stock update for {0} new price {1}\n", stock.Symbol, stock.Price);        }));

Silverlight client code for a method called from server with a parameter

stockTickerHubProxy.On<Stock>("UpdateStockPrice", stock =>     // Context is a reference to SynchronizationContext.Current    Context.Post(delegate    {        textBox.Text += string.Format("Stock update for {0} new price {1}\n", stock.Symbol, stock.Price);    }, null));

Console application client code for a method called from server with a parameter

stockTickerHubProxy.On<Stock>("UpdateStockPrice", stock =>     Console.WriteLine("Symbol {0} Price {1}", stock.Symbol, stock.Price));

Methods with parameters, specifying dynamic objects for the parametersWPF client code for a method called from server with a parameter, using a dynamic object for the parameter

stockTickerHubProxy.On("UpdateStockPrice", stock =>     Dispatcher.InvokeAsync(() =>        {            textBox.Text += string.Format("Stock update for {0} new price {1}\n", stock.Symbol, stock.Price);        }));

Silverlight client code for a method called from server with a parameter, using a dynamic object for theparameter

stockTickerHubProxy.On("UpdateStockPrice", stock =>     // Context is a reference to SynchronizationContext.Current    Context.Post(delegate    {        textBox.Text += string.Format("Stock update for {0} new price {1}\n", stock.Symbol, stock.Price);

Page 14: ASP.net Signalr Hubs API Guide - .Net Client (c#) _ the ASP

8/10/2015 ASP.NET SignalR Hubs API Guide ­ .NET Client (C#) | The ASP.NET Site

http://www.asp.net/signalr/overview/guide­to­the­api/hubs­api­guide­net­client 14/14

    }, null));

Console application client code for a method called from server with a parameter, using a dynamic object forthe parameter

stockTickerHubProxy.On("UpdateStockPrice", stock =>     Console.WriteLine("Symbol {0} Price {1}", stock.Symbol, stock.Price));

This article was originally created on June 10, 2014

Author Information

Tom Dykstra – Tom Dykstra is a Senior Programming Writer on Microsoft's Web Platform &Tools Content Team...

Patrick Fletcher – Patrick Fletcher is a former programmer‐writer on the ASP.NET team.

Comments ﴾9﴿

This site is managed for Microsoft by Neudesic, LLC. | © 2015 Microsoft. All rights reserved.