Skip to main content

Create An Azure Function App To Generate Token - Power BI Embedded - Step By Step - Part Four

Overview
In this article, we will talk about how we can create an Azure Function APP to generate tokens.
Before we start I prefer you read my earlier articles,
Now, let’s get started!
Create an Azure App Function
  1. Open Azure Portal.
  2. Go to All Resources > Add > Serverless Function App.


  3. Give a name for your App function.

    Here, my application name = PBIReportEmbedded
    Click on Create button.


  4. Now, from left navigation,> Click on Function Apps > Click on PBIReportEmbedded which we have created in Step3.


  5. Click on Application Setting.


  6. We need to add the following Key-value Pairs,
    1. PBIE_CLIENT_ID = Application ID for the Application we have registered.
    2. PBIE_GROUP_ID = Workspace ID of Power BI Report.
    3. PBIE_REPORT_ID = Report ID of Power BI Report.
    4. PBIE_USERNAME = Username of Power BI Pro account
    5. PBIE_PASSWORD = Password of Power BI Pro account


  7. From Functions > Click on + icon > Select Webhook + API > CSharp > Create this function.


  8. Click on View Files


  9. Add a file named “project.json”.


  10. Add the following code snippet to “project.json” file.
  1. {  
  2.   "frameworks": {  
  3.     "net46":{  
  4.       "dependencies": {  
  5.         "Microsoft.IdentityModel.Clients.ActiveDirectory""3.19.4",  
  6.         "Microsoft.PowerBI.Api""2.0.12"  
  7.       }  
  8.     }  
  9.    }  
  10. }  
11. Open “run.csx” file.

 
12. Add the following code snippet.
  1. #r "System.Web.Extensions"  
  2. using System.Configuration;  
  3. using System.Net;  
  4. using System.Text;  
  5. using System.Web.Script.Serialization;  
  6. using Microsoft.IdentityModel.Clients.ActiveDirectory;  
  7. using Microsoft.PowerBI.Api.V2;  
  8. using Microsoft.PowerBI.Api.V2.Models;  
  9. using Microsoft.Rest;  
  10.   
  11. // Static Values  
  12. static string authorityUrl = "https://login.windows.net/common/oauth2/authorize/";  
  13. static string resourceUrl = "https://analysis.windows.net/powerbi/api";  
  14. static string apiUrl = "https://api.powerbi.com/";  
  15. static string clientId = ConfigurationManager.AppSettings["PBIE_CLIENT_ID"];  
  16. static string username = ConfigurationManager.AppSettings["PBIE_USERNAME"];  
  17. static string password = ConfigurationManager.AppSettings["PBIE_PASSWORD"];  
  18. static string groupId = ConfigurationManager.AppSettings["PBIE_GROUP_ID"];  
  19. static string reportId = ConfigurationManager.AppSettings["PBIE_REPORT_ID"];  
  20.   
  21. public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)  
  22. {  
  23.   
  24.     // Authenticate with Azure Ad > Get Access Token > Get Token Credentials  
  25.     var credential = new UserPasswordCredential(username, password);  
  26.     var authenticationContext = new AuthenticationContext(authorityUrl);  
  27.     var authenticationResult = await authenticationContext.AcquireTokenAsync(resourceUrl, clientId, credential);  
  28.     string accessToken = authenticationResult.AccessToken;  
  29.     var tokenCredentials = new TokenCredentials(accessToken, "Bearer");  
  30.       
  31.     using (var client = new PowerBIClient(new Uri(apiUrl), tokenCredentials))  
  32.     {  
  33.         // Embed URL  
  34.         Report report = client.Reports.GetReportInGroup(groupId, reportId);  
  35.         string embedUrl = report.EmbedUrl;  
  36.   
  37.         // Embed Token  
  38.         var generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view");  
  39.         EmbedToken embedToken = client.Reports.GenerateTokenInGroup(groupId, reportId, generateTokenRequestParameters);  
  40.   
  41.         // JSON Response  
  42.         EmbedContent data = new EmbedContent();  
  43.         data.EmbedToken = embedToken.Token;  
  44.         data.EmbedUrl = embedUrl;  
  45.         data.ReportId = reportId;  
  46.         JavaScriptSerializer js = new JavaScriptSerializer();  
  47.         string jsonp = "callback(" +  js.Serialize(data) + ");";  
  48.   
  49.         // Return Response  
  50.         return new HttpResponseMessage(HttpStatusCode.OK)   
  51.         {  
  52.             Content = new StringContent(jsonp, Encoding.UTF8, "application/json")  
  53.         };  
  54.     }  
  55. }  
  56.   
  57. public class EmbedContent  
  58. {  
  59.     public string EmbedToken { getset; }  
  60.     public string EmbedUrl { getset; }  
  61.     public string ReportId { getset; }  
  62. }  
