10/23/2021 Admin

Embedding Power BI in Blazor


image

You can easily embed Power BI reports into a Server Side Blazor Application. This method allows you to display a Power BI report without requiring the user to have a Power BI account.

Note: On 10/22/2021 this tutorial was updated to use the Microsoft Authentication Library (MSAL) rather than the deprecated Authentication Library (ADAL) See: Update your applications to use Microsoft Authentication Library and Microsoft Graph API - Microsoft Tech Community

Set-Up For The Application

To set up to run the sample application, we follow the directions in this article: Embed Power BI content with service principal and an application secret.

image

The first step is to start with a Power BI Report in https://app.powerbi.com/.

When viewing the report, you can look at the URL in the web browser to gather (and save for use in following steps):

  • workspaceId
  • reportId

(note: If you have issues completing the following directions, you may not have sufficient permissions)

image

Next, log into: https://portal.azure.com/ and copy the Tenant ID.

image

Now we need to create a Service Principal that will allow us to programmatically call the Power BI Embedded API.

We select App Registrations and click the link to create a New registration.

image

We create a new application.

image

Once the application (the Service Principal), is created, we select it, then click on the Overview tab and copy and save the ClientID.

image

Next, we click the Certificates & secrets tab and click the link to create a New client secret.

image

We create a client secret.

image

After it is created, we click the copy button to copy and save the ClientSecret.

image

Next, select Groups, then New Group.

image

Create a new Security Group.

Add the Service Principal you just created.

image

Click the Create button to save the group.

Next, to allow this Service Principal to access the Power BI Reports, we follow the directions here: Service principal API access….

image

On https://app.powerbi.com/ log into the Admin portal.

image

In Tenant settings, enable the option to Allow Service Principals to use Power BI APIs.

image

Select the Workspace that has your Power BI Paginated Report, and select Workspace access.

image

Add the Security Group (created earlier) to the Workspace.

Create The Project

image

The first step is to create a Server Side Blazor project and select Manage NuGet Packages.

image

Install the Microsoft.Identity.Client and Microsoft.PowerBI.Api packages.

image

The next step is to add the powerbi.min.js file to the wwwroot/js directory.

You can get that file from here: https://github.com/microsoft/PowerBI-JavaScript/releases

image

Next open the _Host.cshtml file.

Add the following code to reference the powerbi.min.js file:

								
									<
									script
									src="js/powerbi.min.js"
									>
									</
									script
									>
								

Add the following code to display the Power BI Report using the code in the powerbi.min.js file:

								
									<
									script
									>
								
									window.ShowMyPowerBI = {
								
									showReport: function (reportContainer, accessToken, embedUrl, embedReportId) {
								

								
									// Get models. models contains enums that can be used.
								
									var models = window['powerbi-client'].models;
								

								
									var config = {
								
									type: 'report',
								
									tokenType: models.TokenType.Embed,
								
									accessToken: accessToken,
								
									embedUrl: embedUrl,
								
									id: embedReportId,
								
									permissions: models.Permissions.All,
								
									settings: {
								
									filterPaneEnabled: true,
								
									navContentPaneEnabled: true
								
									}
								
									};
								

								
									// Embed the report and display it within the div container.
								
									powerbi.embed(reportContainer, config);
								
									},
								
									};
								
									</
									script
									>
								

image

So that our C# code can communicate with the JavaScript, create a interop.cs file using the following code:

								
									using
									Microsoft.AspNetCore.Components;
								
									using
									Microsoft.JSInterop;
								
									using
									System.Threading.Tasks;
								
									namespace
									BlazorPowerBI
								
{
								
									public
									static
									class
									Interop
								
									{
								
									internal
									static
									ValueTask<object> CreateReport(
								
									IJSRuntime jsRuntime,
								
									ElementReference reportContainer,
								
									string
									accessToken,
								
									string
									embedUrl,
								
									string
									embedReportId)
								
									{
								
									return
									jsRuntime.InvokeAsync<object>(
								
									"ShowMyPowerBI.showReport",
								
									reportContainer, accessToken, embedUrl,
								
									embedReportId);
								
									}
								
									}
								
}
								

							

