Base solution for your next web application
Open Closed

Send from console app messages to specific user of a specific tenant #11776


User avatar
0
pliaspzero created

Usage: Angular + .NET core ASPZERO version 12x:

I needs to send messages to specific user of a specific tenant from console app. How could that work? below some proposal fromChatGTP

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

class Program { static async Task Main(string[] args) { // Configuration var apiUrl = "http://your-api-url"; var hubPath = "/yourHubPath"; var accessToken = "your-access-token"; // Obtain from your authentication mechanism

    var hubConnection = new HubConnectionBuilder()
        .WithUrl($"{apiUrl}{hubPath}", options =>
        {
            options.AccessTokenProvider = () => Task.FromResult(accessToken);
        })
        .Build();

    // Handle connection events
    hubConnection.Closed += async (error) =>
    {
        Console.WriteLine($"Connection closed. Reconnecting...");
        await Task.Delay(new Random().Next(0, 5) * 1000);
        await hubConnection.StartAsync();
    };

    // Start the connection
    await hubConnection.StartAsync();
    Console.WriteLine($"Connection started with connection ID: {hubConnection.ConnectionId}");

    // Send a message to a specific user
    await SendMessageToUser(hubConnection, "userId123", "Hello to specific user!");

    // Close the connection when done
    await hubConnection.StopAsync();
    Console.WriteLine("Connection stopped.");
}

static async Task SendMessageToUser(HubConnection hubConnection, string userId, string message)
{
    try
    {
        await hubConnection.InvokeAsync("SendMessageToUser", userId, message);
        Console.WriteLine($"Message sent to user {userId}: {message}");
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Error sending message: {ex.Message}");
    }
}

}


3 Answer(s)