Forum Discussion

Omkar1231's avatar
Omkar1231
Frequent Visitor
8 years ago

C# web application : import pbix file from azure

The following code works perfectly fine for C# console application. I used the same code for web application and it works very well on localhost too. However, when I publish it on Azure <XXX.azurewebsites.net>, it gives me error. I have found a solution that states that this code will run only on local application. It is not meant for azure. So can I know what changes to make so that it runs on Azure too? Thanks!

 

namespace PBIGettingStarted
{

class Program
{
    private static string clientID = "49df1bc7-db68-4fb4-91c0-6d93f770d1a4";

    private static string redirectUri = "https://login.live.com/oauth20_desktop.srf";

    private static string resourceUri = "https://analysis.windows.net/powerbi/api";

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

    private static string PBIAPIUri = "https://api.powerbi.com/v1.0/myorg";

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

    private static string datasetName = "testdataset";
    private static string groupID = "XX";

    private static string pbixPath = localname;
    private static string datasetDisplayName = "test";

    static void Main(string[] args)
    {
        string importResponse = Import(string.Format("{0}/groups/{1}/imports?datasetDisplayName={2}", PBIAPIUri, groupID, datasetDisplayName), pbixPath);
        Console.ReadLine();
    }

    static string AccessToken()
    {
        if (token == String.Empty)
        {
            TokenCache TC = new TokenCache();
            authContext = new AuthenticationContext(authority, TC);
            token = authContext.AcquireToken(resourceUri, clientID, new Uri(redirectUri), PromptBehavior.RefreshSession).AccessToken;
        }
        else
        {
            token = authContext.AcquireTokenSilent(resourceUri, clientID).AccessToken;
        }

        return token;
    }

    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);
        }


        try
        {            using (HttpWebResponse response = request.GetResponse() as System.Net.HttpWebResponse)
            {                responseStatusCode = response.StatusCode.ToString();
                Console.WriteLine("imported pbix ", responseStatusCode);
            }
        }
        catch (WebException wex)
        {
            if (wex.Response != null)
            {                using (var errorResponse = (HttpWebResponse)wex.Response)
                {                    using (var reader = new StreamReader(errorResponse.GetResponseStream()))
                    {
                        string errorString = reader.ReadToEnd();
                        dynamic respJson = JsonConvert.DeserializeObject<dynamic>(errorString);
                        Console.WriteLine(respJson.ToString());
                    }
                }
            }
        }

        return responseStatusCode;
    }

}}

 

