Example #1
0
        /// <summary>
        /// Get embed params for a dashboard
        /// </summary>
        /// <returns>Wrapper object containing Embed token, Embed URL for single dashboard</returns>
        public static async Task <DashboardEmbedConfig> EmbedDashboard(Guid workspaceId)
        {
            // Create a Power BI Client object. It will be used to call Power BI APIs.
            using (var client = await GetPowerBiClient())
            {
                // Get a list of dashboards.
                var dashboards = await client.Dashboards.GetDashboardsInGroupAsync(workspaceId);

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

                if (dashboard == null)
                {
                    throw new NullReferenceException("Workspace has no dashboards");
                }

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

                if (tokenResponse == null)
                {
                    throw new NullReferenceException("Failed to generate embed token");
                }

                // Generate Embed Configuration.
                var dashboardEmbedConfig = new DashboardEmbedConfig
                {
                    EmbedToken  = tokenResponse,
                    EmbedUrl    = dashboard.EmbedUrl,
                    DashboardId = dashboard.Id
                };

                return(dashboardEmbedConfig);
            }
        }
        public async Task <ActionResult> EmbedQnA()
        {
            var error = GetWebConfigErrors();

            if (error != null)
            {
                return(View(new QnAEmbedConfig()
                {
                    ErrorMessage = error
                }));
            }

            // Create a user password cradentials.
            var credential = new UserPasswordCredential(Username, Password);

            // Authenticate using created credentials
            var authenticationContext = new AuthenticationContext(AuthorityUrl);
            var authenticationResult  = await authenticationContext.AcquireTokenAsync(ResourceUrl, ClientId, credential);

            if (authenticationResult == null)
            {
                return(View(new TileEmbedConfig()
                {
                    ErrorMessage = "Authentication Failed."
                }));
            }

            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 datasets.
                var datasets = await client.Datasets.GetDatasetsInGroupAsync(GroupId);

                Dataset dataset;
                if (string.IsNullOrEmpty(DatasetId))
                {
                    // Get the first dataset in the group.
                    dataset = datasets.Value.FirstOrDefault();
                }
                else
                {
                    dataset = datasets.Value.FirstOrDefault(d => d.Id == DatasetId);
                }

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

                // Get the qna in the group and dataset.
                // original power bi clinet does not have Qnas property. i built an extension in PowerBIEmbedded.Extensions project
                var qna = await client.Qnas().GetQnaInGroupAsync(GroupId, DatasetId);

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

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

                // Generate Embed Configuration.
                var embedConfig = new QnAEmbedConfig()
                {
                    EmbedToken = tokenResponse,
                    EmbedUrl   = qna.EmbedUrl,
                    datasetId  = DatasetId,
                    viewMode   = "Interactive",
                    question   = ""
                };

                return(View(embedConfig));
            }
        }
Example #3
0
        public async Task <bool> EmbedTile()
        {
            // Get token credentials for user
            var getCredentialsResult = await GetTokenCredentials();

            if (!getCredentialsResult)
            {
                // The error message set in GetTokenCredentials
                m_tileEmbedConfig.ErrorMessage = m_embedConfig.ErrorMessage;
                return(false);
            }

            try
            {
                // Create a Power BI Client object. It will be used to call Power BI APIs.
                using (var client = new PowerBIClient(new Uri(ApiUrl), m_tokenCredentials))
                {
                    // Get a list of dashboards.
                    var dashboards = await client.Dashboards.GetDashboardsInGroupAsync(WorkspaceId);

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

                    if (dashboard == null)
                    {
                        m_tileEmbedConfig.ErrorMessage = "Workspace has no dashboards.";
                        return(false);
                    }

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

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

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

                    if (tokenResponse == null)
                    {
                        m_tileEmbedConfig.ErrorMessage = "Failed to generate embed token.";
                        return(false);
                    }

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

                    return(true);
                }
            }
            catch (HttpOperationException exc)
            {
                m_embedConfig.ErrorMessage = 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());
                return(false);
            }
        }
Example #4
0
        public async Task <ActionResult> EmbedTile()
        {
            var error = GetWebConfigErrors();

            if (error != null)
            {
                return(View(new TileEmbedConfig()
                {
                    ErrorMessage = error
                }));
            }

            // Create user credentials dictionary.
            var content = new Dictionary <string, string>();

            content["grant_type"] = "password";
            content["resource"]   = ResourceUrl;
            content["username"]   = Username;
            content["password"]   = Password;
            content["client_id"]  = ClientId;

            var httpClient = new HttpClient
            {
                Timeout     = new TimeSpan(0, 5, 0),
                BaseAddress = new Uri(AuthorityUrl)
            };

            httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type: application/x-www-form-urlencoded", "application/json");

            if (content == null)
            {
                content = new Dictionary <string, string>();
            }

            var encodedContent = new FormUrlEncodedContent(content);

            //Authenticate using credentials
            var authResponse = await httpClient.PostAsync(httpClient.BaseAddress, encodedContent);

            if (authResponse == null)
            {
                return(View(new TileEmbedConfig()
                {
                    ErrorMessage = "Authentication Failed."
                }));
            }

            var authObj = JsonConvert.DeserializeObject <AuthObject>(authResponse.Content.ReadAsStringAsync().Result);

            var tokenCredentials = new TokenCredentials(authObj.access_token, "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 dashboards.
                var dashboards = await client.Dashboards.GetDashboardsInGroupAsync(GroupId);

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

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

                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));
            }
        }