13. Run the code.You will get the following output.

 
14. If you get an error like “500: Internal Server” then make sure you have applied “Grant Permission” in Azure Portal like the following image.

 
15. Your Azure App function is ready to use.
In my next article, we will check how we can embed Power BI report in an HTML page using Azure App function
Conclusion
This is how we can create Azure APP Function. Hope you love this article. Stay connected with me!

Comments

Popular posts from this blog

How to partition or split DataTable in C#?

Today we will discuss how we can divide or split a very large data table into fixed size of chunks? Scenario: Suppose there is a data table which has 1000 Rows. When you perform for each loop on data table and read each row at that time it will take too much time. If we devide 1000 Rows datatable into 10 fixed sizes (e.g. 100 Rows) datatable, It will take less time. Let's check how to achieve it. Here is a code. private static List<DataTable> SplitTable(DataTable originalTable, int batchSize) { List<DataTable> tables = new List<DataTable>(); int i = 0; int j = 1; DataTable newDt = originalTable.Clone(); newDt.TableName = "Table_" + j; newDt.Clear(); foreach (DataRow row in originalTable.Rows) { DataRow newRow = newDt.NewRow(); newRow.ItemArray = row.ItemArray; newDt.Rows.Add(newRow); i++; if (i == batchSize) ...

How To Lock Objects In Power BI

Overview Sometimes, there is a situation where when we open a report and click on any visual it accidentally nudges a chart a little bit to the right or left. Sometimes, by mistake when viewing a report, the arrangement of visuals scatters a little bit. Microsoft rolls out one new amazing feature to resolve this issue, that is, Lock Objects in Power BI. Advantages of using this feature When our purpose is to only view a report, this feature is a boon for us. Visualization’s position is not changed. Saves a lot of the developer's time to resolve the position related issues. Note   -  This feature is not saved with the report. So, every time you open a report, you need to enable this feature. Now, let’s understand this feature in a brief manner. To understand this, I will first show you one report in which I have not enabled “Lock Objects” feature. Step 1 The below screenshot shows my report which doesn’t have the enabled Lock Objects feature. ...

Use SharePoint Online List As A Data Source In Power BI

Introduction In this article, we will check how we can use SharePoint List as a data source in Microsoft Power BI. Please follow the below steps to establish the connection of SharePoint Online list with Power BI.  Step 1 Open Power BI Desktop > Get Data > Click More.   Step 2 Search for SharePoint > SharePoint Online List.   Step 3 Enter the URL of your SharePoint site.   Step 4 Click on Organizational account > Sign In.   Step 5 It will open the screen of Office 365 Login > Enter Credentials.   Step 6 Click on Connect.   Step 7 It will show all the lists available in the SharePoint - lists are on the left corner and their preview is on the right. Select all the lists which you want to use directly in the Power BI. Click on Load.   Step 8 It will load all the lists. Expand "Fields" column to view all the fields shown in the SharePoint List.   We can also view all the...