Click here to Skip to main content
15,885,877 members
Please Sign up or sign in to vote.
3.00/5 (2 votes)
I am able to run the Chat App using SignalR independently but after adding the files to the existing Web Application with Master Page, Chat session does not begin it stops working.I reinstalled SignalR Package many times removing it but the error still exists. Below is the code used:

ASPX:
ASP.NET
<asp:Content ID="MyChatContent2" runat="server" ContentPlaceHolderID="ContentPlaceHolder1">

    <script src="/Scripts/jquery-1.8.1.min.js" type="text/javascript"></script>
    <script src="/Bootstrap/js/bootstrap.min.js" type="text/javascript"></script>
    <script src="/Scripts/jquery.signalR-1.1.2.min.js"></script>
    <script src='/signalr/hubs' type="text/javascript"></script>
    <script src="/ChatJs/Scripts/jquery.activity-indicator-1.0.0.min.js" type="text/javascript"></script>
    <script src="/ChatJs/Scripts/jquery.chatjs.signalradapter.js" type="text/javascript"></script>
    <script src="/ChatJs/Scripts/jquery.chatjs.js" type="text/javascript"></script>
    <script src="/Scripts/scripts.js" type="text/javascript"></script>
    <script src="https://google-code-prettify.googlecode.com/svn/loader/run_prettify.js"></script>
    <!--Styles-->
    <link rel="stylesheet" type="text/css" href="/ChatJs/Styles/jquery.chatjs.css" />
    <link rel="stylesheet" type="text/css" href="/Bootstrap/css/bootstrap.min.css" />
    <link rel="stylesheet" type="text/css" href="/Bootstrap/css/bootstrap-responsive.min.css" />

    <% if (!this.IsUserAuthenticated)
       { %>
    <script type="text/javascript">
        function notAutho() {
            aler("not autoh.....");
        }
    </script>
    <% } %>


    <% if (this.IsUserAuthenticated)
       { %>
    <script type="text/javascript">
        //$.connection.hub.start();

        //$.connection.hub.url = "/signalr"
        //$.connection.hub.start().done(init);

        var connection = $.hubConnection("/signalr", { useDefaultPath: false });

        $(function () {
            debugger;
            alert("chat is authenticated..");
            $.chat({
                // your user information
                user: {
                    Id: '<%= this.UserId %>',
                    Name: '<%= this.UserName %>',
                    ProfilePictureUrl: '/ChatJs/Images/spotlight photo.png'
                },
                // text displayed when the other user is typing
                typingText: ' is typing...',
                // the title for the user's list window
                titleText: 'Chat',
                // text displayed when there's no other users in the room
                emptyRoomText: "There's no one around here. You can still open a session in another browser and chat with yourself :)",
                // the adapter you are using
                adapter: new SignalRAdapter()
            });
        });

    </script>
    <% } %>
<%--</head>

        <script type="text/javascript">
            $(document).ready(function () {
                //joinChatwithHandler();
            });
            function joinChatwithHandler() {
                alert("joinChatConclusionButton calling............ ");
                var $userName = $("#userName");
                var $empID = $("#empID");

                if (!$userName.val() || $userName.val() == $userName.attr("placeHolder")) {
                    $userName.closest(".control-group").addClass("error");
                }
                else {
                    alert("handler is calling............ ");
                    $.ajax({
                        url: "../Handlers/ChatService.ashx?action=joinChat&userName=" + $userName.val() + "&empID=" + $empID.val(),
                        success: function (data) {
                            window.location.reload(false);
                        }
                    });
                }
            }
        </script>
<%--    </form>
</body>
</html>--%>

.CS:
C#
protected void Page_Load(object sender, EventArgs e)
{
    try
    {
        LoadChat();
    }
    catch
    {
    }
}
private void LoadChat()
{
    try
    {
        userName.Value = Convert.ToString(Session[SessionVariables.FullName]);
        empID.Value = Convert.ToString(Session[SessionVariables.emplSequ]);

        if (Session[SessionVariables.isChatHandler] == null)
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "chat", "joinChatwithHandler();", true);
            Session[SessionVariables.isChatHandler] = "Y";
        }

        if (Session[SessionVariables.isUserExists] == null)
        {
            var existingUser = ChatCookieHelperStub.GetDbUserFromCookie(new HttpRequestWrapper(this.Request));
            if (existingUser != null)
            {
                //Session["Name"] = existingUser.FullName;
                //Session["id"] = existingUser.Id;
                Session[SessionVariables.isUserExists] = "Y";
                IsUserAuthenticated = true;
                UserId = Convert.ToInt32(Session[SessionVariables.emplSequ]);
                UserName = Convert.ToString(Session[SessionVariables.FullName]);
                UserProfilePictureUrl = "/ChatJs/Images/spotlight photo.png";
            }
        }
    }
    catch
    {
    }

