Click here to Skip to main content
15,887,315 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I took an example https://github.com/venkatbaggu/signalrdatabasenotifications/tree/master/SignalRDbUpdates where SignalR is used with SQL Server. The example works perfectly, however, and in Asp.net MVC. I'm trying to follow the same example by creating it in Asp.net WebAplication (.NET Framework), but I don't know what's missing and I don't understand about jquery. Could someone please try to help me please. When I make changes to the database my method dependency_OnChange works, I believe my problem is when it comes to showing the records in the browser. Help!?!? Thank you!


What I have tried:

Here is my code...

Messages.aspx
ASP.NET
<pre><%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Messages.aspx.cs" Inherits="TesteSignalR.Messages" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="Scripts/jquery-1.10.2.js"></script>
    <script src="Scripts/jquery.signalR-2.1.1.js"></script>
    
        <!--Reference the autogenerated SignalR hub script. -->
    <script src='<%: ResolveClientUrl("/signalr/hubs") %>'></script>



    <script type="text/javascript">
        $(function () {
            
            // Declare a proxy to reference the hub.
            var notifications = $.connection.notificationsHub;
            //debugger;
            // Create a function that the hub can call to broadcast messages.
            notifications.client.updateMessages = function () {
                getAllMessages()
            };
            // Start the connection.
            $.connection.hub.start().done(function () {
                alert("connection started")
                getAllMessages();
            }).fail(function (e) {
                alert(e);
            });
        });


        function getAllMessages() {
            var tbl = $('#messagesTable');
            $.ajax({
                url: '/home/GetMessages',
                contentType: 'application/html ; charset:utf-8',
                type: 'GET',
                dataType: 'html'
            }).success(function (result) {
                tbl.empty().append(result);
            }).error(function () {
                
            });
        }
</script>

</head>
<body>
    <form id="form1" runat="server">


        <div class="row">
            <div class="col-md-12">
                <div id="messagesTable"></div>
            </div>
        </div>


    </form>
</body>

</html>



Messages.aspx.cs
<pre lang="c#">
<pre>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;


namespace TesteSignalR
{
    public partial class Messages : System.Web.UI.Page
    {
    
        public int MessageID { get; set; }

        public string Message { get; set; }

        public string EmptyMessage { get; set; }

        public DateTime MessageDate { get; set; }

 
        readonly string _connString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

        protected void Page_Load(object sender, EventArgs e)
        {
            GetAllMessages();
        }

       
        public IEnumerable<Messages> GetAllMessages()
        {
            var messages = new List<Messages>();
            using (var connection = new SqlConnection(_connString))
            {
                connection.Open();
                //using (var command = new SqlCommand(@"SELECT [MessageID], [Message], [EmptyMessage], [Date] FROM [dbo].[Messages]", connection))
                using (var command = new SqlCommand(@"SELECT ContactID  [MessageID], contactname  [Message], contactno [EmptyMessage], addedon [Date] FROM [dbo].[Contacts]", connection))
                {
                    command.Notification = null;

                    var dependency = new SqlDependency(command);
                    dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);

                    if (connection.State == ConnectionState.Closed)
                        connection.Open();

                    var reader = command.ExecuteReader();

                    while (reader.Read())
                    {
                        messages.Add(item: new Messages { MessageID = (int)reader["MessageID"], Message = (string)reader["Message"], EmptyMessage = reader["EmptyMessage"] != DBNull.Value ? (string)reader["EmptyMessage"] : "", MessageDate = Convert.ToDateTime(reader["Date"]) });
                    }
                }

            }
            return messages;


        }

        private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
        {
            if (e.Type == SqlNotificationType.Change)
            {
                //MessagesHub.SendMessages();
                NotificationsHub.SendMessages();//nome do meu hub
            }
        }
    }
}


NotificationsHub.cs
C#
<pre>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using System.Data.SqlClient;
using Microsoft.AspNet.SignalR;

using Getway.Uteis;

namespace TesteSignalR
{
    public class NotificationsHub : Hub
    {
        private static string conString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
        public void Hello()
        {
            Clients.All.hello();
        }

        //[HubMethodName("sendMessages")]
        public static void SendMessages()
        {
            IHubContext context = GlobalHost.ConnectionManager.GetHubContext<NotificationsHub>();
            context.Clients.All.updateMessages();
        }

    }
}



OwinStartup.cs
C#
using System;
using System.Threading.Tasks;
using Microsoft.Owin;
using Owin;

//[assembly: OwinStartup(typeof(TesteSignalR.Startup))]
[assembly: OwinStartupAttribute(typeof(TesteSignalR.Startup))]
namespace TesteSignalR
{
   
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.MapSignalR();
        }
    }
}


Global.asax.cs
C#
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;

namespace TesteSignalR
{
    public class Global : System.Web.HttpApplication
    {

        string connString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

        protected void Application_Start(object sender, EventArgs e)
        {
            SqlDependency.Start(connString);
        }       

        protected void Application_End(object sender, EventArgs e)
        {
            //Stop SQL dependency
            SqlDependency.Stop(connString);
        }
    }
}
Posted
Updated 5-Apr-20 16:14pm

under your NotificationHubs.cs,

context.Clients.All.UpdateMessages();


Must change the small letter "u" to "U"

In order to verify Signarl is whether working or not, you need check if setting is followed as bellow.

under your NotificationHubs.cs,

protected override Task OnConnected()
{
    Clients.Caller.SetWorking()
    return base.OnConnected()
}


under Messages.aspx
$(function(){
     notification.client.setWorking = function(){
             alert("working");
     }
});
 
Share this answer
 
for working with getAllMessages()

You need to create Web Api function by
create a new Message.svc file under Root directory with below,

[WebMethod]
[WebInvoke(Method = "Get", ResponseFormat = WebMessageFormat.Json)]
public IEnumerable<Messages> GetAllMessage()
{
         //Your code here
}


under Messages.aspx
function getAllMessages()
{
   $.ajax({
                type: "Get",
                contentType: "application/json; charset=utf-8",
                data: null,
                url: "Message.svc/GetAllMessage",
                dataType: "json",
                processData: false,
                success: function (result) {
                  $("#messagesTable").empty();
                  $.each(result, function(key, item){
                      $("#messagesTable").append("<div>" + item.Message + "</div>");
                  });  
                },
                error: function (e) {
                    alert("Failed on :" + e.status + " with:" + e.statusText);
                }
            });
}
 
Share this answer
 
Comments
CHill60 6-Apr-20 6:37am    
Going forward, can you put your answers into a single solution (there is an "Improve Solution" link that will be visible if you select or hover over your solution). It makes it easier for readers to understand and stops the confusion of "which is the correct answer". Thanks

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900