Showing posts with label SignalR. Show all posts
Showing posts with label SignalR. Show all posts

Monday, August 11, 2025

Real-Time Progress Updates with Azure Functions and SignalR Using Python

Real-Time Progress Updates with Azure Functions and SignalR Using Python

https://learn.microsoft.com/en-us/azure/azure-signalr/signalr-quickstart-azure-functions-python?pivots=python-mode-decorators

Real-Time Progress Updates with Azure Functions and SignalR Using Python

This article demonstrates how to build a serverless Python application using Azure Functions and Azure SignalR Service to deliver real-time progress updates to clients. The solution includes HTTP endpoints, negotiation for SignalR connections, and timer triggers that broadcast messages and simulate progress updates for long-running operations.

Project File Structure

├── function_app.py
├── host.json
├── local.settings.json
├── requirements.txt
├── content/
│   └── index.html

Required Files

1. function_app.py

Main Azure Functions app with SignalR integration and timer triggers.

2. host.json

Azure Functions host configuration.

{
    "version": "2.0"
}

3. local.settings.json

Local development settings (update AzureSignalRConnectionString with your value).

{
    "IsEncrypted": false,
    "Values": {
        "AzureWebJobsStorage": "UseDevelopmentStorage=true",
        "FUNCTIONS_WORKER_RUNTIME": "python",
        "AzureSignalRConnectionString": "<your-signalr-connection-string>"
    }
}

4. requirements.txt

Python dependencies for Azure Functions and HTTP requests.

azure-functions
requests

5. content/index.html

Sample HTML page for the index endpoint.

<html>

<body>
  <h1>Azure SignalR Serverless Sample</h1>
  <div id="messages"></div>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/3.1.7
    /signalr.min.js"></script>
  <script>
    let messages = document.querySelector('#messages');
    const apiBaseUrl = window.location.origin;
    const connection = new signalR.HubConnectionBuilder()
        .withUrl(apiBaseUrl + '/api')
        .configureLogging(signalR.LogLevel.Information)
        .build();
      connection.on('newMessage', (message) => {
        document.getElementById("messages").innerHTML = message;
      });

      // Display progress updates from the InsertTables timer
      connection.on('ProgressUpdate', (percent, message) => {
        const div = document.createElement('div');
        div.textContent = `${percent}% - ${message}`;
        messages.appendChild(div);
      });

      connection.start()
        .catch(console.error);
  </script>
</body>

</html>

Overview

  • Azure Functions: Used to create serverless endpoints and timer triggers.
  • Azure SignalR Service: Enables real-time communication between server and clients.
  • Python: Implements the logic for HTTP triggers, negotiation, and progress simulation.

Key Features

  1. HTTP Trigger: Responds to HTTP requests with a personalized message.
  2. Index Endpoint: Serves a static HTML page.
  3. SignalR Negotiation: Provides connection info for SignalR clients.
  4. Broadcast Timer: Periodically fetches GitHub star count and broadcasts it.
  5. Insert Tables Timer: Simulates inserting tables and sends progress updates to SignalR clients.

Complete Code

import azure.functions as func
import logging
import azure.functions as func
import os
import requests
import json 
import time

app = func.FunctionApp(http_auth_level=func.AuthLevel.FUNCTION)

etag = ''
start_count = 0

