Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can SignalR be used with asp.net WebForms?

I want to use SignalR in my project for real time updates.

My project is developed in WebForms.

I searched for for 3,4 days but all I found were MVC examples. Can anyone suggest a solution?

like image 677
Vikas Rana Avatar asked Aug 09 '13 09:08

Vikas Rana


People also ask

What platform does SignalR client supports?

Windows Desktop and Silverlight Applications In addition to running in a web browser, SignalR can be hosted in standalone Windows client or Silverlight applications.

Can SignalR be used in Web API?

SignalR can be used together with Web API just fine, so some functionality in application which is not realtime and doesn't require persistent connection could be served by Web API.

What you can do with ASP.NET and SignalR?

SignalR can be used to add any sort of "real-time" web functionality to your ASP.NET application. While chat is often used as an example, you can do a whole lot more. Any time a user refreshes a web page to see new data, or the page implements long polling to retrieve new data, it is a candidate for using SignalR.

What can SignalR be used for?

SignalR is a free and open-source software library for Microsoft ASP.NET that allows server code to send asynchronous notifications to client-side web applications. The library includes server-side and client-side JavaScript components.


2 Answers

The answer provided by @Stephen is now outdated as it does not apply to the latest Version of SignalR (v2.2.0). Also there are few other things that are not mentioned which IMHO might help future readers to quickly get started with SignalR using the Good old Webforms framework. The solution might appear tedious but it is not. I hope it helps people who visit this page looking to get help on SignalR for Webforms.

Pre-Reqs: (Versions used by me are in brackets) . I have NOT tested this solution on other versions

  1. MS Visual Studio 2015/2013. (2015) On Win-7 x64
  2. .Net FrameWork version 4.5 or Higher (4.5.2)
  3. SignalR version 2.2.0 from NuGet (Release Date 01/13/2015)
  4. jQuery ver 1.6.4
  5. Owin v1.0.0 and few others like Json, owin.Security etc... (see packages.config)
  6. IIS v7.0 and above. Works on IIS Express version 10.0 that ships with VS2015.

Steps:

