Steps to retrieve a roster of active users in SignalR

As someone new to SignalR, I was given my first task to create a simple chat app.

After researching and experimenting, I successfully managed to set up a working chat page.

My next step is to display a list of connected clients. Here is the code I wrote for my HUB:

public class ChatHub: Hub
{

    chatEntities dc = new chatEntities();
    public void Send(string message,string clientName)
    {
        Clients.addMessage(message,clientName);

    }

    // To store user info in the database upon joining
    public void Joined(string userId,string userName)
    {

        CurrentChattingUsers cu = new CurrentChattingUsers();
        cu.ConnectionId = userId;
        cu.UserName = userName;

        dc.CurrentChattingUsers.AddObject(cu);
        dc.SaveChanges();


       Clients.joins(userId, userName);
    }

    // Fetches a list of connected users from the database table
    public List<ClientModel> GetConnectedUsers()
    {
        var query = (from k in dc.CurrentChattingUsers
                     select new ClientModel()
                     {
                         FullName = k.UserName,
                         UserId = k.ConnectionId
                     }).ToList();
        return query;
    }   


}

So where do I go from here? Am I on the right track? And how can I call these methods from the view? Any suggestions are welcome!

EDIT:

I have included this script when the hub starts:

$.connection.hub.start(function () {
            chat.getConnectedUsers();

        });

This method returns the client names in my Hub:

  public List<ClientModel> GetConnectedUsers()
    {
        var data = (from k in dc.Users
                     select new ClientModel()
                     {
                         FullName = k.UserName

                     }).ToList();

         Clients.loadUsers(data);
        return data;
    }

In Firebug, it seems to be returning some data as shown below:

{"State":{},"Result":[{"FullName":"mokarom","UserId":null},  {"FullName":"aka8000","UserId":null},{"FullName":"johnnyno5","UserId":null},{"FullName":"reza","UserId":null},{"FullName":"amyo","UserId":null},{"FullName":"rezatech","UserId":null}],"Id":"0","Error":null,"StackTrace":null}

But how can I display that in my view?

EDIT:

This is the complete view so far:

<script type="text/javascript">
    var chat;
    var myClientName
    $(document).ready(function(){

      myClientName = '@Request.Cookies["ChatterName"].Value';


        // Created proxy
        chat = $.connection.chatHub;
        // Assign a function to be called by the server
        chat.addMessage = onAddMessage;

        // Register a function with the button click
        $("#broadcast").click(onBroadcast);


        $('#message').keydown(function (e) {
            if (e.which == 13) { //Enter
                e.preventDefault();

                onBroadcast();

            }
        });

        // Start the connection
        $.connection.hub.start(function () {
           chat.getConnectedUsers();

        });

        chat.loadUsers = function (data) {
            loadUsers(data); 

         };
    });


    function onAddMessage(message,clientName) {
        // Add the message to the list
        $('#messages').append('<div class="chatterName">' + clientName + ' </div><div class="chatterMessage"> ' + message + '</div><div class="clear">');

    }
    function onBroadcast() {
        // Call the chat method on the server
        chat.send($('#message').val(), myClientName);
        $('#message').val('');
    }
    function loadUsers(data) {
        $('#clientList').html(data.Result[0].FullName);

    }
</script>

Problem: There is nothing displayed here: $('#clientList').html(data.Result[0].FullName); Firebug indicates 'data is not defined'

Answer №1

JavaScript

var chatRoom = $.connection.chatHub;
chatRoom.loadParticipants = function (data) { loadParticipants(data); };
var connectedUserCount = 0;

$.connection.hub.start(function () 
         { chatRoom.getConnectedUsers(); });

function loadParticipants =  = function (data) {
  console.log(data); //viewing data in firebug, etc.
            
  var numberOfParticipants = data.length;  
}

Once the hub is started, the chatRoom will have all the public functions of your hub accessible as JavaScript functions. This leverages the best available connection method between client and server.

Similarly, your C# hub can access any JavaScript functions you set up, for example:

Clients.loadParticipants(query);  
//include this on your server side before returning query

PS - Consider using OnConnectedAsync, or look into persisting these connections. Also, there's anticipation for full web farm support using SQL integration mentioned in the pipeline.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Problem with resizing in CSS and jQuery

I need help creating a chatbox that can be resized. I've almost got it, but the bottom part of the chatbox detaches when I resize it. Also, I'm having trouble making the userList a fixed size that won't be affected by resizing. Check out th ...

Activate continuous speech identification

Is it possible to activate the capability of recognizing continuous speech through the REST API (using javascript SDK) with the Bing Speech API? The Javascript SDK example available at https://github.com/Microsoft/Cognitive-Speech-STT-JavaScript only seem ...

