Skip to main content
cancel
Showing results for 
Search instead for 
Did you mean: 

Register now to learn Fabric in free live sessions led by the best Microsoft experts. From Apr 16 to May 9, in English and Spanish.

Reply
Anonymous
Not applicable

Create a report and uploading it to power bi embedded automatically?

Hello Community,

Is there a way where one could create a Report (Import data, create visuals) and upload it into the Power BI Embedded Service (Workspace) automatically?

 

I have looked into the Power BI API, iirc, it seems the Power BI API does not have the ablity to upload a report to workspace automatically.

 

I have been searching a way to optimize and allow scaliblity for process as we will maintain a template for reports across various products.

 

 

Any input would be great,

Thanks,

bdiouf

1 ACCEPTED SOLUTION
Eric_Zhang
Employee
Employee

@Anonymous

There's no SDK to create a report, you can check this idea Power BI Designer API and vote it up.

 

As to import/upload pbix file to Power BI Embedded workspace or Power BI Service, you can reference below demo.

 

1.Import Pbix file to Power BI Embedded workspace. Do note that Power BI Embedded is being deprecated, consider migrating it  to Power BI Service and use the new Embedding with non-Power BI users.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.PowerBI.Api.V1;
using Microsoft.Rest;
using Microsoft.PowerBI.Api.V1.Models;
using System.IO;
using System.Threading;

namespace ConsoleApplication39
{
    class Program
    { 
        static string accesskey = "KJixxxxxxxxxxxxP5HFp7G45RYHRIO23ViXY8iE/zNVHROCmcaOIFr6a2vmQ==";
        static string workspaceCollectionName = "cisxxxdexxmo";
        static string workspaceId = "79c71931-dxxxxxxc8-b79d2192fe0b";
        static void Main(string[] args)
        {
            var task = ImportPbix(workspaceCollectionName, workspaceId, "datasetname1", @"C:\test\2.pbix");

            task.Wait();

            var result = task.Result;

            Console.Write(result);

        }

        static async Task<Import> ImportPbix(string workspaceCollectionName, string workspaceId, string datasetName, string filePath)
        {
            using (var fileStream = File.OpenRead(filePath.Trim('"')))
            {
                using (var client = await CreateClient())
                {
                    // Set request timeout to support uploading large PBIX files
                    client.HttpClient.Timeout = TimeSpan.FromMinutes(60);
                    client.HttpClient.DefaultRequestHeaders.Add("ActivityId", Guid.NewGuid().ToString());

                    // Import PBIX file from the file stream
                    var import = await client.Imports.PostImportWithFileAsync(workspaceCollectionName, workspaceId, fileStream, datasetName);

                    // Example of polling the import to check when the import has succeeded.
                    while (import.ImportState != "Succeeded" && import.ImportState != "Failed")
                    {
                        import = await client.Imports.GetImportByIdAsync(workspaceCollectionName, workspaceId, import.Id);
                        Console.WriteLine("Checking import state... {0}", import.ImportState);
                        Thread.Sleep(1000);
                    }

                    return import;
                }
            }
        }

        static async Task<PowerBIClient> CreateClient()
        {

            // Create a token credentials with "AppKey" type
            var credentials = new TokenCredentials(accesskey, "AppKey");

            // 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("https://api.powerbi.com");

            return client;
        }


    }
}

 

2.Import a pbix file to Power BI Service.

 

using System; 
using System.Net; 
//Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory -Version 2.21.301221612
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System.IO; 

namespace ConsoleApplication39
{

    class Program
    {

        //Step 1 - Replace {client id} with your client app ID. 
        //To learn how to get a client app ID, see Register a client app (https://msdn.microsoft.com/en-US/library/dn877542.aspx#clientID)
        private static string clientID = "49df1bcxxxxxxxxxd93f770d1a4";

        //RedirectUri you used when you registered your app.
        //For a client app, a redirect uri gives AAD more details on the specific application that it will authenticate.
        private static string redirectUri = "https://login.live.com/oauth20_desktop.srf";

        //Resource Uri for Power BI API
        private static string resourceUri = "https://analysis.windows.net/powerbi/api";

        //OAuth2 authority Uri
        private static string authority = "https://login.windows.net/common/oauth2/authorize";

        private static AuthenticationContext authContext = null;
        private static string token = String.Empty;

        //Uri for Power BI datasets
        private static string datasetsUri = "https://api.powerbi.com/v1.0/myorg";
        private static string datasetsBetaUri = "https://api.powerbi.com/beta/myorg";

        //Example dataset name and group name 
        private static string groupId = "dc581184-a209-463b-8446-5432f16b6c15";

