Skip to main content
cancel
Showing results for 
Search instead for 
Did you mean: 

Register now to learn Fabric in free live sessions led by the best Microsoft experts. From Apr 16 to May 9, in English and Spanish.

Kumail

Setting Up Azure for Analytics in Power BI and Embedding

Azure App FunctionsAzure App Functions

Purpose of this article

The purpose of this article is to embed analytics, reports, and visualizations that different users may require in an organization to 3rd party applications or software as a service SAAS and platform as a service PAAS application.

Embedding in Power BI enables ISVs and developers to integrate Power BI content (reports, dashboards, and tiles) directly into an application.

You just acquire and pay for the dedicated capacity required to serve the content and each individual consumer doesn’t require a license. There only needs to be a single “master” Power BI Pro account.

The power BI embedded offering is targeted at ISVs and developers (i.e. building apps for external users).

For embedding Power BI within the enterprise context, for instance, internal portals, and SharePoint, then Microsoft Power BI Premium is better suited as suggested here https://docs.microsoft.com/en-us/power-bi/developer/embedded-faq

Phase 1 - Register an app to Power BI embed content

Head over to dev.powerbi.com/apps

Step 1 – Logon to Power BI pro account

This also needs to have access to the Azure id tenant.

dev.powerbi.com/appsdev.powerbi.com/apps

Step 2 — Fill in the app details

Register an application for Power BI in AzureRegister an application for Power BI in Azure

For app type, generally, a native app is selected as it has more options.

The current URL is taken from documentation; however, this is the URL that it is going to redirect once we successfully authenticate.

Step 3 — Choosing what type of access to APIs we would need

APIs to accessAPIs to access

Step 4 — When you click on register

It will return a client ID

Register AppRegister App

If you have chosen a web app, the system will generate a client ID and client secret.

Step 5 — Permission Configuration

There is a couple of permissions that we need to configure. To do that, we head over to the Azure portal.

Permission Configuration in AzurePermission Configuration in Azure

To click on permissions, we click on settings.

Azure Power BI Embedded SettingsAzure Power BI Embedded Settings

Click on Required permissions in the API access menu and in Windows Azure Active Directory, click on Access the directory as the signed-in user.

Permission in Azure for Embedded AnalyticsPermission in Azure for Embedded Analytics

Click Save and hit Grant Permissions at the top of the list.

And for Power BI Service, uncheck 2 options;

- Read and write access to all content in the tenant.

  • View all content in the tenant.

Azure Power BI Embedded Permission SettingsAzure Power BI Embedded Permission Settings

Then click Save and Grant Permissions.

Phase 2 — Azure Environment Setup for Analytics

This is Power BI embedded dedicated capacity resource.

Step 1 create a resource group.

When the user clicks on the resource, the system takes them to the resource details view within the Azure tenant.

Azure TenantAzure Tenant

From there, we click on Add to add the Power BI embedded resource.

Power BI EmbeddedPower BI Embedded

Data points for creating Power BI Embedded.

Power BI Embedded Pricing TierPower BI Embedded Pricing Tier

This is the administrator that would be linking the app workspace.

The resource would be available in a minute or 2.

If you pause, you won’t be billed.

If you want to add Power BI Master and Pro to others, you can do so.

Power BI CapacityPower BI Capacity

Step 2 — Head over to Power BI service and create an App workspace

Now we need to create an app workspace in Power BI service, put up some content in there and link up that resource in azure to the app workspace.

Power BI Service App WorkspacePower BI Service App Workspace

The diamond icon indicates that it is premium now.

Power BI Service App WorkspacePower BI Service App Workspace

Step 3 — Add Content to App Workspace

You can do so by using add data set the option in the app workspace.

Azure Sales And MarketingAzure Sales And Marketing

That’s it!! The sample content is ready for embedding in a web app outside of powerbI.com.

Phase 3 — Get an Embed Token Power BI API

The architecture of Embedding Power BI Report with Azure FunctionsThe architecture of Embedding Power BI Report with Azure Functions

What is an embed token? This is something required by the front end typing into that Power BI JavaScript library. The actual embed token comes from Power BI API and whether you want to import a dashboard or report in its entirety, each piece of embed requires a token to embed within the application. This is where Azure functions come in. We are going to have a slab of code that is running as an azure function, that will invoke the Power BI API in order to get that embed token and turn that as a JSON response to the front end.

Step 1 Log in to Azure Portal and create a function app

Function App Azure PortalFunction App Azure Portal

Function AppFunction App

Give it a valid name, valid subscription and select other necessary details.

Microsoft Azure FunctionMicrosoft Azure Function

Step 2 — Select the function

Select the function list and click the plus sign and select the HTTP trigger function and the language that you are looking to use.

Azure App Function TemplateAzure App Function Template

Name the function and select create.

There is already some sample code there that would obviously be running.

We would need this to be set up for Power BI embedded.

- CLIENT_ID; Value: Azure AD > App Name > Application ID