Example #5
0
        public async Task <ActionResult> EmbedReport(string username, string roles)
        {
            var result = new EmbedConfig();

            try
            {
                result = new EmbedConfig {
                    Username = username, Roles = roles
                };
                var error = GetWebConfigErrors();
                if (error != null)
                {
                    result.ErrorMessage = error;
                    return(View(result));
                }


                // Authenticate using created credentials
                var authenticationContext = new AuthenticationContext(AuthorityUrl);

/*
 *              // Create a user password cradentials.
 *              var credential = new UserPasswordCredential(Username, Password);
 *              var authenticationResult = await authenticationContext.AcquireTokenAsync(ResourceUrl, ApplicationId, credential);
 */
                //Prompt for authentication
                var authenticationResult = await authenticationContext.AcquireTokenAsync(ResourceUrl, ApplicationId, new Uri(RedirectUrl), new PlatformParameters(PromptBehavior.Always));

                if (authenticationResult == null)
                {
                    result.ErrorMessage = "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(WorkspaceId);

                    // No reports retrieved for the given workspace.
                    if (reports.Value.Count() == 0)
                    {
                        result.ErrorMessage = "No reports were found in the workspace";
                        return(View(result));
                    }

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

                    if (report == null)
                    {
                        result.ErrorMessage = "No report with the given ID was found in the workspace. Make sure ReportId is valid.";
                        return(View(result));
                    }

                    var datasets = await client.Datasets.GetDatasetByIdInGroupAsync(WorkspaceId, report.DatasetId);

                    result.IsEffectiveIdentityRequired      = datasets.IsEffectiveIdentityRequired;
                    result.IsEffectiveIdentityRolesRequired = datasets.IsEffectiveIdentityRolesRequired;
                    GenerateTokenRequest generateTokenRequestParameters;
                    // This is how you create embed token with effective identities
                    if (!string.IsNullOrWhiteSpace(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");
                    }

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

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

                    // Generate Embed Configuration.
                    result.EmbedToken = tokenResponse;
                    result.EmbedUrl   = report.EmbedUrl;
                    result.Id         = report.Id;

                    return(View(result));
                }
            }
            catch (HttpOperationException exc)
            {
                result.ErrorMessage = 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)
            {
                result.ErrorMessage = exc.ToString();
            }

            return(View(result));
        }
Example #6
0
 /// <summary>
 /// Generate token to view or edit the specified report
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='groupId'>
 /// The group id
 /// </param>
 /// <param name='reportId'>
 /// The report id
 /// </param>
 /// <param name='requestParameters'>
 /// Generate token parameters
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <EmbedToken> GenerateTokenAsync(this IReportsOperations operations, Guid groupId, Guid reportId, GenerateTokenRequest requestParameters, CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.GenerateTokenInGroupWithHttpMessagesAsync(groupId, reportId, requestParameters, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
 /// <summary>
 /// Generates an embed token to view the specified tile from the specified
 /// workspace.&lt;br/&gt;This API is relevant only to ['App owns data' embed
 /// scenario](https://docs.microsoft.com/power-bi/developer/embed-sample-for-customers).
 /// </summary>
 /// <remarks>
 /// &lt;br/&gt;**Required scope**: (all of the below)
 /// &lt;ul&gt;&lt;li&gt;Dashboard.ReadWrite.All or
 /// Dashboard.Read.All&lt;/li&gt;&lt;li&gt;Report.ReadWrite.All or
 /// Report.Read.All &lt;/li&gt;&lt;li&gt;Dataset.ReadWrite.All or
 /// Dataset.Read.All&lt;/li&gt;&lt;/ul&gt; &lt;br/&gt;To set the permissions
 /// scope, see [Register an
 /// app](https://docs.microsoft.com/power-bi/developer/register-app).
 /// </remarks>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='groupId'>
 /// The workspace id
 /// </param>
 /// <param name='dashboardKey'>
 /// The dashboard id
 /// </param>
 /// <param name='tileKey'>
 /// The tile id
 /// </param>
 /// <param name='requestParameters'>
 /// Generate token parameters
 /// </param>
 public static EmbedToken GenerateTokenInGroup(this ITiles operations, string groupId, string dashboardKey, string tileKey, GenerateTokenRequest requestParameters)
 {
     return(operations.GenerateTokenInGroupAsync(groupId, dashboardKey, tileKey, requestParameters).GetAwaiter().GetResult());
 }
Example #8
0
 /// <summary>
 /// Generate token to view or edit the specified report
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='groupId'>
 /// The group id
 /// </param>
 /// <param name='reportKey'>
 /// The report id
 /// </param>
 /// <param name='requestParameters'>
 /// Generate token parameters
 /// </param>
 public static EmbedToken GenerateTokenInGroup(this IReports operations, string groupId, string reportKey, GenerateTokenRequest requestParameters)
 {
     return(operations.GenerateTokenInGroupAsync(groupId, reportKey, requestParameters).GetAwaiter().GetResult());
 }
        public async Task <ActionResult> EmbedReport()
        {
            string tenantID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;

            string reportId = Request.Form["SelectedReport"].ToString();

            using (var client = await CreatePowerBIClientForISV())
            {
                var report = client.Reports.GetReportInGroup(GroupId, reportId);
                GenerateTokenRequest generateTokenRequestParameters = new GenerateTokenRequest(
                    accessLevel: "edit", allowSaveAs: true); //no role specified means you can access everything!
                // Generate Embed Token.
                if (!tenantID.StartsWith("1"))               // the owner tenant of this app starts with 1, which can access everything
                {
                    switch (report.Name.ToLower())
                    {
                    case "adventureworks":
                        // for non Analysis Service, map user to Username()
                        var salesUser = new EffectiveIdentity(
                            username: "******",
                            roles: new List <string> {
                            "Sales"
                        },
                            datasets: new List <string> {
                            report.DatasetId
                        });
                        generateTokenRequestParameters = new GenerateTokenRequest(
                            accessLevel: "edit", allowSaveAs: true,
                            identities: new List <EffectiveIdentity> {
                            salesUser
                        });
                        break;

                    case "testaasrls":
                        // for Analysis Service, map user to CustomData()
                        var embedUser = new EffectiveIdentity(
                            username: MvcApplication.pbiUserName,
                            customData: "embed",
                            roles: new List <string> {
                            "Sales Embedded"
                        },
                            datasets: new List <string> {
                            report.DatasetId
                        });
                        generateTokenRequestParameters = new GenerateTokenRequest(
                            accessLevel: "edit", allowSaveAs: true,
                            identities: new List <EffectiveIdentity> {
                            embedUser
                        });
                        break;
                    }
                }
                else
                {
                    switch (report.Name.ToLower())
                    {
                    case "testaasrls":
                        // for Analysis Service, map user to CustomData()
                        var embedUser = new EffectiveIdentity(
                            username: MvcApplication.pbiUserName,
                            customData: "*****@*****.**",
                            roles: new List <string> {
                            "Sales BiDi"
                        },
                            datasets: new List <string> {
                            report.DatasetId
                        });
                        generateTokenRequestParameters = new GenerateTokenRequest(
                            accessLevel: "edit", allowSaveAs: true,
                            identities: new List <EffectiveIdentity> {
                            embedUser
                        });
                        break;
                    }
                }
                var tokenResponse = await client.Reports.GenerateTokenInGroupAsync(GroupId, reportId, generateTokenRequestParameters);

                // Refresh the dataset
                // await client.Datasets.RefreshDatasetInGroupAsync(GroupId, report.DatasetId);

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

                return(View(embedConfig));
            }
        }
Example #10
0
        public PBReportViewModel GetPowerBIReport(string reportId)
        {
            var    client  = GetPowerBiClient();
            var    reports = client.Reports.GetReportsInGroupAsync(PBIWorkspaceId).Result.Value;
            Report report  = reports.Where(r => r.Id == reportId).FirstOrDefault();

            var generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view", allowSaveAs: true);

            var dataset = client.Datasets.GetDatasetByIdInGroupAsync(PBIWorkspaceId, report.DatasetId).Result;

            var token = client.Reports.GenerateTokenInGroupAsync(PBIWorkspaceId, report.Id, generateTokenRequestParameters).Result;

            var embedConfig = new EmbedConfiguration()
            {
                EmbedToken = token,
                EmbedUrl   = report.EmbedUrl,
                Id         = report.Id
            };

            return(new PBReportViewModel {
                Report = report, EmbedConfig = embedConfig
            });

            //if (!string.IsNullOrEmpty(SettingConfig.FilterTableName) && !string.IsNullOrEmpty(SettingConfig.FilterColumnName) && !string.IsNullOrEmpty(SettingConfig.FilterUserColumnName) && !SessionHelper.IsSuperAdmin)
            //{
            //    string filter = string.Empty;
            //    if (SessionHelper.RoleRightsId > 0)
            //    {
            //        if (SessionHelper.DepartmentId == SessionHelper.RoleRightsId)
            //        {
            //            filter = "&$filter=" + SettingConfig.FilterTableName + "/" + SettingConfig.FilterColumnName + " eq '" + SessionHelper.DepartmentName + "'";
            //            //filter = "&$filter=" + SettingConfig.FilterTableName + "/" + SettingConfig.FilterColumnName + " eq 'activo fijo'";
            //        }
            //        else
            //        {
            //            filter = "&$filter=" + SettingConfig.FilterTableName + "/" + SettingConfig.FilterColumnName + " in ('" + SessionHelper.DepartmentHierarchy + "')";
            //        }
            //    }
            //    else
            //    {
            //        filter = "&$filter=" + SettingConfig.FilterTableName + "/" + SettingConfig.FilterUserColumnName + " eq '" + SessionHelper.WelcomeUser + "'";
            //    }

            //    var embedConfig = new EmbedConfiguration()
            //    {
            //        EmbedToken = token,
            //        //EmbedUrl = report.EmbedUrl + "&$filter=" + SettingConfig.FilterTableName + "/" + SettingConfig.FilterColumnName + " in ('" + SessionHelper.DepartmentHierarchy + "')",
            //        EmbedUrl = report.EmbedUrl + filter,
            //        //EmbedUrl = report.EmbedUrl + "&$filter=" + SettingConfig.FilterTableName.ToUpper() + "/" + SettingConfig.FilterColumnName + " in ('proyectos','gestion corporativa','gestion de servicios')",
            //        Id = report.Id
            //    };
            //    return new ReportViewModel { Report = report, EmbedConfig = embedConfig };
            //}
            //else
            //{
            //    var embedConfig = new EmbedConfiguration()
            //    {
            //        EmbedToken = token,
            //        EmbedUrl = report.EmbedUrl /*+ "&$filter=VIEW_REPORT_EQCAS/DepartmentName in ('td100001','td110001')"*/,
            //        Id = report.Id
            //    };
            //    return new ReportViewModel { Report = report, EmbedConfig = embedConfig };
            //}
        }
        public static ReportWithRlsEmbeddingData GetReportWithRlsEmbeddingData()
        {
            var userName = "******";

            PowerBIClient pbiClient = GetPowerBiClient();

            var report     = pbiClient.Reports.GetReportInGroup(workspaceId, reportWithRlsId);
            var datasetId  = report.DatasetId;
            var embedUrl   = report.EmbedUrl;
            var reportName = report.Name;

            Console.WriteLine("Getting RLS-enabled embed tokens");

            GenerateTokenRequest tokenRequestAllData =
                new GenerateTokenRequest(accessLevel: "view",
                                         identities: new List <EffectiveIdentity> {
                new EffectiveIdentity(username: userName,
                                      datasets: new List <string> {
                    datasetWithRlsId
                },
                                      roles: new List <string> {
                    "All Sales Regions"
                })
            });


            string embedTokenAllData = pbiClient.Reports.GenerateTokenInGroup(workspaceId, reportWithRlsId, tokenRequestAllData).Token;

            EffectiveIdentity identityWesternSales = new EffectiveIdentity(username: userName, roles: new List <string> {
                "Western Sales Region"
            }, datasets: new List <string> {
                datasetWithRlsId
            });
            GenerateTokenRequest tokenRequestWesternSales = new GenerateTokenRequest("view", null, identities: new List <EffectiveIdentity> {
                identityWesternSales
            });
            string embedTokenWesternSales = pbiClient.Reports.GenerateTokenInGroup(workspaceId, report.Id, tokenRequestWesternSales).Token;

            EffectiveIdentity identityCentralSales = new EffectiveIdentity(username: userName, roles: new List <string> {
                "Central Sales Region"
            }, datasets: new List <string> {
                datasetWithRlsId
            });
            GenerateTokenRequest tokenRequestCentralSales = new GenerateTokenRequest(accessLevel: "view", datasetId: datasetId, identities: new List <EffectiveIdentity> {
                identityCentralSales
            });
            string embedTokenCentralSales = pbiClient.Reports.GenerateTokenInGroup(workspaceId, report.Id, tokenRequestCentralSales).Token;

            EffectiveIdentity identityEasternSales = new EffectiveIdentity(userName, roles: new List <string> {
                "Eastern Sales Region"
            }, datasets: new List <string> {
                datasetWithRlsId
            });
            GenerateTokenRequest tokenRequestEasternSales = new GenerateTokenRequest(accessLevel: "view", datasetId: datasetId, identities: new List <EffectiveIdentity> {
                identityEasternSales
            });
            string embedTokenEasternSales = pbiClient.Reports.GenerateTokenInGroup(workspaceId, report.Id, tokenRequestEasternSales).Token;


            EffectiveIdentity identityCombo = new EffectiveIdentity(userName, roles: new List <string> {
                "Central Sales Region", "Eastern Sales Region"
            }, datasets: new List <string> {
                datasetWithRlsId
            });
            GenerateTokenRequest tokenRequestCombo = new GenerateTokenRequest(accessLevel: "view", datasetId: datasetId, identities: new List <EffectiveIdentity> {
                identityCombo
            });
            string embedTokenCombo = pbiClient.Reports.GenerateTokenInGroup(workspaceId, report.Id, tokenRequestCombo).Token;


            return(new ReportWithRlsEmbeddingData {
                reportId = report.Id,
                reportName = reportName,
                embedUrl = embedUrl,
                embedTokenAllData = embedTokenAllData,
                embedTokenWesternSales = embedTokenWesternSales,
                embedTokenCentralSales = embedTokenCentralSales,
                embedTokenEasternSales = embedTokenEasternSales,
                embedTokenCombo = embedTokenCombo
            });
        }
        public static PowerBiEmbedConfig EmbedPbiReport(PowerBiReport reportProperties, string roles, string userName, bool rlsApplied = false)
        {
            var error = GetWebConfigErrors(reportProperties);

            if (error != null)
            {
                return(new PowerBiEmbedConfig()
                {
                    ErrorMessage = error
                });
            }

            // Create a user password cradentials this will be power BI owner license credential.
            var credential = new UserPasswordCredential(reportProperties.LoginUsername, reportProperties.LoginPassword);

            // Authenticate using created credentials
            var authenticationContext = new AuthenticationContext(reportProperties.AuthorityUrl);

            var authenticationResult = authenticationContext.AcquireTokenAsync(reportProperties.ResourceUrl, reportProperties.ApplicationId, credential);

            if (authenticationResult == null)
            {
                return(new PowerBiEmbedConfig()
                {
                    ErrorMessage = "Authentication Failed."
                });
            }

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

            // Create a Power BI Client object. It will be used to call Power BI APIs.
            var generateTokenRequestParameters = new GenerateTokenRequest();

            using (var client = new PowerBIClient(new Uri(reportProperties.ApiUrl), tokenCredentials))
            {
                // Get a list of reports.
                var reports = client.Reports.GetReportsInGroupAsync(reportProperties.WorkspaceId);

                var report = reports.Result.Value.FirstOrDefault(x => x.Id == reportProperties.ReportId);

                if (report == null)
                {
                    return(new PowerBiEmbedConfig()
                    {
                        ErrorMessage = "WOorkspace has no reports."
                    });
                }

                EmbedToken tokenResponse;
                if (rlsApplied)
                {
                    if (userName == null && roles == null)
                    {
                        return(new PowerBiEmbedConfig()
                        {
                            ErrorMessage = "User name or user role is null."
                        });
                    }

                    generateTokenRequestParameters = new GenerateTokenRequest("View", null, identities: new List <EffectiveIdentity>
                    {
                        new EffectiveIdentity(
                            userName,
                            roles: new List <string> {
                            roles
                        },
                            datasets: new List <string> {
                            report.DatasetId
                        }
                            )
                    });

                    tokenResponse = client.Reports.GenerateTokenInGroupAsync(reportProperties.WorkspaceId, report.Id, generateTokenRequestParameters).Result;
                }
                else
                {
                    tokenResponse = client.Reports.GenerateTokenInGroupAsync(reportProperties.WorkspaceId, report.Id, generateTokenRequestParameters).Result;
                }

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

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

                return(embedConfig);
            }
        }
Example #13
0
        private async Task <EmbedToken> GenerateTotkenAsync(IPowerBIClient client, Report report)
        {
            GenerateTokenRequest generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view");

            return(await client.Reports.GenerateTokenInGroupAsync(_configuration.WorkspaceId, report.Id, generateTokenRequestParameters));
        }
Example #14
0
 /// <summary>
 /// This functionality is only available in a workspace context. Use
 /// [Dashboards
 /// GenerateTokenInGroup](/rest/api/power-bi/embedtoken/dashboards_generatetokeningroup).
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='dashboardKey'>
 /// The dashboard id
 /// </param>
 /// <param name='requestParameters'>
 /// Generate token parameters
 /// </param>
 public static EmbedToken GenerateToken(this IDashboards operations, string dashboardKey, GenerateTokenRequest requestParameters)
 {
     return(operations.GenerateTokenAsync(dashboardKey, requestParameters).GetAwaiter().GetResult());
 }
Example #15
0
        private async Task <EmbedConfig> EmbedReport(EmbedReportRequest embedReportRequest)
        {
            var config = new EmbedConfig();

            UserCredential = embedReportRequest.Credential;
            try
            {
                var data = await AuthenticateAsync();

                using (var pClient = new PowerBIClient(new Uri(POWER_BI_API_URL), PTokenCredentials))
                {
                    var groups = await pClient.Groups.GetGroupsWithHttpMessagesAsync();

                    var group = groups.Body.Value.FirstOrDefault(s => s.Id == embedReportRequest.WorkSpaceId);
                    if (group == null)
                    {
                        throw new ValidationException(PowerResource.ValidationErrorParentGroupNotFoundError);
                    }
                    var reports = await pClient.Reports.GetReportsInGroupAsync(group.Id);

                    if (!reports.Value.Any())
                    {
                        config.ErrorMessage = PowerResource.EmbedReportNotFoundError;
                        return(config);
                    }

                    var embeddingReport = reports.Value.FirstOrDefault(s => s.Id == embedReportRequest.ReportId);
                    if (embeddingReport == null)
                    {
                        config.ErrorMessage = PowerResource.EmbedReportNotFoundError;
                    }

                    var dataSet = await pClient.Datasets.GetDatasetByIdInGroupAsync(group.Id, embeddingReport.DatasetId);


                    config.IsEffectiveIdentityRequired      = dataSet.IsEffectiveIdentityRequired;
                    config.IsEffectiveIdentityRolesRequired = dataSet.IsEffectiveIdentityRolesRequired;

                    var upDateResponse = await UpdateAndRefreshDataSet(pClient, embedReportRequest, group.Id, embeddingReport.Id, dataSet.Id);

                    if (upDateResponse)
                    {
                        GenerateTokenRequest generateTokenRequestParameters;
                        if (!string.IsNullOrWhiteSpace(embedReportRequest.EmbedUserName))
                        {
                            var rls = new EffectiveIdentity(embedReportRequest.EmbedUserName, new List <string> {
                                embeddingReport.DatasetId
                            });
                            if (!string.IsNullOrWhiteSpace(embedReportRequest.EmbedRoles))
                            {
                                var rolesList = new List <string>();
                                rolesList.AddRange(embedReportRequest.EmbedRoles.Split(','));
                                rls.Roles = rolesList;
                            }
                            generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view", identities: new List <EffectiveIdentity> {
                                rls
                            });
                        }
                        else
                        {
                            generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view");
                        }
                        var tokenResponse = await pClient.Reports.GenerateTokenInGroupAsync(group.Id, embeddingReport.Id, generateTokenRequestParameters);

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

                        config.EmbedToken = tokenResponse;
                        config.EmbedUrl   = embeddingReport.EmbedUrl;
                        config.Id         = embeddingReport.Id;
                        return(config);
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
            return(null);
        }
 /// <summary>
 /// Generates an embed token to view the specified tile from the specified
 /// workspace.&lt;br/&gt;This API is relevant only to ['App owns data' embed
 /// scenario](https://docs.microsoft.com/power-bi/developer/embed-sample-for-customers).
 /// </summary>
 /// <remarks>
 /// &lt;br/&gt;**Required scope**: (all of the below)
 /// &lt;ul&gt;&lt;li&gt;Dashboard.ReadWrite.All or
 /// Dashboard.Read.All&lt;/li&gt;&lt;li&gt;Report.ReadWrite.All or
 /// Report.Read.All &lt;/li&gt;&lt;li&gt;Dataset.ReadWrite.All or
 /// Dataset.Read.All&lt;/li&gt;&lt;/ul&gt;To set the permissions scope, see
 /// [Register an
 /// app](https://docs.microsoft.com/power-bi/developer/register-app).&lt;/br&gt;&lt;/br&gt;When
 /// using service principal for authentication, refer to [Service Principal
 /// with Power
 /// BI](https://docs.microsoft.com/power-bi/developer/embed-service-principal)
 /// document along with considerations and limitations section.
 /// </remarks>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='groupId'>
 /// The workspace id
 /// </param>
 /// <param name='dashboardId'>
 /// The dashboard id
 /// </param>
 /// <param name='tileId'>
 /// The tile id
 /// </param>
 /// <param name='requestParameters'>
 /// Generate token parameters
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <EmbedToken> GenerateTokenInGroupAsync(this ITilesOperations operations, System.Guid groupId, System.Guid dashboardId, System.Guid tileId, GenerateTokenRequest requestParameters, CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.GenerateTokenInGroupWithHttpMessagesAsync(groupId, dashboardId, tileId, requestParameters, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
Example #17
0
 /// <summary>
 /// Generate token to create a new report on a given dataset
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='requestParameters'>
 /// Generate token parameters
 /// </param>
 public static EmbedToken GenerateTokenForCreate(this IReports operations, GenerateTokenRequest requestParameters)
 {
     return(operations.GenerateTokenForCreateAsync(requestParameters).GetAwaiter().GetResult());
 }
        public static async Task <EmbedConfig> GetEmbedReportConfigData(string clientId, string groupId, string username, string password, string authorityUrl, string resourceUrl, string apiUrl, string reportUniqueId, string reportName, ServiceContext serviceContext, IServiceEventSource serviceEventSource)
        {
            ServiceEventSourceHelper serviceEventSourceHelper = new ServiceEventSourceHelper(serviceEventSource);
            var result = new EmbedConfig();
            var roles  = "";

            try
            {
                var error = GetWebConfigErrors(clientId, groupId, username, password);
                if (error != null)
                {
                    result.ErrorMessage = error;
                    return(result);
                }

                // Create a user password cradentials.
                var credential = new UserPasswordCredential(username, password);

                // Authenticate using created credentials
                var authenticationContext = new AuthenticationContext(authorityUrl);
                var authenticationResult  = await authenticationContext.AcquireTokenAsync(resourceUrl, clientId, credential);

                if (authenticationResult == null)
                {
                    result.ErrorMessage = "Authentication Failed.";
                    return(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(reportName))
                    {
                        // Get the first report in the group.
                        report = reports.Value.FirstOrDefault();
                    }
                    else
                    {
                        report = reports.Value.FirstOrDefault(r => r.Name.Equals(reportName));
                    }

                    if (report == null)
                    {
                        result.ErrorMessage = $"PowerBI Group has no report registered for Name[{reportName}].";
                        return(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 ((result.IsEffectiveIdentityRequired != null && result.IsEffectiveIdentityRequired == true) &&
                        (result.IsEffectiveIdentityRolesRequired != null && result.IsEffectiveIdentityRolesRequired == true) &&
                        !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");
                    }

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

                    if (tokenResponse == null)
                    {
                        serviceEventSourceHelper.ServiceMessage(serviceContext, $"Embed Report - Error during user authentication for report - Result=[{tokenResponse.ToString()}]");
                        result.ErrorMessage = "Failed to authenticate user for report request";
                        return(result);
                    }

                    // Generate Embed Configuration.
                    result.EmbedToken = tokenResponse;
                    result.EmbedUrl   = report.EmbedUrl;
                    result.Id         = report.Id;
                    return(result);
                }
            }
            catch (HttpOperationException exc)
            {
                result.ErrorMessage = string.Format($"Status: {exc.Response.StatusCode} Response Content: [{exc.Response.Content}] RequestId: {exc.Response.Headers["RequestId"].FirstOrDefault()}");
            }
            catch (Exception exc)
            {
                result.ErrorMessage = exc.ToString();
            }

            return(result);
        }
 /// <summary>
 /// This functionality is only available in a workspace context. Use [Tiles
 /// GenerateTokenInGroup](/rest/api/power-bi/embedtoken/tiles_generatetokeningroup).
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='dashboardKey'>
 /// The dashboard id
 /// </param>
 /// <param name='tileKey'>
 /// The tile id
 /// </param>
 /// <param name='requestParameters'>
 /// Generate token parameters
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <EmbedToken> GenerateTokenAsync(this ITiles operations, string dashboardKey, string tileKey, GenerateTokenRequest requestParameters, CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.GenerateTokenWithHttpMessagesAsync(dashboardKey, tileKey, requestParameters, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
Example #20
0
        public async Task <HttpResponseMessage> GetTileEmbedToken()
        {
            var result = new TileEmbedConfig();

            try
            {
                var error = GetWebConfigErrors();
                if (error != null)
                {
                    result.ErrorMessage = error;
                    return(Request.CreateResponse(HttpStatusCode.InternalServerError, result));
                }

                // Create a user password cradentials.
                var credential = new UserPasswordCredential(Username, Password);

                // Authenticate using created credentials
                var authenticationContext = new AuthenticationContext(AuthorityUrl);
                var authenticationResult  = await authenticationContext.AcquireTokenAsync(ResourceUrl, ApplicationId, credential);

                if (authenticationResult == null)
                {
                    result.ErrorMessage = "Authentication Failed.";
                    return(Request.CreateResponse(HttpStatusCode.InternalServerError, 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 dashboards.
                    var dashboards = await client.Dashboards.GetDashboardsInGroupAsync(WorkspaceId);

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

                    if (dashboard == null)
                    {
                        result.ErrorMessage = "Workspace has no dashboards.";
                        return(Request.CreateResponse(HttpStatusCode.InternalServerError, result));
                    }

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

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

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

                    if (tokenResponse == null)
                    {
                        result.ErrorMessage = "Failed to generate embed token.";
                        return(Request.CreateResponse(HttpStatusCode.InternalServerError, result));
                    }

                    // Generate Embed Configuration.
                    result.EmbedToken  = tokenResponse;
                    result.EmbedUrl    = tile.EmbedUrl;
                    result.Id          = tile.Id;
                    result.dashboardId = dashboard.Id;

                    return(Request.CreateResponse(HttpStatusCode.OK, result));
                }
            }
            catch (HttpOperationException exc)
            {
                result.ErrorMessage = 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());
                return(Request.CreateResponse(HttpStatusCode.InternalServerError, result));
            }
            catch (Exception exc)
            {
                result.ErrorMessage = exc.ToString();
                return(this.Request.CreateResponse(HttpStatusCode.InternalServerError, result));
            }
        }
Example #21
0
 /// <summary>
 /// Generate token to view or edit the specified report
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='groupId'>
 /// The group id
 /// </param>
 /// <param name='reportId'>
 /// The report id
 /// </param>
 /// <param name='requestParameters'>
 /// Generate token parameters
 /// </param>
 public static EmbedToken GenerateToken(this IReportsOperations operations, Guid groupId, Guid reportId, GenerateTokenRequest requestParameters)
 {
     return(operations.GenerateTokenAsync(groupId, reportId, requestParameters).GetAwaiter().GetResult());
 }
Example #22
0
        /// <summary>
        /// Generates an embed token to view the specified tile from the specified
        /// workspace.&lt;br/&gt;This API is relevant only to ['App owns data' embed
        /// scenario](https://docs.microsoft.com/power-bi/developer/embed-sample-for-customers).
        /// </summary>
        /// <remarks>
        /// &lt;br/&gt;**Required scope**: (all of the below)
        /// &lt;ul&gt;&lt;li&gt;Dashboard.ReadWrite.All or
        /// Dashboard.Read.All&lt;/li&gt;&lt;li&gt;Report.ReadWrite.All or
        /// Report.Read.All &lt;/li&gt;&lt;li&gt;Dataset.ReadWrite.All or
        /// Dataset.Read.All&lt;/li&gt;&lt;/ul&gt; &lt;br/&gt;To set the permissions
        /// scope, see [Register an
        /// app](https://docs.microsoft.com/power-bi/developer/register-app).
        /// </remarks>
        /// <param name='groupId'>
        /// The workspace id
        /// </param>
        /// <param name='dashboardId'>
        /// The dashboard id
        /// </param>
        /// <param name='tileId'>
        /// The tile id
        /// </param>
        /// <param name='requestParameters'>
        /// Generate token parameters
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="HttpOperationException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task <HttpOperationResponse <EmbedToken> > GenerateTokenInGroupWithHttpMessagesAsync(System.Guid groupId, System.Guid dashboardId, System.Guid tileId, GenerateTokenRequest requestParameters, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (requestParameters == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "requestParameters");
            }
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("groupId", groupId);
                tracingParameters.Add("dashboardId", dashboardId);
                tracingParameters.Add("tileId", tileId);
                tracingParameters.Add("requestParameters", requestParameters);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "GenerateTokenInGroup", tracingParameters);
            }
            // Construct URL
            var _baseUrl = Client.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "v1.0/myorg/groups/{groupId}/dashboards/{dashboardId}/tiles/{tileId}/GenerateToken").ToString();

            _url = _url.Replace("{groupId}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(groupId, Client.SerializationSettings).Trim('"')));
            _url = _url.Replace("{dashboardId}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(dashboardId, Client.SerializationSettings).Trim('"')));
            _url = _url.Replace("{tileId}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(tileId, Client.SerializationSettings).Trim('"')));
            // Create HTTP transport objects
            var _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;

            _httpRequest.Method     = new HttpMethod("POST");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers


            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;

            if (requestParameters != null)
            {
                _requestContent      = Rest.Serialization.SafeJsonConvert.SerializeObject(requestParameters, Client.SerializationSettings);
                _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
                _httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
            }
            // Set Credentials
            if (Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;

            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

            if ((int)_statusCode != 200)
            {
                var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                if (_httpResponse.Content != null)
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                }
                else
                {
                    _responseContent = string.Empty;
                }
                ex.Request  = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new HttpOperationResponse <EmbedToken>();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            // Deserialize Response
            if ((int)_statusCode == 200)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject <EmbedToken>(_responseContent, Client.DeserializationSettings);
                }
                catch (JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
Example #23
0
        public async Task <ActionResult> EmbedTile()
        {
            var error = GetWebConfigErrors();

            if (error != null)
            {
                return(View(new TileEmbedConfig()
                {
                    ErrorMessage = error
                }));
            }

            // Authenticate using created credentials
            var authenticationContext = new AuthenticationContext(AuthorityUrl);

/*
 *          // Create a user password cradentials.
 *          var credential = new UserPasswordCredential(Username, Password);
 *          var authenticationResult = await authenticationContext.AcquireTokenAsync(ResourceUrl, ApplicationId, credential);
 */
            //Prompt for authentication
            var authenticationResult = await authenticationContext.AcquireTokenAsync(ResourceUrl, ApplicationId, new Uri(RedirectUrl), new PlatformParameters(PromptBehavior.Always));

            if (authenticationResult == null)
            {
                return(View(new TileEmbedConfig()
                {
                    ErrorMessage = "Authentication Failed."
                }));
            }

            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 dashboards.
                var dashboards = await client.Dashboards.GetDashboardsInGroupAsync(WorkspaceId);

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

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

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

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

                // Generate Embed Token for a tile.
                var generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view");
                var tokenResponse = await client.Tiles.GenerateTokenInGroupAsync(WorkspaceId, 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));
            }
        }
        public async Task <bool> EmbedReport(string username, string roles, string customdata)
        {
            m_embedConfig.Trace(this, "EmbedReport called. Getting token credentials from SharePoint", 2);

            // Get token credentials for user
            var getCredentialsResult = await GetTokenCredentials();

            if (!getCredentialsResult)
            {
                m_embedConfig.Trace(this, "Failure to get token credentials.", 4);
                // The error message set in GetTokenCredentials
                return(false);
            }
            else
            {
                m_embedConfig.Trace(this, $"Credentials received successfully.", 4);
            }

            try
            {
                m_embedConfig.Trace(this, $"Creating a PowerBi Client for '{ApiUrl ?? "UNDEFINED"}'", 2);
                // Create a Power BI Client object. It will be used to call Power BI APIs.
                using (var client = new PowerBIClient(new Uri(ApiUrl), m_tokenCredentials))
                {
                    #region Get PowerBI Workspace / Report / Dataset
                    m_embedConfig.Trace(this, $"Query the PowerBi environment for all reports for workspace '{WorkspaceId ?? "UNDEFINED"}'", 4);
                    // Get a list of reports.
                    var reports = await client.Reports.GetReportsInGroupAsync(WorkspaceId);

                    // No reports retrieved for the given workspace.
                    if (reports.Value.Count() == 0)
                    {
                        m_embedConfig.Trace(this, $"UNEXPECTED - No reports were found (or accessible) in {WorkspaceId ?? "UNDEFINED"}. Abort processing", 6);
                        m_embedConfig.ErrorMessage = "No reports were found in the workspace";
                        return(false);
                    }

                    Report report;
                    if (string.IsNullOrWhiteSpace(ReportId))
                    {
                        m_embedConfig.Trace(this, $"No report id was configured. Attempt to select the first available report in {WorkspaceId}", 6);
                        // Get the first report in the workspace.
                        report = reports.Value.FirstOrDefault();

                        m_embedConfig.Trace(this, $"First report found: { (report != null ? report.Name : "UNDEFINED") }", 6);
                    }
                    else
                    {
                        m_embedConfig.Trace(this, $"Report Id configured: {ReportId}. Attempt to find this in {WorkspaceId ?? "UNDEFINED"}", 6);

                        report = reports.Value.FirstOrDefault(r => r.Id.Equals(ReportId, StringComparison.InvariantCultureIgnoreCase));

                        m_embedConfig.Trace(this, $"First report found: { (report != null ? report.Name : "UNDEFINED")}", 6);
                    }

                    if (report == null)
                    {
                        m_embedConfig.Trace(this, $"No report was found. Abort further processing.", 6);

                        m_embedConfig.ErrorMessage = "No report with the given ID was found in the workspace. Make sure ReportId is valid.";
                        return(false);
                    }


                    m_embedConfig.Trace(this, $"Report found. Attempt to get dataset specifics for this report's dataset {report.DatasetId ?? "UNDEFINED"}", 4);
                    var datasets = await client.Datasets.GetDatasetByIdInGroupAsync(WorkspaceId, report.DatasetId);

                    m_embedConfig.Trace(this, $"Dataset group found, name: {(datasets != null ? datasets.Name : "UNDEFINED")}", 4);
                    m_embedConfig.Trace(this, $"Dataset group properties: IsEffectiveEntityRequired = {datasets.IsEffectiveIdentityRequired}, IsEffectiveIdentityRolesRequired = {datasets.IsEffectiveIdentityRolesRequired}", 4);

                    m_embedConfig.IsEffectiveIdentityRequired      = datasets.IsEffectiveIdentityRequired;
                    m_embedConfig.IsEffectiveIdentityRolesRequired = datasets.IsEffectiveIdentityRolesRequired;

                    #endregion

                    #region Generate token to access dataset

                    GenerateTokenRequest generateTokenRequestParameters;


                    if (!validateThatWebAppIsLaunchedAsSharePointAppPart || !string.IsNullOrWhiteSpace(username))
                    {
                        m_embedConfig.Trace(this, $"Generating token request parameters for dataset = '{report.DatasetId ?? "UNDEFINED"}', for User = '******', with Roles = '{roles ?? "UNDEFINED"}'", 4);

                        var rls = new EffectiveIdentity(ServicePrincipalObjectId, new List <string> {
                            report.DatasetId
                        })
                        {
                            //for testing purposes, a hardcoded "customdata" value can be provided.
                            CustomData = String.IsNullOrEmpty(defaultCustomDataForEmbedToken)
                            ? customdata
                            : defaultCustomDataForEmbedToken
                        };

                        generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view", identities: new List <EffectiveIdentity> {
                            rls
                        });
                    }
                    else
                    {
                        m_embedConfig.Trace(this, $"Generating generic token request (accessLevel: view) for dataset = '{report.DatasetId ?? "UNDEFINED"}'.", 4);

                        generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view");
                    }

                    m_embedConfig.Trace(this, $"Generating token response for report", 2);
                    var tokenResponse = await client.Reports.GenerateTokenInGroupAsync(WorkspaceId, report.Id, generateTokenRequestParameters);

                    if (tokenResponse == null)
                    {
                        m_embedConfig.Trace(this, $"UNEXPECTED - Generating token respose for report did not yield results", 4);
                        m_embedConfig.ErrorMessage = "Failed to generate embed token.";
                        return(false);
                    }

                    #endregion

                    // Generate Embed Configuration.
                    m_embedConfig.EmbedToken = tokenResponse;
                    m_embedConfig.EmbedUrl   = report.EmbedUrl;
                    m_embedConfig.Id         = report.Id;
                }
            }
            catch (HttpOperationException exc)
            {
                m_embedConfig.Trace(this, $"HttpOperationException received. Message: {exc.Message}, StackTrace: {exc.StackTrace}", 2);
                m_embedConfig.ErrorMessage = 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());
                return(false);
            }

            return(true);
        }
Example #25
0
        public async Task <TokenInfo> getReportToken(string reportId = "", string mode = "", string username = "", string masterUser = "", string ADcode = null)
        {
            if (!string.IsNullOrEmpty(reportId))
            {
                ReportId = reportId;
            }
            string accessLevel;

            switch (mode.ToUpper())
            {
            case "EDIT":
                accessLevel = TokenAccessLevel.Edit;
                break;

            case "CREATE":
                if (!string.IsNullOrEmpty(username))
                {
                    // for RLS we will duplicate the empty template report
                    // ReportId = "d346d02f-2a7d-4f4c-9437-407bf3c9bfb5";
                }
                accessLevel = TokenAccessLevel.Create;
                break;

            default:
                accessLevel = TokenAccessLevel.View;
                break;
            }
            string bearerToken = await AuthenticateAsync(masterUser, ADcode);

            // Create a Power BI Client object. It will be used to call Power BI APIs.
            using (var client = new PowerBIClient(new Uri(ApiUrl), new TokenCredentials(bearerToken)))
            {
                // 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)
                {
                    throw new System.Exception();
                }

                //if using AD auth dont generate token

                /*
                 * if (!String.IsNullOrEmpty(ADcode) || true) {
                 *  return new TokenInfo
                 *  {
                 *      mode = accessLevel,
                 *      EmbedToken = bearerToken,
                 *      EmbedUrl = report.EmbedUrl,
                 *      ReportId = report.Id,
                 *      DatasetId = report.DatasetId
                 *  };
                 * }
                 * /* */
                GenerateTokenRequest generateTokenRequestParameters;
                EmbedToken           tokenResponse;
                if (accessLevel == TokenAccessLevel.Create)
                {
                    if (!string.IsNullOrEmpty(username))
                    {
                        // Duplicate Report
                        CloneReportRequest crr = new CloneReportRequest(name: "prueba");
                        report = client.Reports.CloneReportInGroup(GroupId, report.Id, crr);
                        // apply rls
                        var rls = new EffectiveIdentity(username, new List <string> {
                            report.DatasetId
                        });
                        generateTokenRequestParameters = new GenerateTokenRequest
                                                         (
                            accessLevel: TokenAccessLevel.Edit,
                            datasetId: report.DatasetId,
                            allowSaveAs: false,
                            identities: new List <EffectiveIdentity> {
                            rls
                        }
                                                         );
                    }
                    else
                    {
                        generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: accessLevel, datasetId: report.DatasetId, allowSaveAs: true);
                    }
                    tokenResponse = await client.Reports.GenerateTokenForCreateAsync(groupId : GroupId, requestParameters : generateTokenRequestParameters);
                }
                else
                {
                    // Generate Token Request Parameters
                    if (!string.IsNullOrEmpty(username))
                    {
                        var rls = new EffectiveIdentity(username, new List <string> {
                            report.DatasetId
                        });
                        generateTokenRequestParameters = new GenerateTokenRequest
                                                         (
                            accessLevel: accessLevel,
                            datasetId: report.DatasetId,
                            allowSaveAs: false,
                            identities: new List <EffectiveIdentity> {
                            rls
                        }
                                                         );
                    }
                    else
                    {
                        generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: accessLevel);
                    }
                    tokenResponse = await client.Reports.GenerateTokenInGroupAsync(GroupId, report.Id, generateTokenRequestParameters);
                }
                if (tokenResponse == null)
                {
                    throw new System.Exception("Failed to generate embed token.");
                }
                // Generate Embed Configuration.
                string tokenType = String.IsNullOrEmpty(ADcode) ? "embed" : "AAD";
                return(new TokenInfo
                {
                    mode = accessLevel,
                    EmbedToken = tokenResponse.Token,
                    EmbedUrl = report.EmbedUrl,
                    ReportId = report.Id,
                    DatasetId = report.DatasetId
                });
            }
        }
Example #26
0
        public async Task <ActionResult> EmbedTile()
        {
            var error = GetWebConfigErrors();

            if (error != null)
            {
                return(View(new TileEmbedConfig()
                {
                    ErrorMessage = error
                }));
            }

            //// Create a user password cradentials.
            //var credential = new UserPasswordCredential(Username, Password);

            //// Authenticate using created credentials
            //var authenticationContext = new AuthenticationContext(AuthorityUrl);
            //var authenticationResult = await authenticationContext.AcquireTokenAsync(ResourceUrl, ClientId, credential);

            //if (authenticationResult == null)
            //{
            //    return View(new TileEmbedConfig()
            //    {
            //        ErrorMessage = "Authentication Failed."
            //    });
            //}

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

            OAuthResult oAuthResult;

            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Add("Cache-Control", "no-cache");
                var _result = await client.PostAsync(
                    new Uri(TokenUrl), new FormUrlEncodedContent(
                        new[]
                {
                    new KeyValuePair <string, string>("resource", ResourceUrl),
                    new KeyValuePair <string, string>("client_id", ClientId),
                    new KeyValuePair <string, string>("grant_type", "password"),
                    new KeyValuePair <string, string>("username", Username),
                    new KeyValuePair <string, string>("password", Password),
                    new KeyValuePair <string, string>("scope", "openid"),
                }));

                if (_result.IsSuccessStatusCode)
                {
                    oAuthResult = JsonConvert.DeserializeObject <OAuthResult>(await _result.Content.ReadAsStringAsync());
                }
                else
                {
                    return(View(new TileEmbedConfig()
                    {
                        ErrorMessage = "Authentication Failed."
                    }));
                }
            }

            var tokenCredentials = new TokenCredentials(oAuthResult.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 dashboards.
                var dashboards = await client.Dashboards.GetDashboardsInGroupAsync(GroupId);

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

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

                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));
            }
        }
Example #27
0
        public async Task <IActionResult> EmbedReport()
        {
            // TODO: add this dynamically from user logged in
            String username = null;
            String roles    = null;

            var result = new EmbedConfig();

            try
            {
                result = new EmbedConfig();

                //// Inspired from https://stackoverflow.com/questions/45480532/embed-power-bi-report-in-asp-net-core-website

                var content = new Dictionary <string, string>();
                content["grant_type"] = "password";
                content["resource"]   = ResourceUrl;
                content["username"]   = Username;
                content["password"]   = Password;
                content["client_id"]  = ClientId;
                var httpClient = new HttpClient
                {
                    Timeout     = new TimeSpan(0, 5, 0),
                    BaseAddress = new Uri(AuthorityUrl)
                };

                httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type: application/x-www-form-urlencoded", "application/json");

                if (content == null)
                {
                    content = new Dictionary <string, string>();
                }

                var encodedContent = new FormUrlEncodedContent(content);

                var authResponse = await httpClient.PostAsync(httpClient.BaseAddress, encodedContent);

                if (authResponse == null)
                {
                    return(View(new EmbedConfig()
                    {
                        ErrorMessage = "Authentication Failed."
                    }));
                }

                var authObj = JsonConvert.DeserializeObject <AuthObject>(authResponse.Content.ReadAsStringAsync().Result);

                var tokenCredentials = new TokenCredentials(authObj.access_token, "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)
                    {
                        result.ErrorMessage = "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");
                    }

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

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

                    // Generate Embed Configuration.
                    result.EmbedToken = tokenResponse;
                    result.EmbedUrl   = report.EmbedUrl;
                    result.Id         = report.Id;

                    return(View(result));
                }
            }
            catch (HttpOperationException exc)
            {
                result.ErrorMessage = 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)
            {
                result.ErrorMessage = exc.ToString();
            }

            return(View(result));
        }
