Click here to Skip to main content
15,889,462 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hi,

I've made a chat application using SignalR. To support 1-on-1 chatting I have created a custom HubPipelineModule that adds the SignalR connections to a group named after the owning ProfileID.

But there is no communication possible from server to client, although the SignalR connection is initialised correctly and the Client > Server communication is working correctly, BUT the clientside jQuery code is not being called. My question: Why?

This all used to work correctly but my mobile browser kept crashing randomly, so I dicided to upgrade all SignalR/Jquery code to the latest version to see if that would be a solution, but after the upgrade no Server > Client communication worked anymore.

Global.asax:
C#
protected void Application_Start()
{
    // Add custom ViewEngine
    ViewEngines.Engines.Clear();
    ViewEngines.Engines.Add(new CustomRazorViewEngine());

    // Add custom HubPipeline
    GlobalHost.HubPipeline.AddModule(new CustomHubPipelineModule());

    // Map the Hub
    RouteTable.Routes.MapHubs();

    AreaRegistration.RegisterAllAreas();
    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);
}


CustomHubPipelineModule.cs:
C#
using System;
using System.Web;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
using MyChatApp.DataHelpers;

namespace MyChatApp
{
    public class CustomHubPipelineModule : HubPipelineModule
    {
        protected override bool OnBeforeIncoming(IHubIncomingInvokerContext context)
        {
            // Is the user logged in?
            if (HttpContext.Current.User != null)
            {
                // Get profile information
                Profiel_DataHelper profiel = 
                    new Profiel_DataHelper(HttpContext.Current.User.Identity.Name);

                // Add new connection to group of the ProfielID
                context.Hub.Groups.Add(
                    context.Hub.Context.ConnectionId, 
                    profiel.ProfielID.ToString());
            }

            return base.OnBeforeIncoming(context);
        }
 
        protected override bool OnBeforeOutgoing(IHubOutgoingInvokerContext context)
        {
            return base.OnBeforeOutgoing(context);
        }
    }
}


Then I have created a serverside class to talk to the clients.

ChatServer.cs:
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
using MyChatApp.DataHelpers;

/// <summary>
/// Client-side Methods (SERVER => CLIENT)
/// </summary>
public class ChatServer
{
    // To all users
    public static void addPublicMessage(
        string Bericht, 
        string profielid, 
        string profielnaam, 
        string BerichtID, 
        string DatumActief, 
        string DatumVerzonden)
    {
        try
        {
            var context = GlobalHost.ConnectionManager.GetHubContext<ChatHub>();
            context.Clients.All.addPublicMessage(
                Bericht, profielid.ToString(), 
                profielnaam, 
                BerichtID.ToString(), 
                DatumActief, 
                DatumVerzonden);
        }
        catch
        {
        }
    }

    // To specific user
    public static void addMessage(
        string ProfielID, 
        string Bericht, 
        long? ProfielIDVan, 
        long? ProfielIDNaar, 
        bool lastmessage, 
        int openstaandeberichten, 
        DateTime? DatumActief, 
        bool GelezenDoorOntvanger, 
        int berichtnr, 
        long BerichtID, 
        bool showdate = false, 
        string setdate = "")
    {
        try
        {
            var context = GlobalHost.ConnectionManager.GetHubContext<ChatHub>();
            context.Clients.Group(ProfielID).addMessage(
                Bericht, 
                ProfielIDVan.ToString(), 
                ProfielIDNaar.ToString(), 
                lastmessage.ToString(), 
                openstaandeberichten.ToString(), 
                DatumActief.Value.Hour.ToString("") + ":" +
                DatumActief.Value.Minute.ToString(""), 
                GelezenDoorOntvanger.ToString(), 
                berichtnr.ToString(), 
                BerichtID.ToString(), 
                showdate.ToString(), 
                setdate);
        }
        catch
        {
        }
    }
}


And ofcourse the ClientSide jQuery code.

Chat.js:
JavaScript
var stopevents = false;
var test = null;
var interval = 1000;
var timeout = null;
var tickercheckdate;