- GROUP_ID; Value: <Power BI Group ID> (https://powerbi.com/groups/<Group ID>/reports/<Report ID>/ReportSection) we simply need to hardcode this into application.

- REPORT_ID; Value: <Power BI Report ID>

- USERNAME; Value: Your Power BI Pro Account Username

- PASSWORD; Value: Your Power BI Pro Account Password

Now click to app settings,

Azure Function AppAzure Function App

Step 3 — Add the variables that we just created

Azure Function AppsAzure Function Apps

Then click Save.

Now go back to function, and create new file, filename.json.

Copy and paste this

Code

 

 

 

 

 

{
"frameworks": {
"net46":{
"dependencies": {
"Microsoft.IdentityModel.Clients.ActiveDirectory": "3.19.4",
"Microsoft.PowerBI.Api": "2.0.12"
}
}
}
}

 

 

 

 

 

And save so that would have installed the dependencies.

Now in the run.csx overwrite the code with this one.

Run.csx Code

 

 

 

 

 

#r "System.Web.Extensions"
using System.Configuration;
using System.Net;
using System.Text;
using System.Web.Script.Serialization;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Microsoft.PowerBI.Api.V2;
using Microsoft.PowerBI.Api.V2.Models;
using Microsoft.Rest;
// Static Values
static string authorityUrl = "https://login.windows.net/common/oauth2/authorize/";
static string resourceUrl = "https://analysis.windows.net/powerbi/api";
static string apiUrl = "https://api.powerbi.com/";
static string clientId = ConfigurationManager.AppSettings["PBIE_CLIENT_ID"];
static string username = ConfigurationManager.AppSettings["PBIE_USERNAME"];
static string password = ConfigurationManager.AppSettings["PBIE_PASSWORD"];
static string groupId = ConfigurationManager.AppSettings["PBIE_GROUP_ID"];
static string reportId = ConfigurationManager.AppSettings["PBIE_REPORT_ID"];
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
// Authenticate with Azure Ad > Get Access Token > Get Token Credentials
var credential = new UserPasswordCredential(username, password);
var authenticationContext = new AuthenticationContext(authorityUrl);
var authenticationResult = await authenticationContext.AcquireTokenAsync(resourceUrl, clientId, credential);
string accessToken = authenticationResult.AccessToken;
var tokenCredentials = new TokenCredentials(accessToken, "Bearer");
using (var client = new PowerBIClient(new Uri(apiUrl), tokenCredentials))
{
// Embed URL
Report report = client.Reports.GetReportInGroup(groupId, reportId);
string embedUrl = report.EmbedUrl;
// Embed Token
var generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view");
EmbedToken embedToken = client.Reports.GenerateTokenInGroup(groupId, reportId, generateTokenRequestParameters);
// JSON Response
EmbedContent data = new EmbedContent();
data.EmbedToken = embedToken.Token;
data.EmbedUrl = embedUrl;
data.ReportId = reportId;
JavaScriptSerializer js = new JavaScriptSerializer();
string jsonp = "callback(" + js.Serialize(data) + ");";
// Return Response
return new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(jsonp, Encoding.UTF8, "application/json")
};
}
}
public class EmbedContent
{
public string EmbedToken { get; set; }
public string EmbedUrl { get; set; }
public string ReportId { get; set; }
}

 

 

 

 

 

If there are any issues function picking up dependencies, then restart the function app by hit stop, hit start and run the function.

Azure Function App OverviewAzure Function App Overview

Testing the function

If you are looking to test the function, hit get function URL, copy the function URL and copy the URL in the browser and you will get the response in the form of JSON.

Phase 4 — Embed Content into Web App (Power BI JavaScript Library)

Create an Index.html file and paste the code given below;

Create an index.html file

 

 

 

 

 

<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Power BI Embedded Demo</title>
<link rel="shortcut icon" href="data&colon;image/x-icon;," type="image/x-icon">
<script type="text/javascript" language="javascript" src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script type="text/javascript" language="javascript" src="https://rawgit.com/Microsoft/PowerBI-JavaScript/master/dist/powerbi.min.js"></script> </script>
</head>
<body>
<h1>Power BI Embedded Demo</h1>
<div id="reportContainer" style="width: 80%; height: 600px;"></div>
</body>
<script>
$(document).ready(function () {
var getEmbedToken = "INSERT_YOUR_AZURE_FUNCTION_URL_HERE";
$.ajax({
url: getEmbedToken,
jsonpCallback: 'callback',
contentType: 'application/javascript',
dataType: "jsonp",
success: function (json) {
var models = window['powerbi-client'].models;
var embedConfiguration = {
type: 'report',
id: json.ReportId,
embedUrl: json.EmbedUrl,
tokenType: models.TokenType.Embed,
accessToken: json.EmbedToken
};
var $reportContainer = $('#reportContainer');
var report = powerbi.embed($reportContainer.get(0), embedConfiguration);
},
error: function () {
alert("Error");
}
});
});
</script>
</html>

 

 

 

 

 

Copy and Paste the function URL

Now get the function URL that you just got and paste it into the index.html file as the value in the variable getEmbedToken.

Save and open the index.html file in the browser.

Power BI Embedded with Azure DemoPower BI Embedded with Azure Demo

That’s It. I hope now you know more about text analytics in Microsoft Azure and Power BI ?. May you know someone who would find this article informative, please share!, follow me on Twitter or visit my website and stay tuned.

Comments