Follow the steps below to get SignalR working in a WebForms Project. The Aim of this project is to broadcast timestamps at periodic intervals to all connected clients (browser sessions) using SignalR. Only the first timestamp is generated by the Server Side code in the code behind file. Rest comes from the SignalR HubClass which is responsible for generating the Timestamps at periodic intervals and bradcast them to ALL connected sessions.

  1. In Visual Studio (2015) Create a Empty WebForms Project.( Pick Empty Template and check WebForms under "Add Core Librares and Folders). Lets say we name it as "SignalR_WebForms".
  2. To Download, Install and add references to SignalR+jQuery+Owin libraries

    2a. Tools --> NuGet Package Manager --> Manage Nuget Packages for Solutions.

    2b. Type "Microsoft.ASPNet.SignalR" in Search and pick "Microsoft.ASPNet.SignalR" (server component).

    2c. On the Right Panel Now check the box next to "SignalR_WebForms". This will enable the "Install" button. Pick the latest Version (2.2.0 as of today) and click on the Install Button. This will popup a "Review Changes" dialog box which informs you of all the packages (total 10) that will be installed. Click Ok. Then Click on"Accept" to Accept the License Terms. This will start the download and install process (very quick). Once done open the Packages.config file (which is located under the root of the proj folder) and it should look like this :

`

<-- Packages.config should look like this  -->  <?xml version="1.0" encoding="utf-8"?>     <packages>       <package id="jQuery" version="1.6.4" targetFramework="net452" />       <package id="Microsoft.AspNet.SignalR" version="2.2.0" targetFramework="net452" />       <package id="Microsoft.AspNet.SignalR.Core" version="2.2.0" targetFramework="net452" />       <package id="Microsoft.AspNet.SignalR.JS" version="2.2.0" targetFramework="net452" />       <package id="Microsoft.AspNet.SignalR.SystemWeb" version="2.2.0" targetFramework="net452" />       <package id="Microsoft.CodeDom.Providers.DotNetCompilerPlatform" version="1.0.0" targetFramework="net452" />       <package id="Microsoft.Net.Compilers" version="1.0.0" targetFramework="net452" developmentDependency="true" />       <package id="Microsoft.Owin" version="2.1.0" targetFramework="net452" />       <package id="Microsoft.Owin.Host.SystemWeb" version="2.1.0" targetFramework="net452" />       <package id="Microsoft.Owin.Security" version="2.1.0" targetFramework="net452" />       <package id="Newtonsoft.Json" version="6.0.4" targetFramework="net452" />       <package id="Owin" version="1.0" targetFramework="net452" /> </packages> 

`

  1. Add a webform and name it as default.aspx ( RightClick on Proj Add --> Webform --> type default.aspx --> click ok.

  2. Copy paste this code into the default.aspx file (Markup)

`

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="default.aspx.cs" Inherits="SignalR_WebForms._default" %>  <!DOCTYPE html>  <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server">     <title>SignalR Using webForms</title>      <script src="Scripts/jquery-1.6.4.js"></script>     <script src="Scripts/jquery.signalR-2.2.0.js"></script>     <script src="signalr/hubs"></script>       <script type="text/javascript">          $(function() {              var logger = $.connection.logHub;              logger.client.logMessage = function(msg) {                  $("#logUl").append("<li>" + msg + "</li>");              };              $.connection.hub.start();          });      </script>  </head> <body>     <form id="form1" runat="server">     <div>      <h3>Log Items</h3>     <asp:listview id="logListView" runat="server" itemplaceholderid="itemPlaceHolder" clientidmode="Static" enableviewstate="false">         <layouttemplate>             <ul id="logUl">                 <li runat="server" id="itemPlaceHolder"></li>             </ul>         </layouttemplate>         <itemtemplate>                 <li><span class="logItem"><%#Container.DataItem.ToString() %></span></li>         </itemtemplate>     </asp:listview>        </div>        </form> </body> </html> 

`

  1. Copy paste the code below into the code-behind file (default.aspx.cs)

`

using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls;  namespace SignalR_WebForms {     public partial class _default : System.Web.UI.Page     {         protected void Page_Load(object sender, EventArgs e)         {             var myLog = new List<string>();             myLog.Add(string.Format("{0} - Logging Started", DateTime.UtcNow));              logListView.DataSource = myLog;             logListView.DataBind();         }     } }  ` 
  1. Add the App_Code folder to the project. ( Right Click on Proj --> Add --> Add ASP.Net Folder --> Pick App_Code ).

  2. Add a SignalR Hub Class and name it as LogHub.cs To do this Right click on App_Code Folder --> Add --> Pick Class .. (at the bottom of the list) --> Click on Vsual C# then Web then SignalR --> Pick SignalR HubClass --> type LogHub.cs as filename. Click ok.

  3. Open the LogHub.cs class file and delete existing code and Copy paste code below into it. Save.

`

using System; using System.Collections.Generic; using System.Linq; using System.Web; using Microsoft.AspNet.SignalR;  namespace SignalR_WebForms.App_Code {     public class LogHub : Hub     {         public static readonly System.Timers.Timer _Timer = new System.Timers.Timer();          static LogHub()         {             _Timer.Interval = 5000;             _Timer.Elapsed += TimerElapsed;             _Timer.Start();         }          static void TimerElapsed(object sender, System.Timers.ElapsedEventArgs e)         {             var hub = GlobalHost.ConnectionManager.GetHubContext("LogHub");             hub.Clients.All.logMessage(string.Format("{0} - Still running", DateTime.UtcNow));         }     } } 

`

  1. Add a Owin Startup Class file and name it as Startup1.cs. ( Right Click on App_code --> Add --> Class --> Click on Vsual C# then Web then General --> Pick Owin Startup class.) Delete existing code and Copy paste code below into this class file.Save.

    `

    using System; using System.Threading.Tasks; using Microsoft.Owin; using Owin;  [assembly: OwinStartup(typeof(WebApplication1.App_Code.Startup1))]  namespace WebApplication1.App_Code {     public class Startup1     {         public void Configuration(IAppBuilder app)         {             app.MapSignalR();         }     } } 

`

  1. Build and Run the Proj (F5). If no errors , you should see the following output on the local browser.

`

Log Items •06/04/2016 09:50:02 PM - Logging Started •06/04/2016 09:50:06 PM - Still running •06/04/2016 09:50:11 PM - Still running •06/04/2016 09:50:16 PM - Still running •06/04/2016 09:50:21 PM - Still running ..... ..... ..... ..... Keeps Going **without** having to refresh the Browser. 

`

  1. From a remote PC access the same site and you should get the exact same timestamps. This verifies that the site works as expected.

  2. To further verify Right Click on the Browser and click View Source. On I.E this opens up a Notepad window with page html. Find "logUL" and you should see just the markup that shows the initial timestamp. There is no markup that shows the remaining updates as those are injected by the SignalR hub. This is similar to AJAX.

`

<div> <h3>Log Items</h3>         <ul id="logUl">              <li><span class="logItem">06/04/2016 09:50:02 PM - Logging Started</span></li>          </ul>  </div> 

`

Thats it !. HTH !!

like image 76
objectNotFound Avatar answered Sep 22 '22 17:09

objectNotFound


You can use SignalR with webforms. See below for an example from the tutorial here

  1. Create a new ASP.NET WebForms project targeting .NET Framework 4.5 or later

  2. Change the home page to contain the following

    <asp:content runat="server" id="BodyContent" contentplaceholderid="MainContent">
    
    
        <h3>Log Items</h3>
        <asp:listview id="logListView" runat="server" itemplaceholderid="itemPlaceHolder" clientidmode="Static" enableviewstate="false">
            <layouttemplate>
                <ul id="logUl">
                    <li runat="server" id="itemPlaceHolder"></li>
                </ul>
            </layouttemplate>
            <itemtemplate>
                <li><span class="logItem"><%#Container.DataItem.ToString() %></span></li>
            </itemtemplate>
        </asp:listview>
    
    </asp:content>
    
  3. Edit the default.aspx.cs codebehind file to include the following event

    protected void Page_Load(object sender, EventArgs e)
    {
    
        var myLog = new List<string>();
        myLog.Add(string.Format("{0} - Logging Started", DateTime.UtcNow));
    
        logListView.DataSource = myLog;
        logListView.DataBind();
    
    }
    
  4. Add SignalR packages via NuGet. (Trying searching for "Microsoft ASP.Net SignalR JS" and "Microsoft ASP.Net SignalR JS")

  5. Create a Hub class

    public class LogHub : Hub
    {
    
        public static readonly System.Timers.Timer _Timer = new System.Timers.Timer();
    
        static LogHub()
        {
            _Timer.Interval = 2000;
            _Timer.Elapsed += TimerElapsed;
            _Timer.Start();
        }
    
        static void TimerElapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            var hub = GlobalHost.ConnectionManager.GetHubContext("LogHub");
            hub.Clients.All.logMessage(string.Format("{0} - Still running", DateTime.UtcNow));
        }
    
    }
    
  6. Setup the following script block at the bottom of your page (your jquery and jquery.signalr version may vary)

    <script src="Scripts/jquery.1.7.1.min.js"></script>
    <script src="Scripts/jquery.signalR-1.0.0-rc1.min.js"></script>
    <script src="http://www.codeproject.com/signalr/hubs" type="text/javascript"></script>
    <script type="text/javascript">
    
        $(function() {
    
            var logger = $.connection.logHub;
    
            logger.client.logMessage = function(msg) {
    
                $("#logUl").append("<li>" + msg + "</li>");
    
            };
    
            $.connection.hub.start();
    
        });
    
    </script>
    
  7. Add the following to the Application_Start event handler in global.asax.cs

    void Application_Start(object sender, EventArgs e)
    {
        RouteTable.Routes.MapHubs();
    }
    
like image 39
Stephen Avatar answered Sep 23 '22 17:09

Stephen