Wednesday, April 06, 2016

Power BI embedded step by step

Hi All,

In this blog post i am providing a walk through on how to use Power BI Embedded feature in an asp.net MVC application. Microsoft announced this feature in Build 2016 few days ago.
As of now, Power BI embedded feature is still in preview.

This blog post is describing how to build this app from scratch in a step by step. The source code is in GitHub as well.

Power BI Embedded allows developers to integrate Power BI capabilities in their web or mobile application with out the need to login! so customers can view your power bi reports in custom applications without the need to login or provide o365 credentials to view these reports.


To be able to use Power BI embedded you need the following:
1) A power bi report that you have created & saved in (pbix) file format.
2) Azure subscription because we need to provision Power BI workspace collection that will host our reports.
3) An application to integrate these reports to,
    a) We will create ASP.NET MVC application to visualize a reports (Step #3)
    b) We will create ASP.NET Web Forms application to visualize a report (Step #4)

Screen shot below shows an asp.net MVC application that uses Power BI embedded feature (NO LOGIN IS NEEDED!!!)



How to implement this application:

1) Provision Power BI Workspace Collection:
a) Navigate to Azure Portal, Under Data and + Analytics

Once you select Power BI Embedded, enter the following details:

  • Workspace Collection Name: Demo1
  • Subscription: Select any subscription you have.
  • Resource group: Select any RG or create a new one.
  • Location: Select any location for PBI workspace collection.
  • Click on create button

Once the Power BI Embedded workspace collection is created. We will have an empty collection.

This video shows how to implement step #1 & it covers the basics of Power BI Embedded (Optional)


2) Import pbix report file into Workspace Collection:
Microsoft has created a console application that you need to run to import pbix report file into the create workspace collection in Azure.

You can download the console app utility from GitHub here.

Open the solution in VS 2015 and set "Provision Sample" project as a startup project.
Follow these instructions to import pbix file into Azure Power BI Workspace collection.


First, we will enter "5" so we create a workspace in an existing workspace collection we have just created in step #1.

Enter Workspace Collection Name: Demo1 (Same name as we created in step #1)
Access Key: From Azure Portal, Copy Access Key (Key1) for the created Workspace collection.
Copy the generated Workspace Id, since we will use it in the next step.


Second, we will enter "6" to import pbix into the workspace we just created in the previous step.

Enter workspace collection name: Demo1
Workspace Id: copy what we have created in the previous step, also, you can get workspace if you refresh azure portal.
File Path: full file path for pbix file.

Now, we have imported our report into Power BI workspace collection that we created in Azure.

I have created a video for step #2 (Optional to watch)



3) Create ASP.NET MVC Application to use PowerBI Embedded reports:
I have checked in the code for this sample, here is what you need to know about this application.
Open Home Controller, Check Index action:

  List<ReportViewModel> reportsList = new List<ReportViewModel>();
            var devToken = PowerBIToken.CreateDevToken(this.workspaceCollection, this.workspaceId);
            using (var client = this.CreatePowerBIClient(devToken))
            {
                var reportsResponse = client.Reports.GetReports(this.workspaceCollection, this.workspaceId);
                for (int i = 0; i < reportsResponse.Value.ToList().Count; i++)
                {
                    reportsList.Add(new ReportViewModel
                    {
                        Id = reportsResponse.Value[i].Id,
                        Name = reportsResponse.Value[i].Id,
                        EmbedUrl = reportsResponse.Value[i].EmbedUrl,
                        WebUrl = reportsResponse.Value[i].WebUrl,
                        Report = reportsResponse.Value[i]
                    }
                    );
                }
            }

Above code segment connect to power bi sdk and get all reports we have in the specified workspace id. Once we have this reports list, we can embed  any of them in our pages.

 var reportId = reportsList[0].Id;
            using (var client = this.CreatePowerBIClient(devToken))
            {
                var embedToken = PowerBIToken.CreateReportEmbedToken(this.workspaceCollection, this.workspaceId, reportId);
                var viewModel = new ReportViewModel
                {
                    Report = reportsList[0].Report,
                    AccessToken = embedToken.Generate(this.accessKey)
                };
                return View(viewModel);
            }

Above code segment selects the first report and return the full report object (Power BI Report) and access token to the view (index.cshtml)

In Index.cshtml, Microsoft created an extension to HTML helper for PowerBI reports. PowerBIReportFor that renders PowerBI reports ;-) Amazing!!

<div class="side-body padding-top">
    @Html.PowerBIReportFor(m => m.Report, new { style = "height:85vh", powerbi_access_token = Model.AccessToken })
</div>
One Pro Tip: you need to make sure to include powerbi.js in any page or the masterpage (aka _layout.cshtml) to be able to show any power bi report in your page. This JS file has been added when i added powerbi nuget packages to my project.


Open the web.config and change these keys as you have in your Azure provision keys before running the application:

   <add key="powerbi:AccessKey" value="" />
   <add key="powerbi:WorkspaceCollection" value="" />
    <add key="powerbi:WorkspaceId" value="" />

Run the application :-)

I have created a video for step #3 that covers App Tokens and explains how to build the demo app (Optional)


