Integrate Power BI into Your Application: Part 3 – Embed Content

2017-06-25_12h06_03

In the part 1, you learned how to register an application to be able to interact with Power BI service and Azure environment. In the part 2, you learned how the authentication process works and how you can get the access token. In this part, I’m going to explain what is the process of embedding content (Dashboard, Report, and Tile) into a web page. you will learn about JavaScript part of it, and also the REST API section of it. if you like to learn more about Power BI; read Power BI book; from Rookie to Rock Star.

Step 1: Register your Application

Step 2: Authenticate

Step 3: Embed Content

in this step you will learn about codes and the method to embed the content into your application after registration and authentication of the application.

Sample Code

The sample code for this example can be downloaded from here.

Power BI Client Object

Power BI Client object is the main object needs to be created in order to interact with Power BI Service. As you’ve learned above, you need to have the access token for this step. You just need to parameters to create a Power BI Client object; ApiURL (which is static), and token (which is gained through authentication process mentioned in previous post).

var client = new PowerBIClient(new Uri(ApiUrl), tokenCredentials);

After creating this object, you have access to massive amount of information from Power BI Service, and you can implement many actions through it (Which I explain many of these actions in other posts).

Get List of Reports

For this example; I’m going to Embed a report into web page, so I will get list of reports first (you can even directly mention the report Id).

// Get a list of reports.
                var reports = await client.Reports.GetReportsInGroupAsync(GroupId);

                // Get the first report in the group.
                var report = reports.Value.FirstOrDefault();

                if (report == null)
                {
                    return View(new EmbedConfig()
                    {
                        ErrorMessage = "Group has no reports."
                    });
                }

As you can see the function used is GetReportsInGroupAsync. This function simply returns all reports under a group. Group Id is specified in web.config file. Notice that Id is not name of the group. the name that you see for group, dashboard, report, and data set, are just display labels. Each object in Power BI has an ID which is a unique identifier (GUID). you can easily find it when you browse the group in Power BI Service through URL;

2017-06-25_11h39_59

These Ids can then be used for Power BI REST API functions.

Function above will return first report on that list, because I’ve used FirstOrDefault() function. You can easily mention any other reports if you want to.

Creating Embed Content

In the MVC application the next step is to create the embed content and push it to the view. lines below generating the embed content;

// Generate Embed Token.
                var generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view");
                var tokenResponse = await client.Reports.GenerateTokenInGroupAsync(GroupId, report.Id, generateTokenRequestParameters);

                if (tokenResponse == null)
                {
                    return View(new EmbedConfig()
                    {
                        ErrorMessage = "Failed to generate embed token."
                    });
                }

                // Generate Embed Configuration.
                var embedConfig = new EmbedConfig()
                {
                    EmbedToken = tokenResponse,
                    EmbedUrl = report.EmbedUrl,
                    Id = report.Id
                };

                return View(embedConfig);

JAVA Script in the Web page

In the EmbedReport.Chtml page which is view web page, you need a JavaScript section to embed the content into the page. here is the JavaScript code;

    // Read embed application token from Model
    var accessToken = "@Model.EmbedToken.Token";

    // Read embed URL from Model
    var embedUrl = "@Html.Raw(Model.EmbedUrl)";

    // Read report Id from Model
    var embedReportId = "@Model.Id";

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

    // Embed configuration used to describe the what and how to embed.
    // This object is used when calling powerbi.embed.
    // This also includes settings and options such as filters.
    // You can find more information at https://github.com/Microsoft/PowerBI-JavaScript/wiki/Embed-Configuration-Details.
    var config = {
        type: 'report',
        tokenType: models.TokenType.Embed,
        accessToken: accessToken,
        embedUrl: embedUrl,
        id: embedReportId,
        permissions: models.Permissions.All,
        settings: {
            filterPaneEnabled: true,
            navContentPaneEnabled: true
        }
    };

    // Get a reference to the embedded report HTML element
    var reportContainer = $('#reportContainer')[0];

    // Embed the report and display it within the div container.
    var report = powerbi.embed(reportContainer, config);

As you can see in the above section; Embed Token is required for embedding part again, plus embed content coming from the controller.

Testing Application

If you run the sample application, you can check and see how embedding Report in application works perfectly;

2017-06-25_12h06_03

As you can see, the report is integrated into my application which is running on my localhost. This method of embedding works with any type of report, sourced from any data source with any connection type.

Getting List of Dashboards

There is a function that returns list of dashboards for you, and you can easily select dashboards  you want.

GetDashboardsInGroupAsync, or GetDashboardAsync and many methods as listed below can give you information about dashboards;

2017-06-26_20h45_16

After fetching list of dashboards it can then be passed to view with script below;

                // Get a list of dashboards.
                var dashboards = await client.Dashboards.get.GetDashboardsInGroupAsync(GroupId);

                // Get the first report in the group.
                var dashboard = dashboards.Value.FirstOrDefault();

                if (dashboard == null)
                {
                    return View(new EmbedConfig()
                    {
                        ErrorMessage = "Group has no dashboards."
                    });
                }

                // Generate Embed Token.
                var generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view");
                var tokenResponse = await client.Dashboards.GenerateTokenInGroupAsync(GroupId, dashboard.Id, generateTokenRequestParameters);

                if (tokenResponse == null)
                {
                    return View(new EmbedConfig()
                    {
                        ErrorMessage = "Failed to generate embed token."
                    });
                }

                // Generate Embed Configuration.
                var embedConfig = new EmbedConfig()
                {
                    EmbedToken = tokenResponse,
                    EmbedUrl = dashboard.EmbedUrl,
                    Id = dashboard.Id
                };

                return View(embedConfig);

