/// <summary> /// Get Embed token for multiple reports, datasets, and optional target workspaces /// </summary> /// <returns>Embed token</returns> /// <remarks>This function is not supported for RDL Report</remakrs> public EmbedToken GetEmbedToken(IList <Guid> reportIds, IList <Guid> datasetIds, [Optional] IList <Guid> targetWorkspaceIds) { // Note: This method is an example and is not consumed in this sample app PowerBIClient pbiClient = this.GetPowerBIClient(); // Convert report Ids to required types var reports = reportIds.Select(reportId => new GenerateTokenRequestV2Report(reportId)).ToList(); // Convert dataset Ids to required types var datasets = datasetIds.Select(datasetId => new GenerateTokenRequestV2Dataset(datasetId.ToString())).ToList(); // Convert target workspace Ids to required types IList <GenerateTokenRequestV2TargetWorkspace> targetWorkspaces = null; if (targetWorkspaceIds != null) { targetWorkspaces = targetWorkspaceIds.Select(targetWorkspaceId => new GenerateTokenRequestV2TargetWorkspace(targetWorkspaceId)).ToList(); } // Create a request for getting Embed token // This method works only with new Power BI V2 workspace experience var tokenRequest = new GenerateTokenRequestV2( datasets: datasets, reports: reports, targetWorkspaces: targetWorkspaceIds != null ? targetWorkspaces : null ); // Generate Embed token var embedToken = pbiClient.EmbedToken.GenerateToken(tokenRequest); return(embedToken); }
public IActionResult Dashboard() { _tenantId = GetTenantId(null); _tenantConfig = ReadConfig(_roomsConfig).Result; if (_tenantConfig.PBIConfig == null) { return(View()); } var workspaceId = _tenantConfig.PBIConfig.WorkspaceId; var reportId = _tenantConfig.PBIConfig.ReportId; var powerBiApiUrl = "https://api.powerbi.com/"; string[] pBIScopes = { "https://analysis.windows.net/powerbi/api/.default" }; var pbiAccessToken = _tokenAcquisition.GetAccessTokenOnBehalfOfUserAsync(pBIScopes).Result; using (var client = new PowerBIClient(new Uri(powerBiApiUrl), new TokenCredentials(pbiAccessToken, "Bearer"))) { Microsoft.PowerBI.Api.V2.Models.Report report = null; if (!string.IsNullOrEmpty(workspaceId)) { report = client.Reports.GetReportInGroup(workspaceId, reportId); } if (report != null) { ViewBag.EmbedUrl = report.EmbedUrl; ViewBag.ReportId = report.Id; ViewBag.ReportName = report.Name; ViewBag.AccessToken = pbiAccessToken; } } return(View()); }
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); }
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); }
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)); } }
static void CloneAppWorkspace(string sourceAppWorkspaceName, string targetAppWorkpaceName) { PowerBIClient pbiClient = GetPowerBiClient(); string sourceAppWorkspaceId = ""; string targetAppWorkspaceId = ""; var workspaces = pbiClient.Groups.GetGroups().Value; foreach (var workspace in workspaces) { if (workspace.Name.Equals(sourceAppWorkspaceName)) { sourceAppWorkspaceId = workspace.Id; } if (workspace.Name.Equals(targetAppWorkpaceName)) { targetAppWorkspaceId = workspace.Id; } } if (sourceAppWorkspaceId == "") { throw new ApplicationException("Source Workspace does not exist"); } if (targetAppWorkspaceId == "") { // create app workspace if it doesn't exist Console.WriteLine("Creating app workspace named " + targetAppWorkpaceName); Console.WriteLine(); GroupCreationRequest request = new GroupCreationRequest(targetAppWorkpaceName); Group AppWorkspace = pbiClient.Groups.CreateGroup(request, workspaceV2: true); targetAppWorkspaceId = AppWorkspace.Id; } var reports = pbiClient.Reports.GetReportsInGroup(sourceAppWorkspaceId).Value; string downloadPath = @"C:\Student\downloads\"; // create download folder if it doesn't exist if (!Directory.Exists(downloadPath)) { Directory.CreateDirectory(downloadPath); } foreach (var report in reports) { var reportStream = pbiClient.Reports.ExportReportInGroup(sourceAppWorkspaceId, report.Id); string filePath = downloadPath + report.Name + ".pbix"; Console.WriteLine("Downloading PBIX file for " + report.Name + "to " + filePath); FileStream stream1 = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite); reportStream.CopyToAsync(stream1).Wait(); reportStream.Close(); stream1.Close(); stream1.Dispose(); FileStream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read); Console.WriteLine("Publishing " + filePath + " to " + targetAppWorkpaceName); var import = pbiClient.Imports.PostImportWithFileInGroup(targetAppWorkspaceId, stream, report.Name); Console.WriteLine("Deleing file " + filePath); stream.Close(); stream.Dispose(); File.Delete(filePath); Console.WriteLine(); } Console.WriteLine("Export/Import process completed"); var dashboards = pbiClient.Dashboards.GetDashboardsInGroup(sourceAppWorkspaceId).Value; foreach (var sourceDashboard in dashboards) { // create the target dashboard Console.WriteLine(); Console.WriteLine("Creating Dashboard named " + sourceDashboard.DisplayName); AddDashboardRequest addReq = new AddDashboardRequest(sourceDashboard.DisplayName); Dashboard targetDashboard = pbiClient.Dashboards.AddDashboardInGroup(targetAppWorkspaceId, addReq); // clone tiles IList <Tile> sourceTiles = pbiClient.Dashboards.GetTilesInGroup(sourceAppWorkspaceId, sourceDashboard.Id).Value; foreach (Tile sourceTile in sourceTiles) { Console.WriteLine("Adding dashboard tile with title of " + sourceTile.Title); var sourceDatasetID = sourceTile.DatasetId; var sourceDatasetName = pbiClient.Datasets.GetDatasetByIdInGroup(sourceAppWorkspaceId, sourceDatasetID).Name; var targetWorkspaceDatasets = pbiClient.Datasets.GetDatasetsInGroup(targetAppWorkspaceId).Value; string targetDatasetId = ""; foreach (var ds in targetWorkspaceDatasets) { if (ds.Name.Equals(sourceDatasetName)) { targetDatasetId = ds.Id; } } if (targetDatasetId.Equals("")) { throw new ApplicationException("OOOOOuch!"); } var sourceReportId = sourceTile.ReportId; var sourceReportName = pbiClient.Reports.GetReportInGroup(sourceAppWorkspaceId, sourceReportId).Name; var targetWorkspaceReports = pbiClient.Reports.GetReportsInGroup(targetAppWorkspaceId).Value; string targetReportId = ""; foreach (var r in targetWorkspaceReports) { if (r.Name.Equals(sourceReportName)) { targetReportId = r.Id; } } CloneTileRequest addReqTile = new CloneTileRequest(targetDashboard.Id, targetAppWorkspaceId, targetReportId, targetDatasetId); pbiClient.Dashboards.CloneTileInGroup(sourceAppWorkspaceId, sourceDashboard.Id, sourceTile.Id, addReqTile); } } Console.WriteLine(); Console.WriteLine("All done - wow that was a lot of work :)"); Console.WriteLine(); }
static void CloneAppWorkspace(string sourceAppWorkspaceName, string targetAppWorkpaceName) { PowerBIClient pbiClient = GetPowerBiClient(); string sourceAppWorkspaceId = ""; string targetAppWorkspaceId = ""; var workspaces = pbiClient.Groups.GetGroups().Value; foreach (var workspace in workspaces) { if (workspace.Name.Equals(sourceAppWorkspaceName)) { sourceAppWorkspaceId = workspace.Id; } if (workspace.Name.Equals(targetAppWorkpaceName)) { targetAppWorkspaceId = workspace.Id; } } if (sourceAppWorkspaceId == "") { throw new ApplicationException("Source Workspace does not exist"); } if (targetAppWorkspaceId == "") { // create app workspace if it doesn't exist Console.WriteLine("Creating app workspace named " + targetAppWorkpaceName); GroupCreationRequest request = new GroupCreationRequest(targetAppWorkpaceName); Group AppWorkspace = pbiClient.Groups.CreateGroup(request); targetAppWorkspaceId = AppWorkspace.Id; string masterUserAccount = "*****@*****.**"; Console.WriteLine("Configuring " + masterUserAccount + " as workspace admin"); GroupUserAccessRight user1Permissions = new GroupUserAccessRight("Admin", masterUserAccount); pbiClient.Groups.AddGroupUser(targetAppWorkspaceId, user1Permissions); Console.WriteLine("Configuring workspace to run in dedicated capacity"); string customersCapcityId = "C9CCAA3E-18FB-4F2E-930F-CD3ABF609B8A"; AssignToCapacityRequest capReq = new AssignToCapacityRequest(customersCapcityId); pbiClient.Groups.AssignToCapacity(targetAppWorkspaceId, capReq); Console.WriteLine(); } var reports = pbiClient.Reports.GetReportsInGroup(sourceAppWorkspaceId).Value; foreach (var report in reports) { var reportStream = pbiClient.Reports.ExportReportInGroup(sourceAppWorkspaceId, report.Id); string filePath = @"C:\tempExport\" + report.Name + ".pbix"; Console.WriteLine("Downloading PBIX file for " + report.Name + "to " + filePath); FileStream stream1 = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite); reportStream.CopyToAsync(stream1).Wait(); reportStream.Close(); stream1.Close(); stream1.Dispose(); FileStream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read); Console.WriteLine("Publishing " + filePath + " to " + targetAppWorkpaceName); var import = pbiClient.Imports.PostImportWithFileInGroup(targetAppWorkspaceId, stream, report.Name); Console.WriteLine("Deleing file " + filePath); stream.Close(); stream.Dispose(); File.Delete(filePath); Console.WriteLine(); } Console.WriteLine("Export/Import process completed"); var dashboards = pbiClient.Dashboards.GetDashboardsInGroup(sourceAppWorkspaceId).Value; foreach (var sourceDashboard in dashboards) { // create the target dashboard Console.WriteLine(); Console.WriteLine("Creating Dashboard named " + sourceDashboard.DisplayName); AddDashboardRequest addReq = new AddDashboardRequest(sourceDashboard.DisplayName); Dashboard targetDashboard = pbiClient.Dashboards.AddDashboardInGroup(targetAppWorkspaceId, addReq); // clone tiles IList <Tile> sourceTiles = pbiClient.Dashboards.GetTilesInGroup(sourceAppWorkspaceId, sourceDashboard.Id).Value; foreach (Tile sourceTile in sourceTiles) { Console.WriteLine("Adding title with title of " + sourceTile.Title); var sourceDatasetID = sourceTile.DatasetId; var sourceDatasetName = pbiClient.Datasets.GetDatasetByIdInGroup(sourceAppWorkspaceId, sourceDatasetID).Name; var targetWorkspaceDatasets = pbiClient.Datasets.GetDatasetsInGroup(targetAppWorkspaceId).Value; string targetDatasetId = ""; foreach (var ds in targetWorkspaceDatasets) { if (ds.Name.Equals(sourceDatasetName)) { targetDatasetId = ds.Id; } } if (targetDatasetId.Equals("")) { throw new ApplicationException("OOOOOuch!"); } var sourceReportId = sourceTile.ReportId; var sourceReportName = pbiClient.Reports.GetReportInGroup(sourceAppWorkspaceId, sourceReportId).Name; var targetWorkspaceReports = pbiClient.Reports.GetReportsInGroup(targetAppWorkspaceId).Value; string targetReportId = ""; foreach (var r in targetWorkspaceReports) { if (r.Name.Equals(sourceReportName)) { targetReportId = r.Id; } } CloneTileRequest addReqTile = new CloneTileRequest(targetDashboard.Id, targetAppWorkspaceId, targetReportId, targetDatasetId); pbiClient.Dashboards.CloneTileInGroup(sourceAppWorkspaceId, sourceDashboard.Id, sourceTile.Id, addReqTile); } } Console.WriteLine(); Console.WriteLine("All done - wow that was a lot of work :)"); Console.WriteLine(); }
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 Report GetReport() { PowerBIClient client = new PowerBIClient(new Uri(powerBiApiUri), new TokenCredentials(accessToken, "Bearer")); return(client.Reports.GetReports().Value.FirstOrDefault()); }
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); } }
public async void RefreshAllDatasets() { List <ReportDetails> reportDetailsList = new List <ReportDetails>(); string username = ""; string roles = ""; var result = new EmbedConfig(); ReportDetails reportDetails = new ReportDetails(); try { result = new EmbedConfig { Username = username, Roles = roles }; var error = GetWebConfigErrors(); if (error != null) { result.ErrorMessage = error; //return View(result); return(null); } //azure key vault // 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 View(result); return(null); } 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); for (int index = 0; index < reports.Value.Count; index++) { reportDetails = new ReportDetails(); Report report = reports.Value[index]; HttpWebRequest request; var url = "https://api.powerbi.com/v1.0/myorg/groups/{0}/datasets/{1}/refreshes"; request = System.Net.HttpWebRequest.CreateHttp(String.Format(url, GroupId, report.DatasetId)); request.KeepAlive = true; request.Method = "POST"; request.ContentLength = 0; request.Headers.Add("Authorization", String.Format("Bearer {0}", authenticationResult.AccessToken)); using (Stream writer = request.GetRequestStream()) { var response = (HttpWebResponse)request.GetResponse(); Console.WriteLine("Dataset refresh request{0}", response.StatusCode.ToString()); } ////To Get History of Refresh //using (var response = (HttpWebResponse)request.GetResponse()) //{ // var responseString = new System.IO.StreamReader(response.GetResponseStream()).ReadToEnd(); // dynamic responseJson = JsonConvert.DeserializeObject<dynamic>(responseString); // foreach (var refresh in responseJson.value) // { // Console.WriteLine("Dataset {0} refreshed is {1}", report.DatasetId, refresh["status"]); // Console.WriteLine("StartTime at {0} EndTime at {1}", refresh["startTime"], refresh["endTime"]); // } }//end for(int index=0; index< reports.Value.Count; index++) } } catch (HttpOperationException exc) { Console.log(exc.Message); } catch (Exception exc) { Console.log(exc.Message); } return(await GetAllReportsDetails()); }
public async Task <bool> UpdateDataSource(string username, string roles) { // Get token credentials for user var getCredentialsResult = await GetTokenCredentials(); if (!getCredentialsResult) { return(false); } try { using (var client = new PowerBIClient(new Uri(ApiUrl), m_tokenCredentials)) { var ddx = await client.Groups.GetGroupsWithHttpMessagesAsync(); var group = ddx.Body.Value.FirstOrDefault(s => s.Name == "My Workspace"); var reports = await client.Reports.GetReportsInGroupAsync(group.Id); var dataset = await client.Datasets.GetDatasetByIdInGroupWithHttpMessagesAsync(group.Id, reports.Value.FirstOrDefault()?.DatasetId); var dataSourceOrg = await client.Datasets.GetDatasourcesAsync(group.Id, dataset.Body.Id); var data = await client.Datasets.GetParametersInGroupWithHttpMessagesAsync(group.Id, dataset.Body.Id); var dd = data.Body.Value; var response = await client.Datasets.UpdateParametersInGroupWithHttpMessagesAsync(@group.Id, dataset.Body.Id, new UpdateDatasetParametersRequest { UpdateDetails = new List <UpdateDatasetParameterDetails> { new UpdateDatasetParameterDetails { Name = "ConnectionUrl", NewValue = "https://gist.githubusercontent.com/curran/a08a1080b88344b0c8a7/raw/d546eaee765268bf2f487608c537c05e22e4b221/iris.csv" } } }); var refresh = await client.Datasets.RefreshDatasetInGroupWithHttpMessagesAsync(@group.Id, dataset.Body.Id); var report = reports.Value.FirstOrDefault(); await client.Reports.RebindReportInGroupWithHttpMessagesAsync(group.Id, report.Id, new RebindReportRequest { DatasetId = dataset.Body.Id }); data = await client.Datasets.GetParametersInGroupWithHttpMessagesAsync(group.Id, dataset.Body.Id); dd = data.Body.Value; } } 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); }
public async Task <bool> CloneReport(string username, string roles) { var data = await GetPowerBiAccessToken(); var getCredentialsResult = await GetTokenCredentials(); if (!getCredentialsResult) { return(false); } try { using (var client = new PowerBIClient(new Uri(ApiUrl), m_tokenCredentials)) { var ddx = await client.Groups.GetGroupsWithHttpMessagesAsync(); var group = ddx.Body.Value.FirstOrDefault(s => s.Name == "My Workspace"); var reports = await client.Reports.GetReportsInGroupAsync(group.Id); var dataset = await client.Datasets.GetDatasetByIdInGroupWithHttpMessagesAsync(group.Id, reports.Value.FirstOrDefault()?.DatasetId); var dataSourceOrg = await client.Datasets.GetDatasourcesAsync(group.Id, dataset.Body.Id); var report = reports.Value.FirstOrDefault(); var export = await client.Reports.ExportReportInGroupAsync(@group.Id, report.Id); //c7461d03-6cbb-4e93-bf67-343314792907 await TryUploadAsync(client, "c7461d03-6cbb-4e93-bf67-343314792907", export, "CloneReportTwo"); // using (var stream = new MemoryStream()) // { // CopyStream(export.Body, stream); // var response = await client.Imports.PostImportFileWithHttpMessage(stream, "newDataSet", "Overwrite"); // } // // // var rep=await client.Reports.CloneReportInGroupWithHttpMessagesAsync(@group.Id, report.Id, new CloneReportRequest // { // Name = "SepalReportCloneSecond", // TargetWorkspaceId = @group.Id, // TargetModelId = dataset.Body.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(false); }
private static void Main(string[] args) { var command = args[0]; var path = args[1]; var groupName = args[2]; var clientId = args[3]; var clientSecret = args[4]; var username = args[5]; var password = args[6]; var dataSourceUpdates = args[7]; // Example JSON below //var dataSourceUpdates = //@"{ //""updateDetails"":[ // { // ""connectionDetails"": // { // ""url"": ""https://marcsc-corrmgmt.api.crm.dynamics.com/api/data/v8.2"" // }, // ""datasourceSelector"": // { // ""datasourceType"": ""OData"", // ""connectionDetails"": { // ""url"": ""https://cmv9.api.crm.dynamics.com/api/data/v8.2"" // } // } // } //] //}"; //@"{""updateDetails"":[{""connectionDetails"":{""url"": ""https://marcsc-corrmgmt.api.crm.dynamics.com/api/data/v8.2""},""datasourceSelector"":{""datasourceType"": ""OData"",""connectionDetails"": {""url"": ""https://cmv9.api.crm.dynamics.com/api/data/v8.2""}}}]}"; var token = AuthenticationHelper.GetAccessToken(clientId, clientSecret, username, password); var tokenCredentials = new TokenCredentials(token, "Bearer"); Group group; using (var pbiClient = new PowerBIClient(tokenCredentials)) { // Get groups/workspaces var groups = pbiClient.Groups.GetGroups().Value; var groupsQuery = from g in groups where g.Name == groupName select g; group = groupsQuery.FirstOrDefault(); // Create group if it doesn't exist if (group == null) { group = pbiClient.Groups.CreateGroupAsync(new GroupCreationRequest { Name = groupName }).Result; } // Import .pbix into group var fileName = Path.GetFileName(path); var fileStream = File.OpenRead(path); HttpOperationResponse <Import> response; try { response = pbiClient.Imports.PostImportFileWithHttpMessage(group.Id, fileStream, fileName, "Overwrite").Result; } catch (Exception) { fileStream = File.OpenRead(path); response = pbiClient.Imports.PostImportFileWithHttpMessage(group.Id, fileStream, fileName).Result; } // Get the datasource of the updated .pbix var dataSets = pbiClient.Datasets.GetDatasetsInGroupAsync(group.Id).Result; var dataSetsQuery = from d in dataSets.Value where d.Name == fileName.Replace(".pbix", "") select d; var dataSetId = dataSetsQuery.First().Id; // Update the data sources so that they point to the right Dynamics instance. var content = new StringContent(dataSourceUpdates, Encoding.UTF8, "application/json"); Thread.Sleep(TimeSpan.FromSeconds(5)); //REST API seems to fail sporadically when updating a datasource immediately after import. Waiting 5 seconds seems to fix it. using (var httpClient = new HttpClient()) { httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); //httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var result = httpClient.PostAsync( $"{pbiClient.BaseUri}/v1.0/myorg/groups/{group.Id}/datasets/{dataSetId}/updatedatasources", content).Result; if (!result.IsSuccessStatusCode) { Console.Error.WriteLine("ERROR: Failed to update the datasource"); } } // TODO: would be great if we could update the data source credentials and then refresh it. // Don't see how to do that with the current API:https://msdn.microsoft.com/en-us/library/mt784652.aspx } }
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); }
public override void ExecuteCmdlet() { PSPowerBIEmbeddedCapacity capacity = null; WriteObject(PowerBIClient.TestCapacity(string.Empty, Name, out capacity)); }
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)); } }
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 }); } }
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)); } }
static void PostRows(string workspaceCollectionName, string workspaceId, string datasetid, string tableName, object datajson, PowerBIClient client) { //public static object PostRows(this IDatasets operations, string collectionName, string workspaceId, string datasetKey, string tableName, object requestMessage); var response = client.Datasets.PostRows(workspaceCollectionName, workspaceId, datasetid, tableName, datajson); }
static string CreateDatasets(string workspaceCollectionName, string workspaceId, PowerBIClient client) { Dataset ds = new Dataset(); ds.Name = "testdataset"; Table table1 = new Table(); table1.Name = "testTable"; Column column1 = new Column("id", "Int64"); Column column2 = new Column("name", "string"); table1.Columns = new List <Column>() { column1, column2 }; ds.Tables = new List <Table>() { table1 }; var response = client.Datasets.PostDataset(workspaceCollectionName, workspaceId, ds); dynamic obj = Newtonsoft.Json.JsonConvert.DeserializeObject <Object>(response.ToString()); return(obj["id"].ToString()); }
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 <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)); }
public async Task <bool> ExportReport() { // 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(new Guid(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.ToString().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); } CancellationToken token = new CancellationToken(); ExportedFile file = await ExportPowerBIReport( client, report.Id, new Guid(WorkspaceId), FileFormat.PPTX, 3, token ); m_exportConfig.File = file; m_exportConfig.FileName = String.Concat(report.Name, file.FileSuffix); } } catch (HttpOperationException exc) { m_exportConfig.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); }
private static async Task RunAsync(string configurationFile, CancellationToken ct) { var configuration = JsonConvert.DeserializeObject <ClientConfiguration>(File.ReadAllText(configurationFile)); var tokenProvider = new DeviceCodeTokenProvider(configuration.ClientId, configuration.TokenCacheState); using (var powerBIClient = new PowerBIClient(new TokenCredentials(tokenProvider))) { var existingDatasets = await powerBIClient.Datasets.GetDatasetsAsync(ct).ConfigureAwait(false); var dataset = CreateDatasetDefinition(); var datasetId = await GetOrCreateDataset(powerBIClient, dataset, existingDatasets.Value, ct).ConfigureAwait(false); var perMinuteStatus = dataset.Tables[0].Name; var liveDataset = CreateLiveDatasetDefinition(); var liveDatasetId = await GetOrCreateDataset(powerBIClient, liveDataset, existingDatasets.Value, ct).ConfigureAwait(false); var liveStatus = liveDataset.Tables[0].Name; var random = new Random(); var activePlayers = random.Next(0, 10); var playersToday = activePlayers; var playersAllTime = activePlayers; var resetDaysDuration = TimeSpan.FromMinutes(10); var dayStart = DateTime.MinValue; var minuteStart = DateTime.MinValue; while (!ct.IsCancellationRequested) { var now = DateTime.UtcNow; if (now > dayStart + TimeSpan.FromMinutes(10)) { playersToday = 0; dayStart = now; } var newActivePlayers = random.Next(0, 10); var delta = newActivePlayers - activePlayers; if (delta > 0) { playersToday += delta; playersAllTime += delta; } activePlayers = newActivePlayers; var liveRow = new { TimestampUtc = now, ActivePlayers = activePlayers, PlayersToday = playersToday, PlayersAllTime = playersAllTime }; await RetryPolicy.ExecuteAsync(cancel => powerBIClient.Datasets.PostRowsAsync(liveDatasetId, liveStatus, new[] { liveRow }, cancel), ct, false ).ConfigureAwait(false); if (now > minuteStart + TimeSpan.FromMinutes(1)) { var minuteRows = new object[random.Next(3, 10)]; for (var i = 0; i < minuteRows.Length; i++) { minuteRows[i] = new { TimestampUtc = now, Name = $"Player {i + 1}", Image = $"https://lorempixel.com/400/200/sports/{i + 1}", Count = random.Next(10, 50), Score = random.Next(50, 10000) }; } await RetryPolicy.ExecuteAsync(cancel => powerBIClient.Datasets.PostRowsAsync(datasetId, perMinuteStatus, minuteRows, cancel), ct, false ).ConfigureAwait(false); minuteStart = now; } await Task.Delay(5000, ct).ConfigureAwait(false); } } }
static void Main(string[] args) { try { // Create a user password cradentials. credential = new ClientCredential(Secrets.ClientID, Secrets.ClientSecret); // Authenticate using created credentials Authorize().Wait(); using (var client = new PowerBIClient(new Uri(apiUrl), tokenCredentials)) { #region Embed Token EmbedToken embedToken = null; if (useEmbedToken && !useRLS) { // **** Without RLS **** embedToken = client.Reports.GenerateTokenInGroup(groupId, reportId, new GenerateTokenRequest(accessLevel: "View", datasetId: datasetId.ToString())); } else if (useEmbedToken && useRLS) { // **** With RLS **** // Documentation: https://docs.microsoft.com/power-bi/developer/embedded/embedded-row-level-security // Example: // // Define Embed Token request: //var generateTokenRequestParameters = new GenerateTokenRequest("View", null, // identities: new List<EffectiveIdentity> { new EffectiveIdentity(username: "******", // roles: new List<string> { "roleA", "roleB" }, // datasets: new List<string> { "datasetId" }) }); // // Generate Embed Token: //var tokenResponse = await client.Reports.GenerateTokenInGroupAsync("groupId", "reportId", // generateTokenRequestParameters); var rls = new EffectiveIdentity(username: "******", new List <string> { datasetId.ToString() }); var rolesList = new List <string>(); rolesList.Add("<ENTER ROLE>"); rls.Roles = rolesList; embedToken = client.Reports.GenerateTokenInGroup(groupId, reportId, new GenerateTokenRequest(accessLevel: "View", datasetId: datasetId.ToString(), rls)); } #endregion #region Output Embed Token if (useEmbedToken) { // Get a single report used for embedding Report report = client.Reports.GetReportInGroup(groupId, reportId); Console.WriteLine("\r*** EMBED TOKEN ***\r"); Console.Write("Report Id: "); Console.ForegroundColor = ConsoleColor.Cyan; Console.WriteLine(reportId); Console.ResetColor(); Console.Write("Report Embed Url: "); Console.ForegroundColor = ConsoleColor.Cyan; Console.WriteLine(report.EmbedUrl); Console.ResetColor(); Console.WriteLine("Embed Token Expiration: "); Console.ForegroundColor = ConsoleColor.Cyan; Console.WriteLine(embedToken.Expiration.ToString()); Console.ResetColor(); Console.WriteLine("Report Embed Token: "); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine(embedToken.Token); Console.ResetColor(); } #endregion #region Output Datasets Console.WriteLine("\r*** DATASETS ***\r"); try { // List of Datasets // This method calls for items in a Group/App Workspace. To get a list of items within your "My Workspace" // call GetDatasets() var datasetList = client.Datasets.GetDatasetsInGroup(groupId); foreach (Dataset ds in datasetList.Value) { Console.WriteLine(ds.Id + " | " + ds.Name); } } catch (Exception ex) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Error fetching datasets: " + ex.Message); Console.ResetColor(); } #endregion #region Output Reports Console.WriteLine("\r*** REPORTS ***\r"); try { // List of reports // This method calls for items in a Group/App Workspace. To get a list of items within your "My Workspace" // call GetReports() var reportList = client.Reports.GetReportsInGroup(groupId); foreach (Report rpt in reportList.Value) { Console.WriteLine(rpt.Id + " | " + rpt.Name + " | DatasetID = " + rpt.DatasetId); } } catch (Exception ex) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Error fetching reports: " + ex.Message); Console.ResetColor(); } #endregion #region Output Dashboards Console.WriteLine("\r*** DASHBOARDS ***\r"); try { // List of reports // This method calls for items in a Group/App Workspace. To get a list of items within your "My Workspace" // call GetReports() var dashboards = client.Dashboards.GetDashboardsInGroup(groupId); foreach (Dashboard db in dashboards.Value) { Console.WriteLine(db.Id + " | " + db.DisplayName); } } catch (Exception ex) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Error fetching dashboards: " + ex.Message); Console.ResetColor(); } #endregion #region Output Gateways Console.WriteLine("\r*** Gateways ***\r"); try { var gateways = client.Gateways.GetGateways(); Console.WriteLine(gateways.Value[0].Name); //foreach (Gateway g in gateways) //{ // Console.WriteLine(g.Name + " | " + g.GatewayStatus); //} } catch (Exception ex) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Error fetching gateways: " + ex.Message); Console.ResetColor(); } #endregion } } catch (Exception ex) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(ex.ToString()); Console.ResetColor(); } }
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)); }
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); } }
private async Task <CloneReportResponse[]> Clone(CloneReportRequest cloneReportRequest) { var responseList = new List <CloneReportResponse>(); try { 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 == cloneReportRequest.ParentWorkSpaceId); if (group == null) { throw new ValidationException(PowerResource.ValidationErrorParentGroupNotFoundError); } var clientGroup = groups.Body.Value.FirstOrDefault(s => s.Id == cloneReportRequest.ClientWorkSpaceId); if (clientGroup == null) { throw new ValidationException(PowerResource.ValidationErrorClientGroupNotFoundError); } var reports = await pClient.Reports.GetReportsInGroupAsync(group.Id); if (reports.Value.Any()) { foreach (var cloneReport in cloneReportRequest.CloneReports) { var parentReport = reports.Value.FirstOrDefault(s => s.Id == cloneReport.ParentReportId); if (parentReport == null) { continue; } var export = await pClient.Reports.ExportReportInGroupAsync(@group.Id, parentReport.Id); var import = await TryUploadAsync(pClient, clientGroup.Id, export, cloneReport.CloneReportName); var reportDatasetId = import.Datasets.First().Id; try { var parameter = new Dictionary <string, string> { { "ConnectionUrl", cloneReport.WebApiEndPoint } }; var reportParameters = await pClient.Datasets.GetParametersInGroupAsync(clientGroup.Id, reportDatasetId); if (reportParameters != null && reportParameters.Value.Any()) { await SetReportParameters(pClient, clientGroup.Id, reportDatasetId, reportParameters.Value, parameter); } foreach (var impDataset in import.Datasets) { var refresh = await pClient.Datasets.RefreshDatasetInGroupWithHttpMessagesAsync(clientGroup.Id, impDataset.Id); } var clientGroupReports = await pClient.Reports.GetReportsInGroupAsync(clientGroup.Id); foreach (var impReport in import.Reports) { var cloneResultReport = clientGroupReports.Value.FirstOrDefault(s => s.Id == impReport.Id); await pClient.Reports.RebindReportInGroupWithHttpMessagesAsync(clientGroup.Id, impReport.Id, new RebindReportRequest { DatasetId = cloneResultReport.DatasetId }); } responseList.Add(new CloneReportResponse { CloneReportName = cloneReport.CloneReportName, CloneReportId = import.Reports.FirstOrDefault()?.Id, ParentReportId = cloneReport.ParentReportId, ParentReportName = parentReport.Name, Success = true }); } catch (Exception e) { throw e; } } } } } catch (Exception exp) { throw new ApplicationException(exp.Message); } return(responseList.ToArray()); }
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)); }
/// <summary> /// Gets the embed url for the report to render /// </summary> /// <returns></returns> protected override string GetEmbedUrl() { if (string.IsNullOrWhiteSpace(this.ReportId)) { return null; } var accessToken = base.GetAccessToken(); if (string.IsNullOrWhiteSpace(accessToken)) { return null; } var credentials = new TokenCredentials(accessToken); using (var client = new PowerBIClient(new Uri(this.BaseUri), credentials)) { var report = client.Reports.GetReports(this.CollectionName, this.WorkspaceId).Value.FirstOrDefault(r => r.Id == this.ReportId); return report?.EmbedUrl; } }
private static IPowerBIClient CreatePowerBiClient(PowerBIToken token) { var jwt = token.Generate(ConfigHelper.PowerbiSigningKey); var credentials = new TokenCredentials(jwt, "AppToken"); var client = new PowerBIClient(credentials) { BaseUri = new Uri(ConfigHelper.PowerbiApiUrl) }; return client; }
protected IPowerBIClient CreatePowerBIClient(PowerBIToken token) { var jwt = token.Generate(accessKey); var credentials = new TokenCredentials(jwt, "AppToken"); var client = new PowerBIClient(credentials) { BaseUri = new Uri(apiUrl) }; return client; }
protected override string GetEmbedUrl() { if(string.IsNullOrWhiteSpace(this.DashboardId) || string.IsNullOrWhiteSpace(this.TileId)) { return null; } var accessToken = base.GetAccessToken(); if (string.IsNullOrWhiteSpace(accessToken)) { return null; } var credentials = new TokenCredentials(accessToken); using (var client = new PowerBIClient(new Uri(this.BaseUri), credentials)) { var tile = client.Dashboards.GetTileByDashboardkeyAndTilekey(this.DashboardId, this.TileId); return tile.EmbedUrl; } }
static IPowerBIClient CreateClient(PowerBIToken token, string accessKey, string apiUrl) { WorkspaceCollectionKeys accessKeys = new WorkspaceCollectionKeys() { Key1 = accessKey }; // Generate a JWT token used when accessing the REST APIs var jwt = token.Generate(accessKeys.Key1); // Create a token credentials with "AppToken" type var credentials = new TokenCredentials(jwt, "AppToken"); // Instantiate your Power BI client passing in the required credentials var client = new PowerBIClient(credentials); // Override the api endpoint base URL. Default value is https://api.powerbi.com client.BaseUri = new Uri(apiUrl); return client; }