4

Blazor Power BI Paginated Reports

 3 years ago
source link: https://blazorhelpwebsite.com/ViewBlogPost/49
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Blazor Power BI Paginated Reports


image

You can easily embed Power BI Paginated reports into a Microsoft Server Side Blazor Application.

Microsoft Blazor is a technology that lets you build interactive web applications using C#.

Power BI allows you to create enterprise business intelligence (BI) dashboards and reports, however, unlike a Power BI dashboard, Power BI Paginated reports are designed to be printed and shared (for example, exported as a PDF and emailed).

The method described in this article allows you to display a Power BI Paginated report in a Blazor application, without requiring the user to have a Power BI license. This is called “App owns data” or “ Embed Power BI paginated reports for your customers ”, therefore it has these limitations (from: Tutorial: Embed Power BI paginated reports into an application for your customers):

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 Paginated Report in https://app.powerbi.com/.

  • The report must work on app.powerbi.com
  • The report must not use a Power BI dataset as a data source

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 Paginated 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.

Run The Application

image

Next, navigate to the Downloads page on this site.

image

Download “Blazor Power BI Paginated Reports”.

image

We unzip the code and open it in Visual Studio 2019 (or higher).

We replace the configuration values with the values we saved from the earlier steps.

image

When we run the application, the report displays.

How The Blazor Application Was Created

image

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

image

Install the Microsoft.PowerBI.Api and Microsoft.IdentityModel.Clients.ActiveDirectory 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 Paginated Report using the code in the powerbi.min.js file:

									window.BlazorPowerBI = {
								
									showPaginatedReport:
									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);
								
									}
								
									};

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

									public
									static
									class
									Interop
								
									{
								
									internal
									static
									ValueTask<object> CreateReportPaginated(
								
									IJSRuntime jsRuntime,
								
									ElementReference reportContainer,
								
									string
									accessToken,
								
									string
									embedUrl,
								
									string
									embedReportId)
								
									{
								
									return
									jsRuntime.InvokeAsync<object>(
								
									"BlazorPowerBI.showPaginatedReport",
								
									reportContainer, accessToken, embedUrl, embedReportId);
								
									}
								
									}

Also, add a PowerBIEmbedConfig.cs Configuration class:

									public
									class
									PowerBIEmbedConfig
									{
									public
									string
									Id {
									get;
									set; }
									public
									string
									EmbedUrl {
									get;
									set; }
									public
									EmbedToken EmbedToken {
									get;
									set; }
									public
									int
									MinutesToExpiration
									{
									get
								
									{
									var minutesToExpiration = EmbedToken.Expiration - DateTime.UtcNow;
									return
									minutesToExpiration.Minutes;
									}
									}
									public
									bool? IsEffectiveIdentityRolesRequired {
									get;
									set; }
									public
									bool? IsEffectiveIdentityRequired {
									get;
									set; }
									public
									bool
									EnableRLS {
									get;
									set; }
									public
									string
									Username {
									get;
									set; }
									public
									string
									Roles {
									get;
									set; }
									public
									string
									ErrorMessage {
									get;
									internal
									set; }
									}

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

@page "/"
								
@using
									System.Net.Http
								
@using
									System.Threading.Tasks
								
@using
									Microsoft.IdentityModel.Clients.ActiveDirectory
								
@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>Paginated Report</h3>
								
<div @ref="@PowerBIElement" style="width:100%;height:600px;max-width: 2000px" />
								
@code {
								
									private
									ElementReference PowerBIElement;
								
									string
									TenantID = "*** ADD YOUR VALUES ***";
								
									string
									ClientID = "*** ADD YOUR VALUES ***";
								
									string
									ClientSecret = "*** ADD YOUR VALUES ***";
								
									string
									workspaceId = "*** ADD YOUR VALUES ***";
								
									string
									reportId = "*** ADD YOUR VALUES ***";
								
									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.CreateReportPaginated(
								
									JSRuntime,
								
									PowerBIElement,
								
									tokenResponse.Token,
								
									report.EmbedUrl,
								
									report.Id.ToString());
								
									}
								
									}
								
									}
								
									private
									async Task<AuthenticationResult> DoAuthentication()
								
									{
								
									AuthenticationResult authenticationResult =
									null;
								
									// For app only authentication,
								
									// we need the specific tenant id in the authority url
								
									var tenantSpecificURL =
								
									"https://login.microsoftonline.com/common/".Replace("common", TenantID);
								
									var authenticationContext =
									new
									AuthenticationContext(tenantSpecificURL);
								
									// Authentication using app credentials
								
									var credential =
									new
									ClientCredential(ClientID, ClientSecret);
								
									authenticationResult = await authenticationContext.AcquireTokenAsync(
								
									"https://analysis.windows.net/powerbi/api", credential);
								
									return
									authenticationResult;
								
									}
								
}

If You Have Problems

If you have problems, see this Microsoft article for more details: Embed Power BI content in an embedded analytics application with service principal and an application secret enabling better embedded BI insights - Power BI | Microsoft Docs and try using their sample application.

Links

Supported data sources for Power BI paginated reports

Embed Power BI content with service principal and an application secret

Embedding Power BI in Blazor

Power BI Embedded Playground

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.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK