Quantcast
Channel: Developer topics
Viewing all articles
Browse latest Browse all 17884

Power Bi Embedded App Owns Data - Asp.Net Web Forms

$
0
0

Hi I am fairly new to Asp.Net Web forms and Power Bi. I am trying to make a sample app owns data for a web forms application.

 

I have referenced the code in the github samples and I am trying to create app owns data scenario.

 

When I am loading my page my report does not load and I get an error on the console that powerbi is not defined. I have referenced powerbi correctly. Can someone please help me with this.

 

I have attached the codebehind and page files below.

 

 

<%@ Page Title="Home Page" Async="true" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="SampleEmbedding._Default" %><asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server"><script src="~/scripts/powerbi.js"></script><script src="https://npmcdn.com/es6-promise@3.2.1"></script><div id="reportContainer"></div><div style="display:none; visibility:hidden"><h4>My first report</h4><div class="field"><div class="fieldtxt">Report Name</div><asp:Textbox ID="txtEmbedToken" runat="server" Width="750px"></asp:Textbox></div><div class="field"><div class="fieldtxt">Report Id</div><asp:Textbox ID="txtReportId" runat="server" Width="750px"></asp:Textbox></div><div class="field"><div class="fieldtxt">Report Embed URL</div><asp:Textbox ID="txtEmbedUrl" runat="server" Width="750px"></asp:Textbox></div></div><script type="text/javascript">

        
            var sAccessToken = document.getElementById("MainContent_txtEmbedToken").value;
            var sEmbedUrl = document.getElementById("MainContent_txtEmbedUrl").value;
            var sReportId = document.getElementById("MainContent_txtReportId").value;

            console.log('Here',sAccessToken);
            //var models = window['powerbi-client'].models;
            

            var config = {
                type: 'report',
                accessToken: sAccessToken,
                embedUrl: sEmbedUrl,
                id: sReportId,
             
                settings: {
                    filterPaneEnabled: true,
                    navContentPaneEnabled: true
                }
            };

            var reportContainer = document.getElementById("reportContainer");
            var report = powerbi.embed(reportContainer, config);
            
        
 </script></asp:Content>




--------------------------Codebehind-----------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Microsoft.PowerBI.Api.V2;
using Microsoft.PowerBI.Api.V2.Models;
using System.Configuration;
using Microsoft.Rest;


namespace SampleEmbedding
{
    public partial class _Default : Page
    {
        private static readonly string Username = ConfigurationManager.AppSettings["pbiUsername"];
        private static readonly string Password = ConfigurationManager.AppSettings["pbiPassword"];
        private static readonly string AuthorityUrl = ConfigurationManager.AppSettings["authorityUrl"];
        private static readonly string ResourceUrl = ConfigurationManager.AppSettings["resourceUrl"];
        private static readonly string ClientId = ConfigurationManager.AppSettings["clientId"];
        private static readonly string ApiUrl = ConfigurationManager.AppSettings["apiUrl"];
        private static readonly string GroupId = ConfigurationManager.AppSettings["groupId"];
        private static readonly string ReportId = ConfigurationManager.AppSettings["reportId"];

        public String sErrorMessage = "";
        public String sReportId = "";
        public String sEmbedUrl = "";
        public EmbedToken eEmbedToken;

        protected void Page_Load(object sender, EventArgs e)
        {
            EmbedReport();
        }


        


        private string GetWebConfigErrors()
        {
            // Client Id must have a value.
            if (string.IsNullOrEmpty(ClientId))
            {
                return "ClientId is empty. please register your application as Native app in https://dev.powerbi.com/apps and fill client Id in web.config.";
            }

            // Client Id must be a Guid object.
            Guid result;
            if (!Guid.TryParse(ClientId, out result))
            {
                return "ClientId must be a Guid object. please register your application as Native app in https://dev.powerbi.com/apps and fill client Id in web.config.";
            }

            // Group Id must have a value.
            if (string.IsNullOrEmpty(GroupId))
            {
                return "GroupId is empty. Please select a group you own and fill its Id in web.config";
            }

            // Group Id must be a Guid object.
            if (!Guid.TryParse(GroupId, out result))
            {
                return "GroupId must be a Guid object. Please select a group you own and fill its Id in web.config";
            }

            // Username must have a value.
            if (string.IsNullOrEmpty(Username))
            {
                return "Username is empty. Please fill Power BI username in web.config";
            }

            // Password must have a value.
            if (string.IsNullOrEmpty(Password))
            {
                return "Password is empty. Please fill password of Power BI username in web.config";
            }

            return null;
        }

        public async void EmbedReport()
        {
            //var result = new EmbedConfig();
            try
            {
                //result = new EmbedConfig { Username = username, Roles = roles };
                var error = GetWebConfigErrors();
                if (error != null)
                {
                    sErrorMessage = error;
                    //return View(result);
                }

                // Create a user password cradentials - From Active Directory
                var credential = new UserPasswordCredential(Username, Password);

                // Authenticate using created credentials
                //The AuthenticationContext class retrieves authentication tokens from Azure Active Directory and ADFS services.
                var authenticationContext = new AuthenticationContext(AuthorityUrl);

                //Acquires security token from the authority
                var authenticationResult = await authenticationContext.AcquireTokenAsync(ResourceUrl, ClientId, credential);


                if (authenticationResult == null)
                {
                    sErrorMessage = "Authentication Failed.";
                    //return View(result);
                }

                var tokenCredentials = new TokenCredentials(authenticationResult.AccessToken, "Bearer");

                // Create a Power BI Client object. It will be used to call Power BI APIs.
                using (var client = new PowerBIClient(new Uri(ApiUrl), tokenCredentials))
                {
                    // Get a list of reports.
                    var reports = await client.Reports.GetReportsInGroupAsync(GroupId);

                    Report report;
                    if (string.IsNullOrEmpty(ReportId))
                    {
                        // Get the first report in the group.
                        report = reports.Value.FirstOrDefault();
                    }
                    else
                    {
                        report = reports.Value.FirstOrDefault(r => r.Id == ReportId);
                    }

                    if (report == null)
                    {
                        sErrorMessage = "Group has no reports.";
                        //return View(result);
                    }


                    /*
                    var datasets = await client.Datasets.GetDatasetByIdInGroupAsync(GroupId, report.DatasetId);
                    //result.IsEffectiveIdentityRequired = datasets.IsEffectiveIdentityRequired;
                    //result.IsEffectiveIdentityRolesRequired = datasets.IsEffectiveIdentityRolesRequired;
                    GenerateTokenRequest generateTokenRequestParameters;
                    // This is how you create embed token with effective identities
                    if (!string.IsNullOrEmpty(username))
                    {
                        var rls = new EffectiveIdentity(username, new List<string> { report.DatasetId });
                        if (!string.IsNullOrWhiteSpace(roles))
                        {
                            var rolesList = new List<string>();
                            rolesList.AddRange(roles.Split(','));
                            rls.Roles = rolesList;
                        }
                        // Generate Embed Token with effective identities.
                        generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view", identities: new List<EffectiveIdentity> { rls });
                    }
                    else
                    {
                        // Generate Embed Token for reports without effective identities.
                        generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view");
                    }
                    */
                    GenerateTokenRequest generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view");

                    var tokenResponse = await client.Reports.GenerateTokenInGroupAsync(GroupId, report.Id, generateTokenRequestParameters);

                    if (tokenResponse == null)
                    {
                        sErrorMessage = "Failed to generate embed token.";
                        //return View(result);
                    }

                    // Generate Embed Configuration.
                    //eEmbedToken = tokenResponse;
                    txtEmbedToken.Text = tokenResponse.Token;
                    //sEmbedUrl = report.EmbedUrl;
                    txtEmbedUrl.Text = report.EmbedUrl;
                    //sReportId = report.Id;
                    txtReportId.Text = report.Id;

                    //return View(result);
                }
            }
            catch (HttpOperationException exc)
            {
                sErrorMessage = string.Format("Status: {0} ({1})\r\nResponse: {2}\r\nRequestId: {3}", exc.Response.StatusCode, (int)exc.Response.StatusCode, exc.Response.Content, exc.Response.Headers["RequestId"].FirstOrDefault());
            }
            catch (Exception exc)
            {
                sErrorMessage = exc.ToString();
            }

            //return View(result);
        }


    }
}
 

Viewing all articles
Browse latest Browse all 17884

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>