@app.route(route="http_trigger")
def http_trigger(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')

    name = req.params.get('name')
    if not name:
        try:
            req_body = req.get_json()
        except ValueError:
            pass
        else:
            name = req_body.get('name')

    if name:
        return func.HttpResponse(f"Hello, {name}. This HTTP triggered function executed successfully.")
    else:
        return func.HttpResponse(
             "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.",
             status_code=200
        )
    

@app.route(route="index", auth_level=func.AuthLevel.ANONYMOUS)
def index(req: func.HttpRequest) -> func.HttpResponse:
    f = open(os.path.dirname(os.path.realpath(__file__)) + '/content/index.html')
    return func.HttpResponse(f.read(), mimetype='text/html')


@app.route(route="negotiate", auth_level=func.AuthLevel.ANONYMOUS, methods=["POST"])
@app.generic_input_binding(arg_name="connectionInfo", type="signalRConnectionInfo", hubName="serverless", connectionStringSetting="AzureSignalRConnectionString")
def negotiate(req: func.HttpRequest, connectionInfo) -> func.HttpResponse:
    return func.HttpResponse(connectionInfo)


@app.timer_trigger(schedule="*/1 * * * *", arg_name="myTimer",
              run_on_startup=False,
              use_monitor=False)
@app.generic_output_binding(arg_name="signalRMessages", type="signalR", hubName="serverless", connectionStringSetting="AzureSignalRConnectionString")
def broadcast(myTimer: func.TimerRequest, signalRMessages: func.Out[str]) -> None:
    global etag
    global start_count
    headers = {'User-Agent': 'serverless', 'If-None-Match': etag}
    res = requests.get('https://api.github.com/repos/azure/azure-functions-python-worker', headers=headers)
    if res.headers.get('ETag'):
        etag = res.headers.get('ETag')

    if res.status_code == 200:
        jres = res.json()
        start_count = jres['stargazers_count']

    signalRMessages.set(json.dumps({
        'target': 'newMessage',
        'arguments': [ 'Current star count of https://api.github.com/repos/azure/azure-functions-python-worker is: ' + str(start_count) ]
    }))


# New timer trigger: simulate inserting 10 tables and emit progress updates to SignalR
@app.timer_trigger(schedule="*/1 * * * *", arg_name="tablesTimer",
              run_on_startup=False,
              use_monitor=False)
@app.generic_output_binding(arg_name="signalRMessages", type="signalR", hubName="serverless", connectionStringSetting="AzureSignalRConnectionString")
def insert_tables_timer(tablesTimer: func.TimerRequest, signalRMessages: func.Out[str]) -> None:
    logging.info('InsertTables timer started.')

    total_tables = 10
    messages = []

    for i in range(1, total_tables + 1):
        # Simulate time-consuming insert
        time.sleep(1)

        percent = (i * 100) // total_tables
        msg = f"Table {i} of {total_tables} inserted."
        messages.append({
            'target': 'ProgressUpdate',
            'arguments': [percent, msg]
        })

    # Final success message
    messages.append({
        'target': 'ProgressUpdate',
        'arguments': [100, 'All tables inserted successfully.']
    })

    # Note: SignalR output binding in Python sends messages when the function completes.
    # We therefore batch all progress updates in a single payload.
    signalRMessages.set(json.dumps(messages))
    logging.info('InsertTables timer completed and progress sent to SignalR.')

How It Works

  • The broadcast function fetches the latest star count from GitHub and sends it to all connected SignalR clients every minute.
  • The insert_tables_timer function simulates a long-running operation (inserting tables) and sends progress updates to SignalR clients in real time.
  • All SignalR messages are sent when the function completes, so progress is batched and delivered together.

Next Steps

  • Deploy the function app to Azure.
  • Configure the Azure SignalR Service and connection string.
  • Build a client (e.g., web app) to receive and display real-time updates.

This approach is ideal for scenarios where you need to inform users about the progress of background tasks, such as data imports or batch processing, using serverless technologies and real-time messaging.

OutPut:
Run Function App: func host start
Open this url: http://localhost:7071/api/index


----------------------------------------------------------------------

index.html
<html>

<body>
  <h1>Azure SignalR Serverless Sample</h1>
  <div id="messages"></div>
  <button id="startProgress">Start Progress</button>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/3.1.7
    /signalr.min.js"></script>
  <script>
    let messages = document.querySelector('#messages');
    const apiBaseUrl = window.location.origin;
   
    // Generate a new GUID when page loads
    function generateGUID() {
      return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
      });
    }
   
    const sessionGuid = generateGUID();
    console.log('Generated GUID:', sessionGuid);
   
    const connection = new signalR.HubConnectionBuilder()
        .withUrl(apiBaseUrl + '/api')
        .configureLogging(signalR.LogLevel.Information)
        .build();
      connection.on('newMessage', (message) => {
        document.getElementById("messages").innerHTML = message;
      });

      // Display progress updates using the generated GUID
      connection.on(sessionGuid, (percent, message) => {
        const div = document.createElement('div');
        div.textContent = `[Manual] ${percent}% - ${message}`;
        div.style.color = 'blue';
        messages.appendChild(div);
      });

      // Display timer progress updates (broadcasted to all clients)
      // connection.on('TimerProgress', (percent, message, sessionId) => {
      //   const div = document.createElement('div');
      //   div.textContent = `[Auto] ${percent}% - ${message}`;
      //   div.style.color = 'green';
      //   messages.appendChild(div);
      // });

      connection.start()
        .then(() => {
          console.log('SignalR connection established');
         
          // Add event listener for the start progress button
          document.getElementById('startProgress').addEventListener('click', () => {
            // Clear previous messages
            messages.innerHTML = '';
           
            // Start the progress
            fetch(apiBaseUrl + '/api/startProgress', {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json',
              },
              body: JSON.stringify({ guid: sessionGuid })
            }).catch(console.error);
          });
        })
        .catch(console.error);
  </script>
