<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:taxo="http://purl.org/rss/1.0/modules/taxonomy/" version="2.0">
  <channel>
    <title>topic Create a report and uploading it to power bi embedded automatically? in Developer</title>
    <link>https://community.fabric.microsoft.com/t5/Developer/Create-a-report-and-uploading-it-to-power-bi-embedded/m-p/207544#M6568</link>
    <description>&lt;P&gt;Hello Community,&lt;/P&gt;&lt;P&gt;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?&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;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.&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;I have been searching a way to optimize and allow scaliblity for process as we will maintain a template for reports across various products.&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;Any input would be great,&lt;/P&gt;&lt;P&gt;Thanks,&lt;/P&gt;&lt;P&gt;bdiouf&lt;/P&gt;</description>
    <pubDate>Thu, 06 Jul 2017 19:53:46 GMT</pubDate>
    <dc:creator>Anonymous</dc:creator>
    <dc:date>2017-07-06T19:53:46Z</dc:date>
    <item>
      <title>Create a report and uploading it to power bi embedded automatically?</title>
      <link>https://community.fabric.microsoft.com/t5/Developer/Create-a-report-and-uploading-it-to-power-bi-embedded/m-p/207544#M6568</link>
      <description>&lt;P&gt;Hello Community,&lt;/P&gt;&lt;P&gt;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?&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;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.&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;I have been searching a way to optimize and allow scaliblity for process as we will maintain a template for reports across various products.&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;Any input would be great,&lt;/P&gt;&lt;P&gt;Thanks,&lt;/P&gt;&lt;P&gt;bdiouf&lt;/P&gt;</description>
      <pubDate>Thu, 06 Jul 2017 19:53:46 GMT</pubDate>
      <guid>https://community.fabric.microsoft.com/t5/Developer/Create-a-report-and-uploading-it-to-power-bi-embedded/m-p/207544#M6568</guid>
      <dc:creator>Anonymous</dc:creator>
      <dc:date>2017-07-06T19:53:46Z</dc:date>
    </item>
    <item>
      <title>Re: Create a report and uploading it to power bi embedded automatically?</title>
      <link>https://community.fabric.microsoft.com/t5/Developer/Create-a-report-and-uploading-it-to-power-bi-embedded/m-p/207753#M6571</link>
      <description>&lt;P&gt;Anonymous&lt;/LI-USER&gt;&lt;/P&gt;
&lt;P&gt;There's no SDK to create a report, you can check this idea &lt;A href="https://ideas.powerbi.com/forums/265200-power-bi-ideas?query=DESIGNER%20API" target="_self"&gt;Power BI Designer API&lt;/A&gt;&amp;nbsp;and vote it up.&lt;/P&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;P&gt;As to import/upload pbix file to Power BI Embedded workspace or Power BI Service, you can reference below demo.&lt;/P&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;P&gt;1.Import Pbix file to Power BI Embedded workspace. Do note that Power BI Embedded is being deprecated, consider &lt;A href="https://powerbi.microsoft.com/en-us/documentation/powerbi-developer-migrate-from-powerbi-embedded/" target="_self"&gt;migrating&lt;/A&gt;&amp;nbsp;it &amp;nbsp;to Power BI Service and use the new&amp;nbsp;&lt;A href="https://powerbi.microsoft.com/en-us/documentation/powerbi-developer-embedding/#embedding-with-non-power-bi-users" target="_self"&gt;Embedding with non-Power BI users&lt;/A&gt;.&lt;/P&gt;
&lt;PRE&gt;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&amp;lt;Import&amp;gt; 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" &amp;amp;&amp;amp; 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&amp;lt;PowerBIClient&amp;gt; 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;
        }


    }
}
&lt;/PRE&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;P&gt;2.Import a pbix file to Power BI Service.&lt;/P&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;PRE&gt;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;
        } 
    }
}
&lt;/PRE&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;</description>
      <pubDate>Fri, 07 Jul 2017 07:22:21 GMT</pubDate>
      <guid>https://community.fabric.microsoft.com/t5/Developer/Create-a-report-and-uploading-it-to-power-bi-embedded/m-p/207753#M6571</guid>
      <dc:creator>Eric_Zhang</dc:creator>
      <dc:date>2017-07-07T07:22:21Z</dc:date>
    </item>
  </channel>
</rss>