Embed Dashboard

Finally embedding dashboard is similar to embedding report, with slight difference;

    // Read embed application token from Model
    var accessToken = "@Model.EmbedToken.Token";

    // Read embed URL from Model
    var embedUrl = "@Html.Raw(Model.EmbedUrl)";

    // Read dashboard Id from Model
    var embedDashboardId = "@Model.Id";

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

    // Embed configuration used to describe the what and how to embed.
    // This object is used when calling powerbi.embed.
    // This also includes settings and options such as filters.
    // You can find more information at https://github.com/Microsoft/PowerBI-JavaScript/wiki/Embed-Configuration-Details.
    var config = {
        type: 'dashboard',
        tokenType: models.TokenType.Embed,
        accessToken: accessToken,
        embedUrl: embedUrl,
        id: embedDashboardId
    };

    // Get a reference to the embedded dashboard HTML element
    var dashboardContainer = $('#dashboardContainer')[0];

    // Embed the dashboard and display it within the div container.
    var dashboard = powerbi.embed(dashboardContainer, config);

so as a result this is the embedded dashboard;

2017-06-26_20h52_57

Getting Tiles

You first need to have the dashboard object in order to get tiles under it.

2017-06-26_20h54_36

As you can see above there are some functions that fetch Tiles from Dashboard and group. Code below will fetch first tile in a dashboard and pass it to the view page.

                var tiles = await client.Dashboards.GetTilesInGroupAsync(GroupId, dashboard.Id);

                // Get the first tile in the group.
                var tile = tiles.Value.FirstOrDefault();

                // Generate Embed Token for a tile.
                var generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view");
                var tokenResponse = await client.Tiles.GenerateTokenInGroupAsync(GroupId, dashboard.Id, tile.Id, generateTokenRequestParameters);

                if (tokenResponse == null)
                {
                    return View(new TileEmbedConfig()
                    {
                        ErrorMessage = "Failed to generate embed token."
                    });
                }

                // Generate Embed Configuration.
                var embedConfig = new TileEmbedConfig()
                {
                    EmbedToken = tokenResponse,
                    EmbedUrl = tile.EmbedUrl,
                    Id = tile.Id,
                    dashboardId = dashboard.Id 
                };

                return View(embedConfig);

Embedding Content Limitless

Very important consideration of the new REST API way of integrating Power BI content is that, now you can embed any type of content: Dashboard, Report, and Tile. Your data set can be connected to any data set, online or on-premises, import data or DirectQuery. With this method of integration, you can integrate anything that you have in Power BI account easily into your application. I will explain another post later about FAQs of such integration plan. Stay tuned for next blog posts from this series.

Reza Rad on FacebookReza Rad on LinkedinReza Rad on TwitterReza Rad on Youtube
Reza Rad
Trainer, Consultant, Mentor
Reza Rad is a Microsoft Regional Director, an Author, Trainer, Speaker and Consultant. He has a BSc in Computer engineering; he has more than 20 years’ experience in data analysis, BI, databases, programming, and development mostly on Microsoft technologies. He is a Microsoft Data Platform MVP for 12 continuous years (from 2011 till now) for his dedication in Microsoft BI. Reza is an active blogger and co-founder of RADACAD. Reza is also co-founder and co-organizer of Difinity conference in New Zealand, Power BI Summit, and Data Insight Summit.
Reza is author of more than 14 books on Microsoft Business Intelligence, most of these books are published under Power BI category. Among these are books such as Power BI DAX Simplified, Pro Power BI Architecture, Power BI from Rookie to Rock Star, Power Query books series, Row-Level Security in Power BI and etc.
He is an International Speaker in Microsoft Ignite, Microsoft Business Applications Summit, Data Insight Summit, PASS Summit, SQL Saturday and SQL user groups. And He is a Microsoft Certified Trainer.
Reza’s passion is to help you find the best data solution, he is Data enthusiast.
His articles on different aspects of technologies, especially on MS BI, can be found on his blog: https://radacad.com/blog.

10 thoughts on “Integrate Power BI into Your Application: Part 3 – Embed Content

    • This should be a group not from Shared with me. the link you have here is from “Shared With Me” section. group basically is under Work Spaces. just click on the work space, and you will be able to see Group GUID in the url of that page.
      Cheers
      Reza

      • Hi Reza,
        Thanks for your reply. I am at the exact same page as per your screenshot. I am using my own account/works space. All the dashboard, reports and data sets are all mine as I am not a pro user,therefore nothing is shared with me. But yet i dont see the groupID

        Regards,
        Tim

        • Hi Tim.
          You need to have Pro user to be able to create work spaces. it should not be “My work space”. it should be a new created work space.
          Cheers
          Reza

  • I followed your instructions and everything seems to be displaying properly, however when I click on a tile in my dashboard to get to the report below it nothing happens.
    Clicking on a tile to a report seems to do nothing.

    Any suggesstions as to why that is?

    Thanks,

    • clicking on dashboard and navigating to report is a functionality of Power BI Service. When you embed that into your application, you won’t have such functionality. clicking on dashboard tiles in web app won’t navigate to reports. however you will have some “click” events which you can program on those to navigate to another page in your web app that brings the report.
      Cheers
      Reza

  • Hi Reza, Nice blog. Does the embed token always need to be generated server side? Is there JavaScript equivalent API where I can get the token without writing anything server side?

    • Hi Unnie,
      Yes, Embed token needs to be created server side through a controller, then after authentication the JScript API can be used for embedding.

  • Hi Reza,
    we have a Power BI report in an app workspace.
    our developer plan to embed a report from the app workspace into the application.
    what should I provide to developers?

Leave a Reply