Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
503 views
in Technique[技术] by (71.8m points)

visual studio 2010 - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 !!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...