Startup.cs:
C#
using System.Security.Cryptography;
using Microsoft.AspNet.SignalR;
using Microsoft.Owin;
using Owin;

[assembly: OwinStartup(typeof(HRMSUI.Startup))]
namespace HRMSUI
{
    public static class Startup
    {
        public static void Configuration(IAppBuilder app)
        {
            try
            {
                CryptoConfig.AddAlgorithm(typeof(SHA256Cng), "System.Security.Cryptography.SHA256");
                //app.MapSignalR();

                var hubConfiguration = new HubConfiguration();
                hubConfiguration.EnableDetailedErrors = true;
                hubConfiguration.EnableJavaScriptProxies = false;
                app.MapSignalR("/signalr", hubConfiguration);
            }
            catch
            {
            }
        }
    }
}

Route.config:
C#
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Routing;
using Microsoft.AspNet.FriendlyUrls;

namespace HRMSUI
{
    public static class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            try
            {
                var settings = new FriendlyUrlSettings();
                settings.AutoRedirectMode = RedirectMode.Permanent;
                routes.EnableFriendlyUrls(settings);
            }
            catch
            {
            }
        }
    }
}

Web.Config:
XML
<configuration>
  <configsections>
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirepermission="false" />
  <sectiongroup name="dotNetOpenAuth" type="DotNetOpenAuth.Configuration.DotNetOpenAuthSection, DotNetOpenAuth.Core">
  <section name="messaging" type="DotNetOpenAuth.Configuration.MessagingElement, DotNetOpenAuth.Core" requirepermission="false" allowlocation="true" />
  <section name="reporting" type="DotNetOpenAuth.Configuration.ReportingElement, DotNetOpenAuth.Core" requirepermission="false" allowlocation="true" />
  <section name="openid" type="DotNetOpenAuth.Configuration.OpenIdElement, DotNetOpenAuth.OpenId" requirepermission="false" allowlocation="true" />
  <section name="oauth" type="DotNetOpenAuth.Configuration.OAuthElement, DotNetOpenAuth.OAuth" requirepermission="false" allowlocation="true" />
  </sectiongroup>
  </configsections>
  <appsettings>
    <add key="owin:AppStartup" value="HRMSUI.Startup" />
  </appsettings>

  <system.web>
    <compilation debug="true" targetframework="4.5" />
    
    <httpruntime targetframework="4.5" />
    <pages controlrenderingcompatibilityversion="4.0">
      <namespaces>
        <add namespace="System.Web.Optimization" />
      </namespaces>
      
    <controls>
      <add assembly="Microsoft.AspNet.Web.Optimization.WebForms" namespace="Microsoft.AspNet.Web.Optimization.WebForms" tagprefix="webopt" />
    <add tagprefix="ajaxToolkit" assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" /></controls></pages>
    <authentication mode="Forms">
      <forms loginUrl="~/Account/Login.aspx" timeout="2880" />
    </authentication>
    <sessionstate mode="InProc" customprovider="DefaultSessionProvider">
      <providers>
        <add name="DefaultSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionstringname="DefaultConnection" />
      </providers>
    </sessionstate>
  </system.web>
