C# PowerBI API |导入PBIX
我有一种方法可以将.PBIX文件上载到我的PowerBI应用程序,该方法会按预期返回一个id。但是,报告和数据集不会出现在PowerBI上 我的方法:C# PowerBI API |导入PBIX,c#,powerbi,C#,Powerbi,我有一种方法可以将.PBIX文件上载到我的PowerBI应用程序,该方法会按预期返回一个id。但是,报告和数据集不会出现在PowerBI上 我的方法: public static string SendFile() { string[] files = { "D://David/Documents//PBIX_TEST.pbix" }; string boundary = "-----------------------
public static string SendFile()
{
string[] files = { "D://David/Documents//PBIX_TEST.pbix" };
string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("https://api.powerbi.com/beta/myorg/imports?datasetDisplayName=PBI_TESTT");
httpWebRequest.ContentType = "multipart/form-data; boundary=" + boundary;
httpWebRequest.Method = "POST";
httpWebRequest.KeepAlive = true;
//httpWebRequest./*Credentials*/ = System.Net.CredentialCache.DefaultCredentials;
httpWebRequest.Headers.Add("Authorization", String.Format("Bearer {0}", nsToken.TokenSingleton.Instance.token.AccessToken));
Stream memStream = new System.IO.MemoryStream();
byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
string formdataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}";
string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n Content-Type: application/octet-stream\r\n\r\n";
memStream.Write(boundarybytes, 0, boundarybytes.Length);
for (int i = 0; i < files.Length; i++)
{
string header = string.Format(headerTemplate, "fieldNameHere", "PBIX_TEST.pbix");
//string header = string.Format(headerTemplate, "uplTheFile", files[i]);
byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
memStream.Write(headerbytes, 0, headerbytes.Length);
FileStream fileStream = new FileStream(files[i], FileMode.Open,
FileAccess.Read);
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
memStream.Write(buffer, 0, bytesRead);
}
memStream.Write(boundarybytes, 0, boundarybytes.Length);
fileStream.Close();
}
httpWebRequest.ContentLength = memStream.Length;
Stream requestStream = httpWebRequest.GetRequestStream();
memStream.Position = 0;
byte[] tempBuffer = new byte[memStream.Length];
memStream.Read(tempBuffer, 0, tempBuffer.Length);
memStream.Close();
requestStream.Write(tempBuffer, 0, tempBuffer.Length);
requestStream.Close();
try
{
WebResponse webResponse = httpWebRequest.GetResponse();
Stream stream = webResponse.GetResponseStream();
StreamReader reader = new StreamReader(stream);
string var = reader.ReadToEnd();
var jsonSerializer = new JavaScriptSerializer();
var dataset = (dataset)jsonSerializer.Deserialize(var, typeof(dataset));
return dataset.Id;
}
catch (Exception ex)
{
throw ex;
}
httpWebRequest = null;
}
公共静态字符串SendFile()
{
string[]files={“D://David/Documents//PBIX_TEST.PBIX”};
字符串边界=“------------------------------------”+DateTime.Now.Ticks.ToString(“x”);
HttpWebRequest HttpWebRequest=(HttpWebRequest)WebRequest.Create(“https://api.powerbi.com/beta/myorg/imports?datasetDisplayName=PBI_TESTT");
httpWebRequest.ContentType=“多部分/表单数据;边界=“+boundary;
httpWebRequest.Method=“POST”;
httpWebRequest.KeepAlive=true;
//httpWebRequest./*凭据*/=System.Net.CredentialCache.DefaultCredentials;
httpWebRequest.Headers.Add(“Authorization”,String.Format(“Bearer{0}”,nsToken.TokenSingleton.Instance.token.AccessToken));
Stream memStream=new System.IO.MemoryStream();
byte[]boundarybytes=System.Text.Encoding.ASCII.GetBytes(“\r\n--”+boundary+”\r\n”);
字符串formdataTemplate=“\r\n--“+boundary+”\r\n内容处理:表单数据;名称=\“{0}\”;\r\n\r\n{1}”;
string headerTemplate=“内容处置:表单数据;名称=\”{0}\“文件名=\”{1}\“\r\n内容类型:应用程序/八位字节流\r\n\r\n”;
memStream.Write(boundarybytes,0,boundarybytes.Length);
for(int i=0;i
有人能帮我吗
谢谢
大卫·阿尔马斯
PT-PT如果您确实获得了…/imports/{import id you received},它将返回数据集的id,并在创建完成后报告。如果您确实获得了…/imports/{import id you received},创建完成后,它将返回数据集的ID并报告。我认为您的解决方案是正确的。我在编写解决方案时使用了它,它使用HttpClient方法 这个参数不是很具体,但是dataSetDisplayName查询字符串参数是必需的,我知道您已经完成了 此外,API文档没有提到它,但是这里支持组。这是我的代码,它按预期工作
public async Task<UploadFileResponse> UploadImportAsync(string displayName, Guid? groupId = null, ConflictInstruction conflictInstruction = ConflictInstruction.None)
{
if (string.IsNullOrEmpty(displayName))
throw new ArgumentNullException(nameof(displayName), "Display name cannot be null");
await AcquireTokenAsync();
string url = "https://api.powerbi.com/beta/myorg/imports/?dataSetDisplayName=" + HttpUtility.UrlEncode(displayName);
if (groupId.HasValue)
{
url = string.Concat("https://api.powerbi.com/beta/myorg/groups/", groupId, "/imports/?datasetDisplayName=", displayName);
}
if (conflictInstruction != ConflictInstruction.None)
{
url += "&nameConflict=" + conflictInstruction;
}
//just a test file
byte[] bytes = File.ReadAllBytes(@"C:\Users\chris\Documents\Power BI\FarmData.pbix");
string fileName = "Myfile.pbix";
var result = await PerformFileUploadAsync(url, bytes, fileName);
UploadFileResponse uploadFileResponse = JsonConvert.DeserializeObject<UploadFileResponse>(result, serializerSettings);
return uploadFileResponse;
}
public async Task UploadImportAsync(字符串显示名称,Guid?groupId=null,ConflictInstruction=ConflictInstruction.None)
{
if(string.IsNullOrEmpty(displayName))
抛出新ArgumentNullException(nameof(displayName),“显示名称不能为null”);
等待AcquireTokenAsync();
字符串url=”https://api.powerbi.com/beta/myorg/imports/?dataSetDisplayName=“+HttpUtility.UrlEncode(显示名称);
if(groupId.HasValue)
{
url=string.Concat(“https://api.powerbi.com/beta/myorg/groups/,groupId,“/imports/?datasetDisplayName=”,displayName);
}
if(conflictInstruction!=conflictInstruction.None)
{
url+=“&nameConflict=“+conflictInstruction;
}
//只是一个测试文件
byte[]bytes=File.ReadAllBytes(@“C:\Users\chris\Documents\Power BI\FarmData.pbix”);
字符串fileName=“Myfile.pbix”;
var result=等待PerformFileUploadAsync(url、字节、文件名);
UploadFileResponse UploadFileResponse=JsonConvert.DeserializeObject(结果,SerializeSettings);
返回uploadFileResponse;
}
然后是过程中的肉:
private async Task<string> PerformFileUploadAsync(string url, byte[] bytes, string fileName)
{
using (HttpClient client = new HttpClient())
{
using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url))
{
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authenticationResult.AccessToken);
request.Headers.Add("Keep-Alive", "true");
request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/json"));
string boundary = string.Concat("---------------------------", DateTime.Now.Ticks.ToString("x", CultureInfo.InvariantCulture));
MultipartFormDataContent requestContent = new MultipartFormDataContent(boundary);
ByteArrayContent byteArrayContent = new ByteArrayContent(bytes);
byteArrayContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/x-zip-compressed");
byteArrayContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { Name = "file0", FileName = fileName };
requestContent.Add(byteArrayContent);
request.Content = requestContent;
try
{
HttpResponseMessage response = await client.SendAsync(request);
var responseData = await response.Content.ReadAsStringAsync();
if (response.IsSuccessStatusCode)
return responseData;
StringBuilder sb = new StringBuilder();
sb.AppendLine("Url:" + url);
sb.AppendLine("Method: " + HttpMethod.Post);
sb.AppendLine("HttpStatusCode: " + (int)response.StatusCode);
sb.AppendLine("Unable to retrieve data from service: " + responseData);
Log.Error(sb.ToString());
throw new HttpException((int)response.StatusCode, responseData);
}
catch (Exception ex)
{
Console.Write(ex.Message);
throw;
}
}
}
}
专用异步任务PerformFileUploadAsync(字符串url,字节[]字节,字符串文件名)
{
使用(HttpClient=new HttpClient())
{
使用(HttpRequestMessage请求=新的HttpRequestMessage(HttpMethod.Post,url))
{
request.Headers.Authorization=新的AuthenticationHeaderValue(“承载者”,authenticationResult.AccessToken);
request.Headers.Add(“Keep-Alive”、“true”);
request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse(“application/json”);
字符串边界=字符串