Showing posts with label signalr-hub. Show all posts
Showing posts with label signalr-hub. Show all posts

Sunday, September 23, 2018

How to bring Hub content from Any server to *another server* project Hub?

Leave a Comment

There is a confusion in the arrangement of codes and the place where it pleases so I hope to find an explanation for the following:

When I have a server "https://localhost:48009/" and the application is equipped with all the requirements of Signal-R and also Hub exists on it. in folder Hubs There is a Hub Class ChatHub.cs

using System; using System.Web; using Microsoft.AspNet.SignalR; namespace SignalRChat {     public class ChatHub : Hub     {         public void Send(string name, string message)         {             // Call the addNewMessageToPage method to update clients.             Clients.All.addNewMessageToPage(name, message);         }     } } 

and in Chat.cshtml

@{     ViewBag.Title = "Chat"; } <h2>Chat</h2> <div class="container">     <input type="text" id="message" />     <input type="button" id="sendmessage" value="Send" />     <input type="hidden" id="displayname" />     <ul id="discussion">     </ul> </div> @section scripts {     <!--Script references. -->     <!--The jQuery library is required and is referenced by default in _Layout.cshtml. -->     <!--Reference the SignalR library. -->     <script src="~/Scripts/jquery.signalR-2.1.0.min.js"></script>     <!--Reference the autogenerated SignalR hub script. -->     <script src="~/signalr/hubs"></script>     <!--SignalR script to update the chat page and send messages.-->      <script>         $(function () {             // Reference the auto-generated proxy for the hub.               var chat = $.connection.chatHub;             // Create a function that the hub can call back to display messages.             chat.client.addNewMessageToPage = function (name, message) {                 // Add the message to the page.                  $('#discussion').append('<li><strong>' + htmlEncode(name)                      + '</strong>: ' + htmlEncode(message) + '</li>');             };             // Get the user name and store it to prepend to messages.             $('#displayname').val(prompt('Enter your name:', ''));             // Set initial focus to message input box.               $('#message').focus();             // Start the connection.             $.connection.hub.start().done(function () {                 $('#sendmessage').click(function () {                     // Call the Send method on the hub.                      chat.server.send($('#displayname').val(), $('#message').val());                     // Clear text box and reset focus for next comment.                      $('#message').val('').focus();                 });             });         });         // This optional function html-encodes messages for display in the page.         function htmlEncode(value) {             var encodedValue = $('<div />').text(value).html();             return encodedValue;         }     </script> } 

Everything works fine as you open the page on more than one browser

Here all operations occur within the server "https://localhost:48009/"

I happened to have another project on another server For example "http://localhost:18098/"

in index.cshtml

@{     ViewBag.Title = "index"; } <h2>Chat</h2> <div class="container">     <input type="text" id="message" />     <input type="button" id="sendmessage" value="Send" />     <input type="hidden" id="displayname" />     <ul id="discussion">     </ul> </div> @section scripts {     <!--Script references. -->     <!--The jQuery library is required and is referenced by default in _Layout.cshtml. -->     <!--Reference the SignalR library. -->     <script src="~/Scripts/jquery.signalR-2.1.0.min.js"></script>     <!--Reference the autogenerated SignalR hub script. -->       ///////////////////gotohub here     <script src="https://localhost:48009//signalr/hubs"></script>     <!--SignalR script to update the chat page and send messages.-->        <script>         $(function () {             // Reference the auto-generated proxy for the hub.                ///////Link to the other server              var chat = $.connection.chatHub.url="https://localhost:48009/";             // Create a function that the hub can call back to display messages.             chat.client.addNewMessageToPage = function (name, message) {                 // Add the message to the page.                  $('#discussion').append('<li><strong>' + htmlEncode(name)                      + '</strong>: ' + htmlEncode(message) + '</li>');             };             // Get the user name and store it to prepend to messages.             $('#displayname').val(prompt('Enter your name:', ''));             // Set initial focus to message input box.               $('#message').focus();             // Start the connection.             $.connection.hub.start().done(function () {                 $('#sendmessage').click(function () {                     // Call the Send method on the hub.                      chat.server.send($('#displayname').val(), $('#message').val());                     // Clear text box and reset focus for next comment.                      $('#message').val('').focus();                 });             });         });         // This optional function html-encodes messages for display in the page.         function htmlEncode(value) {             var encodedValue = $('<div />').text(value).html();             return encodedValue;         }     </script> } 

Here I also seem to apply solutions to similar problems. Is this method correct?

Knowing another server "http://localhost:18098/" It is also equipped Signal-R

I want to bring Hub content from there to another server Hub.

1 Answers

Answers 1

  1. Add Nuget package SignalR

  2. Add "Startup" Class to App_Start

  3. Change your web.config as bellow

    <appSettings>         <add key="owin:AppStartup" value="YourProjectName.App_Start.Startup"/> </appSettings> 
  4. Add Hub Folder under your project

  5. Modify Hub Class As Bellow

    namespace YourProjectName.ChatHub {     [HubName("ChatHub")]     public class ChatHub : Hub {         [HubMethodName("Sendchat")]         public void Send(String Message,String Touser) {              Clients.Client(Touser).GotMessages(Message);//send messages to specific user            //Clients.All.GotMessages(Message); //seln messages to all user             String CName = Message;         }          [HubMethodName("hubconnect")]         public void Get_Connect(String Name) {             Clients.All.GotMessages(Name +" Connected  Connection Id is "+ this.Context.ConnectionId);             String CName = Name;         }          public override System.Threading.Tasks.Task OnConnected() {             return base.OnConnected();         }          public override System.Threading.Tasks.Task OnReconnected() {             return base.OnReconnected();         }          public override System.Threading.Tasks.Task OnDisconnected(bool stopCalled) {             return base.OnDisconnected(stopCalled);         }     } } 

Change your Cshtml as Bellow

<h2>Chat</h2> <div class="container">     <input type="text" id="name" placeholder="tousername"/>     <input type="text" id="message" placeholder="message" />     <input type="button" id="sendmessage" value="Send" />     <input type="hidden" id="displayname" />     <ul id="discussion"></ul> </div>  @section scripts{  <script src="~/Scripts/jquery.signalR-2.3.0.min.js"></script> <!--Add your jquery.signalR- version above--> <script src="~/signalr/hubs"></script> <script>         $(function () {             // Reference the auto-generated proxy for the hub.             var chatProxy;             chatProxy = $.connection.ChatHub;              $('#displayname').val(prompt('Enter your name:', ''));              chatProxy.client.GotMessages = function (Message) {                 alert(Message);                 $('#discussion').append('<div>'+Message+'</br></div>');             };              $.connection.hub.start().done(function () {                 try {                     $.connection.ChatHub.server.hubconnect($('#displayname').val());                 } catch (e) {                     alert(e.message);                 }             });              $('#sendmessage').click(function () {                 // Call the Send method on the hub.                 chatProxy.server.Sendchat($('#message').val(), $('#name').val());                 // Clear text box and reset focus for next comment.                 $('#message').val('').focus();             });          });  </script> } 
Read More

Monday, June 20, 2016

Troubleshooting SignalR Serialization

Leave a Comment

I have the following code:

 try {             _hubConnection = new HubConnection(_baseUrl);             _hubConnection.CookieContainer = new CookieContainer();             _hubConnection.CookieContainer.Add(_cookie);             _hubProxy = _hubConnection.CreateHubProxy("appHub");             _hubConnection.Start().Wait();         }  catch (Exception e) {             Elmah.ErrorSignal.FromCurrentContext().Raise(new Exception("Serialization error [hubConnection] - " + e.Message + ", " + e.InnerException.Message + ", " + e.ToString()));         } 

Usually, this works. Every once in a while, I get a random serialization error though:

Serialization error [hubConnection] - One or more errors occurred., Unexpected character encountered while parsing value: <. Path '', line 0, position 0., System.AggregateException: One or more errors occurred. ---> Newtonsoft.Json.JsonReaderException: Unexpected character encountered while parsing value: <. Path '', line 0, position 0.  at Newtonsoft.Json.JsonTextReader.ParseValue()  at Newtonsoft.Json.JsonTextReader.Read()  at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.ReadForType(JsonReader reader, JsonContract contract, Boolean hasConverter)  at  

This Unexpected character encountered while parsing value: < seems very difficult to reproduce, and I don't know how to get detailed information around this. I do have this configured:

        var hubConfiguration = new HubConfiguration { EnableDetailedErrors = true };         app.MapSignalR(hubConfiguration); 

Does anyone know what might be causing this, or how I might go about troubleshooting?

Full trace:

System.Exception: Messaging Error [hubConnection]    at App.Services.NotificationService.SignalObjectToUser(Object data, String username, Boolean isTypingNotification)    at App.Services.NotificationService.MessageSentNotification(User toUser, Message message, Int32 conversationId, Boolean isOnline)    at App.Services.MessageService.SendMessage(MessageDto message, FStopContext altContext)    at App.ApiControllers.MessageController.SendMessage(MessageDto message) at lambda_method(Closure , Object , Object[] )    at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass10.b__9(Object instance, Object[] methodParameters)    at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)    at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken) --- End of stack trace from previous location where exception was thrown ---    at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)    at System.Web.Http.Controllers.ApiControllerActionInvoker.d__0.MoveNext() --- End of stack trace from previous location where exception was thrown ---    at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)    at System.Web.Http.Filters.ActionFilterAttribute.d__5.MoveNext() --- End of stack trace from previous location where exception was thrown ---    at System.Web.Http.Filters.ActionFilterAttribute.d__5.MoveNext() --- End of stack trace from previous location where exception was thrown ---    at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)    at System.Web.Http.Filters.ActionFilterAttribute.d__0.MoveNext() --- End of stack trace from previous location where exception was thrown ---    at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)    at System.Web.Http.Filters.ActionFilterAttribute.d__5.MoveNext() --- End of stack trace from previous location where exception was thrown ---    at System.Web.Http.Filters.ActionFilterAttribute.d__5.MoveNext() --- End of stack trace from previous location where exception was thrown ---    at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)    at System.Web.Http.Filters.ActionFilterAttribute.d__0.MoveNext() --- End of stack trace from previous location where exception was thrown ---    at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)    at System.Web.Http.Filters.ActionFilterAttribute.d__5.MoveNext() --- End of stack trace from previous location where exception was thrown ---    at System.Web.Http.Filters.ActionFilterAttribute.d__5.MoveNext() --- End of stack trace from previous location where exception was thrown ---    at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)    at System.Web.Http.Filters.ActionFilterAttribute.d__0.MoveNext() --- End of stack trace from previous location where exception was thrown ---    at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)    at System.Web.Http.Filters.ActionFilterAttribute.d__5.MoveNext() --- End of stack trace from previous location where exception was thrown ---    at System.Web.Http.Filters.ActionFilterAttribute.d__5.MoveNext() --- End of stack trace from previous location where exception was thrown ---    at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)    at System.Web.Http.Filters.ActionFilterAttribute.d__0.MoveNext() --- End of stack trace from previous location where exception was thrown ---    at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)    at System.Web.Http.Controllers.ActionFilterResult.d__2.MoveNext() --- End of stack trace from previous location where exception was thrown ---    at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)    at System.Web.Http.Filters.AuthorizationFilterAttribute.d__2.MoveNext() --- End of stack trace from previous location where exception was thrown ---    at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)    at System.Web.Http.Controllers.ExceptionFilterResult.d__0.MoveNext() 

1 Answers

Answers 1

There are a couple of things I would try before digging deeper into the content being transmitted:

  1. Set up the hub connection without a cookie container. This would narrow down whether this is causing the issue.
  2. Rather than using .Wait() on your hub connection, try use an async/await function. I seem to recall having a similar exception when I was using Wait() in the past.

Post back your results.

Read More