Example #28
0
        public async Task <ActionResult> EmbedReport(string username, string roles)
        {
            var result = new EmbedConfig();

            try
            {
                result = new EmbedConfig {
                    Username = username, Roles = roles
                };
                var error = GetWebConfigErrors();
                if (error != null)
                {
                    result.ErrorMessage = error;
                    return(View(result));
                }

                //**********Removed as UserPasswordCredential won't work in .NET Core ************************************************//
                //// Create a user password cradentials.
                //var credential = new UserPasswordCredential(Username, Password);
                //var authenticationContext =
                //    new AuthenticationContext("https://login.microsoftonline.com/common/oauth2/token");
                //// Authenticate using created credentials
                //var authenticationContext = new AuthenticationContext(AuthorityUrl);
                //var authenticationResult = await authenticationContext.AcquireTokenAsync(ResourceUrl, ClientId, credential);
                //*******************************************************************************************************************//

                OAuthResult oAuthResult;
                using (var client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Add("Cache-Control", "no-cache");
                    var _result = await client.PostAsync(
                        new Uri(TokenUrl), new FormUrlEncodedContent(
                            new[]
                    {
                        new KeyValuePair <string, string>("resource", ResourceUrl),
                        new KeyValuePair <string, string>("client_id", ClientId),
                        new KeyValuePair <string, string>("grant_type", "password"),
                        new KeyValuePair <string, string>("username", Username),
                        new KeyValuePair <string, string>("password", Password),
                        new KeyValuePair <string, string>("scope", "openid"),
                    }));

                    if (_result.IsSuccessStatusCode)
                    {
                        oAuthResult = JsonConvert.DeserializeObject <OAuthResult>(await _result.Content.ReadAsStringAsync());
                    }
                    else
                    {
                        result.ErrorMessage = "Authentication Failed.";
                        return(View(result));
                    }
                }

                var tokenCredentials = new TokenCredentials(oAuthResult.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)
                    {
                        result.ErrorMessage = "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");
                    }

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

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

                    // Generate Embed Configuration.
                    result.EmbedToken = tokenResponse;
                    result.EmbedUrl   = report.EmbedUrl;
                    result.Id         = report.Id;

                    return(View(result));
                }
            }
            catch (HttpOperationException exc)
            {
                result.ErrorMessage = 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)
            {
                result.ErrorMessage = exc.ToString();
            }

            return(View(result));
        }
