Search results

Embedding Bold BI Dashboards in Blazor using the Embedded SDK

The sample has been provided in the following sections for the Blazor WebAssembly, which demonstrates the dashboard rendering available in your Bold BI server and is followed by steps to create a new embedding application in the Blazor WebAssembly on your own.

NOTE: Reading the Getting Started section of the documentation is the best way to get started. The Getting Started guide gives you enough information that you need to know before working on the sample.

Prerequisites

How to run Blazor WebAssembly sample

  1. Please get the Blazor WebAssembly sample from GitHub.

  2. Please ensure you have enabled embed authentication on the embed settings page. If it is not currently enabled, please refer to the following image or detailed instructions to enable it. Embed Settings

  3. To download the embedConfig.json file, please follow this link for reference. Additionally, you can refer to the following image for visual guidance. EmbedSettings image EmbedConfig Properties

  4. Copy the downloaded embedConfig.json file and paste it into the Server folder location within the application. Please ensure you have placed it in the application, as shown in the following image.

    EmbedConfig image

    ServerUrl Dashboard Server BI URL (ex: http://localhost:5000/bi, https://demo.boldbi.com/bi)
    SiteIdentifier For the Bold BI Enterprise edition, it should be like site/site1. For Bold BI Cloud, it should be an empty string.
    UserEmail UserEmail of the Admin in your Bold BI, which would be used to get the dashboard list.
    EmbedSecret Get your EmbedSecret key from the Embed tab by enabling the Enable embed authentication in the Administration page
    Environment Your Bold BI application environment. (If it is a cloud analytics server, use `BoldBI.Environment.Cloud`; if it is your server, use `BoldBI.Environment.Enterprise`)
    DashboardId Item ID of the dashboard to be embedded in your application.
    ExpirationTime Token expiration time. (In the EmbedConfig.json file, the default token expiration time is 10000 seconds)
  5. Open your project in Visual Studio Code.

  6. Open the terminal and navigate to the Server project directory using the cd command(e.g., cd C:\BlazorProject\Server).

  7. To run the application, use the command dotnet watch run in the terminal of Visual Studio Code.

  8. The dashboard can be editable in design mode and create a new dashboard with the following changes in the renderDashboard() method.

    dashboardId Provide the dashboard ID of the dashboard you want to embed in view or edit mode. In order to create a new dashboard, please exclude this specific property.
    mode In which mode do you want to render the dashboard? It can either be 'BoldBI.Mode.View' or 'BoldBI.Mode.Design' mode.
    authorizationServer Url of the 'authorizationServerAPI' action in the application.
        function renderDashboard() {
          this.dashboard = BoldBI.create({
                serverUrl: data.ServerUrl + "/" + data.SiteIdentifier,
                dashboardId: data.DashboardId,
                embedContainerId: "dashboard",
                embedType: data.EmbedType,
                environment: data.Environment,
                mode: BoldBI.Mode.Design,
                width: window.innerWidth - 300 + "px",
                height: window.innerHeight - 100 + "px",
                expirationTime: 100000,
                authorizationServer: {
                    url: authorizationServerUrl
                },
            });
            dashboard.loadDesigner();
        };

How the Blazor WebAssembly sample works

  1. Based on the dashboard provided in the index.html, authorize the server URL by calling the AuthorizationServer function as follows. Authorization Server

  2. In the above authorization, generate the SignatureUrl with the provided EmbedSecret key and validate the authorization in Bold BI. Once authorization is validated, the dashboard starts to render.

  3. In embedConfig.json, change the dashboard ID of the respective dashboard as you wish to embed. EmbedProperties

Steps to create new Blazor WebAssembly application to embed dashboard

  1. Create a folder in the desired location and open it in the Visual Studio Code.

  2. Open the terminal in the Visual Studio Code. Please refer to the following image. Terminal Image

  3. To create a new project, we need to run this command in the terminal.

         dotnet new blazorwasm --hosted
  4. Please ensure you have enabled embed authentication on the embed settings page. If it is not currently enabled, please refer to the following image or detailed instructions to enable it. Embed Settings

  5. To download the embedConfig.json file, please follow this link for reference. Additionally, you can refer to the following image for visual guidance. EmbedSettings image EmbedConfig Properties

  6. Copy the downloaded embedConfig.json file and paste it into the Server folder location within the application. Please ensure you have placed it in the application, as shown in the following image.

    EmbedConfig image

  7. In the Shared project, create a new folder called Models. Create a model class as DataClass.cs to define the following properties. These properties are used to get the dashboard details from the server.

    Open the terminal and navigate to the Shared project directory using the cd command(e.g., cd C:\BlazorProject\Shared). Execute the following commands in the terminal to add the necessary references to the project: dotnet add package Newtonsoft.Json and dotnet add package System.Runtime.Serialization.Primitives. Ensure the System.Runtime.Serialization and Newtonsoft.Json namespaces are in the DataClass.cs model file.

    [DataContract]
    public class EmbedClass
    {
        [DataMember]
        public string embedQuerString { get; set; }
        [DataMember]
        public string dashboardServerApiUrl { get; set; }
    }
    
    public class EmbedDetails
    {
        public string Environment { get; set; }
    
        public string SiteIdentifier { get; set; }
    
        public string ServerUrl { get; set; }
    
        public string EmbedSecret { get; set; }
    
        public string UserEmail { get; set; }
    
        public string EmbedType { get; set; }
        
        public string DashboardId { get; set; }
    }
    
  8. In the Shared Project, create another model class as GlobalAppSettings.cs to define the following properties. These properties maintain the embedConfig.json file object within the GlobalAppSettings.

    public class GlobalAppSettings
    {
        public static EmbedDetails EmbedDetails { get; set; }
    }
  9. In the Client project, the following scripts and style sheets are mandatory to render the dashboard. Include the following code in your \wwwroot\index.html page of the <head> tag.

    <script type="text/javascript" src="https://cdn.boldbi.com/embedded-sdk/v7.3.8/boldbi-embed.js"></script>
  10. Inside the <body> tag, include the following code. Create the DOM element with the id dashboard and implement a function to render the dashboard.

        <script>
        var data;
        var authorizationServerUrl = "api/EmbedData/AuthorizationServer";
        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() {
            this.dashboard = BoldBI.create({
                serverUrl: data.ServerUrl + "/" + data.SiteIdentifier,
                dashboardId: data.DashboardId, // Provide the item id here to render the dashboard in design mode or to create dashboard don't initialize this property
                embedContainerId: "dashboard",
                embedType: data.EmbedType,
                environment: data.Environment,
                mode: BoldBI.Mode.View,
                width: "100%",
                height: window.innerHeight - 20 + "px",
                expirationTime: 100000,
                authorizationServer: {
                    url: authorizationServerUrl
                },
            });
            this.dashboard.loadDashboard();
        }
        </script>
  11. Open the Index.razor file within the Client project and implement the code as follows to invoke the renderDashboard() method.

       @page "/"
       @inject IJSRuntime JsRuntime
    
       <div id="dashboard"> </div>
    
       @functions {
       protected override void OnAfterRender(bool firstRender)
       {
    
           JsRuntime.InvokeAsync<object>("renderDashboard");
       }
       }
  12. Open the MainLayout.razor file within the Client project and replace the following code.

         @inherits LayoutComponentBase
         <div class="page">
         <main>
            <article class="content px-4">
            @Body
            </article>
         </main>
         </div>
  13. In the Server project, under the controller folder, create the controller EmbedDataController.cs. To get particular dashboard details, define an API AuthorizationServer() using the GetSignatureUrl() method to generate the algorithm. In this API, the embedQuerString,userEmail and the value from the GetSignatureUrl() method are appended as the query parameters in the URL to the authorization server of the particular dashboard.

    Open the terminal and navigate to the Server project directory using the cd command (e.g., cd C:\BlazorProject\Server). Execute the following commands in the terminal to add the necessary reference to the project: dotnet add package Newtonsoft.Json. Include the Newtonsoft.Json, System.Security.Cryptography, System.Net.Http, Microsoft.AspNetCore.Mvc and Models folder namespaces.

       [Route("api/[controller]")]
       [ApiController]
       public class EmbedDataController : Controller
       {
       [HttpGet]
       [Route("GetConfig")]
       public IActionResult GetConfig()
       {
           var jsonData = System.IO.File.ReadAllText("embedConfig.json");
           string basePath = AppDomain.CurrentDomain.BaseDirectory;
           string jsonString = System.IO.File.ReadAllText(Path.Combine(basePath, "embedConfig.json"));
           GlobalAppSettings.EmbedDetails = JsonConvert.DeserializeObject<EmbedDetails>(jsonString);
           return Ok(jsonData);
       }
       [HttpPost("[action]")]
       [Route("AuthorizationServer")]
       public string AuthorizationServer([FromBody] object embedQuerString)
       {
           var embedClass = JsonConvert.DeserializeObject<EmbedClass>(embedQuerString.ToString());
           var embedQuery = embedClass.embedQuerString;
           // User your user-email as embed_user_email
           embedQuery += "&embed_user_email=" + GlobalAppSettings.EmbedDetails.UserEmail;
           //To set embed_server_timestamp to overcome the EmbedCodeValidation failing while different timezone using at client application.
           double timeStamp = (int)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;
           embedQuery += "&embed_server_timestamp=" + timeStamp;
           var embedDetailsUrl = "/embed/authorize?" + embedQuery + "&embed_signature=" + GetSignatureUrl(embedQuery);
    
           using (var client = new HttpClient())
           {
               client.BaseAddress = new Uri(embedClass.dashboardServerApiUrl);
               client.DefaultRequestHeaders.Accept.Clear();
    
               var result = client.GetAsync(embedClass.dashboardServerApiUrl + embedDetailsUrl).Result;
               string resultContent = result.Content.ReadAsStringAsync().Result;
               return resultContent;
           }
       }
    
       public string GetSignatureUrl(string message)
       {
           var encoding = new System.Text.UTF8Encoding();
           var keyBytes = encoding.GetBytes(GlobalAppSettings.EmbedDetails.EmbedSecret);
           var messageBytes = encoding.GetBytes(message);
           using (var hmacsha1 = new System.Security.Cryptography.HMACSHA256(keyBytes))
           {
               var hashMessage = hmacsha1.ComputeHash(messageBytes);
               return Convert.ToBase64String(hashMessage);
           }
       }
       }
  14. Navigate to the Server project directory using the cd command (e.g., cd C:\BlazorProject\Server). Run your Blazor WebAssembly sample with the command dotnet watch run in Visual Studio Code.