4 Replies

  • Anonymous's avatar
    Anonymous
    Not applicable

    Hi Omkar1231,

     

    probably you have problem with the AccessToken as you use the TokenCache.

    Maybe you can try this to obtain an access code:

     

    Note that the AAD application should be a native app.
    
    using Microsoft.IdentityModel.Clients.ActiveDirectory;
    
    /// <summary>
    /// Returns an AccessToken for the PowerBi service.
    /// </summary>
    private async Task<string> GetPowerBiAccessToken()
    {
    	var powerBiAccountCredentials = new UserCredential("PowerBIAADUserName", PowerBIAADUserPassword");
    	var authenticationContext = new AuthenticationContext("https://login.windows.net/common/oauth2/authorize/");
    	var authenticationResult = await authenticationContext.AcquireTokenAsync("https://analysis.windows.net/powerbi/api", "PowerBIAADAppId", powerBiAccountCredentials);
    
    	return authenticationResult.AccessToken;
    }

    The prerequisites for the above code is to register a native app for the PowerBI following this guide

     

    Hope this helps.

     

    Regards,


    Thanos

    • Omkar1231's avatar
      Omkar1231
      Frequent Visitor

      Getting this error after adding the above code:

      HttpWebRequest-GetResponse-The-remote-server-returned-an-error-500-Internal-Server-Error

       

      'iisexpress.exe' (CLR v4.0.30319: /LM/W3SVC/2/ROOT-1-131692930805767465): Loaded 'C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Web.Mobile\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Web.Mobile.dll'. Cannot find or open the PDB file.
      'iisexpress.exe' (CLR v4.0.30319: /LM/W3SVC/2/ROOT-1-131692930805767465): Loaded 'A_ccac4ab7_29d9_4a8c_9f8d_cbac359a2db3'. 
      'iisexpress.exe' (CLR v4.0.30319: /LM/W3SVC/2/ROOT-1-131692930805767465): Loaded 'C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Web.Entity\v4.0_4.0.0.0__b77a5c561934e089\System.Web.Entity.dll'. Cannot find or open the PDB file.
      'iisexpress.exe' (CLR v4.0.30319: /LM/W3SVC/2/ROOT-1-131692930805767465): Loaded 'C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Design\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Design.dll'. Cannot find or open the PDB file.
      'iisexpress.exe' (CLR v4.0.30319: DefaultDomain): Loaded 'C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Design\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Design.dll'. Cannot find or open the PDB file.
      'iisexpress.exe' (CLR v4.0.30319: /LM/W3SVC/2/ROOT-1-131692930805767465): Loaded 'C:\Users\ashish\AppData\Local\Temp\Temporary ASP.NET Files\vs\36374898\d356574d\App_Web_o0xr5jqj.dll'. 
      'iisexpress.exe' (CLR v4.0.30319: /LM/W3SVC/2/ROOT-1-131692930805767465): Loaded 'C:\Users\ashish\AppData\Local\Temp\Temporary ASP.NET Files\vs\36374898\d356574d\App_Web_mqynwa0x.dll'. 
      'iisexpress.exe' (CLR v4.0.30319: DefaultDomain): Loaded 'C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Drawing\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Drawing.dll'. Cannot find or open the PDB file.
      Application Insights Telemetry (unconfigured): {"name":"Microsoft.ApplicationInsights.Dev.Request","time":"2018-04-27T08:59:16.5029538Z","tags":{"ai.internal.sdkVersion":"web:2.2.0-738","ai.operation.id":"qWZlxFAvxR4=","ai.location.ip":"::1","ai.cloud.roleInstance":"ashish","ai.operation.name":"GET /WebForm1"},"data":{"baseType":"RequestData","baseData":{"ver":2,"id":"qWZlxFAvxR4=","name":"GET /WebForm1","duration":"00:00:21.2490000","success":true,"responseCode":"200","url":"http://localhost:56863/WebForm1","properties":{"DeveloperMode":"true"}}}}
      'iisexpress.exe' (CLR v4.0.30319: /LM/W3SVC/2/ROOT-1-131692930805767465): Loaded 'C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\PrivateAssemblies\Runtime\Microsoft.VisualStudio.Debugger.Runtime.dll'. 
      The thread 0x3304 has exited with code 0 (0x0).
      The thread 0x23d0 has exited with code 0 (0x0).
      Microsoft.IdentityModel.Clients.ActiveDirectory Information: 2 : 04/27/2018 09:00:21:  - AuthenticationContext: ADAL .NET with assembly version '2.29.0.1078', file version '2.29.40822.1520' and informational version 'f9bca6d39d5898099b28db5e57f069cefa44334b' is running...
      iisexpress.exe Information: 0 : 04/27/2018 09:00:21:  - AuthenticationContext: ADAL .NET with assembly version '2.29.0.1078', file version '2.29.40822.1520' and informational version 'f9bca6d39d5898099b28db5e57f069cefa44334b' is running...
      Microsoft.IdentityModel.Clients.ActiveDirectory Information: 2 : 04/27/2018 09:00:21: 69d2b691-fc2b-4a6e-90a5-9a66ee677672 - AcquireTokenHandlerBase: === Token Acquisition started:
          Authority: https://login.windows.net/common/oauth2/authorize/
          Resource: https://analysis.windows.net/powerbi/api
          ClientId: acb34953-93be-4b08-a0c6-7c73376bed6b
          CacheType: Microsoft.IdentityModel.Clients.ActiveDirectory.TokenCache (0 items)
          Authentication Target: Client
          
      iisexpress.exe Information: 0 : 04/27/2018 09:00:21: 69d2b691-fc2b-4a6e-90a5-9a66ee677672 - AcquireTokenHandlerBase: === Token Acquisition started:
          Authority: https://login.windows.net/common/oauth2/authorize/
          Resource: https://analysis.windows.net/powerbi/api
          ClientId: acb34953-93be-4b08-a0c6-7c73376bed6b
          CacheType: Microsoft.IdentityModel.Clients.ActiveDirectory.TokenCache (0 items)
          Authentication Target: Client
          
      Microsoft.IdentityModel.Clients.ActiveDirectory Verbose: 1 : 04/27/2018 09:00:21: 69d2b691-fc2b-4a6e-90a5-9a66ee677672 - TokenCache: Looking up cache for a token...
      iisexpress.exe Information: 0 : 04/27/2018 09:00:21: 69d2b691-fc2b-4a6e-90a5-9a66ee677672 - TokenCache: Looking up cache for a token...
      Microsoft.IdentityModel.Clients.ActiveDirectory Information: 2 : 04/27/2018 09:00:22: 69d2b691-fc2b-4a6e-90a5-9a66ee677672 - TokenCache: No matching token was found in the cache
      iisexpress.exe Information: 0 : 04/27/2018 09:00:22: 69d2b691-fc2b-4a6e-90a5-9a66ee677672 - TokenCache: No matching token was found in the cache
      Exception thrown: 'System.ArgumentNullException' in mscorlib.dll
      Application Insights Telemetry (unconfigured): {"name":"Microsoft.ApplicationInsights.Dev.RemoteDependency","time":"2018-04-27T09:00:22.2213705Z","tags":{"ai.internal.sdkVersion":"rddf:2.2.0-738","ai.internal.nodeName":"ashish","ai.operation.id":"0tP1iFPqhZA=","ai.location.ip":"::1","ai.cloud.roleInstance":"ashish","ai.operation.name":"POST /WebForm1","ai.operation.parentId":"0tP1iFPqhZA="},"data":{"baseType":"RemoteDependencyData","baseData":{"ver":2,"name":"/common/oauth2/token","id":"BzxkVRvTGs8=","data":"https://login.windows.net/common/oauth2/token","duration":"00:00:01.8520000","resultCode":"200","success":true,"type":"Http","target":"login.windows.net","properties":{"DeveloperMode":"true"}}}}
      Microsoft.IdentityModel.Clients.ActiveDirectory Verbose: 1 : 04/27/2018 09:00:24: 69d2b691-fc2b-4a6e-90a5-9a66ee677672 - TokenCache: Storing token in the cache...
      iisexpress.exe Information: 0 : 04/27/2018 09:00:24: 69d2b691-fc2b-4a6e-90a5-9a66ee677672 - TokenCache: Storing token in the cache...
      Microsoft.IdentityModel.Clients.ActiveDirectory Verbose: 1 : 04/27/2018 09:00:24: 69d2b691-fc2b-4a6e-90a5-9a66ee677672 - TokenCache: An item was stored in the cache
      iisexpress.exe Information: 0 : 04/27/2018 09:00:24: 69d2b691-fc2b-4a6e-90a5-9a66ee677672 - TokenCache: An item was stored in the cache
      Microsoft.IdentityModel.Clients.ActiveDirectory Information: 2 : 04/27/2018 09:00:24: 69d2b691-fc2b-4a6e-90a5-9a66ee677672 - AcquireTokenHandlerBase: === Token Acquisition finished successfully. An access token was retuned:
          Access Token Hash: jjpnyT7T4EXfEr2DGUlxI2xdRKTfSZWE+DYgfKswvu0=
          Refresh Token Hash: [No Refresh Token]
          Expiration Time: 04/27/2018 10:00:23 +00:00
          User Hash: null
          
      iisexpress.exe Information: 0 : 04/27/2018 09:00:24: 69d2b691-fc2b-4a6e-90a5-9a66ee677672 - AcquireTokenHandlerBase: === Token Acquisition finished successfully. An access token was retuned:
          Access Token Hash: jjpnyT7T4EXfEr2DGUlxI2xdRKTfSZWE+DYgfKswvu0=
          Refresh Token Hash: [No Refresh Token]
          Expiration Time: 04/27/2018 10:00:23 +00:00
          User Hash: null
          
      The thread 0x1a50 has exited with code 0 (0x0).
      The thread 0x4188 has exited with code 0 (0x0).
      The thread 0x3ed8 has exited with code 0 (0x0).
      Exception thrown: 'System.Net.WebException' in System.dll
      Exception thrown: 'System.Net.WebException' in System.dll
      Application Insights Telemetry (unconfigured): {"name":"Microsoft.ApplicationInsights.Dev.RemoteDependency","time":"2018-04-27T09:00:34.4768441Z","tags":{"ai.internal.sdkVersion":"rddf:2.2.0-738","ai.internal.nodeName":"ashish","ai.operation.id":"0tP1iFPqhZA=","ai.location.ip":"::1","ai.cloud.roleInstance":"ashish","ai.operation.name":"POST /WebForm1","ai.operation.parentId":"0tP1iFPqhZA="},"data":{"baseType":"RemoteDependencyData","baseData":{"ver":2,"name":"/v1.0/myorg/groups/2f4ebbea-892b-4708-bf6b-aeeb54c3f283/imports","id":"LCi4kyLckvg=","data":"https://api.powerbi.com/v1.0/myorg/groups/2f4ebbea-892b-4708-bf6b-aeeb54c3f283/imports?datasetDisplayName=fcdafad","duration":"00:00:20.2410000","resultCode":"500","success":false,"type":"Http","target":"api.powerbi.com","properties":{"DeveloperMode":"true"}}}}
      The thread 0x398 has exited with code 0 (0x0).
      The thread 0x2e0c has exited with code 0 (0x0).
      Application Insights Telemetry (unconfigured): {"name":"Microsoft.ApplicationInsights.Dev.Request","time":"2018-04-27T08:59:51.5286860Z","tags":{"ai.internal.sdkVersion":"web:2.2.0-738","ai.operation.id":"0tP1iFPqhZA=","ai.location.ip":"::1","ai.cloud.roleInstance":"ashish","ai.operation.name":"POST /WebForm1"},"data":{"baseType":"RequestData","baseData":{"ver":2,"id":"0tP1iFPqhZA=","name":"POST /WebForm1","duration":"00:02:34.0570000","success":true,"responseCode":"200","url":"http://localhost:56863/WebForm1","properties":{"DeveloperMode":"true"}}}}
      The thread 0x2df0 has exited with code 0 (0x0).

      • Anonymous's avatar
        Anonymous
        Not applicable

        Hi Omkar1231,

         

        it would be helpful if you get the real message from the WebException. It should be under Response in the headers. This may help in order to identify what's the problem. 

        I would initially try to separate the request to the PowerBI service from the web form. I would just take the AccessToken and try to import a file through Fiddler/Postman using the access token as an Authorization header. If this works, then I would try to find out what's going to the form code.

         

        Hope it helps.

         

        Thanos