Using AngularJS to access JSON files through the $http service

I'm experiencing difficulties reading data from my test.json file using the #http service. I have everything set up on a xampp localhost, but I can't seem to figure out what's going wrong. Here's the JavaScript code. Thank you in advanc ...

Encountering difficulties when trying to send requests to an API through AJAX

Our company relies on the software nocrm.io for managing leads and customers. I am looking to integrate their API into our web application to streamline information exchange through GET and POST requests. However, I am facing challenges while trying to mak ...

What is the best way to extract the date January 1, 1970 from a datepicker?

Currently, I am utilizing a datepicker along with a function that converts dates from dd-mm-yyyy to yyyy-mm-dd format. The dates in the database are stored in yyyy-mm-dd format, so I need to first convert them to dd-mm-yyyy for better readability. When sub ...

What are some ways to reuse an angular component multiple times?

I am utilizing an angular component to dynamically load charts into my widget: Below is an example of the component: angular.module("generalApp").component("chartPie", { template: "<div class=Pie></div>", bindings: { data: "=", }, control ...

Leveraging D3.js in combination with Total.js and node.js

I have been attempting to utilize total.js in conjunction with D3 for creating a tree visualization. However, I am encountering issues when trying to download D3. This is what I do: npm install D3 Upon running the above command, I receive the following e ...

Error: "Exceeded Time Limit of xx seconds" encountered during wait.until command with Selenium WebDriver in C#

Exploring the process of waiting for a condition before logging into a web page using Selenium Driver has proven to be more complex than initially expected. Currently, I am resorting to utilizing Thread.Sleep(3000); as a workaround, although I am certain t ...

Is it feasible to showcase certain debug messages within the HTML code directly from a .cs file?

Here's the issue I'm facing: I have both my view and controller set up. The controller accesses backend classes and methods. Now, I want to create a debug version of my site. In this debug version, I want to display information generated in the ...

Check in Winforms dot.net to determine if there are more than x letters from string one present in string two and vice versa

Can someone assist me with finding the most efficient method to detect if more than a certain number of alphabets from one string are present in another string, in the same pattern and vice versa? I am currently working on a C# Windows form application. F ...

Retrieve current active Ethernet IP Address using .NET

Seeking guidance on retrieving the active IP address in .NET, specifically the one associated with the Ethernet adapter. To obtain a list of currently assigned IPs to the machine, I can use: IPHostEntry entry = Dns.GetHostEntry(Dns.GetHostName()); Addit ...

transferring information from PHP to JavaScript through the use of JSON encoding

I am currently in the process of developing a Google maps page that utilizes latitude and longitude data coordinates to generate a heat map displaying the distribution of foxes within a specific area. At present, my application functions properly when the ...

Update the path dynamically in Next.js without the need to reload the page

Every time the user clicks on the continue button, a function is triggered. Within that function, I make the following call: push("/signup/page-2", undefined, { shallow: true }); All dynamic routes resembling /signup/[page].js that return <Component / ...

The performance of the animation on http://responsive-nav.com/ becomes erratic when viewed on Android devices

Recently, I came across a fantastic plugin that works perfectly on regular computer browsers. However, when I tested it on my android phone, the css3 animation for the dropdown appeared choppy and seemed to be dropping frames. Does anyone have suggestions ...

What are some ways to prevent sorting and dragging of an element within ul lists?

A list styled with bullets contains various items. It is important that the last item in the list remains in a fixed position. I attempted to disable sorting using the cancel option of the .sortable() method, but it only prevented dragging without disablin ...

Navigating through nested objects in JSON when working with D3: a guide

Currently, I am in the process of learning D3 using various tutorials. Here is the code snippet I have been working with: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title ...

Enclosing Material UI's DataGrid GridActionsCellItem within a custom wrapper component triggers a visual glitch if showInMenu is enabled

Here is how my MUI DataGrid columns are structured: const columns = [ { field: "name", type: "string" }, { field: "actions", type: "actions", width: 80, getActions: (params) => [ ...

In what scenarios would you choose to use "class" instead of "id"?

I am currently utilizing Bootstrap to style my table, which serves as a basic to-do list. My intention is to insert a form input into one cell and place a check button in the cell adjacent to it on the right side. To achieve this, I plan to utilize id="che ...

What is the best way to select a random item from a DropDownList using JavaScript?

I am looking to automate the process of selecting random items from a dropdown list. Currently, it is selecting items in order from first to last, but I would like it to select items randomly. /* function to automatically select items from DropDownList1 * ...

Issue with sending functions to other components in Angular

I'm currently facing an issue with passing functions to other objects in Angular. Specifically, I've developed a function generateTile(coords) that fills a tile to be used by leaflet. This function is located within a method in the MapComponent. ...