4) Create ASP.NET Web Forms Application to use PowerBI Embedded reports:
I have checked in the code for this sample, here is what you need to know about this application.

Open the web.config and change these keys as you have in your Azure provision keys before running the application:

   <add key="powerbi:AccessKey" value="" />
   <add key="powerbi:WorkspaceCollection" value="" />
    <add key="powerbi:WorkspaceId" value="" />
In Default.aspx.cs, check out the code to connect to PBI REST API to get DevTok and then AccessToken for the displayed report.

 if (!Page.IsPostBack)
            {    

                List<ReportViewModel> reportsList = new List<ReportViewModel>();
                var devToken = PowerBIToken.CreateDevToken(workspaceCollection, workspaceId);
                using (var client = this.CreatePowerBIClient(devToken))
                {
                    var reportsResponse = client.Reports.GetReports(workspaceCollection, workspaceId);

                    for (int i = 0; i < reportsResponse.Value.ToList().Count; i++)
                    {
                        reportsList.Add(new ReportViewModel
                        {
                            Id = reportsResponse.Value[i].Id,
                            Name = reportsResponse.Value[i].Id,
                            EmbedUrl = reportsResponse.Value[i].EmbedUrl,
                            WebUrl = reportsResponse.Value[i].WebUrl,
                            Report = reportsResponse.Value[i]
                        }
                        );
                    }
                }
             
                var reportId = reportsList[0].Id;
                using (var client = this.CreatePowerBIClient(devToken))
                {
                    var embedToken = PowerBIToken.CreateReportEmbedToken(workspaceCollection, workspaceId, reportId);

                    var viewModel = new ReportViewModel
                    {
                        Report = reportsList[0].Report,
                        AccessToken = embedToken.Generate(accessKey)
                    };

                    accessTokenText.Value = viewModel.AccessToken;
                    embedUrlText.Value = viewModel.Report.EmbedUrl;
                }

In Default.aspx, check out the iframe and JS function to load PBI report:


<iframe ID="iFrameEmbedReport" src="" height="768px" width="1024px" frameborder="1" seamless></iframe>

 
    <!-- Js function to assign iframe embedUrl and access token -->
     <script type="text/javascript">

          window.onload = function () {

              //debugger;
              // find the iFrame on the page and handle the loaded event.
              var iframe = document.getElementById('iFrameEmbedReport');
              iframe.src = document.getElementById('MainContent_embedUrlText').value;  //embedReportUrl;
              iframe.onload = postActionLoadReport;
              // post the access token to the iFrame to load the tile
              function postActionLoadReport() {
                  // get the app token.
                  accessToken = document.getElementById('MainContent_accessTokenText').value;//{generate app token};
                  // construct the push message structure
                  var m = { action: "loadReport", accessToken: accessToken };
                  message = JSON.stringify(m);
                  // push the message.
                  iframe = document.getElementById('iFrameEmbedReport');
                  iframe.contentWindow.postMessage(message, "*");
              }
          };

    </script>

Here is a video for step 4 on how to use Power BI embedded in asp.net web forms:




References:
* Source Code GitHub Repos:
ASP.NET MVC: https://github.com/melzoghbi/PowerBIEmbeddedSimplified
ASP.NET Web Forms: https://github.com/melzoghbi/PowerBIEmbeddedWebForms

* Power BI Embedded Resources:
https://azure.microsoft.com/en-us/documentation/articles/power-bi-embedded-get-started/

Enjoy!

Monday, April 04, 2016

Integrate a Power BI report into an app

Hi All,

This blog post is a walk through article on how to embed a PowerBI report in an application. This blog post with source code is available in GitHub.

I can say this feature is one of the most requested features from clients i worked with directly.
Below is a screen shot of the running application i have created that contains an integrated PowerBI report i have created in Office 365 tenant using PowerBI.


How to run the application:

1) Register your application in Azure AD, here are the configurations we need to update ASP.NET MVC app:

  • Client Id
  • Secret Id
  • Return Url: If you want to change it from the original app code.
Below screen shots show Azure AD (AAD) app registration settings in Azure portal:





2) Login to your PowerBI (app.powerbi.com) and get the Report Id you want to embed in the app:

Select a report that you would like to embed, grab a report Id from the browser url.
Below screen show shows a selected report "RPT1" and highlighted ReportId we will embed in our app.




3) Open ASP.NET MVC Project settings in VS 2015 and update Client Id and Secret Id from Azure Portal after registering your app.



4) Open index.cshtml and update iframe src attribute by adding the Report Id we captured in step #2.

 <iframe ID="iFrameEmbedReport" src="https://app.powerbi.com/reportEmbed?reportId=11156ed2-ede7-4b60-ac26-10cda004bdee" height="768px" width="1024px" frameborder="1" seamless></iframe>
 5) Run the app, Click on o365 login, Sign In and then PowerBI report will be showing after your login to the app.


Demo source code url: https://github.com/melzoghbi/PowerBIEmbeddedApp


References:
1) Integrate a Power BI tile or report into an app

2) Power BI Embedded home page:
https://azure.microsoft.com/en-us/services/power-bi-embedded/

Enjoy!