### Install required packages for dialog example Source: https://learn.microsoft.com/en-us/power-bi/developer/visuals/create-display-dialog-box Command to install the packages required by the example dialog box implementation. ```bash npm i react-dom react react-datepicker ``` -------------------------------- ### Install Python dependencies for DAX query quickstart Source: https://learn.microsoft.com/en-us/power-bi/developer/execute-dax-queries-arrow/get-started Install the required Python packages (msal, pyarrow, pandas) for the quickstart. Requires Python 3.10 or later. ```bash pip install msal pyarrow pandas ``` -------------------------------- ### Install .NET dependencies for DAX query quickstart Source: https://learn.microsoft.com/en-us/power-bi/developer/execute-dax-queries-arrow/get-started Add the Microsoft.Identity.Client and Apache.Arrow NuGet packages. Requires .NET 8 SDK or later. ```bash dotnet add package Microsoft.Identity.Client dotnet add package Apache.Arrow ``` -------------------------------- ### Install D3 JavaScript library Source: https://learn.microsoft.com/en-us/power-bi/developer/visuals/create-bar-chart Run this command in PowerShell to install the D3 library if it wasn't installed during environment setup. This is a prerequisite for the tutorial. ```powershell npm i d3@latest --save ``` -------------------------------- ### Install MSAL.PS module for PowerShell Source: https://learn.microsoft.com/en-us/power-bi/developer/execute-dax-queries-arrow/get-started Install the MSAL.PS PowerShell module for authentication. Requires PowerShell 7.4 or later. ```powershell Install-Module -Name MSAL.PS -Scope CurrentUser ``` -------------------------------- ### touchStartEventName function signature Source: https://learn.microsoft.com/en-us/power-bi/developer/visuals/utils-tooltip Returns a touch start event name. ```typescript function touchStartEventName(): string ``` -------------------------------- ### Start the visual development server with pbiviz start Source: https://learn.microsoft.com/en-us/power-bi/developer/visuals/create-r-based-power-bi-desktop Run this command from the newly created rVisualSample directory to start the development server for the visual. ```bash pbiviz start ``` -------------------------------- ### Run the sample app with npm run start Source: https://learn.microsoft.com/en-us/power-bi/developer/embedded/embed-sample-for-your-organization Starts the application. On first sign-in, you'll be prompted to allow Microsoft Entra permissions for the app. ```bash npm run start ``` -------------------------------- ### hide usage example Source: https://learn.microsoft.com/en-us/power-bi/developer/visuals/utils-tooltip Example of hiding the tooltip. options are from the VisualConstructorOptions. ```typescript import {createTooltipServiceWrapper} from "powerbi-visuals-utils-tooltiputils"; let tooltipServiceWrapper = createTooltipServiceWrapper(options.host.tooltipService, options.element); // options are from the VisualConstructorOptions. tooltipServiceWrapper.hide(); ``` -------------------------------- ### pbiviz.json supportUrl and gitHubUrl example Source: https://learn.microsoft.com/en-us/power-bi/developer/visuals/package-visual Example values for the supportUrl and gitHubUrl fields in the pbiviz.json file. These URLs let users get support and view the visual's GitHub project. ```json { "supportUrl": "https://community.powerbi.com", "gitHubUrl": "https://github.com/microsoft/PowerBI-visuals-circlecard" } ``` -------------------------------- ### createTooltipServiceWrapper usage example Source: https://learn.microsoft.com/en-us/power-bi/developer/visuals/utils-tooltip Example of creating a tooltip service wrapper inside a custom visual constructor. Returns an instance of ITooltipServiceWrapper. ```typescript import { createTooltipServiceWrapper } from "powerbi-visuals-utils-tooltiputils"; export class YourVisual implements IVisual { // implementation of IVisual. constructor(options: VisualConstructorOptions) { createTooltipServiceWrapper( options.host.tooltipService, options.element); // returns: an instance of ITooltipServiceWrapper. } } ``` -------------------------------- ### Check openssl and certutil installation Source: https://learn.microsoft.com/en-us/power-bi/developer/visuals/create-ssl-certificate Run these commands to verify that openssl and certutil are installed before creating certificates. If they are not installed, install the openssl and libnss3 utilities. ```bash which openssl which certutil ``` -------------------------------- ### touchStartEventName Source: https://learn.microsoft.com/en-us/power-bi/developer/visuals/utils-tooltip Returns a touch start event name. This function is part of the touch events utilities. ```APIDOC ## touchStartEventName ### Description Returns a touch start event name. ### Function Signature ```typescript function touchStartEventName(): string ``` ### Parameters None. ### Returns - **string** - The touch start event name. ``` -------------------------------- ### End-to-end example (ExportPaginatedReport) Source: https://learn.microsoft.com/en-us/power-bi/developer/embedded/export-paginated-report Combines the three steps: sending the export request, polling, and getting the file. Returns the ExportedFile if successful, or null on failure. Includes error handling that rethrows exceptions. ```csharp private async Task ExportPaginatedReport( Guid reportId, Guid groupId, int pollingtimeOutInMinutes, CancellationToken token) { try { var exportId = await PostExportRequest(reportId, groupId); var export = await PollExportRequest(reportId, groupId, exportId, pollingtimeOutInMinutes, token); if (export == null || export.Status != ExportState.Succeeded) { // Error, failure in exporting the report return null; } return await GetExportedFile(reportId, groupId, export); } catch { // Error handling throw; } } ``` -------------------------------- ### Install pbiviz with npm Source: https://learn.microsoft.com/en-us/power-bi/developer/visuals/environment-setup Run this command in Windows PowerShell to install the latest version of the pbiviz package globally. Warnings may appear but should not prevent installation. ```powershell npm i -g powerbi-visuals-tools@latest ``` -------------------------------- ### addTooltip usage example Source: https://learn.microsoft.com/en-us/power-bi/developer/visuals/utils-tooltip Example of adding tooltips to a D3 selection. The tooltipService is from the IVisualHost. A tooltip appears on mouseover. ```typescript import { createTooltipServiceWrapper, TooltipEventArgs, ITooltipServiceWrapper, TooltipEnabledDataPoint } from "powerbi-visuals-utils-tooltiputils"; let bodyElement = d3.select("body"); let element = bodyElement .append("div") .style({ "background-color": "green", "width": "150px", "height": "150px" }) .classed("visual", true) .data([{ tooltipInfo: [{ displayName: "Power BI", value: 2016 }] }]); let tooltipServiceWrapper: ITooltipServiceWrapper = createTooltipServiceWrapper(tooltipService, bodyElement.get(0)); // tooltipService is from the IVisualHost. tooltipServiceWrapper.addTooltip(element, (eventArgs: TooltipEventArgs) => { return eventArgs.data.tooltipInfo; }); // You will see a tooltip if you mouseover the element. ``` -------------------------------- ### Run the service with dotnet run Source: https://learn.microsoft.com/en-us/power-bi/developer/execute-dax-queries-arrow/dotnet-mid-tier-service Start the service using the project name Microsoft.Samples.XMLA.ExecuteQueries. ```bash dotnet run --project Microsoft.Samples.XMLA.ExecuteQueries ``` -------------------------------- ### getSeriesName usage example Source: https://learn.microsoft.com/en-us/power-bi/developer/visuals/utils-dataview Example of using converterHelper.getSeriesName to get the series name from metadata. Returns 'Power BI'. ```typescript import powerbi from "powerbi-visuals-api"; import DataViewMetadataColumn = powerbi.DataViewMetadataColumn; import { converterHelper } from "powerbi-visuals-utils-dataviewutils"; // This object is actually a part of the dataView object. let metadata: DataViewMetadataColumn = { displayName: "Microsoft", roles: { "power": true, "bi": true }, groupName: "Power BI" }; converterHelper.getSeriesName(metadata); // returns: Power BI ``` -------------------------------- ### Clone and build the sample repository Source: https://learn.microsoft.com/en-us/power-bi/developer/execute-dax-queries-arrow/dotnet-mid-tier-service Clones the Microsoft.Samples.XMLA.ExecuteQueries repository and verifies the solution compiles with dotnet build. The solution contains a mid-tier service and a load test client (Tester); only the build needs to succeed before making changes. ```bash git clone https://github.com/dbrownems/Microsoft.Samples.XMLA.ExecuteQueries.git cd Microsoft.Samples.XMLA.ExecuteQueries dotnet build ``` -------------------------------- ### Start the Node.js app Source: https://learn.microsoft.com/en-us/power-bi/developer/embedded/embed-sample-for-customers Execute this command in the IDE terminal to run the project, then open http://localhost:5300 in a browser. ```bash npm start ``` -------------------------------- ### Authenticate with C# using MSAL Source: https://learn.microsoft.com/en-us/power-bi/developer/execute-dax-queries-arrow/get-started Acquires an interactive bearer token for the Power BI API scope. Replace YOUR_APP_CLIENT_ID and YOUR_TENANT_ID with your values. ```csharp using Microsoft.Identity.Client; var clientId = "YOUR_APP_CLIENT_ID"; var tenantId = "YOUR_TENANT_ID"; var scopes = new[] { "https://analysis.windows.net/powerbi/api/.default" }; var app = PublicClientApplicationBuilder .Create(clientId) .WithAuthority(AzureCloudInstance.AzurePublic, tenantId) .WithRedirectUri("http://localhost") .Build(); var result = await app.AcquireTokenInteractive(scopes).ExecuteAsync(); var accessToken = result.AccessToken; ``` -------------------------------- ### Prepare semantic model for AI with /semantic-model-authoring Source: https://learn.microsoft.com/en-us/power-bi/developer/agentic/semantic-model-authoring-skill-overview Run this prompt in GitHub Copilot to invoke the Semantic Model AI Readiness workflow. It loads the semantic-model-ai-readiness.md reference and prepares the model for conversational AI experiences like Fabric Copilot and Power BI Data Agents. ```text /semantic-model-authoring Connect to Power BI Desktop and prepare the semantic model for AI ``` -------------------------------- ### Run the Python Flask app Source: https://learn.microsoft.com/en-us/power-bi/developer/embedded/embed-sample-for-customers Execute this command in the AppOwnesData folder to start the Flask server, then open http://localhost:5000 in a browser. ```bash flask run ``` -------------------------------- ### usePointerEvents Source: https://learn.microsoft.com/en-us/power-bi/developer/visuals/utils-tooltip Returns whether the current touch start event is related to a pointer. This function is part of the touch events utilities. ```APIDOC ## usePointerEvents ### Description Returns the current touchStart event related to a pointer or not. ### Function Signature ```typescript function usePointerEvents(): boolean ``` ### Parameters None. ### Returns - **boolean** - True if the touch start event is related to a pointer, false otherwise. ``` -------------------------------- ### startsWith usage example Source: https://learn.microsoft.com/en-us/power-bi/developer/visuals/utils-formatting Shows how to use stringExtensions.startsWith to check if 'Power BI' starts with 'Power', returning true. ```typescript import { stringExtensions } from "powerbi-visuals-utils-formattingutils"; // ... stringExtensions.startsWith("Power BI", "Power"); // returns: true ``` -------------------------------- ### Clone the source code repository Source: https://learn.microsoft.com/en-us/power-bi/developer/visuals/create-bar-chart Use this command to clone the source code repository for the tutorial, allowing you to follow along without creating your own visual. ```bash git clone ``` -------------------------------- ### Authenticate with Python using MSAL Source: https://learn.microsoft.com/en-us/power-bi/developer/execute-dax-queries-arrow/get-started Acquires an interactive bearer token for the Power BI API scope. Replace YOUR_APP_CLIENT_ID and YOUR_TENANT_ID with your values. ```python from msal import PublicClientApplication client_id = "YOUR_APP_CLIENT_ID" authority = "https://login.microsoftonline.com/YOUR_TENANT_ID" scopes = ["https://analysis.windows.net/powerbi/api/.default"] app = PublicClientApplication(client_id, authority=authority) result = app.acquire_token_interactive(scopes=scopes) access_token = result["access_token"] ``` -------------------------------- ### ITooltipServiceWrapper.addTooltip Source: https://learn.microsoft.com/en-us/power-bi/developer/visuals/utils-tooltip Adds tooltips to the current selection. This method accepts a D3 selection, a delegate to get tooltip info, and optional parameters for data point identity and reload behavior. ```APIDOC ## ITooltipServiceWrapper.addTooltip ### Description Adds tooltips to the current selection. ### Method Signature ```typescript addTooltip(selection: d3.Selection, getTooltipInfoDelegate: (args: TooltipEventArgs) => VisualTooltipDataItem[], getDataPointIdentity?: (args: TooltipEventArgs) => ISelectionId, reloadTooltipDataOnMouseMove?: boolean): void; ``` ### Parameters - **selection** (d3.Selection) - Required - The D3 selection to attach tooltips to. - **getTooltipInfoDelegate** ((args: TooltipEventArgs) => VisualTooltipDataItem[]) - Required - Delegate to get tooltip data. - **getDataPointIdentity** ((args: TooltipEventArgs) => ISelectionId) - Optional - Delegate to get data point identity. - **reloadTooltipDataOnMouseMove** (boolean) - Optional - Whether to reload tooltip data on mouse move. ### Returns - **void** - No return value. ### Example ```typescript import { createTooltipServiceWrapper, TooltipEventArgs, ITooltipServiceWrapper, TooltipEnabledDataPoint } from "powerbi-visuals-utils-tooltiputils"; let bodyElement = d3.select("body"); let element = bodyElement .append("div") .style({ "background-color": "green", "width": "150px", "height": "150px" }) .classed("visual", true) .data([{ tooltipInfo: [{ displayName: "Power BI", value: 2016 }] }]); let tooltipServiceWrapper: ITooltipServiceWrapper = createTooltipServiceWrapper(tooltipService, bodyElement.get(0)); // tooltipService is from the IVisualHost. tooltipServiceWrapper.addTooltip(element, (eventArgs: TooltipEventArgs) => { return eventArgs.data.tooltipInfo; }); // You will see a tooltip if you mouseover the element. ``` ``` -------------------------------- ### Configure Startup.cs for Microsoft.Identity.Web Source: https://learn.microsoft.com/en-us/power-bi/developer/embedded/embed-organization-app Add this code to your app's Startup.cs file to initialize the Microsoft.Identity.Web authentication service. The ConfigureServices method calls AddMicrosoftWebAppCallsWebApi to acquire Microsoft Entra tokens, AddInMemoryTokenCaches for token caching, and registers PowerBiServiceApi for dependency injection. ```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(); } } } ``` -------------------------------- ### DatePickerDialog class implementation Source: https://learn.microsoft.com/en-us/power-bi/developer/visuals/create-display-dialog-box Example dialog box class that uses the initialState parameter to set a start date, renders a date picker, and uses IDialogHost methods to set a result and close the dialog. The constructor receives DialogConstructorOptions and an initialState object. ```typescript export class DatePickerDialog { static id = "DatePickerDialog"; constructor(options: DialogConstructorOptions, initialState: object) { const host = options.host; let pickedDate: Date; const startDate = new Date(initialState['startDate']); // Dialog rendering implementation ReactDOM.render( React.createElement( reactDatepicker, { inline: true, openToDate: startDate, onChange: (date: Date) => { pickedDate = date host.setResult({ date: pickedDate }) } }, null), options.element ); document.addEventListener('keydown', e => { if (e.code == 'Enter' && pickedDate) { host.close(DialogAction.Close, {date: pickedDate}); } }); } } ``` -------------------------------- ### Get locale from visual host Source: https://learn.microsoft.com/en-us/power-bi/developer/visuals/localization The Power BI locale is passed as a string during visual initialization. If the locale changes in Power BI, the visual is regenerated in the new language. In Power BI Desktop, the locale property contains the language of the installed Power BI Desktop. ```typescript private locale: string; ... this.locale = options.host.locale; ``` -------------------------------- ### Example prompts for modeling tasks Source: https://learn.microsoft.com/en-us/power-bi/developer/mcp/power-bi-authoring-mcp These prompts illustrate possible scenarios for the agent, such as standardizing naming, documenting the model, translating, refactoring into calculation groups, or creating a Direct Lake semantic model. They are examples, not a fixed set. ```text Analyze the naming convention of the 'Sales' table and apply the same pattern across the entire model. ``` ```text Add descriptions to all measures, columns, and tables that explain their purpose and the logic behind the DAX in plain business terms. ``` ```text Generate a French translation for my model, including tables, columns, and measures. ``` ```text Refactor measures 'Sales Amount 12M Avg' and 'Sales Amount 6M Avg' into a calculation group, and add 24M and 3M variants. ``` ```text Create a Direct Lake semantic model against lakehouse 'LH_CorpData' using tables 'Product', 'Sales', 'Store' ``` -------------------------------- ### Package the visual with pbiviz package Source: https://learn.microsoft.com/en-us/power-bi/developer/visuals/create-r-based-power-bi-desktop Run this command from the root directory of your visual to package it into a pbiviz file. Before running, fill in the displayName, supportUrl, description, author's name and email, and other important information in the pbivis.json file, and optionally replace the icon.png file in the assets folder to change the visual's icon on the visualization pane. After packaging, import the pbiviz file into any Power BI report. ```bash pbiviz package ``` -------------------------------- ### Call Power BI REST API with profile ID header Source: https://learn.microsoft.com/en-us/power-bi/developer/embedded/embed-multi-tenancy ISV apps call Power BI REST APIs by providing the service principal Microsoft Entra token in the Authorization header and the profile ID in the X-PowerBI-Profile-Id header. This example shows a GET request to list groups. ```http GET https://api.powerbi.com/v1.0/myorg/groups HTTP/1.1 Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUz.....SXBwasfg X-PowerBI-Profile-Id: 5f1aa5ed-5983-46b5-bd05-999581d361a5 ``` -------------------------------- ### Step 3 - getting the file (GetExportedFile and ExportedFile class) Source: https://learn.microsoft.com/en-us/power-bi/developer/embedded/export-to Retrieves the exported file stream after polling returns a successful status. The method checks that the export status is Succeeded, then calls GetFileOfExportToFileAsync to obtain the file stream and returns an ExportedFile object containing the stream and the file suffix. The ExportedFile class is defined in the same example. ```csharp private async Task GetExportedFile( Guid reportId, Guid groupId, Export export /* Get from the PollExportRequest response */) { if (export.Status == ExportState.Succeeded) { // The 'Client' object is an instance of the Power BI .NET SDK var fileStream = await Client.Reports.GetFileOfExportToFileAsync(groupId, reportId, export.Id); return new ExportedFile { FileStream = fileStream, FileSuffix = export.ResourceFileExtension, }; } return null; } public class ExportedFile { public Stream FileStream; public string FileSuffix; } ``` -------------------------------- ### Example of using create Source: https://learn.microsoft.com/en-us/power-bi/developer/visuals/utils-formatting Shows how to call create with an empty options object. The comment indicates that it returns an instance of IValueFormatter. ```typescript import { valueFormatter } from "powerbi-visuals-utils-formattingutils"; valueFormatter.create({}); // returns: an instance of IValueFormatter. ``` -------------------------------- ### Authenticate with PowerShell using MSAL.PS Source: https://learn.microsoft.com/en-us/power-bi/developer/execute-dax-queries-arrow/get-started Acquires an interactive bearer token for the Power BI API scope. Replace YOUR_APP_CLIENT_ID and YOUR_TENANT_ID with your values. ```powershell $clientId = "YOUR_APP_CLIENT_ID" $tenantId = "YOUR_TENANT_ID" $scopes = @("https://analysis.windows.net/powerbi/api/.default") $token = Get-MsalToken -ClientId $clientId -TenantId $tenantId -Scopes $scopes -Interactive $accessToken = $token.AccessToken ``` -------------------------------- ### Configure Startup.cs for Microsoft.Identity.Web authentication Source: https://learn.microsoft.com/en-us/power-bi/developer/embedded/embed-customer-app Modify Startup.cs to initialize Microsoft.Identity.Web authentication. ConfigureServices calls AddMicrosoftIdentityWebAppAuthentication, EnableTokenAcquisitionToCallDownstreamApi, and AddInMemoryTokenCaches to acquire and cache Microsoft Entra tokens. It also registers PowerBiServiceApi for dependency injection and enforces authenticated users on all controllers and Razor pages. ```csharp using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.OpenIdConnect; using Microsoft.AspNetCore.Authorization; using Microsoft.Identity.Web; using Microsoft.Identity.Web.UI; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.AspNetCore.Mvc.Authorization; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using AppOwnsData.Services; namespace AppOwnsData { 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() .AddInMemoryTokenCaches(); services.AddScoped(typeof(PowerBiServiceApi)); services.AddControllersWithViews(options => { var policy = new AuthorizationPolicyBuilder() .RequireAuthenticatedUser() .Build(); options.Filters.Add(new AuthorizeFilter(policy)); }); services.AddRazorPages() .AddMicrosoftIdentityUI(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); // The default HSTS value is 30 days. You might want to change this for production scenarios. See https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); endpoints.MapRazorPages(); }); } } } ```