</body>

</html>


function_app.py
import azure.functions as func
import logging
import azure.functions as func
import os
import requests
import json
import time

app = func.FunctionApp(http_auth_level=func.AuthLevel.FUNCTION)

etag = ''
start_count = 0

@app.route(route="http_trigger")
def http_trigger(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')

    name = req.params.get('name')
    if not name:
        try:
            req_body = req.get_json()
        except ValueError:
            pass
        else:
            name = req_body.get('name')

    if name:
        return func.HttpResponse(f"Hello, {name}.
            This HTTP triggered function executed successfully.")
    else:
        return func.HttpResponse(
             "This HTTP triggered function executed successfully. Pass a name in the
    query string or in the request body for a personalized response.",
             status_code=200
        )
   

@app.route(route="index", auth_level=func.AuthLevel.ANONYMOUS)
def index(req: func.HttpRequest) -> func.HttpResponse:
    f = open(os.path.dirname(os.path.realpath(__file__)) + '/content/index.html')
    return func.HttpResponse(f.read(), mimetype='text/html')


@app.route(route="negotiate", auth_level=func.AuthLevel.ANONYMOUS, methods=["POST"])
@app.generic_input_binding(arg_name="connectionInfo", type="signalRConnectionInfo",
    hubName="serverless", connectionStringSetting="AzureSignalRConnectionString")
def negotiate(req: func.HttpRequest, connectionInfo) -> func.HttpResponse:
    return func.HttpResponse(connectionInfo)


@app.route(route="startProgress", auth_level=func.AuthLevel.ANONYMOUS,
    methods=["POST"])
@app.generic_output_binding(arg_name="signalRMessages", type="signalR",
    hubName="serverless", connectionStringSetting="AzureSignalRConnectionString")
def start_progress(req: func.HttpRequest, signalRMessages: func.Out[str]) ->
    func.HttpResponse:
    try:
        req_body = req.get_json()
        if req_body and req_body.get('guid'):
            client_guid = req_body.get('guid')
            logging.info(f'Starting progress for client GUID: {client_guid}')
           
            total_tables = 10
            messages = []

            for i in range(1, total_tables + 1):
                # Simulate time-consuming insert
                time.sleep(1)

                percent = (i * 100) // total_tables
                msg = f"Table {i} of {total_tables} inserted. {client_guid}"
                messages.append({
                    'target': client_guid,
                    'arguments': [percent, msg]
                })

            # Final success message
            messages.append({
                'target': client_guid,
                'arguments': [100, 'All tables inserted successfully.']
            })

            signalRMessages.set(json.dumps(messages))
            return func.HttpResponse(f"Progress started for GUID: {client_guid}",
    status_code=200)
        else:
            return func.HttpResponse("No GUID provided", status_code=400)
    except Exception as e:
        logging.error(f'Error starting progress: {str(e)}')
        return func.HttpResponse("Error starting progress", status_code=500)


# @app.timer_trigger(schedule="*/10 * * * * *", arg_name="myTimer",
run_on_startup=False, use_monitor=False)
# @app.generic_output_binding(arg_name="signalRMessages1", type="signalR",
hubName="serverless", connectionStringSetting="AzureSignalRConnectionString")
# def broadcast(myTimer: func.TimerRequest, signalRMessages1: func.Out[str]) -> None:
#     global etag
#     global start_count
#     headers = {'User-Agent': 'serverless', 'If-None-Match': etag}
#     res = requests.get('https://api.github.com/repos/azure
/azure-functions-python-worker', headers=headers)
#     if res.headers.get('ETag'):
#         etag = res.headers.get('ETag')

#     if res.status_code == 200:
#         jres = res.json()
#         start_count = jres['stargazers_count']

#     signalRMessages1.set(json.dumps({
#         'target': 'newMessage',
#         'arguments': [ 'Current star count of https://api.github.com/repos
/azure/azure-functions-python-worker is: ' + str(start_count) ]
#     }))


# # Timer trigger: simulate inserting 10 tables and emit progress updates to SignalR
# # This version broadcasts to all clients - each client can choose to display or
ignore
# @app.timer_trigger(schedule="*/15 * * * * *", arg_name="tablesTimer",
run_on_startup=False, use_monitor=False)
# @app.generic_output_binding(arg_name="signalRMessages2", type="signalR",
hubName="serverless", connectionStringSetting="AzureSignalRConnectionString")
# def insert_tables_timer(tablesTimer: func.TimerRequest, signalRMessages2:
func.Out[str]) -> None:
#     logging.info('InsertTables timer started.')

#     # Generate a unique session ID for this timer run
#     import uuid
#     timer_session_id = str(uuid.uuid4())
   
#     total_tables = 10
#     messages = []

#     for i in range(1, total_tables + 1):
#         # Simulate time-consuming insert
#         time.sleep(1)

#         percent = (i * 100) // total_tables
#         msg = f"Timer Session: Table {i} of {total_tables} inserted."
#         messages.append({
#             'target': 'TimerProgress',
#             'arguments': [percent, msg, timer_session_id]
#         })

#     # Final success message
#     messages.append({
#         'target': 'TimerProgress',
#         'arguments': [100, 'Timer Session: All tables inserted successfully.',
timer_session_id]
#     })

#     signalRMessages2.set(json.dumps(messages))
#     logging.info(f'InsertTables timer completed. Session ID: {timer_session_id}')



OutPut:
Run Function App: func host start
Open this url: http://localhost:7071/api/index




Friday, August 8, 2025

Real-Time Progress Updates with ASP.NET Core and SignalR

Real-Time Progress Updates with ASP.NET Core and SignalR

In this article, we'll walk through building a simple web application to demonstrate real-time progress updates for a long-running server task using ASP.NET Core and SignalR. This is a common requirement in web applications where you need to provide feedback to the user for operations like file uploads, data processing, or report generation.

Prerequisites

Before you begin, ensure you have the following installed:

Project Setup

First, let's create a new ASP.NET Core Web API project. Open your terminal and run the following commands:

dotnet new webapi -n SignalRProgressDemo
cd SignalRProgressDemo

Next, we need to add the necessary SignalR package.

dotnet add package Microsoft.Azure.SignalR

This will set up a basic project structure for us to build upon.

Project Structure

Here is the folder structure of our SignalRProgressDemo project:

SignalRProgressDemo/
├── Controllers/
│   └── InsertController.cs
├── Properties/
│   └── launchSettings.json
├── wwwroot/
│   └── index.html
├── appsettings.Development.json
├── appsettings.json
├── Program.cs
├── ProgressHub.cs
├── SignalRProgressDemo.csproj
└── SignalRProgressDemo.sln

File-by-File Breakdown

Here’s a detailed look at each of the files we'll be creating or modifying.

1. Program.cs

This is the entry point of our application. We need to configure services for SignalR and controllers, and map the SignalR hub and controller endpoints.

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddSignalR();
//builder.Services.AddSignalR().AddAzureSignalR("<connection_string>");
//builder.Services.AddSignalR().
AddAzureSignalR(builder.Configuration["AzureSignalR:ConnectionString"]);
builder.Services.AddControllers(); builder.Services.AddOpenApi(); var app = builder.Build(); app.UseDefaultFiles(); app.UseStaticFiles(); app.MapHub<SignalRProgressDemo.ProgressHub>("/progressHub"); app.MapControllers(); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.MapOpenApi(); } var summaries = new[] { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" }; app.MapGet("/weatherforecast", () => { var forecast = Enumerable.Range(1, 5).Select(index => new WeatherForecast ( DateOnly.FromDateTime(DateTime.Now.AddDays(index)), Random.Shared.Next(-20, 55), summaries[Random.Shared.Next(summaries.Length)] )) .ToArray(); return forecast; }) .WithName("GetWeatherForecast"); app.Run(); record WeatherForecast(DateOnly Date, int TemperatureC, string? Summary) { public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); }

2. ProgressHub.cs

This is our SignalR hub. A hub is a class that serves as a high-level pipeline that handles client-server communication. It has methods that can be called by clients, and the server can also invoke methods on the clients.

Create a new file ProgressHub.cs and add the following code:

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

namespace SignalRProgressDemo
{
    public class ProgressHub : Hub
    {
        // Method to send progress updates to clients
        public async Task SendProgress(int percent)
        {
            await Clients.All.SendAsync("ProgressUpdate", percent);
        }
    }
}

3. Controllers/InsertController.cs

This API controller will simulate a long-running task. When the InsertTables endpoint is called, it will loop and send progress updates to the clients via the ProgressHub.

Create a Controllers folder if it doesn't exist, and add a new file InsertController.cs with the following code:

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

namespace SignalRProgressDemo.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class InsertController : ControllerBase
    {
        private readonly IHubContext<ProgressHub> _hubContext;

        public InsertController(IHubContext<ProgressHub> hubContext)
        {
            _hubContext = hubContext;
        }

        [HttpPost]
        public async Task<IActionResult> InsertTables()
        {
            int totalTables = 10;
            for (int i = 1; i <= totalTables; i++)
            {
                // Simulate table insert (replace with actual DB logic)
                await Task.Delay(1000); // Simulate time-consuming insert
                int percent = (i * 100) / totalTables;
                var message = $"Table {i} of {totalTables} inserted.";
                await _hubContext.Clients.All.SendAsync("ProgressUpdate", percent, message);
            }
            await _hubContext.Clients.All.SendAsync("ProgressUpdate", 100, "All tables inserted successfully.");
            return Ok(new { message = "All tables inserted." });
        }
    }
}