Example #29
0
        public async Task <bool> EmbedReport(string username, string roles)
        {
            // Get token credentials for user
            var getCredentialsResult = await GetTokenCredentials();

            if (!getCredentialsResult)
            {
                // The error message set in GetTokenCredentials
                return(false);
            }

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

                    // No reports retrieved for the given workspace.
                    if (reports.Value.Count() == 0)
                    {
                        m_embedConfig.ErrorMessage = "No reports were found in the workspace";
                        return(false);
                    }

                    Report report;
                    if (string.IsNullOrWhiteSpace(ReportId))
                    {
                        // Get the first report in the workspace.
                        report = reports.Value.FirstOrDefault();
                    }
                    else
                    {
                        report = reports.Value.FirstOrDefault(r => r.Id.Equals(ReportId, StringComparison.InvariantCultureIgnoreCase));
                    }

                    if (report == null)
                    {
                        m_embedConfig.ErrorMessage = "No report with the given ID was found in the workspace. Make sure ReportId is valid.";
                        return(false);
                    }

                    var datasets = await client.Datasets.GetDatasetByIdInGroupAsync(WorkspaceId, report.DatasetId);

                    m_embedConfig.IsEffectiveIdentityRequired      = datasets.IsEffectiveIdentityRequired;
                    m_embedConfig.IsEffectiveIdentityRolesRequired = datasets.IsEffectiveIdentityRolesRequired;
                    GenerateTokenRequest generateTokenRequestParameters;
                    // This is how you create embed token with effective identities
                    if (!string.IsNullOrWhiteSpace(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");
                    }

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

                    if (tokenResponse == null)
                    {
                        m_embedConfig.ErrorMessage = "Failed to generate embed token.";
                        return(false);
                    }

                    // Generate Embed Configuration.
                    m_embedConfig.EmbedToken = tokenResponse;
                    m_embedConfig.EmbedUrl   = report.EmbedUrl;
                    m_embedConfig.Id         = report.Id;
                }
            }
            catch (HttpOperationException exc)
            {
                m_embedConfig.ErrorMessage = 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());
                return(false);
            }

            return(true);
        }
 /// <summary>
 /// Generates an embed token to view the specified tile from the specified
 /// workspace.&lt;br/&gt;This API is relevant only to ['App owns data' embed
 /// scenario](https://docs.microsoft.com/power-bi/developer/embed-sample-for-customers).
 /// </summary>
 /// <remarks>
 /// &lt;br/&gt;**Required scope**: (all of the below)
 /// &lt;ul&gt;&lt;li&gt;Dashboard.ReadWrite.All or
 /// Dashboard.Read.All&lt;/li&gt;&lt;li&gt;Report.ReadWrite.All or
 /// Report.Read.All &lt;/li&gt;&lt;li&gt;Dataset.ReadWrite.All or
 /// Dataset.Read.All&lt;/li&gt;&lt;/ul&gt;To set the permissions scope, see
 /// [Register an
 /// app](https://docs.microsoft.com/power-bi/developer/register-app).&lt;/br&gt;&lt;/br&gt;When
 /// using service principal for authentication, refer to [Service Principal
 /// with Power
 /// BI](https://docs.microsoft.com/power-bi/developer/embed-service-principal)
 /// document along with considerations and limitations section.
 /// </remarks>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='groupId'>
 /// The workspace id
 /// </param>
 /// <param name='dashboardId'>
 /// The dashboard id
 /// </param>
 /// <param name='tileId'>
 /// The tile id
 /// </param>
 /// <param name='requestParameters'>
 /// Generate token parameters
 /// </param>
 public static EmbedToken GenerateTokenInGroup(this ITilesOperations operations, System.Guid groupId, System.Guid dashboardId, System.Guid tileId, GenerateTokenRequest requestParameters)
 {
     return(operations.GenerateTokenInGroupAsync(groupId, dashboardId, tileId, requestParameters).GetAwaiter().GetResult());
 }