Quantcast
Viewing all articles
Browse latest Browse all 17916

401 - Unauthorized error during Dataset Refresh

I am trying to do the Dataset refresh for a PowerBI Report. I created the gateway and I am able to do the dataset refresh from the admin portal. I could validate that the refresh happend successfully from UI i.e. Last Refresh column in the Admin portal. But when I try to do the refresh from a C# webapi code, I am getting the below mentioned error.

 

Error Message:
The remote server returned an error: (401) Unauthorized.

Stack Trace:
at System.Net.HttpWebRequest.GetResponse()
at BlueSkyPowerBIService.Controllers.PowerBIController.<RefreshDatasetsForReports>d__13.MoveNext() in C:\Krishnan\RSI\SourceCode\Bluesky Developement\BlueSky Development\BlueSkyPowerBIService\BlueSkyPowerBIService\Controllers\PowerBIController.cs:line 258

Before the refresh code, I am able to do the authentication agains the Azure AD and it succeeds and generated the auth token, but when it call the API to refresh it crashes with the above said error.

Please find my code which i am use for data refresh

List<ReportDetails> reportDetailsList = new List<ReportDetails>();

            var result = new EmbedConfig();
            ReportDetails reportDetails = new ReportDetails();
            try
            {
                result = new EmbedConfig { Username = username, Roles = roles };
                var error = GetWebConfigErrors();
                if (error != null)
                {
                    result.ErrorMessage = error;
                    //return View(result);
                    return null;
                }
                var credential = new UserPasswordCredential(Username, Password);

                var authenticationContext = new AuthenticationContext(AuthorityUrl);
                var authenticationResult = await authenticationContext.AcquireTokenAsync(ResourceUrl, ClientId, credential);

                if (authenticationResult == null)
                {
                    result.ErrorMessage = "Authentication Failed.";
                    //return View(result);
                    return null;
                }

                var tokenCredentials = new TokenCredentials(authenticationResult.AccessToken, "Bearer");

                // Create a Power BI Client object. It will be used to call Power BI APIs.
                using (var client = new PowerBIClient(new Uri(ApiUrl), tokenCredentials))
                {
                    // Get a list of reports.
                    var reports = await client.Reports.GetReportsAsync();
                    for (int index = 0; index < reports.Value.Count; index++)
                    {
                        reportDetails = new ReportDetails();
                        Report report = reports.Value[index];

                        HttpWebRequest request;

                        if (report.Id == "6317f207-57d3-4f5f-9644-18bfbb9bef99")
                        {
                            var url = "https://api.powerbi.com/v1.0/myorg/groups/{0}/datasets/{1}/refreshes";
                            request = System.Net.HttpWebRequest.CreateHttp(String.Format(url, GroupId, report.DatasetId));

                            request.KeepAlive = true;
                            request.Method = "POST";
                            request.ContentLength = 0;

                            request.Headers.Add("Authorization", String.Format("Bearer {0}", authenticationResult.AccessToken));

                            using (Stream writer = request.GetRequestStream())
                            {
                                var response = (HttpWebResponse)request.GetResponse();
                                Console.WriteLine("Dataset refresh request{0}", response.StatusCode.ToString());
                            }
                        }
                    }//end for(int index=0; index< reports.Value.Count; index++)
                    return reportDetailsList;
                }
            }
            catch (HttpOperationException exc)
            {
                result.ErrorMessage = string.Format("Status: {0} ({1})\r\nResponse: {2}\r\nRequestId: {3}", exc.Response.StatusCode, (int)exc.Response.StatusCode, exc.Response.Content, exc.Response.Headers["RequestId"].FirstOrDefault());
            }
            catch (Exception exc)
            {
                result.ErrorMessage = exc.ToString();
            }

Any ideas why I am getting this error? How to fix this issue?


Viewing all articles
Browse latest Browse all 17916

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>