$(function () {

    // CLIENT: SIGNALR CONNECTION VERLOREN
    $.connection.hub.stateChanged(function (change) {
        if (stopevents == false) {
            if (change.newState == $.signalR.connectionState.reconnecting) {
                timeout = setTimeout(function () {
                    $('#state').css('color', 'red')
                        .html('The server is unreachable...');
                }, interval);
            }
            else if (timeout && change.newState === $.signalR.connectionState.connected) {
                $('#state').css('color', '')
                        .html('');

                clearTimeout(timeout);
                timeout = null;
            }
        }
    });

    // CLIENT: SIGNALR CONNECTION START
    $.connection.hub.start().done(function () {
    
        var chat = $.connection.Chat;

        // SERVER > CLIENT: BERICHT ONTVANGEN VOOR PUBLIEKE CHATBOX
        chat.client.addPublicMessage = function (msg, prof_id, prof_naam, bericht_id, bericht_tijd, bericht_datum) {
            if (stopevents == false) {
                //genereer de chatgeschiedenis met de juiste divs + classes
                var bubble = '';

                if ($("#ActiveDate").val() != bericht_datum) {
                    bubble = bubble + '<center><div class=\"bubble_date\" >' + bericht_datum + '</div></center><br/>';
                    $("#ActiveDate").val(bericht_datum)
                }
                if (prof_id == 0) {
                    bubble = bubble + '<div class=\"bubble_receiver\" style=\"max-width:' + ($(document).width() - 70) + 'px;\"><div class=\"border_receiver\"></div><div class=\"content_receiver\">' + prof_naam + ' (' + bericht_tijd + '): ' + msg + '</div></div>';
                }
                else {
                    bubble = bubble + '<div class=\"bubble_receiver\" style=\"max-width:' + ($(document).width() - 70) + 'px;\"><div class=\"border_receiver\"></div><div class=\"content_receiver\"><a href=\"/Profielen/Details/' + prof_id + '\">' + prof_naam + '</a> (' + bericht_tijd + '): ' + msg + '</div></div>';
                }

                $('#publicmessages').append(bubble);

                jQuery('html, body').animate({ scrollTop: $(document).height() }, 1000);
            }
        };

        // SERVER > CLIENT: BERICHT ONTVANGEN
        chat.client.addMessage = function (msg, prof, profvan, lastmessage, unreadablemessagecount, datumactief, gelezen, berichtnr, berichtid, showdate, setdate) {
            if (stopevents == false) {
                if (($("#profielid").val() == prof && $("#profielidNaar").val() == profvan) || ($("#profielid").val() == profvan && $("#profielidNaar").val() == prof) || (prof == 0) || (profvan == 0)) {
                    //genereer de chatgeschiedenis met de juiste divs + classes
                    var cssclass = "receiver";
                    if (prof == $("#profielid").val()) {
                        cssclass = "sender";
                    }
                    var bubble = '';

                    if (showdate == true) {
                        bubble = bubble + '<center><div class=\"bubble_date\" >' + setdate + '</div></center><br/>';
                    }

                    bubble = bubble + '<div class=\"bubble_' + cssclass + '\" style=\"max-width:' + ($(document).width() - 70) + 'px;\"><div class=\"border_' + cssclass + '\"></div><div class=\"content_' + cssclass + '\">' + msg + '<div class=\"tijd_' + cssclass + '\">' + datumactief;
                    if (prof != $("#profielidNaar").val()) {
                        bubble = bubble + '<div class=\"gelezen_' + gelezen + '\" id=\"read_img' + berichtid + '\"></div>';
                    }
                    bubble = bubble + '</div></div></div>';

                    $('#messages').append(bubble);
                }
                if (lastmessage == true) {
                    jQuery('html, body').animate({ scrollTop: $(document).height() }, 1000);
                }
            }
        };
    });
}); 


And of course the header information:
HTML
<!DOCTYPE html>
<html lang="en">
    <head>
        <title></title>

        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width" />
        <meta name="apple-mobile-web-app-status-bar-style" content="black" />
        <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport" />
    	<meta name="apple-mobile-web-app-capable" content="yes" />
        
        <link href="/Content/jquery.mobile-1.3.0.min.css" rel="stylesheet" />
        
        <link href="/Files/Styles/Site.css" rel="stylesheet" type="text/css" />
        <link href="/Files/Styles/Chat.css" rel="stylesheet" type="text/css" />
                
        <script src="/Scripts/jQuery/jquery-1.8.3.min.js" type="text/javascript"></script>
        <script src="/Scripts/jQuery/jquery.mobile-1.3.0.min.js" type="text/javascript"></script>
        
        <script src="/Scripts/SignalR/jquery.signalR-1.0.1.min.js" type="text/javascript"></script>
        <script src="/signalr/hubs" type="text/javascript"></script>

        <script src="/Scripts/Website/Chat.js" type="text/javascript"></script>

    </head>
Posted
Updated 20-Mar-13 23:45pm
v3

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