Signal Sending Messages to Group

76 Views Asked by At

I am writing an excel add-in to receive messages through SignalR with SignalR broadcast messages to a group. I have my backend functions and frontend working properly without using the groups. But after I added group to it, it is not working. For my backend, I have a AddToGroup function:

[Function("AddToGroup")]
[SignalROutput(HubName = "chatHub", ConnectionStringSetting = "AzureSignalRConnectionString")]
public static async Task<SignalRGroupAction> AddToGroup([HttpTrigger(AuthorizationLevel.Anonymous, "post")] HttpRequestData req, FunctionContext context)
{
    var logger = context.GetLogger("AddToGroup");
    try
    {
        string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
        var data = JsonConvert.DeserializeObject<AddToGroupData>(requestBody);
        logger.LogInformation($"Request Data: UserId = {data.UserId}, GroupName = {data.GroupName}");

        return new SignalRGroupAction(SignalRGroupActionType.Add)
        {
            UserId = data.UserId,
            GroupName = data.GroupName
        };
    }
    catch (Exception ex)
    {
        logger.LogError($"Exception occurred in AddToGroup: {ex.Message}");
        throw;
    }
}

And for my frontend, I am communicating with this part:

connection.start()
    .then(() => {
        console.log("Connected to SignalR hub.");
        // After connection, join the group
        fetch("http://localhost:7146/api/AddToGroup", { 
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({ 
            UserId: connection.connectionId, 
            GroupName: "Group1", 
          }),
        })
        .then(response => response.json())
        .then(data => console.log("Joined group", data))
        .catch(error => console.error("Error joining group", error));
      })
    .catch(err => console.error('Error during connection: ', err));

But when I test for my codes, it is only showing "Joined group Group1". But when I send messages, there is no display of message on my taskpane in excel. What could be the problem?

I have tried the connection.invoke method, but it is totally not working.

1

There are 1 best solutions below

0
Suresh Chikkam On

But when I send messages, there is no display of message on my taskpane in excel. What could be the problem?

Joining a SignalR group typically doesn't return data like a standard HTTP request. Instead, it might just indicate success or failure. Your server-side function AddToGroup returns a SignalRGroupAction, but the client side treats it as JSON.

  • Here, I have a SignalR hub hosted in Azure Functions and can successfully connect and receive messages with using groups.

ChatHub.cs:

using Microsoft.AspNetCore.SignalR;
using System.Threading.Tasks;

public class ChatHub : Hub
{
    public async Task AddToGroup(string groupName)
    {
        await Groups.AddToGroupAsync(Context.ConnectionId, groupName);
    }

    public async Task SendMessageToGroup(string groupName, string message)
    {
        await Clients.Group(groupName).SendAsync("ReceiveMessage", message);
    }
}

Server-Side Code (Azure Function):

[Function("AddToGroup")]
[SignalROutput(HubName = "chatHub", ConnectionStringSetting = "AzureSignalRConnectionString")]
public static async Task<SignalRGroupAction> AddToGroup([HttpTrigger(AuthorizationLevel.Anonymous, "post")] HttpRequestData req, FunctionContext context)
{
    var logger = context.GetLogger("AddToGroup");
    try
    {
        string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
        var data = JsonConvert.DeserializeObject<AddToGroupData>(requestBody);
        logger.LogInformation($"Request Data: UserId = {data.UserId}, GroupName = {data.GroupName}");

        return new SignalRGroupAction(SignalRGroupActionType.Add)
        {
            UserId = data.UserId,
            GroupName = data.GroupName
        };
    }
    catch (Exception ex)
    {
        logger.LogError($"Exception occurred in AddToGroup: {ex.Message}");
        throw;
    }
}

Client-Side Code (Excel Add-In):

var connection = new signalR.HubConnectionBuilder()
   .withUrl("https://your-api-url/chatHub")
   .configureLogging(signalR.LogLevel.Information)
   .build();

connection.on('ReceiveMessage', function (message) {
   console.log('Received message:', message);
   // Process and display the received message in your Excel task pane
});

connection.start()
   .then(function () {
       console.log('Connected to SignalR hub.');
       // Join the group
       connection.invoke('AddToGroup', 'Group1')
           .then(function () {
               console.log('Joined group Group1');
           })
           .catch(function (err) {
               console.error('Error joining group', err);
           });
   })
   .catch(function (err) {
       console.error('Error during connection: ', err);
   });
  • AddToGroup method is invoked on the server to add the Excel add-in to the specified group ("Group1"). Then, when a message is sent to the group, the clients in that group will receive the message.

  • Checking the console logs in the browser developer tools to ensure the connection is successful and that you are joining the group.

  • Send a message from the backend to the group. The received message should be logged in the browser console.

enter image description here