<runtime>
    <assemblybinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentassembly>
        <assemblyidentity name="DotNetOpenAuth.Core" publickeytoken="2780ccd10d57b246" />
        <bindingredirect oldversion="0.0.0.0-4.3.0.0" newversion="4.3.0.0" />
      </dependentassembly>
      <dependentassembly>
        <assemblyidentity name="DotNetOpenAuth.AspNet" publickeytoken="2780ccd10d57b246" />
        <bindingredirect oldversion="0.0.0.0-4.3.0.0" newversion="4.3.0.0" />
      </dependentassembly>
      <dependentassembly>
        <assemblyidentity name="Microsoft.Owin" publickeytoken="31bf3856ad364e35" culture="neutral" />
        <bindingredirect oldversion="0.0.0.0-2.1.0.0" newversion="2.1.0.0" />
      </dependentassembly>
      <dependentassembly>
        <assemblyidentity name="Microsoft.AspNet.SignalR.Core" publickeytoken="31bf3856ad364e35" culture="neutral" />
        <bindingredirect oldversion="0.0.0.0-2.0.3.0" newversion="2.0.3.0" />
      </dependentassembly>
      <dependentassembly>
        <assemblyidentity name="WebGrease" publickeytoken="31bf3856ad364e35" culture="neutral" />
        <bindingredirect oldversion="0.0.0.0-1.5.2.14234" newversion="1.5.2.14234" />
      </dependentassembly>
      <dependentassembly>
        <assemblyidentity name="HtmlAgilityPack" publickeytoken="bd319b19eaf3b43a" culture="neutral" />
        <bindingredirect oldversion="0.0.0.0-1.4.0.0" newversion="1.4.0.0" />
      </dependentassembly>
      <dependentassembly>
        <assemblyidentity name="Microsoft.WindowsAzure.Storage" publickeytoken="31bf3856ad364e35" culture="neutral" />
        <bindingredirect oldversion="0.0.0.0-2.1.0.4" newversion="2.1.0.4" />
      </dependentassembly>
      <dependentassembly>
        <!--<assemblyidentity name="Microsoft.Owin.Security" publickeytoken="31bf3856ad364e35" culture="neutral" />
        <bindingredirect oldversion="0.0.0.0-2.1.0.0" newversion="2.1.0.0" />-->
        <assemblyidentity name="Microsoft.Owin.Security" publickeytoken="31bf3856ad364e35" culture="neutral" />
        <bindingredirect oldversion="0.0.0.0-2.1.0.0" newversion="2.1.0.0" />
      </dependentassembly>
    </assemblybinding>
</runtime>
  <entityframework>
    <defaultconnectionfactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
  </entityframework>
  <!-- For Signalr-->
    <system.webserver>
      <modules runallmanagedmodulesforallrequests="true">
      </modules>
    </system.webserver>
</configuration>

I get the below error when i try running the Project:
C#
Error Caught in 
Error in: http://localhost:2256/signalr/hubs
Main Exception: System.NullReferenceException: Object reference not set to an instance of an object.
   at Microsoft.Owin.Mapping.MapMiddleware.<invoke>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.Owin.Host.SystemWeb.Infrastructure.ErrorState.Rethrow()
   at Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.StageAsyncResult.End(IAsyncResult ar)
   at Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContext.EndFinalWork(IAsyncResult ar)
   at System.Web.HttpApplication.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
   at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
Base Exception : System.NullReferenceException: Object reference not set to an instance of an object.
   at Microsoft.Owin.Mapping.MapMiddleware.<invoke>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.Owin.Host.SystemWeb.Infrastructure.ErrorState.Rethrow()
   at Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.StageAsyncResult.End(IAsyncResult ar)
   at Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContext.EndFinalWork(IAsyncResult ar)
   at System.Web.HttpApplication.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
   at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

Please help me with the solution.


[Edit member="Tadit"]
Corrected formatting issues.
Added pre tags.
[/Edit]
Posted
v3
Comments
There is a "Object reference not set to an instance of an object." Exception. Can you debug and see where exactly and what object is null?

1 solution

As Tadit Dash noticed, you show some System.NullReferenceException exceptions in your exception stack. But you don't show the lines in the code where the exception is thrown/propagated.

Not to worry. This is one of the very easiest cases to detect and fix. It simply means that some member/variable of some reference type is dereferenced by using and of its instance (non-static) members, which requires this member/variable to be non-null, but in fact it appears to be null. Simply execute it under debugger, it will stop the execution where the exception is thrown. Put a break point on that line, restart the application and come to this point again. Evaluate all references involved in next line and see which one is null while it needs to be not null. After you figure this out, fix the code: either make sure the member/variable is properly initialized to a non-null reference, or check it for null and, in case of null, do something else.

Please see also: want to display next record on button click. but got an error in if condition of next record function "object reference not set to an instance of an object"[^].

Sometimes, you cannot do it under debugger, by one or another reason. One really nasty case is when the problem is only manifested if software is built when debug information is not available. In this case, you have to use the harder way. First, you need to make sure that you never block propagation of exceptions by handling them silently (this is a crime of developers against themselves, yet very usual). The you need to catch absolutely all exceptions on the very top stack frame of each thread. You can do it if you handle the exceptions of the type System.Exception. In the handler, you need to log all the exception information, especially the System.Exception.StackTrace:
http://msdn.microsoft.com/en-us/library/system.exception.aspx[^],
http://msdn.microsoft.com/en-us/library/system.exception.stacktrace.aspx[^].

The stack trace is just a string showing the full path of exception propagation from the throw statement to the handler. By reading it, you can always find ends. For logging, it's the best (in most cases) to use the class System.Diagnostics.EventLog:
http://msdn.microsoft.com/en-us/library/system.diagnostics.eventlog.aspx[^].

Good luck,
—SA
 
Share this answer
 
Comments
DamithSL 30-Jun-14 23:28pm    
5wd

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