convert webclient.upload file to httpclient code - c#

i'm trying to convert the following code to httpclient code, webclient works fine, but i suppose it's obsolete and microsoft is recommending we moe to httpclient, it is uploading a zip file to an azure blob storage url, then another api kicks off a process to import that zip file to dynamics 365
Again, this webclient code works perfectly
using var webClient = new WebClient();
webClient.Headers.Add("Content-Type", "application/zip");
webClient.Headers.Add("x-ms-blob-type", "BlockBlob");
webClient.Headers.Add("Overwrite", "T");
webClient.UploadFile(azureWriteUrl, WebRequestMethods.Http.Put, filePath);`
i have tried this httpclient code, it uploads the file successfully, get back a 201 created, but something is not "creating" or "uploading" the zip file correctly here, as the api that consumes this uploaded file (to azure blob url) doesn't like it.
_httpClient = new HttpClient();
_httpClient.DefaultRequestHeaders.Add("x-ms-blob-type", "BlockBlob");
_httpClient.DefaultRequestHeaders.Add("Overwrite", "T");
var formContent = new MultipartFormDataContent();
using var stream = File.OpenRead(filePath);
formContent.Add(new StreamContent(stream), "testImportPackage", "testImportPackage.zip");
using var response = await _httpClient.PutAsync(azureWriteUrl, formContent);
var responseContent = response.Content.ReadAsStringAsync().Result;
The import API returns the following error:
Exception occurred while executing action ImportFromPackage on Entity DataManagementDefinitionGroup: Number of entries expected in End Of Central Directory does not correspond to number of entries in Central Directory.

Related

How do I create a System.IO.Stream from blob:https://localhost:5001/2b28e86c-fef1-482e-ae16-12466e6f729f

I'm submitting a trusted url path to my webapi and then trying to upload the image to azure-storage. The uri I have to upload includes blob:https://localhost/... Which points to a image stored locally. I need to read this stream however I'm receiving an exception on first line of code:
"The URI prefix is not recognized."
var req = System.Net.WebRequest.Create("blob:https://localhost:5001/2b28e86c-fef1-482e-ae16-12466e6f729f");
using (var stream = req.GetResponse().GetResponseStream())
{
containerClient.UploadBlob(image.guid.ToString(), stream);
}
I did a bunch more searching and discovered that only the browser can access blob: files. Ended up switching back to FormData.

C# read content of a file accessed via url into byte-array

my company is working with an Excel-file (xlsx) on Sharepoint. For my application I need the content of the file as a byte array.
When located on my local machine, I would use System.IO.File.ReadAllBytes(path).
How can I do the same with a file hosted on a server? The url is something like "https://sharepoint.com/excel.xlsx"
I tried new WebClient().DownloadData(url) but this returns something different I can't use. I think it returns the byte array of the file itself and not the content of the file.
Any ideas?
Rather than WebClient, try HttpClient:
using (var client = new HttpClient())
using (HttpResponseMessage response = await client.GetAsync("https://sharepoint.com/excel.xlsx"))
{
byte[] fileContents = await response.Content.ReadAsByteArrayAsync();
}

Issue while creating product using Shopify API

I am experiencing a weird issue while exporting some products to Shopify. When I save a JSON generated using JSON.net to txt file and then read it and then send it to Shopify's create product API, it works fine. However, if I just save the JSON to string and send post request directly, I get a 502 gateway error from Shopify. This happens only when creating certain products, where the JSON payload is somewhat bigger than normal. On other products, just saving JSON to a string and then sending to Shopify works OK. Weirdly, when I save the JSON to file from C#, then read that file a few lines below in the same code, and use that content as JSON string and send a post request, it again doesn't work. What do you think could be the issue?
Here's the JSON generated using JSON.net which works OK when read from file (https://pastebin.com/9SKFPjGJ)
var jsonContent = JsonConvert.SerializeObject(myObject);
using (var requestMessage = new HttpRequestMessage(HttpMethod.Put, $"https://{shopifySlug}.myshopify.com/admin/products/{originalShopifyProductId}.json"))
{
requestMessage.AddShopifyHeaders(shopifyAccessToken); // just a method for adding necessary shopify headers
requestMessage.Content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
response = await client.SendAsync(requestMessage);
}
Its getting hard for me to know the reason.
Here's what works:
Code that works:
json.txt was generated using this separately:
System.IO.File.WriteAllText("E:\\json.txt",JsonConvert.SerializeObject(myObject));
(Note that if the above line of code is inserted before the code below in the same file, then the code below doesn't work, i.e. the file has to be saved separately for it to work).
And then, just reading the JSON from file and sending that in the POST request works. Code below:
var jsonContent = System.IO.File.ReadAllText("E:\\json.txt");
using (var requestMessage = new HttpRequestMessage(HttpMethod.Put, $"https://{shopifySlug}.myshopify.com/admin/products/{originalShopifyProductId}.json"))
{
requestMessage.AddShopifyHeaders(shopifyAccessToken); // just a method for adding necessary shopify headers
requestMessage.Content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
response = await client.SendAsync(requestMessage);
}
Also the not working code at the very top works OK for smaller JSON payloads like this one https://pastebin.com/RhYjVuvv

Getting a list of attached documents and downloading them into local storage using Microsoft Graph API in UWP

I am developing a UWP app using Microsoft Graph API. I am getting a list of meetings for the current day for a logged in user using the below API
https://graph.microsoft.com/v1.0/me/calendarView?startDateTime=2017-06-20T20:00:00.0000000&endDateTime=2017-06-21T10:00:00.0000000
While creating the meeting , I had attached a document in the invite for the invited participants.
The JSON Response received has "hasAttachments": true,. My requirement is to download the file that were send in the invite.
I need to download those files in using my app and then attach them and send it to the participants. How can I do that?
My requirement is to download the file that were send in the invite.
It seems like you are using List calendarView API to get the events. In that case you should be able get the event "id" property of the Event resource you want from the response, please check "id": "string (identifier)".
After then, you can get all the attachments of this event by List attachments API, and get a special one attachment by Get attachment. You could get the binary contents of the attached file by contentBytes property which contains the base64-encoded contents of the file. If your attachment is fileAttachment resource type. For example, if the attachment is a .txt file, you can download it and save it in application local folder as follows:
HttpClient client = new HttpClient();
string token =await AuthenticationHelper.GetTokenForUserAsync();
client.DefaultRequestHeaders.Add("Authorization", "Bearer "+token);
HttpResponseMessage httpresponse = await client.GetAsync(new Uri("https://graph.microsoft.com/v1.0/me/events/{id}/attachments/{id}"));
StorageFile downloadedfile = await ApplicationData.Current.LocalFolder.CreateFileAsync("attachment.txt",CreationCollisionOption.ReplaceExisting);
JObject resObj = JObject.Parse(await httpresponse.Content.ReadAsStringAsync());
string contentbyte = resObj["contentBytes"].ToString();
await FileIO.WriteTextAsync(downloadedfile, Encoding.UTF8.GetString(Convert.FromBase64String(contentbyte)));
Update:
If the attachment is not a .txt, what actually needed is correctly transfer the base64-encode contents to file, for example:
StorageFile downloadedfile = await ApplicationData.Current.LocalFolder.CreateFileAsync("attachment.xlsx", CreationCollisionOption.ReplaceExisting);
string contentbyte = "contentbyte";
byte[] filecontent = Convert.FromBase64String(contentbyte);
await FileIO.WriteBytesAsync(downloadedfile, filecontent);

HttpClient upload file without multipart in .net

I am using HttpCilent (System.Net.Http). What I am seeing is, there is no way to post a file content in request body. I have to use multipart content to add file there and upload. The api I am calling does not support multipart file content and I have to put file content in the request body itself. Along with file, I do need to add access token and other client data(json). Is there anyway here that I can supply the filebytes along with access token and other cilent data (json)?
var client = new HttpClient
{
BaseAddress = new Uri(endpoint);
};
var result = await client.PostAsync("api/storage/upload?fileName=test.csv", fileBytes);

Categories