image

Finally, create a PowerBI.razor page using the following code:

								
@page "/PowerBI"
								
@using
									System.Net.Http
								
@using
									System.Threading.Tasks
								
@using
									Microsoft.Identity.Client
								
@using
									Microsoft.PowerBI.Api
								
@using
									Microsoft.PowerBI.Api.Models
								
@using
									Microsoft.Rest
								
@using
									Newtonsoft.Json.Linq
								
@using
									Microsoft.Extensions.Configuration
								
@inject IJSRuntime JSRuntime
								
@inject IConfiguration _configuration
								

								
<h3>PowerBI Embedded</h3>
								

								
<div @ref="@PowerBIElement" style="width:100%;height:600px;max-width: 2000px" />
								

								
@code {
								
									private
									ElementReference PowerBIElement;
								

								
									string
									TenantID = "{{ Your TenantID }}";
								

								
									string
									ClientID = "{{ Your ClientID }}";
								
									string
									ClientSecret = "{{ Your ClientSecret }}";
								

								
									string
									workspaceId = "{{ Your workspaceId }}";
								
									string
									reportId = "{{ Your reportId }}";
								

								
									protected
									override
									async Task
								
									OnAfterRenderAsync(bool
									firstRender)
								
									{
								
									if
									(firstRender)
								
									{
								
									var result =
									new
									PowerBIEmbedConfig();
								

								
									// Authenticate using created credentials
								
									AuthenticationResult authenticationResult =
									null;
								

								
									authenticationResult = await DoAuthentication();
								

								
									var tokenCredentials =
								
									new
									TokenCredentials(authenticationResult.AccessToken, "Bearer");
								

								
									using
									(var client =
									new
									PowerBIClient(
								
									new
									Uri("https://api.powerbi.com/"), tokenCredentials))
								
									{
								
									var report =
								
									await client.Reports.GetReportInGroupAsync(
								
									new
									Guid(workspaceId),
								
									new
									Guid(reportId));
								

								
									var generateTokenRequestParameters =
								
									new
									GenerateTokenRequest(accessLevel: "view");
								

								
									var tokenResponse =
								
									await client.Reports.GenerateTokenAsync(
								
									new
									Guid(workspaceId),
								
									new
									Guid(reportId),
								
									generateTokenRequestParameters);
								

								
									result.EmbedToken = tokenResponse;
								
									result.EmbedUrl = report.EmbedUrl;
								
									result.Id = report.Id.ToString();
								

								
									await Interop.CreateReport(
								
									JSRuntime,
								
									PowerBIElement,
								
									tokenResponse.Token,
								
									report.EmbedUrl,
								
									report.Id.ToString());
								
									}
								
									}
								
									}
								

								
									private
									const
									string
									AuthorityFormat = "https://login.microsoftonline.com/{0}/v2.0";
								
									private
									const
									string
									MSGraphScope = "https://analysis.windows.net/powerbi/api/.default";
								

								
									private
									async Task<AuthenticationResult> DoAuthentication()
								
									{
								
									IConfidentialClientApplication daemonClient;
								

								
									daemonClient = ConfidentialClientApplicationBuilder.Create(ClientID)
								
									.WithAuthority(string.Format(AuthorityFormat, TenantID))
								
									.WithClientSecret(ClientSecret)
								
									.Build();
								

								
									AuthenticationResult authResult =
								
									await daemonClient.AcquireTokenForClient(new[] { MSGraphScope }).ExecuteAsync();
								

								
									return
									authResult;
								
									}
								
}

Links

Blazor Power BI Paginated Reports

Create View and Edit Power BI Reports In Blazor

Download

The project is available on the Downloads page on this site.

You must have Visual Studio 2019 Version 16.3 (or higher) installed to run the code.

An error has occurred. This application may no longer respond until reloaded. Reload 🗙