        static void Main(string[] args)
        {
            //Import sample 
            string pbixPath = @"C:\test\2.pbix";
            string datasetDisplayName = "mydataset";

            string importResponse = Import(string.Format("{0}/groups/{1}/imports?datasetDisplayName={2}", datasetsBetaUri, groupId, datasetDisplayName), pbixPath);
              
            Console.WriteLine(importResponse);

        }

        public static string Import(string url, string fileName)
        {
            string responseStatusCode = string.Empty;

            string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
            byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            request.ContentType = "multipart/form-data; boundary=" + boundary;
            request.Method = "POST";
            request.KeepAlive = true;
            request.Headers.Add("Authorization", String.Format("Bearer {0}", AccessToken()));

            using (Stream rs = request.GetRequestStream())
            {
                rs.Write(boundarybytes, 0, boundarybytes.Length);

                string headerTemplate = "Content-Disposition: form-data; filename=\"{0}\"\r\nContent-Type: application / octet - stream\r\n\r\n";
                string header = string.Format(headerTemplate, fileName);
                byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
                rs.Write(headerbytes, 0, headerbytes.Length);

                using (FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
                {
                    byte[] buffer = new byte[4096];
                    int bytesRead = 0;
                    while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                    {
                        rs.Write(buffer, 0, bytesRead);
                    }
                }

                byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
                rs.Write(trailer, 0, trailer.Length);
            }
            using (HttpWebResponse response = request.GetResponse() as System.Net.HttpWebResponse)
            {
                responseStatusCode = response.StatusCode.ToString();
            }

            return responseStatusCode;
        }


        static string AccessToken()
        {
            if (token == String.Empty)
            {
                //Get Azure access token
                // Create an instance of TokenCache to cache the access token
                TokenCache TC = new TokenCache();
                // Create an instance of AuthenticationContext to acquire an Azure access token
                authContext = new AuthenticationContext(authority, TC);
                // Call AcquireToken to get an Azure token from Azure Active Directory token issuance endpoint
                token = authContext.AcquireToken(resourceUri, clientID, new Uri(redirectUri), PromptBehavior.RefreshSession).AccessToken;
            }
            else
            {
                // Get the token in the cache
                token = authContext.AcquireTokenSilent(resourceUri, clientID).AccessToken;
            }

            return token;
        } 
    }
}

 

View solution in original post

1 REPLY 1
Eric_Zhang
Employee
Employee

@Anonymous

There's no SDK to create a report, you can check this idea Power BI Designer API and vote it up.

 

As to import/upload pbix file to Power BI Embedded workspace or Power BI Service, you can reference below demo.

 

1.Import Pbix file to Power BI Embedded workspace. Do note that Power BI Embedded is being deprecated, consider migrating it  to Power BI Service and use the new Embedding with non-Power BI users.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.PowerBI.Api.V1;
using Microsoft.Rest;
using Microsoft.PowerBI.Api.V1.Models;
using System.IO;
using System.Threading;

namespace ConsoleApplication39
{
    class Program
    { 
        static string accesskey = "KJixxxxxxxxxxxxP5HFp7G45RYHRIO23ViXY8iE/zNVHROCmcaOIFr6a2vmQ==";
        static string workspaceCollectionName = "cisxxxdexxmo";
        static string workspaceId = "79c71931-dxxxxxxc8-b79d2192fe0b";
        static void Main(string[] args)
        {
            var task = ImportPbix(workspaceCollectionName, workspaceId, "datasetname1", @"C:\test\2.pbix");

            task.Wait();

            var result = task.Result;

            Console.Write(result);

        }

        static async Task<Import> ImportPbix(string workspaceCollectionName, string workspaceId, string datasetName, string filePath)
        {
            using (var fileStream = File.OpenRead(filePath.Trim('"')))
            {
                using (var client = await CreateClient())
                {
                    // Set request timeout to support uploading large PBIX files
                    client.HttpClient.Timeout = TimeSpan.FromMinutes(60);
                    client.HttpClient.DefaultRequestHeaders.Add("ActivityId", Guid.NewGuid().ToString());

                    // Import PBIX file from the file stream
                    var import = await client.Imports.PostImportWithFileAsync(workspaceCollectionName, workspaceId, fileStream, datasetName);

                    // Example of polling the import to check when the import has succeeded.
                    while (import.ImportState != "Succeeded" && import.ImportState != "Failed")
                    {
                        import = await client.Imports.GetImportByIdAsync(workspaceCollectionName, workspaceId, import.Id);
                        Console.WriteLine("Checking import state... {0}", import.ImportState);
                        Thread.Sleep(1000);
                    }

                    return import;
                }
            }
        }

