Quickstart: Create an App showing GitHub star count with Azure Functions and SignalR Service using C#

Azure SignalR Service lets you easily add real-time functionality to your application. Azure Functions is a serverless platform that lets you run your code without managing any infrastructure. In this quickstart, learn how to use SignalR Service and Azure Functions to build a serverless application with C# to broadcast messages to clients.

Note

You can get all codes mentioned in the article from GitHub

Prerequisites

If you don't already have Visual Studio Code installed, you can download and use it for free(https://code.visualstudio.com/Download).

You may also run this tutorial on the command line (macOS, Windows, or Linux) using the Azure Functions Core Tools). Also the .NET Core SDK, and your favorite code editor.

If you don't have an Azure subscription, create one for free before you begin.

Having issues? Try the troubleshooting guide or let us know.

Log in to Azure and create SignalR Service instance

Sign in to the Azure portal at https://portal.azure.com/ with your Azure account.

Having issues? Try the troubleshooting guide or let us know.

Create an Azure SignalR Service instance

Your application will connect to a SignalR Service instance in Azure.

  1. Select the New button found on the upper left-hand corner of the Azure portal. In the New screen, type SignalR Service in the search box and press enter.

    Screenshot shows search for SignalR Service in the Azure portal.

  2. Select SignalR Service from the search results, then select Create.

  3. Enter the following settings.

    Setting Suggested value Description
    Resource name Globally unique name Name that identifies your new SignalR Service instance. Valid characters are a-z, 0-9, and -.
    Subscription Your subscription The subscription under which this new SignalR Service instance is created.
    Resource Group myResourceGroup Name for the new resource group in which to create your SignalR Service instance.
    Location West US Choose a region near you.
    Pricing tier Free Try Azure SignalR Service for free.
    Unit count Not applicable Unit count specifies how many connections your SignalR Service instance can accept. It is only configurable in the Standard tier.
    Service mode Serverless For use with Azure Functions or REST API.

    Screenshot shows SignalR Basics tab with values.

  4. Select Create to start deploying the SignalR Service instance.

  5. After the instance is deployed, open it in the portal and locate its Settings page. Change the Service Mode setting to Serverless only if you are using Azure SignalR Service through Azure Functions binding or REST API. Leave it in Classic or Default otherwise.

Having issues? Try the troubleshooting guide or let us know.

Setup and run the Azure Function locally

  1. Make sure you have Azure Function Core Tools installed. And create an empty directory and navigate to the directory with command line.

    # Initialize a function project
    func init --worker-runtime dotnet
    
    # Add SignalR Service package reference to the project
    dotnet add package Microsoft.Azure.WebJobs.Extensions.SignalRService
    
  2. After you initialize a project. Create a new file with name Function.cs. Add the following code to Function.cs.

    using System;
    using System.IO;
    using System.Net.Http;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Http;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Azure.WebJobs;
    using Microsoft.Azure.WebJobs.Extensions.Http;
    using Microsoft.Azure.WebJobs.Extensions.SignalRService;
    using Newtonsoft.Json;
    
    namespace CSharp
    {
        public static class Function
        {
            private static HttpClient httpClient = new HttpClient();
    
            [FunctionName("index")]
            public static IActionResult Index([HttpTrigger(AuthorizationLevel.Anonymous)]HttpRequest req, ExecutionContext context)
            {
                var path = Path.Combine(context.FunctionAppDirectory, "content", "index.html");
                return new ContentResult
                {
                    Content = File.ReadAllText(path),
                    ContentType = "text/html",
                };
            }
    
            [FunctionName("negotiate")]
            public static SignalRConnectionInfo Negotiate( 
                [HttpTrigger(AuthorizationLevel.Anonymous)] HttpRequest req,
                [SignalRConnectionInfo(HubName = "serverlessSample")] SignalRConnectionInfo connectionInfo)
            {
                return connectionInfo;
            }
    
            [FunctionName("broadcast")]
            public static async Task Broadcast([TimerTrigger("*/5 * * * * *")] TimerInfo myTimer,
            [SignalR(HubName = "serverlessSample")] IAsyncCollector<SignalRMessage> signalRMessages)
            {
                var request = new HttpRequestMessage(HttpMethod.Get, "https://api.github.com/repos/azure/azure-signalr");
                request.Headers.UserAgent.ParseAdd("Serverless");
                var response = await httpClient.SendAsync(request);
                var result = JsonConvert.DeserializeObject<GitResult>(await response.Content.ReadAsStringAsync());
                await signalRMessages.AddAsync(
                    new SignalRMessage
                    {
                        Target = "newMessage",
                        Arguments = new[] { $"Current star count of https://github.com/Azure/azure-signalr is: {result.StarCount}" }
                    });
            }
    
            private class GitResult
            {
                [JsonRequired]
                [JsonProperty("stargazers_count")]
                public string StarCount { get; set; }
            }
        }
    }
    

    These codes have three functions. The Index is used to get a website as client. The Negotiate is used for client to get access token. The Broadcast is periodically get star count from GitHub and broadcast messages to all clients.

  3. The client interface of this sample is a web page. Considered we read HTML content from content/index.html in GetHomePage function, create a new file index.html in content directory under project root folder. And copy the following content.

    <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;
          });
    
          connection.start()
            .catch(console.error);
      </script>
    </body>
    
    </html>
    
  4. Update your *.csproj to make the content page in build output folder.

    <ItemGroup>
      <None Update="content/index.html">
        <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
      </None>
    </ItemGroup>
    
  5. It's almost done now. The last step is to set a connection string of the SignalR Service to Azure Function settings.

    1. In the browser where the Azure portal is opened, confirm the SignalR Service instance you deployed earlier was successfully created by searching for its name in the search box at the top of the portal. Select the instance to open it.

      Search for the SignalR Service instance

    2. Select Keys to view the connection strings for the SignalR Service instance.

      Screenshot that highlights the primary connection string.

    3. Copy the primary connection string. And execute the command below.

      func settings add AzureSignalRConnectionString "<signalr-connection-string>"
      
  6. Run the Azure Function in local:

    func start
    

    After Azure Function running locally. Use your browser to visit http://localhost:7071/api/index and you can see the current star count. And if you star or unstar in the GitHub, you will get a star count refreshing every few seconds.

    Note

    SignalR binding needs Azure Storage, but you can use local storage emulator when the Function is running locally. If you got some error like There was an error performing a read operation on the Blob Storage Secret Repository. Please ensure the 'AzureWebJobsStorage' connection string is valid. You need to download and enable Storage Emulator

Having issues? Try the troubleshooting guide or let us know

Clean up resources

If you're not going to continue to use this app, delete all resources created by this quickstart with the following steps so you don't incur any charges:

  1. In the Azure portal, select Resource groups on the far left, and then select the resource group you created. Alternatively, you may use the search box to find the resource group by its name.

  2. In the window that opens, select the resource group, and then click Delete resource group.

  3. In the new window, type the name of the resource group to delete, and then click Delete.

Having issues? Try the troubleshooting guide or let us know.

Next steps

In this quickstart, you built and ran a real-time serverless application in local. Learn more how to use SignalR Service bindings for Azure Functions. Next, learn more about how to bi-directional communicating between clients and Azure Function with SignalR Service.