locked
Multiple Hubs connections RRS feed

  • Question

  • User-762556441 posted

    Hello

    I'm trying to get data from 2 sql tables to show them in 2 differents view in asp mvc. I've created 2 different Hub class :

    The first for the table AppSubTasks and the second for the table AppTasks

    using Microsoft.AspNet.SignalR;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using Microsoft.AspNet.SignalR.Hubs;
    using System.Configuration;
    
    namespace MyApp.Web.Hubs
    {
        public class AppSubTasksHub : Hub
        {
            private static string conString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString();
            public void Hello()
            {
                Clients.All.hello();
            }
    
            [HubMethodName("sendMessagesSub")]
            public static void SendMessagesSub()
            {
                IHubContext context = GlobalHost.ConnectionManager.GetHubContext<AppSubTasksHub>();
                context.Clients.All.updateMessages();
            }
        }
    }
    using Microsoft.AspNet.SignalR;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using Microsoft.AspNet.SignalR.Hubs;
    using System.Configuration;
    
    namespace MyApp.Web.Hubs
    {
        public class AppTasksHub : Hub
        {
            private static string conString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString();
            public void Hello()
            {
                Clients.All.hello();
            }
    
            [HubMethodName("sendMessages")]
            public static void SendMessages()
            {
                IHubContext context = GlobalHost.ConnectionManager.GetHubContext<AppTasksHub>();
                context.Clients.All.updateMessages();
            }
        }
    }

    Well for the first view that shows data from AppTasks table all works fine . This is the view and the controller action and the database operations :

    @model IEnumerable<MyApp.Web.Models.AppTasks>
     @using Microsoft.AspNet.Identity;   
    
    @{
        ViewBag.Title = "Index";
    }
    
    <div class="row wrapper border-bottom white-bg page-heading">
        <div class="col-sm-4">
            <h2>Robots Dashboard</h2>
        </div>
        <div class="col-lg-2">
    
        </div>
    </div>
    <div class="wrapper wrapper-content animated fadeInRight">
    
        <div class="row">
            <div class="col-lg-12">
                <div class="ibox float-e-margins">
                    <div class="ibox-title">
                        <h5>List of App</h5>
                        <div class="ibox-tools">
                            <a class="collapse-link">
                                <i class="fa fa-chevron-up"></i>
                            </a>
                            <a class="dropdown-toggle" data-toggle="dropdown" href="#">
                                <i class="fa fa-wrench"></i>
                            </a>
                            <ul class="dropdown-menu dropdown-user">
                                <li>
                                    @Html.ActionLink("Create New", "Create", new { valoareselectata = "", weburltree = "" , weburl="" , snapshots ="", numevm="", descriptiontree =""}, new { @class = "btn btn-primary btn-xs" })
                                   @* <a href=@Url.Action("Create", "TestingImages")>Add new Testing Image</a>*@
    
                                </li>
                            </ul>
                            <a class="close-link">
                                <i class="fa fa-times"></i>
                            </a>
                        </div>
    
                       
                    </div>
                    <div class="ibox-content">
                        <div style="overflow:scroll;width:100%;overflow:auto">
                            <div id="tasksTable"></div>
                       </div>
                        </div>
                </div>
            </div>
        </div>
    
    </div>
    
    
    @section Styles {
        @Styles.Render("~/Content/plugins/dataTables/dataTablesStyles")
    }
    @section Scripts {
        @Scripts.Render("~/plugins/jeditable")
        @Scripts.Render("~/plugins/dataTables")
    
    <script src="/Scripts/jquery.signalR-2.2.0.js"></script>
    <!--Reference the autogenerated SignalR hub script. -->
    <script src="/signalr/hubs"></script>
    
    
        <script type="text/javascript">
            $(function () {
                // Declare a proxy to reference the hub.
                var notifications = $.connection.appTasksHub;
    
                //debugger;
                // Create a function that the hub can call to broadcast messages.
                notifications.client.updateMessages = function () {
                    getAllTasks()
    
                };
                // Start the connection.
                $.connection.hub.start().done(function () {
                    alert("connection started")
                    getAllTasks();
                }).fail(function (e) {
                    alert(e);
                });
    
            });
            function getAllTasks() {
                var tbl = $('#tasksTable');
                $.ajax({
                    url: '/RobotsDashboard/GetAppTasks',
                    contentType: 'application/html ; charset:utf-8',
                    type: 'GET',
                    dataType: 'html'
                }).success(function (result) {
                    tbl.empty().append(result);
                    $('.dataTables_wrapper').DataTable();
                   }).error(function () {
    
                });
            }
        </script>
    }
    The actions from controller 
    
       public ActionResult Index()
            {
                string usercreat = User.Identity.GetUserId();
                try
                {
                    var allbyuser = db.AppTasks.Where(x => x.CreatedBy == usercreat).ToList();
                    return View(allbyuser);
                }
                catch (System.Data.Entity.ModelConfiguration.ModelValidationException ex)
                {
    
                    throw new DbEntityValidationException(ex.Message, ex.InnerException);
                }
    
            }
    
            public ActionResult GetAppTasks()
            {
                string useridcurent = User.Identity.GetUserId();
                AppTasksRepository _tasksRepository = new AppTasksRepository();
                return PartialView("_AppTasksList", _tasksRepository.GetAllAppTasks(useridcurent));
            }
    
    using MyApp.Web.Hubs;
    using System;
    using System.Collections.Generic;
    using System.Configuration;
    using System.Data;
    using System.Data.Entity;
    using System.Data.SqlClient;
    using System.Linq;
    using System.Web;
    
    namespace MyApp.Web.Models
    {
        public class AppTasksRepository
        {
                   readonly string _connString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
    
            public IEnumerable<AppTasks> GetAllAppTasks(string userid)
            {
                var tasks = new List<AppTasks>();
                using (var connection = new SqlConnection(_connString))
                {
                    connection.Open();
                    using (var command = new SqlCommand(@"SELECT [AppTaskId], [IdIntern], [ApplicationName], [Project], [PackageType],[AppStatusId] ,[CreatedDate], [CreatedBy] FROM [dbo].[AppTasks] WHERE CreatedBy='" + userid + "'", 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())
                        {
                            tasks.Add(item: new AppTasks { AppTaskId = (int)reader["AppTaskId"], IdIntern = (string)reader["Idintern"], ApplicationName =  (string)reader["ApplicationName"], Project = (string) reader ["Project"], PackageType = (string ) reader["PackageType"] , AppStatusId = (int)reader["AppStatusId"], CreatedDate = Convert.ToDateTime(reader["CreatedDate"]), CreatedBy = (string)reader["CreatedBy"] });
                        }
                    }
                  
                }
                return tasks;
               
                
            }
    
    
    
    
            private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
            {
                if (e.Type == SqlNotificationType.Change)
                {
                    AppTasksHub.SendMessages();
                }
            }
        }
    }
    

    The problem is that from the second view  the data is showed but when i insert new line in the table AppSubTasks this line is not writed in real time in the table . This is the view /action from controller and database operations  for the second table

    @model IEnumerable<MyApp.Web.Models.AppSubTasks>
    
    @{
        ViewBag.Title = "Index";
    }
    <div class="row wrapper border-bottom white-bg page-heading">
        <div class="col-sm-4">
            <h2>Tasks Details</h2>
        </div>
        <div class="col-lg-2">
        </div>
    </div>
    <div class="wrapper wrapper-content animated fadeInRight">
        <div class="row">
            <div class="col-lg-12">
                <div class="ibox float-e-margins">
                    <div class="ibox-title">
                        <h5>List of task</h5>
                        <div class="ibox-tools">
                            <a class="collapse-link">
                                <i class="fa fa-chevron-up"></i>
                            </a>
                            <a class="dropdown-toggle" data-toggle="dropdown" href="#">
                                <i class="fa fa-wrench"></i>
                            </a>
                            <ul class="dropdown-menu dropdown-user">
                                <li>
                                    @Html.ActionLink("Create New", "Create", new { valoareselectata = "", weburltree = "", weburl = "", snapshots = "", numevm = "", descriptiontree = "" }, new { @class = "btn btn-primary btn-xs" })
                                    @* <a href=@Url.Action("Create", "TestingImages")>Add new Testing Image</a>*@
    
                                </li>
                            </ul>
                            <a class="close-link">
                                <i class="fa fa-times"></i>
                            </a>
                        </div>
    
                    </div>
                    <div class="ibox-content">
                        <div style="overflow:scroll;width:100%;overflow:auto">
                            <div id="subtasksTable"></div>  
                            <input type="hidden" value="@ViewBag.IdSelected" id="idvalue" /> 
                        </div>
                    </div>
                </div>
            </div>
        </div>
    
    
    
    </div>
    
    @section Styles {
        @Styles.Render("~/Content/plugins/dataTables/dataTablesStyles")
    }
    @section Scripts {
        @Scripts.Render("~/plugins/jeditable")
        @Scripts.Render("~/plugins/dataTables")
    
        <script src="/Scripts/jquery.signalR-2.2.0.js"></script>
        <!--Reference the autogenerated SignalR hub script. -->
        <script src="/signalr/hubs"></script>
    
    
        <script type="text/javascript">
            $(function () {
                // Declare a proxy to reference the hub.
                var notifications = $.connection.appSubTasksHub;
    
                //debugger;
                // Create a function that the hub can call to broadcast messages.
                notifications.client.updateMessages = function () {
                    getAllSubTasks()
    
                };
                // Start the connection.
                $.connection.hub.start().done(function () {
                    alert("connection started")
                    getAllSubTasks();
                }).fail(function (e) {
                    alert(e);
                });
    
            });
    
            function getAllSubTasks() {
                var tbl = $('#subtasksTable');
                var idv = $('#idvalue').val();
                $.ajax({
                    url: '/RobotsDashboard/GetAppSubTasks',
                    contentType: 'application/html ; charset:utf-8',
                    type: 'GET',
                    data: { id: idv },
                    dataType: 'html'
                }).success(function (result) {
                    tbl.empty().append(result);
                    $('.dataTables_wrapper').DataTable();
                }).error(function () {
    
                });
            }
        </script>
    }
      public ActionResult GetAppSubTasks(int id)
            {
                AppSubTasksRepository _subtasksRepository = new AppSubTasksRepository();
                return PartialView("_AppSubTasksList", _subtasksRepository.GetAllAppSubTasks(id));
            }
    
    using MyApp.Web.Hubs;
    using System;
    using System.Collections.Generic;
    using System.Configuration;
    using System.Data;
    using System.Data.Entity;
    using System.Data.SqlClient;
    using System.Linq;
    using System.Web;
    
    namespace MyApp.Web.Models
    {
        public class AppSubTasksRepository
        {
                   readonly string _connString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
    
            public IEnumerable<AppSubTasks> GetAllAppSubTasks(int AppTaskIdSelected)
            {
                var subtasks = new List<AppSubTasks>();
                using (var connection = new SqlConnection(_connString))
                {
                    connection.Open();
                    string qry = "SELECT AppSubTaskId,AppTaskId,ModuleName,SubTaskName,IdIntern,ApplicationName,Project,AppStatusId,CreatedDate,StartedDate,FinishedDate,SubTaskOperations,IsAutomated FROM AppSubTasks WHERE AppTaskId=" + AppTaskIdSelected.ToString();
                    using (var command = new SqlCommand(qry, 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())
                        {
                            var item = new AppSubTasks();
                            item.AppSubTaskId = (int)reader["AppSubTaskId"];
                            item.AppTaskId = (int)reader["AppTaskId"];
                            item.ModuleName = (string)reader["ModuleName"];
                            item.SubTaskName = (string)reader["SubTaskName"];
                            item.IdIntern = (string)reader["IdIntern"];
                            item.ApplicationName = (string)reader["ApplicationName"];
                            item.Project = (string)reader["Project"];
                            item.AppStatusId = (int)reader["AppStatusId"];
                            item.CreatedDate = Convert.ToDateTime(reader["CreatedDate"]);
                            item.StartedDate = Convert.ToDateTime(reader["StartedDate"]);
                            item.FinishedDate = Convert.ToDateTime(reader["FinishedDate"]);
                            item.SubTaskOperations = (string)reader["SubTaskOperations"];
                            item.IsAutomated = (bool)reader["IsAutomated"];
    
    
                            subtasks.Add(item);
                        }
    
    
                    }
                  
                }
                return subtasks;
               
                
            }
    
            private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
            {
                if (e.Type == SqlNotificationType.Change)
                {
                    AppSubTasksHub.SendMessagesSub();
                }
            }
        }
    }
    

    When I run the first time the view that shows the data from AppSubTasks table all works fine, but after I added new lines to the sql table these lines is not push in real time to that view. Where I wrong ? The first hub that connects works fine but the second will not receive events.
    Please help me . Thanks in advance

    Tuesday, April 26, 2016 1:15 PM

Answers

  • User61956409 posted

    Hi clauhd,

    When I run the first time the view that shows the data from AppSubTasks table all works fine, but after I added new lines to the sql table these lines is not push in real time to that view. Where I wrong ? The first hub that connects works fine but the second will not receive events.

    Firstly, you could use F12 developer tools Network tool to check if you could start hub and call hub method successfully.

    Secondly, according to your description, it seems that dependency_OnChange event could not fire, please debug client-side&server-side code of SignalR to check if any error with the code.

    Besides, you could try to enable tracing for SignalR servers and clients. And you could try to define all Hub functionality in a single class.

    http://www.asp.net/signalr/overview/testing-and-debugging/enabling-signalr-tracing

    Best Regards,

    Fei Han

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, April 27, 2016 3:24 AM