如何在 MVC(C#) 中刷新嵌入式 PowerBI
How to refresh Embedded PowerBI in MVC(C#)
我们使用 PowerBI 和 Azure 创建了一个报告。我添加了工作区、reportid 等,并显示了报告。但是我需要在每次加载页面时更新报告(即用户刷新页面,或单击 link 重定向到报告所在的页面)。
我已经搜索过,看到您可以设置定时刷新,但是那行不通,它需要更实时。有没有办法按照我上面指定的方式刷新报告?
以下是我的控制器中的内容:
public async Task<ActionResult> Dashboard(string username = null, string roles = null)
{
var result = new EmbedConfig();
try
{
result = new EmbedConfig { Username = username, Roles = roles };
var error = GetWebConfigErrors();
if (error != null)
{
result.ErrorMessage = error;
return View(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 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);
}
//refreshDataset(ReportId, report.DatasetId, tokenCredentials);
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);
}
下面是用于创建报告的Javascript:
<script>
window.onload = function () {
//Creating breadcrumbs
$('#ribbon ol').empty();
$('#ribbon ol').append('<li>Dashboard</li>');
}
// Read embed application token from Model
var accessToken = "@Model.EmbedToken.Token";
// Read embed URL from Model
var embedUrl = "@Html.Raw(Model.EmbedUrl)";
// Read report Id from Model
var embedReportId = "@Model.Id";
// Get models. models contains enums that can be used.
var models = window['powerbi-client'].models;
// Embed configuration used to describe the what and how to embed.
// This object is used when calling powerbi.embed.
// This also includes settings and options such as filters.
// You can find more information at https://github.com/Microsoft/PowerBI-JavaScript/wiki/Embed-Configuration-Details.
var config = {
type: 'report',
tokenType: models.TokenType.Embed,
accessToken: accessToken,
embedUrl: embedUrl,
id: embedReportId,
permissions: models.Permissions.All,
settings: {
filterPaneEnabled: false,
navContentPaneEnabled: false
}
};
// Get a reference to the embedded report HTML element
var reportContainer = $('#reportContainer')[0];
// Embed the report and display it within the div container.
var report = powerbi.embed(reportContainer, config);
</script>
感谢您的帮助。
如果您的报告如 Andrey 所问,是直接查询,那么您可以致电 report.refresh() on your embedded report in the JavaScript. The difference between Direct Query and Imported is explained here。
我们使用 PowerBI 和 Azure 创建了一个报告。我添加了工作区、reportid 等,并显示了报告。但是我需要在每次加载页面时更新报告(即用户刷新页面,或单击 link 重定向到报告所在的页面)。
我已经搜索过,看到您可以设置定时刷新,但是那行不通,它需要更实时。有没有办法按照我上面指定的方式刷新报告?
以下是我的控制器中的内容:
public async Task<ActionResult> Dashboard(string username = null, string roles = null)
{
var result = new EmbedConfig();
try
{
result = new EmbedConfig { Username = username, Roles = roles };
var error = GetWebConfigErrors();
if (error != null)
{
result.ErrorMessage = error;
return View(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 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);
}
//refreshDataset(ReportId, report.DatasetId, tokenCredentials);
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);
}
下面是用于创建报告的Javascript:
<script>
window.onload = function () {
//Creating breadcrumbs
$('#ribbon ol').empty();
$('#ribbon ol').append('<li>Dashboard</li>');
}
// Read embed application token from Model
var accessToken = "@Model.EmbedToken.Token";
// Read embed URL from Model
var embedUrl = "@Html.Raw(Model.EmbedUrl)";
// Read report Id from Model
var embedReportId = "@Model.Id";
// Get models. models contains enums that can be used.
var models = window['powerbi-client'].models;
// Embed configuration used to describe the what and how to embed.
// This object is used when calling powerbi.embed.
// This also includes settings and options such as filters.
// You can find more information at https://github.com/Microsoft/PowerBI-JavaScript/wiki/Embed-Configuration-Details.
var config = {
type: 'report',
tokenType: models.TokenType.Embed,
accessToken: accessToken,
embedUrl: embedUrl,
id: embedReportId,
permissions: models.Permissions.All,
settings: {
filterPaneEnabled: false,
navContentPaneEnabled: false
}
};
// Get a reference to the embedded report HTML element
var reportContainer = $('#reportContainer')[0];
// Embed the report and display it within the div container.
var report = powerbi.embed(reportContainer, config);
</script>
感谢您的帮助。
如果您的报告如 Andrey 所问,是直接查询,那么您可以致电 report.refresh() on your embedded report in the JavaScript. The difference between Direct Query and Imported is explained here。