### Create Install Ticket API Source: https://learn.microsoft.com/pt-pt/power-bi/connect-data/template-apps-auto-install_source=recommendations This section explains how to use the CreateInstallTicket API to generate an installation ticket, which is necessary when redirecting users to Power BI for app installation. ```APIDOC ## Step 2: Create an Install Ticket ### Description This step involves using the `CreateInstallTicket` API to generate a ticket. This ticket is used when redirecting users to Power BI to install a template app. The operation is part of automating the template app installation process. ### Method POST ### Endpoint `/apps/{appId}/installTicket` (This is a conceptual endpoint based on the description; refer to official Power BI REST API documentation for the exact endpoint) ### Parameters #### Path Parameters - **appId** (Guid) - Required - The ID of the template app for which to create an install ticket. #### Query Parameters N/A #### Request Body - **InstallDetails** (Array of TemplateAppInstallDetails) - Required - Details required for the installation ticket. - **AppId** (Guid) - Required - The ID of the template app. - **PackageKey** (String) - Required - The package key of the template app. ### Request Example ```csharp using Microsoft.PowerBI.Api.V2; using Microsoft.PowerBI.Api.V2.Models; // Create Install Ticket Request. InstallTicket ticketResponse = null; var request = new CreateInstallTicketRequest() { InstallDetails = new List() { new TemplateAppInstallDetails() { AppId = Guid.Parse(AppId), PackageKey = PackageKey, ``` ### Response #### Success Response (200) - **ticket** (String) - A ticket that can be used for installation. #### Response Example ```json { "ticket": "your_install_ticket_string" } ``` ``` -------------------------------- ### Power BI Desktop Installation Command-Line Options Source: https://learn.microsoft.com/pt-pt/power-bi/fundamentals/desktop-get-the-desktop_source=recommendations This section details command-line options for installing Power BI Desktop. These are useful for administrators managing deployments. Options include silent installation, progress display, restart control, logging, uninstallation, and repair. ```command-line msiexec.exe /i "Path\To\PowerBI.msi" -q msiexec.exe /i "Path\To\PowerBI.msi" -passive msiexec.exe /i "Path\To\PowerBI.msi" -norestart msiexec.exe /i "Path\To\PowerBI.msi" -forcerestart msiexec.exe /i "Path\To\PowerBI.msi" -promptrestart msiexec.exe /i "Path\To\PowerBI.msi" -l"C:\Logs\PowerBI.log" msiexec.exe /i "Path\To\PowerBI.msi" -uninstall msiexec.exe /i "Path\To\PowerBI.msi" -repair msiexec.exe /i "Path\To\PowerBI.msi" ``` -------------------------------- ### Installation Source: https://learn.microsoft.com/pt-pt/power-bi/developer/visuals/utils-tooltip Install the powerbi-visuals-utils-tooltiputils package using npm. ```APIDOC ## npm install powerbi-visuals-utils-tooltiputils ### Description Installs the package and adds it as a dependency to your `package.json` file. ### Method `npm install` ### Parameters None ### Request Example ```bash npm install powerbi-visuals-utils-tooltiputils --save ``` ### Response #### Success Response (200) Package installed successfully. #### Response Example None ``` -------------------------------- ### Install Power BI Tooltip Utilities (Bash) Source: https://learn.microsoft.com/pt-pt/power-bi/developer/visuals/utils-tooltip Installs the powerbi-visuals-utils-tooltiputils package using npm. This command saves the package as a dependency in your project's package.json file. Ensure you have Node.js and npm installed. ```bash npm install powerbi-visuals-utils-tooltiputils --save ``` -------------------------------- ### Get Start of Previous Month in Power BI Source: https://learn.microsoft.com/pt-pt/power-bi/paginated-reports/expressions/report-builder-expression-examples This example displays the start date of the previous month based on the current month. It uses DateAdd and DateDiff functions along with CDate to calculate the date. ```DAX =DateAdd(DateInterval.Month,DateDiff(DateInterval.Month,CDate("01/01/1900"),Now())-1,CDate("01/01/1900")) ``` -------------------------------- ### Exemplo de Requisição POST para Função do Azure Source: https://learn.microsoft.com/pt-pt/power-bi/connect-data/template-apps-auto-install-tutorial_source=recommendations Um exemplo de como invocar a função de instalação automatizada do Power BI via requisição HTTP POST. O endpoint de exemplo é `http://localhost:7071/api/install`. ```HTTP POST http://localhost:7071/api/install ``` -------------------------------- ### Pré-requisitos para Instalação Automatizada Source: https://learn.microsoft.com/pt-pt/power-bi/connect-data/template-apps-auto-install-tutorial_source=recommendations Lista os requisitos necessários para configurar e implementar a instalação automatizada de aplicativos modelo do Power BI. ```APIDOC ## Pré-requisitos para Instalação Automatizada ### Descrição Para implementar a automação da instalação de aplicativos modelo do Power BI, os seguintes pré-requisitos devem ser atendidos. ### Requisitos: * **Tenant do Microsoft Entra**: Uma configuração de tenant do Microsoft Entra existente. Consulte a documentação para configuração. * **Principal de Serviço**: Um principal de serviço (token apenas de aplicativo) registrado no tenant do Microsoft Entra. * **Aplicativo Modelo Parametrizado**: Um aplicativo modelo criado no Power BI que esteja parametrizado e pronto para ser instalado. Este aplicativo deve estar no mesmo tenant onde o principal de serviço foi registrado. ``` -------------------------------- ### Get Start of Current Year in Power BI Source: https://learn.microsoft.com/pt-pt/power-bi/paginated-reports/expressions/report-builder-expression-examples The CDate function converts a value to a date. The Now function returns a date value containing the current date and time. DateDiff returns the number of time intervals between two dates. This example displays the start date of the current year. ```DAX =DateAdd(DateInterval.Year,DateDiff(DateInterval.Year,CDate("01/01/1900"),Now()),CDate("01/01/1900")) ``` -------------------------------- ### Fluxo Básico de Instalação Automatizada Source: https://learn.microsoft.com/pt-pt/power-bi/connect-data/template-apps-auto-install-tutorial_source=recommendations Este fluxo descreve os passos envolvidos quando um cliente inicia o processo de instalação automatizada de um aplicativo modelo do Power BI. ```APIDOC ## Fluxo Básico de Instalação Automatizada ### Descrição Este fluxo detalha os passos que ocorrem quando um cliente seleciona um link especial fornecido pelo ISV (provedor de serviços de dados) para instalar um aplicativo modelo do Power BI. ### Passos: 1. **Início pelo Cliente**: O usuário acessa o portal do ISV e seleciona um link preparado, que inicia o processo de automação. 2. **Token de Acesso**: O ISV obtém um token de acesso de aplicativo exclusivo usando um principal de serviço registrado. 3. **Criação do Tíquete de Instalação**: Utilizando as APIs REST do Power BI, o ISV cria um tíquete de instalação que inclui a configuração específica do usuário. 4. **Redirecionamento para o Power BI**: O ISV redireciona o usuário para o Power BI usando um método `POST` com o tíquete de instalação. 5. **Instalação do Aplicativo Modelo**: O usuário é levado à sua conta do Power BI, onde pode instalar o aplicativo modelo pré-configurado, apenas precisando autenticar nas fontes de dados. ### Observação Importante: As credenciais da fonte de dados são fornecidas apenas pelo usuário na fase final da instalação para garantir a segurança e evitar a exposição a terceiros. ``` -------------------------------- ### Set Up Python Environment and Configure Power BI Embed Source: https://learn.microsoft.com/pt-pt/power-bi/developer/embedded/embed-sample-for-customers This snippet guides the setup of a Python environment for Power BI embedding. It involves installing required packages using `pip3 install -r requirements.txt` and configuring parameters in `config.py`, including authentication mode and workspace ID. It assumes the user is in the correct directory containing `requirements.txt`. ```bash pip3 install -r requirements.txt ``` ```python # Depending on your authentication method, fill in the following parameter values: AUTHENTICATION_MODE = "Service Principal" # or "User Principal" WORKSPACE_ID = "The ID of the workspace with the embedded report" # Other parameters like reportId, clientId, pbiUsername, pbiPassword, clientSecret, tenantId would also be configured here. ``` -------------------------------- ### Open Power BI Desktop and Load Sample .pbix File Source: https://learn.microsoft.com/pt-pt/power-bi/connect-data/desktop-shape-and-combine-data_source=recommendations Instructions for opening Power BI Desktop and navigating to a downloaded .pbix file. This is the initial step to access the sample report and its data. ```plaintext 1. Open Power BI Desktop. 2. Select File > Open and navigate to the downloaded .pbix file. ``` -------------------------------- ### Check Power BI Refresh Status (JSON Response Example) Source: https://learn.microsoft.com/pt-pt/power-bi/connect-data/asynchronous-refresh_source=recommendations This JSON response shows the status of an in-progress refresh operation when using the GET verb on a specific refresh object with its requestId. It details the start and end times, type of refresh, overall status, and status of individual objects. ```json { "startTime": "2020-12-07T02:06:57.1838734Z", "endTime": "2020-12-07T02:07:00.4929675Z", "type": "Full", "status": "InProgress", "currentRefreshType": "Full", "objects": [ { "table": "DimCustomer", "partition": "DimCustomer", "status": "InProgress" }, { "table": "DimDate", "partition": "DimDate", "status": "InProgress" } ] } ``` -------------------------------- ### Exemplo de URL de Instalação do Power BI Source: https://learn.microsoft.com/pt-pt/power-bi/connect-data/template-apps-auto-install-tutorial_source=recommendations Este é um exemplo de URL de instalação do Power BI que contém os parâmetros necessários para configurar um aplicativo. Esses parâmetros incluem appId, packageKey e ownerId, que são cruciais para a integração automatizada. ```html https://app.powerbi.com/Redirect?action=InstallApp&appId=66667...9cccc0000&packageKey=b2df4b...dLpHIUnum2pr6k&ownerId=aaaa...22222&buildVersion=5 ``` -------------------------------- ### List Power BI Refresh Operations (JSON Response Example) Source: https://learn.microsoft.com/pt-pt/power-bi/connect-data/asynchronous-refresh_source=recommendations This JSON structure illustrates the response received when using the GET verb on the /refreshes collection to list historical, current, and pending refresh operations. It includes details like request ID, refresh type, start and end times, and status. ```json [ { "requestId": "ddddeeee-3333-ffff-4444-aaaa5555bbbb", "refreshType": "ViaEnhancedApi", "startTime": "2020-12-07T02:06:57.1838734Z", "endTime": "2020-12-07T02:07:00.4929675Z", "status": "Completed", "extendedStatus": "Completed" }, { "requestId": "474fc5a0-3d69-4c5d-adb4-8a846fa5580b", "startTime": "2020-12-07T01:05:54.157324Z", "refreshType": "ViaEnhancedApi", "status": "Unknown" } { "requestId": "85a82498-2209-428c-b273-f87b3a1eb905", "refreshType": "ViaEnhancedApi", "startTime": "2020-12-07T01:05:54.157324Z", "status": "Unknown", "extendedStatus": "NotStarted" } ] ``` -------------------------------- ### POST /CreateInstallTicket Source: https://learn.microsoft.com/pt-pt/power-bi/connect-data/template-apps-auto-install_source=recommendations Utiliza as APIs REST do Power BI para criar um tíquete de instalação que contém a configuração de parâmetro específica do usuário. ```APIDOC ## POST /CreateInstallTicket ### Description Creates an install ticket with user-specific parameter configuration for a Power BI template app installation. ### Method POST ### Endpoint /CreateInstallTicket ### Parameters #### Query Parameters - **installTicket** (string) - Required - The install ticket containing user-specific parameter configuration. ### Request Example ```json { "installTicket": "user_specific_configuration_details" } ``` ### Response #### Success Response (200) - **installationUrl** (string) - The URL to redirect the user to for installing the template app. #### Response Example ```json { "installationUrl": "https://app.powerbi.com/redirect/install?ticket=user_specific_configuration_details" } ``` ``` -------------------------------- ### Create a Power BI Circular Card Visual Example Source: https://learn.microsoft.com/pt-pt/power-bi/developer/visuals/create-react-visual This tutorial guides you through developing a Power BI visual using the circular card as an example. It details the process of creating custom visuals for Power BI. ```typescript import { IVisual, VisualUpdateOptions } from "powerbi-visuals-api"; export class CircularCardVisual implements IVisual { private target: HTMLElement; private textValue: SVGTextElement; constructor(options: VisualConstructorOptions) { this.target = options.element; this.textValue = document.createElementNS("http://www.w3.org/2000/svg", "text") as SVGTextElement; this.textValue.setAttribute("class", "card-text"); this.target.appendChild(this.textValue); } public update(options: VisualUpdateOptions) { const dataView = options.dataViews[0]; if (!dataView || !dataView.categorical || !dataView.categorical.values || dataView.categorical.values.length === 0) { return; } const value = dataView.categorical.values[0].values[0]; const radius = Math.min(options.viewport.width, options.viewport.height) / 2; // Clear previous content while (this.target.firstChild) { this.target.removeChild(this.target.firstChild); } // Create SVG element const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg"); svg.setAttribute("width", options.viewport.width.toString()); svg.setAttribute("height", options.viewport.height.toString()); // Draw a circle const circle = document.createElementNS("http://www.w3.org/2000/svg", "circle"); circle.setAttribute("cx", radius.toString()); circle.setAttribute("cy", radius.toString()); circle.setAttribute("r", (radius - 10).toString()); circle.setAttribute("fill", "lightblue"); circle.setAttribute("stroke", "blue"); circle.setAttribute("stroke-width", "2"); svg.appendChild(circle); // Add text value this.textValue = document.createElementNS("http://www.w3.org/2000/svg", "text") as SVGTextElement; this.textValue.setAttribute("x", radius.toString()); this.textValue.setAttribute("y", radius.toString()); this.textValue.setAttribute("text-anchor", "middle"); this.textValue.setAttribute("dy", ".35em"); this.textValue.setAttribute("font-size", "20"); this.textValue.setAttribute("fill", "black"); this.textValue.textContent = value.toString(); svg.appendChild(this.textValue); this.target.appendChild(svg); } } ``` -------------------------------- ### Power BI Deep Link: Open Dashboard within App Example Source: https://learn.microsoft.com/pt-pt/power-bi/consumer/mobile/mobile-apps-deep-link-specific-location This example demonstrates how to create a deep link to open a specific dashboard that is part of a Power BI application. It requires the 'action' set to 'OpenDashboard', the 'appId', and the 'dashboardObjectId'. ```url https://app.powerbi.com/Redirect?action=OpenDashboard&appId=<>&dashboardObjectId=****< &ctid=> ``` -------------------------------- ### Download do arquivo .pbix do repositório GitHub Source: https://learn.microsoft.com/pt-pt/power-bi/create-reports/sample-competitive-marketing-analysis_source=recommendations Guia para baixar o arquivo .pbix do exemplo de Análise de Marketing Competitivo a partir do repositório do GitHub. Este arquivo é usado com o Power BI Desktop. ```text 1. Abra o repositório de amostras do GitHub no arquivo .pbix de exemplo da Análise de Marketing Competitiva. 2. Selecione Download no canto superior direito. Ele é baixado automaticamente para sua pasta de Downloads. ``` -------------------------------- ### Power BI Deep Link: Open App Example Source: https://learn.microsoft.com/pt-pt/power-bi/consumer/mobile/mobile-apps-deep-link-specific-location An example of a Power BI deep link specifically designed to open a Power BI application. This link requires the 'action' parameter set to 'OpenApp' and the 'appId' for the target application. ```url https://app.powerbi.com/Redirect?action=OpenApp&appId=****&ctid=**** ``` -------------------------------- ### Criar tíquete de instalação do aplicativo de modelo com .NET SDK Source: https://learn.microsoft.com/pt-pt/power-bi/connect-data/template-apps-auto-install_source=recommendations Este snippet demonstra como criar um tíquete de instalação para um aplicativo de modelo usando o SDK do .NET. Ele constrói um objeto de solicitação e o envia para a API REST. As dependências incluem o namespace System.Guid e a classe TemplateAppConfigurationRequest. A entrada é um objeto de solicitação que contém um OwnerTenantId e uma configuração, e a saída é um objeto InstallTicket. ```csharp InstallTicket ticketResponse = await client.TemplateApps.CreateInstallTicketAsync(request); ``` -------------------------------- ### Power BI Deep Link: Open Report in Different Workspace Example Source: https://learn.microsoft.com/pt-pt/power-bi/consumer/mobile/mobile-apps-deep-link-specific-location An example URL for opening a Power BI report that resides in a workspace other than 'My Workspace'. This deep link uses 'Action=OpenReport', 'reportObjectId', and 'groupObjectId' to specify the target report and its workspace. ```url https://app.powerbi.com/Redirect?Action=OpenReport&reportObjectId=<>&groupObjectId=****< &reportPage=> ``` -------------------------------- ### Teste de Função Localmente para Instalação Automatizada do Power BI Source: https://learn.microsoft.com/pt-pt/power-bi/connect-data/template-apps-auto-install-tutorial_source=recommendations Demonstra como testar uma função do Azure localmente para a instalação automatizada de aplicativos do Power BI. Envolve o envio de solicitações POST para um endpoint de API de função com um corpo JSON contendo pares chave-valor de parâmetros. ```JSON { "parameterName": "parameterValue" } ``` -------------------------------- ### Get Touch Start Event Name using touchStartEventName in TypeScript Source: https://learn.microsoft.com/pt-pt/power-bi/developer/visuals/utils-tooltip This function returns the appropriate event name for detecting the start of a touch interaction. This is useful for handling touch events across different devices and browsers, ensuring consistent behavior for mobile development. ```TypeScript function touchStartEventName(): string ``` -------------------------------- ### Gerenciar instaladores de gateway com PowerShell Source: https://learn.microsoft.com/pt-pt/power-bi/guidance/powerbi-implementation-planning-data-gateways_source=recommendations Use cmdlets do PowerShell para gerenciar programaticamente quem pode instalar gateways pessoais e de modo padrão. Isso envolve definir a política de locatário do gateway para controlar as permissões de instalação. ```powershell Set-DataGatewayTenantPolicy -TenantPolicy "{ \"InstallerPolicy\": \"Restricted\", \"AllowedInstallerUsers\": [ \"user1@example.com\", \"user2@example.com\" ] }" ``` -------------------------------- ### Power BI REST API: Dataset User Management (GET) Source: https://learn.microsoft.com/pt-pt/power-bi/developer/embedded/datasets-permissions Provides an example of using GET APIs to retrieve a list of entities that have access to a specific Power BI dataset. This helps in auditing and understanding current access configurations. ```json { "value": [ { "displayName": "User Name", "emailAddress": "user@example.com", "principalType": "User", "accessRight": "Read" } ] } ``` -------------------------------- ### Criar tíquete de instalação do aplicativo de modelo com SDK do .NET do Power BI Source: https://learn.microsoft.com/pt-pt/power-bi/connect-data/template-apps-auto-install Este snippet demonstra como usar o SDK .NET do Power BI para criar um tíquete de instalação para um aplicativo de modelo. Ele constrói uma solicitação com detalhes de instalação, incluindo ID do aplicativo, chave do pacote e configuração. A resposta contém o tíquete de instalação necessário para redirecionar os usuários. ```csharp using Microsoft.PowerBI.Api.V2; using Microsoft.PowerBI.Api.V2.Models; // Create Install Ticket Request. InstallTicket ticketResponse = null; var request = new CreateInstallTicketRequest() { InstallDetails = new List() { new TemplateAppInstallDetails() { AppId = Guid.Parse(AppId), PackageKey = PackageKey, OwnerTenantId = Guid.Parse(OwnerId), Config = new TemplateAppConfigurationRequest() { Configuration = Parameters .GroupBy(p => p.Name) .ToDictionary(k => k.Key, k => k.Select(p => p.Value).Single()) } } } }; // Issue the request to the REST API using .NET SDK. InstallTicket ticketResponse = await client.TemplateApps.CreateInstallTicketAsync(request); ``` -------------------------------- ### Power BI PowerShell Tutorial Source: https://learn.microsoft.com/pt-pt/power-bi/developer/embedded/dev-camp-links_tabs=app-owns-data-tutorials%2Capp-owns-data-examples This repository contains student files for a Power BI PowerShell tutorial from Power BI Dev Camp. It likely includes scripts and examples for automating Power BI tasks using PowerShell cmdlets. ```powershell # This is a placeholder for PowerShell code related to the Power BI PowerShell tutorial. # Actual scripts would involve cmdlets for managing datasets, reports, dashboards, etc. # Example: Connect to Power BI Service # Import-Module MicrosoftPowerBIMgmt # Connect-PowerBIServiceAccount # Example: Get a list of reports in a workspace # Get-PowerBIReport -WorkspaceId "your-workspace-id" # Example: Get a list of datasets # Get-PowerBIDataset # Example: Refresh a dataset # Start-PowerBIDatasetRefresh -WorkspaceId "your-workspace-id" -DatasetId "your-dataset-id" Write-Host "Power BI PowerShell examples would go here." ``` -------------------------------- ### Baixar Arquivo PBIX de Exemplo do Power BI Source: https://learn.microsoft.com/pt-pt/power-bi/create-reports/sample-employee-hiring-history_source=recommendations Instruções para baixar o arquivo .pbix do exemplo de Contratação e Histórico de Funcionários do repositório GitHub do Power BI. Este arquivo é projetado para ser usado com o Power BI Desktop. ```markdown 1. Abra o repositório de amostras do GitHub no [arquivo .pbix de exemplo de contratação e histórico de funcionários](https://github.com/microsoft/powerbi-desktop-samples/blob/main/new-power-bi-service-samples/Employee%20Hiring%20and%20History.pbix). 2. Selecione **Download** no canto superior direito. Ele é baixado automaticamente para sua **pasta de Downloads** . ``` -------------------------------- ### Formatting Settings Card Implementation Example Source: https://learn.microsoft.com/pt-pt/power-bi/developer/visuals/formatting-model-card_tabs=compositeCard This example demonstrates a basic structure for implementing a formatting settings card. It assumes the necessary prerequisites, including updated powerbi-visuals-api and installed powerbi-visuals-utils-formattingmodel, are met. The code initializes the formatting settings service and the formatting settings model class. ```TypeScript import { FormattingSettingsService, FormattingSettingsModel } from "powerbi-visuals-utils-formattingmodel"; // Initialize the formatting settings service const formattingSettingsService = new FormattingSettingsService(); // Initialize the formatting settings model class const formattingSettingsModel = new FormattingSettingsModel(); // Further implementation details would follow... ``` -------------------------------- ### Get End of Previous Month in Power BI Source: https://learn.microsoft.com/pt-pt/power-bi/paginated-reports/expressions/report-builder-expression-examples The DateSerial function returns a Date value representing a specified year, month, and day, with the time information set to midnight. This example displays the end date of the previous month, based on the current month. It uses Now() to get the current date and then manipulates it. ```DAX =DateSerial(Year(Now()), Month(Now()), "1").AddDays(-1) ``` -------------------------------- ### Instalar PowerBI-visuals-utils-testutils com npm Source: https://learn.microsoft.com/pt-pt/power-bi/developer/visuals/utils-test_source=recommendations Instala o pacote powerbi-visuals-utils-testutils e o adiciona como uma dependência ao seu package.json. Este comando é executado no diretório raiz do seu projeto de visual do Power BI. ```bash npm install powerbi-visuals-utils-testutils --save ``` -------------------------------- ### Redirecionar usuários para instalação do aplicativo Power BI com formulário HTML Source: https://learn.microsoft.com/pt-pt/power-bi/connect-data/template-apps-auto-install Este snippet mostra como usar um formulário HTML para redirecionar automaticamente um usuário para a URL de instalação do Power BI com um tíquete de instalação fornecido. O formulário é configurado para enviar uma solicitação POST com o tíquete oculto após o carregamento da página, facilitando a experiência de instalação do usuário. ```html
``` -------------------------------- ### Power BI Range Formatting with #FROMVALUE and #TOVALUE Source: https://learn.microsoft.com/pt-pt/power-bi/paginated-reports/report-design/visualizations/vary-polygon-line-point-display-by-rules-analytical-data_source=recommendations Displays the start and end numeric values of a range. Uses N0 format to show numbers without decimal places. ```Power BI #FROMVALUE{N0} - #TOVALUE{N0} ``` -------------------------------- ### Configurar Startup.cs para Autenticação com Microsoft.Identity.Web - C# Source: https://learn.microsoft.com/pt-pt/power-bi/developer/embedded/embed-organization-app Este trecho de código C# demonstra como configurar `Startup.cs` para autenticação usando `Microsoft.Identity.Web`. Ele configura o cache de tokens em memória e registra a classe `PowerBiServiceApi` para injeção de dependência, permitindo a aquisição de tokens de acesso para chamar APIs downstream. ```csharp using Microsoft.Identity.Web; using Microsoft.Identity.Web.TokenCacheProviders; using Microsoft.Identity.Web.TokenCacheProviders.InMemory; using Microsoft.Identity.Web.UI; using UserOwnsData.Services; namespace UserOwnsData { public class Startup { public Startup (IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices (IServiceCollection services) { services .AddMicrosoftIdentityWebAppAuthentication(Configuration) .EnableTokenAcquisitionToCallDownstreamApi(PowerBiServiceApi.RequiredScopes) .AddInMemoryTokenCaches(); services.AddScoped (typeof (PowerBiServiceApi)); var mvcBuilder = services.AddControllersWithViews (options => { var policy = new AuthorizationPolicyBuilder() .RequireAuthenticatedUser() .Build(); options.Filters.Add (new AuthorizeFilter (policy)); }); mvcBuilder.AddMicrosoftIdentityUI(); services.AddRazorPages(); } } } ``` -------------------------------- ### Execute Project in Visual Studio Code Source: https://learn.microsoft.com/pt-pt/power-bi/developer/embedded/embed-sample-for-customers_source=recommendations&tabs=net-core Instructions for executing the Power BI integration project when using Visual Studio Code. This involves navigating the 'Run' menu to start debugging. ```Text 1. Open the project folder in Visual Studio Code. 2. Ensure the configuration files are set up correctly. 3. Go to the 'Run' menu. 4. Select 'Start Debugging'. ``` -------------------------------- ### Criar tíquete de instalação para aplicativo de modelo do Power BI Source: https://learn.microsoft.com/pt-pt/power-bi/connect-data/template-apps-auto-install_source=recommendations Este snippet mostra como usar a API REST CreateInstallTicket para criar um tíquete de instalação para um aplicativo de modelo do Power BI. Isso é usado ao redirecionar usuários para o Power BI para instalação e configuração do aplicativo. As entradas incluem AppId e PackageKey. ```csharp using Microsoft.PowerBI.Api.V2; using Microsoft.PowerBI.Api.V2.Models; // Create Install Ticket Request. InstallTicket ticketResponse = null; var request = new CreateInstallTicketRequest() { InstallDetails = new List() { new TemplateAppInstallDetails() { AppId = Guid.Parse(AppId), PackageKey = PackageKey, ``` -------------------------------- ### Export Report with Specific Page Range Source: https://learn.microsoft.com/pt-pt/power-bi/developer/embedded/export-paginated-report_source=recommendations This example demonstrates how to export a paginated report to an image format, specifying a start and end page. ```APIDOC ## POST /api/v1.0/myorg/groups/{groupId}/reports/{reportId}/ExportToFile ### Description Exports a paginated report to a specified file format, with options to define page ranges. ### Method POST ### Endpoint `/api/v1.0/myorg/groups/{groupId}/reports/{reportId}/ExportToFile` ### Parameters #### Query Parameters - **groupId** (string) - Required - The ID of the group (workspace) containing the report. - **reportId** (string) - Required - The ID of the report to export. #### Request Body - **format** (string) - Required - The desired output format (e.g., "IMAGE", "PDF"). - **paginatedReportConfiguration.formatSettings.OutputFormat** (string) - Optional - The specific image output format (e.g., "JPEG"). - **paginatedReportConfiguration.formatSettings.StartPage** (integer) - Optional - The starting page number for the export. - **paginatedReportConfiguration.formatSettings.EndPage** (integer) - Optional - The ending page number for the export. ### Request Example ```json { "format": "IMAGE", "paginatedReportConfiguration":{ "formatSettings":{ "OutputFormat": "JPEG", "StartPage": "3", "EndPage": "3" } } } ``` ### Response #### Success Response (200) - **status** (string) - The status of the export operation. - **resultUrl** (string) - A URL to access the exported file (if export is completed). #### Response Example ```json { "status": "Queued", "resultUrl": null } ``` ``` -------------------------------- ### Get Centroid of a Rectangle in TypeScript Source: https://learn.microsoft.com/pt-pt/power-bi/developer/visuals/utils-svg_source=recommendations This TypeScript function, getCentroid, calculates and returns the central point of a given rectangle. It requires an IRect object as input and returns an IPoint object. The example demonstrates its usage with a Rect object from the powerbi-visuals-utils-svgutils library. ```typescript function getCentroid(rect: IRect): IPoint; import { shapes } from "powerbi-visuals-utils-svgutils"; import Rect = shapes.Rect; // ... Rect.getCentroid({ left: 0, top: 0, width: 100, height: 100 }); /* returns: { x: 50, y: 50 }*/ ``` -------------------------------- ### Install Windows ADK and Performance Tools Source: https://learn.microsoft.com/pt-pt/power-bi/connect-data/desktop-error-launching-desktop_source=recommendations This snippet outlines the steps to download and install the Windows Assessment and Deployment Kit (ADK), specifically selecting the Windows Performance Toolkit. This toolkit is necessary for recording system performance to diagnose issues. ```powershell # Download the Windows ADK # Example: Invoke-WebRequest -Uri "https://download.microsoft.com/download/A/7/4/A74377E5-6064-4634-B1C8-5F2E6AF0A5A9/adksetup.exe" -OutFile "adksetup.exe" # Run adksetup.exe and select "Install the Windows Assessment and Development Kit on this computer" # During feature selection, choose "Windows Performance Toolkit" and proceed with installation. ``` -------------------------------- ### Exemplo de URL de Instalação do Power BI Source: https://learn.microsoft.com/pt-pt/power-bi/connect-data/template-apps-auto-install-tutorial Este é um exemplo de URL de instalação do Power BI que contém os parâmetros appId, packageKey e ownerId necessários para a configuração automatizada. ```plaintext https://app.powerbi.com/Redirect?action=InstallApp&appId=66667...9cccc0000&packageKey=b2df4b...dLpHIUnum2pr6k&ownerId=aaaa...22222&buildVersion=5 ``` -------------------------------- ### Get Activity Events API Source: https://learn.microsoft.com/pt-pt/power-bi/guidance/powerbi-implementation-planning-auditing-monitoring-tenant-level-auditing This endpoint allows you to programmatically retrieve user activities related to the Power BI service. It's recommended as a starting point for organizations planning to extract user activities. ```APIDOC ## GET /v1.0/myorg/activityevents ### Description Retrieves a list of user activities from the Power BI activity log. ### Method GET ### Endpoint /v1.0/myorg/activityevents ### Parameters #### Query Parameters - **startTime** (datetime) - Optional - The start of the time range to query for activity events. - **endTime** (datetime) - Optional - The end of the time range to query for activity events. - **datasetId** (string) - Optional - Filters activities to a specific dataset. - **reportId** (string) - Optional - Filters activities to a specific report. - **workspaceId** (string) - Optional - Filters activities to a specific workspace (referred to as 'folders' in audit logs). ### Request Example ```json { "startTime": "2023-10-26T10:00:00Z", "endTime": "2023-10-27T10:00:00Z" } ``` ### Response #### Success Response (200) - **activityEvents** (array) - A list of activity event objects. - **Id** (string) - Unique identifier for the activity event. - **RecordType** (string) - The type of activity recorded. - **UserKey** (string) - Identifier for the user who performed the activity. - **UserType** (string) - The type of user (e.g., 'User', 'Admin'). - **Operation** (string) - The specific operation performed. - **OrganizationId** (string) - The identifier of the organization. - **CreationTime** (datetime) - The timestamp when the activity occurred. - **WorkSpaceId** (string) - The ID of the workspace where the activity occurred. - **WorkSpaceName** (string) - The name of the workspace where the activity occurred. - **ReportId** (string) - The ID of the report related to the activity. - **ReportName** (string) - The name of the report related to the activity. - **DatasetId** (string) - The ID of the dataset related to the activity. - **DatasetName** (string) - The name of the dataset related to the activity. - **ConsumptionMethod** (string) - The method used for consumption (e.g., 'View', 'Edit'). - **UserAgent** (string) - The user agent string of the client that performed the activity. - **IpAddress** (string) - The IP address from which the activity was performed. - **ClientIP** (string) - The client IP address. - **UserPrincipalName** (string) - The User Principal Name (UPN) of the user. - **AppId** (string) - The application ID used for the activity. - **AppName** (string) - The application name used for the activity. - **ServiceType** (string) - The type of service the activity relates to (e.g., 'PowerBI'). #### Response Example ```json { "activityEvents": [ { "Id": "a1b2c3d4-e5f6-7890-1234-567890abcdef", "RecordType": 15, "UserKey": "10032000A668B359", "UserType": "User", "Operation": "ViewReport", "OrganizationId": "7f23d92d-8a27-4753-8b06-6f93169057a8", "CreationTime": "2023-10-26T11:30:00Z", "WorkSpaceId": "a1a1a1a1-b2b2-c3c3-d4d4-e5e5e5e5e5e5", "WorkSpaceName": "Sales Dashboard", "ReportId": "f1f1f1f1-f2f2-f3f3-f4f4-f5f5f5f5f5f5", "ReportName": "Quarterly Sales Report", "DatasetId": "g1g1g1g1-g2g2-g3g3-g4g4-g5g5g5g5g5g5", "DatasetName": "Sales Data", "ConsumptionMethod": "View", "UserAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36", "IpAddress": "192.168.1.100", "ClientIP": "192.168.1.100", "UserPrincipalName": "user@example.com", "AppId": "", "AppName": "", "ServiceType": "PowerBI" } ] } ``` ``` -------------------------------- ### Apply Advanced Date Range Filter in Power BI Source: https://learn.microsoft.com/pt-pt/power-bi/developer/visuals/bookmarks-support Applies an advanced filter to the data based on a start and end date. This example uses the 'powerbi-models' library to create an AdvancedFilter and applies it using the host.applyJsonFilter method. ```TypeScript import { AdvancedFilter } from "powerbi-models"; const filter: IAdvancedFilter = new AdvancedFilter( target, "And", { operator: "GreaterThanOrEqual", value: startDate ? startDate.toJSON() : null }, { operator: "LessThanOrEqual", value: endDate ? endDate.toJSON() : null }); this.host.applyJsonFilter( filter, "general", "filter", (startDate && endDate) ? FilterAction.merge : FilterAction.remove ); ``` -------------------------------- ### Gerar formulário de redirecionamento de instalação de aplicativo de modelo (C#) Source: https://learn.microsoft.com/pt-pt/power-bi/connect-data/template-apps-auto-install_source=recommendations Este snippet C# gera dinamicamente um formulário HTML de autoenvio para redirecionar usuários para o Power BI com um tíquete de instalação. A função `RedirectWithData` constrói o HTML necessário, incluindo a ação do formulário e o campo de tíquete oculto. A entrada são os URLs e o tíquete, e a saída é uma string HTML que representa o formulário. ```csharp public static string RedirectWithData(string url, string ticket) { StringBuilder s = new StringBuilder(); s.Append(""); s.AppendFormat(""); s.AppendFormat("
", url); s.AppendFormat("", ticket); s.Append("
"); return s.ToString(); } ``` -------------------------------- ### Constructor Method for Power BI Visuals (TypeScript) Source: https://learn.microsoft.com/pt-pt/power-bi/developer/visuals/visual-api The `constructor` method is the entry point for initializing a Power BI custom visual. It is called once when the visual is first instantiated and is used for any setup operations that need to occur before the visual starts interacting with data or the user. ```TypeScript constructor(options: VisualConstructorOptions) ``` -------------------------------- ### Exemplo de Solicitação POST para Instalação de Função do Azure Source: https://learn.microsoft.com/pt-pt/power-bi/connect-data/template-apps-auto-install-tutorial Este exemplo descreve o formato de uma solicitação POST para uma função do Azure, especificamente o endpoint /api/install. O corpo da solicitação deve ser um objeto JSON contendo pares chave-valor que representam os parâmetros a serem definidos no aplicativo do modelo do Power BI. ```json { "parameterName1": "desiredValue1", "parameterName2": "desiredValue2" } ``` -------------------------------- ### GET /v1.0/myorg/admin/activityevents Source: https://learn.microsoft.com/pt-pt/power-bi/enterprise/service-admin-auditing_source=recommendations Retrieves Power BI activity events for a specified date range. The start and end dates must be within the same day. For large datasets, a continuation token is returned to fetch subsequent batches of data. ```APIDOC ## GET /v1.0/myorg/admin/activityevents ### Description Retrieves Power BI activity events for a specified date range. The start and end dates must be within the same day. For large datasets, a continuation token is returned to fetch subsequent batches of data. ### Method GET ### Endpoint `https://api.powerbi.com/v1.0/myorg/admin/activityevents` ### Parameters #### Query Parameters - **startDateTime** (string) - Required - The start date and time for the activity events in UTC format (e.g., '2019-08-31T00:00:00'). - **endDateTime** (string) - Required - The end date and time for the activity events in UTC format (e.g., '2019-08-31T23:59:59'). - **continuationToken** (string) - Optional - A token received from a previous request to retrieve the next batch of activity events. ### Request Example ```http GET https://api.powerbi.com/v1.0/myorg/admin/activityevents?startDateTime='2019-08-31T00:00:00'&endDateTime='2019-08-31T23:59:59' ``` ### Response #### Success Response (200) - **activityEventEntities** (array) - A list of activity event objects. - **continuationUri** (string) - A URI to fetch the next set of results, if available. - **continuationToken** (string) - A token to use in subsequent requests to get the next batch of entries, if available. - **lastResultSet** (boolean) - Indicates if this is the last set of results. #### Response Example ```json { "activityEventEntities": [ // ... activity event objects ... ], "continuationUri": "https://wabi-staging-us-east-redirect.analysis.windows.net/v1.0/myorg/admin/activityevents?continuationToken='LDIwMjAtMDgtMTNUMDc6NTU6MDBaLDIwMjAtMDgtMTNUMDk6MDA6MDBaLDEsLA%3D%3D'", "continuationToken": "LDIwMjAtMDgtMTNUMDc6NTU6MDBaLDIwMjAtMDgtMTNUMDk6MDA6MDBaLDEsLA%3D%3D", "lastResultSet": false } ``` ``` -------------------------------- ### Inicializar host.launchUrl() em Construtor Visual - TypeScript Source: https://learn.microsoft.com/pt-pt/power-bi/developer/visuals/launch-url Importa a interface `IVisualHost` e salva o link para o objeto `host` no construtor do visual. Esta é a configuração inicial necessária para usar a funcionalidade `host.launchUrl()` em visuais do Power BI. ```TypeScript import powerbi from "powerbi-visuals-api"; import IVisualHost = powerbi.extensibility.visual.IVisualHost; export class Visual implements IVisual { private host: IVisualHost; // ... constructor(options: VisualConstructorOptions) { // ... this.host = options.host; // ... } // ... } ``` -------------------------------- ### Instalar Bootstrap com npm Source: https://learn.microsoft.com/pt-pt/power-bi/developer/visuals/adding-external-libraries_source=recommendations Este comando instala o pacote Bootstrap e o salva como uma dependência do projeto. É um passo essencial para começar a usar os estilos CSS do Bootstrap. ```powershell npm install bootstrap --save ``` -------------------------------- ### Basic Rendering Events in Power BI Visuals Source: https://learn.microsoft.com/pt-pt/power-bi/developer/visuals/event-service_source=recommendations This example illustrates the basic usage of rendering events in a Power BI visual's update method. It shows calls to renderingStarted and renderingFinished, which are essential for signaling the start and successful completion of the visual rendering process. ```typescript export class Visual implements IVisual { ... private events: IVisualEventService; ... constructor(options: VisualConstructorOptions) { ... this.events = options.host.eventService; ... } public update(options: VisualUpdateOptions) { this.events.renderingStarted(options); ... this.events.renderingFinished(options); } ``` -------------------------------- ### Instalar Power BI Visuals ChartUtils Source: https://learn.microsoft.com/pt-pt/power-bi/developer/visuals/utils-chart_source=recommendations Comando para instalar o pacote powerbi-visuals-utils-chartutils usando npm. Deve ser executado no diretório do visual atual. ```bash npm install powerbi-visuals-utils-chartutils --save ``` -------------------------------- ### Power BI Desktop Installation Properties Source: https://learn.microsoft.com/pt-pt/power-bi/fundamentals/desktop-get-the-desktop_source=recommendations These properties can be used with Power BI Desktop installation commands to customize the installation. They allow control over EULA acceptance, customer experience programs, desktop shortcuts, installation location, language, and update notifications. ```command-line msiexec.exe /i "Path\To\PowerBI.msi" ACCEPT_EULA=1 msiexec.exe /i "Path\To\PowerBI.msi" ENABLECXP=1 msiexec.exe /i "Path\To\PowerBI.msi" INSTALLDESKTOPSHORTCUT=1 msiexec.exe /i "Path\To\PowerBI.msi" INSTALLLOCATION="C:\Program Files\Power BI Desktop" msiexec.exe /i "Path\To\PowerBI.msi" LANGUAGE=en-US msiexec.exe /i "Path\To\PowerBI.msi" DISABLE_UPDATE_NOTIFICATION=1 ```