DEV Community

Askar Musthaffa
Askar Musthaffa

Posted on

Embed PowerBI report in Angular 9 application using .NET Core 3.1

Introduction

Power BI is a business analytics service that delivers insights to enable fast, informed decisions. In this post, I will take you to step by step run the powerBi report in the Angular9 application.

Step 1.

Get the access token from API

Update appsettings.json with following setting

"PowerBI": {
    "ApplicationId": "667b9837-3300-4762-8e61-68a4d25513835",
    "ApplicationSecret": "",
    "AuthorityUrl": "https://login.windows.net/common/oauth2/token/",
    "ResourceUrl": "https://analysis.windows.net/powerbi/api",
    "ApiUrl": "https://api.powerbi.com/",
    "EmbedUrlBase": "https://app.powerbi.com/",
    "UserName": "hello@aquip.io",
    "Password": "123456789"
  },
namespace GetAccessToken.Controllers
{
    public class PowerBISettings
    {
        public Guid ApplicationId { get; set; }
        public string ApplicationSecret { get; set; }
        public Guid ReportId { get; set; }
        public Guid? WorkspaceId { get; set; }
        public string AuthorityUrl { get; set; }
        public string ResourceUrl { get; set; }
        public string ApiUrl { get; set; }
        public string EmbedUrlBase { get; set; }
        public string UserName { get; set; }
        public string Password { get; set; }
    }

    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private readonly IConfiguration _configuration;
        public WeatherForecastController( IConfiguration configuration)
        {
            _configuration = configuration;
        }

        public static async Task<string> GetPowerBIAccessToken(IConfiguration _configuration)
        {
            using (var client = new HttpClient())
            {
                var form = new Dictionary<string, string>();
                form["grant_type"] = "password";
                form["resource"] = _configuration["PowerBI:ResourceUrl"];
                form["username"] = _configuration["PowerBI:UserName"];
                form["password"] = _configuration["PowerBI:Password"];
                form["client_id"] = _configuration["PowerBI:ApplicationId"];
                form["client_secret"] = _configuration["PowerBI:ApplicationSecret"];
                form["scope"] = "openid";
                client.DefaultRequestHeaders.TryAddWithoutValidation(
                    "Content-Type", "application/x-www-form-urlencoded");
                using (var formContent = new FormUrlEncodedContent(form))
                using (var response =
                    await client.PostAsync(_configuration["PowerBI:AuthorityUrl"],
                    formContent))
                {
                    var body = await response.Content.ReadAsStringAsync();
                    var jsonBody = JObject.Parse(body);
                    var errorToken = jsonBody.SelectToken("error");
                    if (errorToken != null)
                    {
                        throw new Exception(errorToken.Value<string>());
                    }
                    return jsonBody.SelectToken("access_token").Value<string>();
                }
            }
        }

        [HttpGet]
        public async Task<IActionResult> GetPowerBIAccessToken()
        {
            var accessToken = await  GetPowerBIAccessToken(_configuration);
            var tokenCredentials = new TokenCredentials(accessToken, "Bearer");
            using (var client = new PowerBIClient(new Uri(_configuration["PowerBI:ApiUrl"]), tokenCredentials))
            {

                var workspaceId = Guid.Parse("07684e64-c1f0-482d-b715-c8bef07a80dc");
                var reportId = Guid.Parse("3682417d-63d2-440c-92dc-a09aef1f3d8f");

                var report = await client.Reports.GetReportInGroupAsync(workspaceId, reportId);

                var generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view");
                var tokenResponse = await client.Reports.GenerateTokenAsync(workspaceId, reportId, generateTokenRequestParameters);

                return Ok(  new { token = tokenResponse.Token , embedUrl = report.EmbedUrl  } );
            }
        }
    }
}

About code return token and embed Url to use in the angular application.

Step 2.

Create a new angular application using below angular CLI command.
ng new powerbiembed

After creating the project open the index.html page and add the powerbil client javascript from the CDN. before closing body tag.

Open app.component.html page add below code to render the report

<div style=" width: 100%;" [ngStyle]="{ 'height': (screenHeight-150)+ 'px' }" #embeddedReport></div>  

Finally, let's write the code to render the report

import { Component, ViewChild, ElementRef, OnInit, AfterViewInit } from '@angular/core';
import * as pbi from 'powerbi-client';
import { HttpClient } from '@angular/common/http';
declare var powerbi: any;


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
 export class AppComponent implements OnInit  {
  @ViewChild('embeddedReport')
  embeddedReport: ElementRef;
  config: any;
  screenHeight: number;

  constructor(private httpClient: HttpClient) { }

  ngOnInit() {
    this.screenHeight = (window.screen.height);  
    this.httpClient.get<any>("<Your API URL>")
    .subscribe(config => {
      this.config = config;
      const model = window['powerbi-client'].models;
      const embedConfig = {
        type: 'report',
        tokenType: model.TokenType.Embed,
        accessToken: config.token,
        embedUrl: config.embedUrl,
        permissions: model.Permissions.All,
        settings: {
          filterPaneEnabled: true,
          navContentPaneEnabled: true
        }
      };
      powerbi.embed(this.embeddedReport.nativeElement, embedConfig);
    });
  }
}

Summary

In this article, I discussed how to embed a PowerBI report in an Angular9 application using .net core 3.1. I hope this article is useful.

Top comments (2)

Collapse
 
jamendieta profile image
jamendieta

could you please upload your project, i have a problem with the angular 9 version, which powerbi-client version are you using, thanks!!!

Collapse
 
jonycv profile image
jonycv

Hello, thanks for your example, How I can validate "AuthenticationMode": "ServicePrincipal" for this?