4. wwwroot/index.html

This is our client-side application. It's a simple HTML page with JavaScript to connect to the SignalR hub, display a progress bar, and provide a button to start the server-side task.

Create a wwwroot folder in your project root, and inside it, create an index.html file:

<!DOCTYPE html>
<html>
<head>
    <title>SignalR Progress Demo</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/7.0.5/signalr.min.js"></script>
    <style>
        #progressBar {
            width: 100%;
            background-color: #eee;
        }
        #progress {
            width: 0%;
            height: 30px;
            background-color: #4caf50;
            text-align: center;
            color: white;
        }
    </style>
</head>
<body>
    <h2>Insert Progress</h2>
    <div id="progressBar">
        <div id="progress">0%</div>
    </div>
    <div id="message"></div>
    <button onclick="startInsert()">Start Insert</button>
    <script>
        const connection = new signalR.HubConnectionBuilder()
            .withUrl("/progressHub")
            .build();

        connection.on("ProgressUpdate", function (percent, message) {
            const progress = document.getElementById("progress");
            const messageDiv = document.getElementById("message");
            progress.style.width = percent + "%";
            progress.textContent = percent + "%";
            messageDiv.textContent = message;
        });

        async function startInsert() {
            await fetch("/api/insert", { method: "POST" });
        }

        connection.start().catch(function (err) {
            return console.error(err.toString());
        });
    </script>
</body>
</html>

5. SignalRProgressDemo.csproj

This is the project file. It should include the package reference for SignalR.

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net9.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.6" />
    <PackageReference Include="Microsoft.AspNetCore.SignalR" Version="1.2.0" />
    <PackageReference Include="Microsoft.Azure.SignalR" Version="1.31.0" />
  </ItemGroup>

</Project>

6. appsettings.json

This file contains configuration settings for the application. For this demo, we can also include the Azure SignalR connection string if we were to deploy it.

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "AzureSignalR": {
    "ConnectionString": "Endpoint=https://rg2signalrr.service.signalr.net;AccessKey=;Version=1.0;"
  }
}

7. Properties/launchSettings.json

This file configures how the application is launched for development.

{
  "$schema": "https://json.schemastore.org/launchsettings.json",
  "profiles": {
    "http": {
      "commandName": "Project",
      "dotnetRunMessages": true,
      "launchBrowser": false,
      "applicationUrl": "http://localhost:5186",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

How It Works

  1. Client Connection: When the index.html page is loaded, the JavaScript code establishes a connection to our ProgressHub on the server.
  2. Initiating the Task: The user clicks the "Start Insert" button, which sends a POST request to the /api/insert endpoint.
  3. Server-Side Processing: The InsertController receives the request and starts a simulated long-running task.
  4. Broadcasting Progress: Inside the loop, the controller calculates the progress percentage and uses the IHubContext<ProgressHub> to send a "ProgressUpdate" message to all connected clients.
  5. Client-Side Update: The JavaScript on the client side is listening for the "ProgressUpdate" message. When it receives one, it updates the width and text of the progress bar.

Running the Project

To run the project, open your terminal in the project's root directory and execute:

dotnet run

Then, open your web browser and navigate to http://localhost:5186 (the port may vary, check the terminal output). You should see the "Insert Progress" page. Click the "Start Insert" button to see the progress bar update in real-time.

Conclusion

You've successfully built a web application that provides real-time progress updates using ASP.NET Core and SignalR. This pattern is incredibly useful for improving user experience in applications with long-running background tasks. From here, you could extend this project to handle real database operations, file processing, or any other asynchronous task.

OutPut:







Featured Post

Extract Power Automate Desktop Flow Code from a Solution Export with PowerShell

Reviewing Power Automate Desktop (PAD) flows is harder than reviewing normal code. The logic lives inside the designer, spread across Main a...

Popular posts