Client Implementation Examples

Complete examples for connecting to the SpecificationQuestionnaireHub

Quick Start

1

Install
@microsoft/signalr

2

Configure
Hub URL + Auth token

3

Register Handlers
connection.on(...)

4

Subscribe
invoke("SubscribeToSpecification")

Hub Information

Endpoint/default/hubs/specification-questionnaires
AuthenticationJWT Bearer token (via accessTokenFactory)
Client MethodsSubscribeToSpecification, UnsubscribeFromSpecificationId
Server EventsSpecificationQuestionnaireSectionUpdated
TransportsWebSocket, Server-Sent Events, Long Polling

TypeScript / JavaScript

import * as signalR from "@microsoft/signalr";

export class SpecificationQuestionnaireClient {
  private connection: signalR.HubConnection;
  private subscribedSpecifications: Set<string> = new Set();

  constructor(private hubUrl: string, private getToken: () => Promise<string>) {
    this.connection = new signalR.HubConnectionBuilder()
      .withUrl(hubUrl, {
        accessTokenFactory: getToken
      })
      .withAutomaticReconnect([0, 2000, 5000, 10000, 30000])
      .configureLogging(signalR.LogLevel.Information)
      .build();

    this.setupEventHandlers();
    this.setupReconnection();
  }

  private setupEventHandlers(): void {
    this.connection.on("SpecificationQuestionnaireSectionUpdated", (data) => {
      console.log("Questionnaire section updated:", data);
      this.onQuestionnaireUpdated?.(data);
    });
  }

  private setupReconnection(): void {
    this.connection.onreconnected(async () => {
      console.log("Reconnected - resubscribing to specifications");
      for (const specId of this.subscribedSpecifications) {
        await this.connection.invoke("SubscribeToSpecification", specId);
      }
    });
  }

  async connect(): Promise<void> {
    await this.connection.start();
  }

  async subscribe(specificationId: string): Promise<void> {
    await this.connection.invoke("SubscribeToSpecification", specificationId);
    this.subscribedSpecifications.add(specificationId);
  }

  async unsubscribe(specificationId: string): Promise<void> {
    await this.connection.invoke("UnsubscribeFromSpecificationId", specificationId);
    this.subscribedSpecifications.delete(specificationId);
  }

  async disconnect(): Promise<void> {
    this.subscribedSpecifications.clear();
    await this.connection.stop();
  }

  // Event callback
  onQuestionnaireUpdated?: (data: { specificationId: string; chapterType: string }) => void;
}

React Hook

import { useEffect, useRef, useCallback, useState } from "react";
import * as signalR from "@microsoft/signalr";

export function useSpecificationQuestionnaires(specificationId, getToken) {
  const connectionRef = useRef(null);
  const [updates, setUpdates] = useState([]);
  const [connectionState, setConnectionState] = useState("Disconnected");

  useEffect(() => {
    if (!specificationId) return;

    const connection = new signalR.HubConnectionBuilder()
      .withUrl("/default/hubs/specification-questionnaires", {
        accessTokenFactory: getToken
      })
      .withAutomaticReconnect()
      .build();

    connection.on("SpecificationQuestionnaireSectionUpdated", (data) => {
      setUpdates(prev => [data, ...prev]);
    });

    connection.onreconnected(async () => {
      setConnectionState("Connected");
      await connection.invoke("SubscribeToSpecification", specificationId);
    });

    connection.onclose(() => setConnectionState("Disconnected"));

    const start = async () => {
      try {
        await connection.start();
        setConnectionState("Connected");
        await connection.invoke("SubscribeToSpecification", specificationId);
      } catch (err) {
        console.error("SignalR connection failed:", err);
        setConnectionState("Error");
      }
    };

    start();
    connectionRef.current = connection;

    return () => {
      connection.stop();
    };
  }, [specificationId, getToken]);

  const clearUpdates = useCallback(() => setUpdates([]), []);

  return { updates, connectionState, clearUpdates };
}

C# / .NET Client

using Microsoft.AspNetCore.SignalR.Client;

public class SpecificationQuestionnaireSignalRClient : IAsyncDisposable
{
    private readonly HubConnection _connection;
    private readonly HashSet<Guid> _subscriptions = new();

    public event Action<Guid, string>? OnQuestionnaireSectionUpdated;

    public SpecificationQuestionnaireSignalRClient(string hubUrl, Func<Task<string>> tokenProvider)
    {
        _connection = new HubConnectionBuilder()
            .WithUrl(hubUrl, options =>
            {
                options.AccessTokenProvider = tokenProvider;
            })
            .WithAutomaticReconnect()
            .Build();

        _connection.On<QuestionnaireSectionDto>("SpecificationQuestionnaireSectionUpdated", dto =>
        {
            OnQuestionnaireSectionUpdated?.Invoke(dto.SpecificationId, dto.ChapterType);
        });

        _connection.Reconnected += async _ =>
        {
            foreach (var specId in _subscriptions)
                await _connection.InvokeAsync("SubscribeToSpecification", specId);
        };
    }

    public async Task ConnectAsync() => await _connection.StartAsync();

    public async Task SubscribeAsync(Guid specificationId)
    {
        await _connection.InvokeAsync("SubscribeToSpecification", specificationId);
        _subscriptions.Add(specificationId);
    }

    public async Task UnsubscribeAsync(Guid specificationId)
    {
        await _connection.InvokeAsync("UnsubscribeFromSpecificationId", specificationId);
        _subscriptions.Remove(specificationId);
    }

    public async ValueTask DisposeAsync()
    {
        _subscriptions.Clear();
        await _connection.DisposeAsync();
    }

    private record QuestionnaireSectionDto(Guid SpecificationId, string ChapterType);
}

Best Practices

Register handlers before connecting — Ensures you don't miss events during the connection handshake.
Use withAutomaticReconnect() — Handles transient disconnections without manual intervention.
Resubscribe on reconnect — Group memberships are lost on disconnect; resubscribe in the onreconnected handler.
Avoid subscribing to many specifications simultaneously — Subscribe only to the specification the user is currently viewing.
Always unsubscribe when navigating away — Clean up subscriptions when the component unmounts or the user navigates to a different specification.

Common Issues

Ensure your accessTokenFactory returns a valid, non-expired JWT token. The token must have the required scopes for the Specification API.

Use withAutomaticReconnect() to handle this automatically. If using Long Polling, ensure keep-alive is configured on the server.

SignalR group memberships are not persisted across reconnections. Use the onreconnected handler to re-invoke SubscribeToSpecification.

Your company must be either the retailer or supplier on the specification. Verify the specification is shared with your company.