        static async Task<PowerBIClient> CreateClient()
        {

            // Create a token credentials with "AppKey" type
            var credentials = new TokenCredentials(accesskey, "AppKey");

            // 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("https://api.powerbi.com");

            return client;
        }


    }
}

 

2.Import a pbix file to Power BI Service.

 

using System; 
using System.Net; 
//Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory -Version 2.21.301221612
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System.IO; 

namespace ConsoleApplication39
{

    class Program
    {

        //Step 1 - Replace {client id} with your client app ID. 
        //To learn how to get a client app ID, see Register a client app (https://msdn.microsoft.com/en-US/library/dn877542.aspx#clientID)
        private static string clientID = "49df1bcxxxxxxxxxd93f770d1a4";

        //RedirectUri you used when you registered your app.
        //For a client app, a redirect uri gives AAD more details on the specific application that it will authenticate.
        private static string redirectUri = "https://login.live.com/oauth20_desktop.srf";

        //Resource Uri for Power BI API
        private static string resourceUri = "https://analysis.windows.net/powerbi/api";

        //OAuth2 authority Uri
        private static string authority = "https://login.windows.net/common/oauth2/authorize";

        private static AuthenticationContext authContext = null;
        private static string token = String.Empty;

        //Uri for Power BI datasets
        private static string datasetsUri = "https://api.powerbi.com/v1.0/myorg";
        private static string datasetsBetaUri = "https://api.powerbi.com/beta/myorg";

        //Example dataset name and group name 
        private static string groupId = "dc581184-a209-463b-8446-5432f16b6c15";

        static void Main(string[] args)
        {
            //Import sample 
            string pbixPath = @"C:\test\2.pbix";
            string datasetDisplayName = "mydataset";

            string importResponse = Import(string.Format("{0}/groups/{1}/imports?datasetDisplayName={2}", datasetsBetaUri, groupId, datasetDisplayName), pbixPath);
              
            Console.WriteLine(importResponse);

        }

        public static string Import(string url, string fileName)
        {
            string responseStatusCode = string.Empty;

            string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
            byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            request.ContentType = "multipart/form-data; boundary=" + boundary;
            request.Method = "POST";
            request.KeepAlive = true;
            request.Headers.Add("Authorization", String.Format("Bearer {0}", AccessToken()));

            using (Stream rs = request.GetRequestStream())
            {
                rs.Write(boundarybytes, 0, boundarybytes.Length);

                string headerTemplate = "Content-Disposition: form-data; filename=\"{0}\"\r\nContent-Type: application / octet - stream\r\n\r\n";
                string header = string.Format(headerTemplate, fileName);
                byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
                rs.Write(headerbytes, 0, headerbytes.Length);

                using (FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
                {
                    byte[] buffer = new byte[4096];
                    int bytesRead = 0;
                    while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                    {
                        rs.Write(buffer, 0, bytesRead);
                    }
                }

                byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
                rs.Write(trailer, 0, trailer.Length);
            }
            using (HttpWebResponse response = request.GetResponse() as System.Net.HttpWebResponse)
            {
                responseStatusCode = response.StatusCode.ToString();
            }

            return responseStatusCode;
        }


        static string AccessToken()
        {
            if (token == String.Empty)
            {
                //Get Azure access token
                // Create an instance of TokenCache to cache the access token
                TokenCache TC = new TokenCache();
                // Create an instance of AuthenticationContext to acquire an Azure access token
                authContext = new AuthenticationContext(authority, TC);
                // Call AcquireToken to get an Azure token from Azure Active Directory token issuance endpoint
                token = authContext.AcquireToken(resourceUri, clientID, new Uri(redirectUri), PromptBehavior.RefreshSession).AccessToken;
            }
            else
            {
                // Get the token in the cache
                token = authContext.AcquireTokenSilent(resourceUri, clientID).AccessToken;
            }

            return token;
        } 
    }
}

 

Helpful resources

Announcements
Microsoft Fabric Learn Together

Microsoft Fabric Learn Together

Covering the world! 9:00-10:30 AM Sydney, 4:00-5:30 PM CET (Paris/Berlin), 7:00-8:30 PM Mexico City

PBI_APRIL_CAROUSEL1

Power BI Monthly Update - April 2024

Check out the April 2024 Power BI update to learn about new features.

April Fabric Community Update

Fabric Community Update - April 2024

Find out what's new and trending in the Fabric Community.

Top Kudoed Authors