Articles in this section
Category / Section

How to Embed the Bold BI Dashboard in Blazor Using JavaScript Interoperability?

Published:

This article provides a step-by-step guide on how to embed a Bold BI dashboard in a Blazor application using JavaScript interoperability. This allows developers to invoke JavaScript functions from within a non-JavaScript environment like Blazor and, conversely, invoke the functions in Blazor from JavaScript.

Prerequisites

  • Download the Blazor WebAssembly project.
  • Ensure that the Bold BI application is hosted and embed authentication is enabled in the embed settings.

Steps to Embed Bold BI Dashboard

1. Setup JavaScript Interoperability

In your Blazor project, you need to set up JavaScript interoperability to call JavaScript functions from Blazor and vice versa.

Modifyindex.razor

Open the index.razor file located in the Pages folder and include the following code:

@page "/"
@inject IJSRuntime JsRuntime
<div id="dashboard"> </div>
@functions {
    protected override void OnAfterRender(bool firstRender)
    {
        JsRuntime.InvokeAsync<object>("callCSharpMethod");
    }
}

image.png

2. Include Bold BI SDK in index.html

Open the index.html file located in the wwwroot folder of your Blazor project and add the following script tags, which has the Bold BI Embed SDK and the method to invoke the backend method. Here we use a method callCSharpMethod() which invokes the “CSharp” method to handle back-end functionality.

<script type="text/javascript" src="https://cdn.boldbi.com/embedded-sdk/latest/boldbi-embed.js"></script>
<script>
    var data;
    async function fetchDataAndHandleErrors() {
        try {
            const response = await fetch('/api/EmbedData/GetConfig');
            const embedConfig = await response.json();
            data = embedConfig;
        } catch (error) {
            window.location.href = 'api/EmbedData/EmbedConfigErrorLog';
        }
    }

    fetchDataAndHandleErrors();

    function renderDashboard(EmbedData) {
        this.dashboard = BoldBI.create({
            serverUrl: data.ServerUrl + "/" + data.SiteIdentifier,
            dashboardId: data.DashboardId,
            embedContainerId: "dashboard",
            embedType: data.EmbedType,
            environment: data.Environment,
            mode: BoldBI.Mode.View,
            width: "100%",
            height: window.innerHeight - 3 + "px",
            expirationTime: 100000,
            authorizationServer: {
                url: "",
                data: EmbedData
            },
        });
        this.dashboard.loadDashboard();
    }

    async function callCSharpMethod() {
        try {
            const result = await DotNet.invokeMethodAsync('BlazorWebAssembly.Client', 'CSCallBackMethod', JSON.stringify(data));
            console.log(result);
            renderDashboard(JSON.parse(result));
        } catch (error) {
            console.error('Error:', error);
        }
    }
</script>

image.png

3. Create Backend Functionality

Create a new C# file in the same pages folder to handle the backend functionality for the JavaScript InterOp. Below is an example implementation, this will render the dashboard by default to embed widget and other embedding modules’ code must be modified accordingly.

using Microsoft.JSInterop;
using Newtonsoft.Json;

namespace BlazorWebAssembly.Client.Pages
{
    public class InterOp
    {
        [JSInvokable]
        public static async Task<string> CSCallBackMethod(string testing)
        {
            var data = JsonConvert.DeserializeObject<ServerDetails>(testing);
            var dashboardServerApiUrl = data.ServerUrl + "/api/" + data.SiteIdentifier;
            var embedQuerString = "embed_nonce=" + Guid.NewGuid().ToString();
            embedQuerString += "&embed_timestamp=" + (int)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;
            embedQuerString += "&embed_mode=view";
            embedQuerString += "&embed_expirationtime=100000";
            embedQuerString += "&embed_dashboard_id=" + data.DashboardId;
            embedQuerString += "&embed_user_email=" + data.UserEmail;
            embedQuerString += "&embed_server_timestamp=" + (int)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;
            var embedDetailsUrl = "/embed/authorize?" + embedQuerString + "&embed_signature=" + GetSignatureUrl(embedQuerString, data.EmbedSecret);

            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(dashboardServerApiUrl);
                client.DefaultRequestHeaders.Accept.Clear();

                var result = await client.GetAsync(dashboardServerApiUrl + embedDetailsUrl);
                var resultContent = await result.Content.ReadAsStringAsync();
                return resultContent;
            }
        }

        public static string GetSignatureUrl(string message, string embedSecret)
        {
            var encoding = new System.Text.UTF8Encoding();
            var keyBytes = encoding.GetBytes(embedSecret);
            var messageBytes = encoding.GetBytes(message);
            using (var hmacsha1 = new System.Security.Cryptography.HMACSHA256(keyBytes))
            {
                var hashMessage = hmacsha1.ComputeHash(messageBytes);
                return Convert.ToBase64String(hashMessage);
            }
        }

        public class ServerDetails
        {
            [JsonProperty("DashboardId")]
            public string DashboardId { get; set; }

            [JsonProperty("ServerUrl")]
            public string ServerUrl { get; set; }

            [JsonProperty("UserEmail")]
            public string UserEmail { get; set; }

            [JsonProperty("EmbedSecret")]
            public string EmbedSecret { get; set; }

            [JsonProperty("SiteIdentifier")]
            public string SiteIdentifier { get; set; }
        }
    }
}

image.png

4. Run the application

To run the application download the embedConfig.json from the Bold BI application and include it as highlighted below,

image.png

image.png

Conclusion

By following the steps outlined above, you can successfully embed a Bold BI dashboard in your Blazor application using JavaScript interoperability. This integration allows for a seamless user experience and enhances the functionality of your Blazor applications.

Additional References

Was this article useful?
Like
Dislike
Help us improve this page
Please provide feedback or comments
SM
Written by Soundarya Mani Meharan
Updated:
Comments (0)
Please  to leave a comment
Access denied
Access denied