Google drive api, wont upload async - c#

I am using Google.Apis.Drive.v3 to manage some files. My problem is I can only upload files the sync way.
This async upload just wont upload the file:
var service = GetService(i_user_credential, i_application_name);
var fileMetadata = new Google.Apis.Drive.v3.Data.File();
fileMetadata.Name = i_file_name;
fileMetadata.Parents = new List<string> { i_folder_id };
FilesResource.CreateMediaUpload request;
CancellationToken ctsUpload = new CancellationToken();
using (var stream = new System.IO.FileStream(i_file_path, System.IO.FileMode.Open))
{
request = service.Files.Create(
fileMetadata, stream, i_file_type);
request.Fields = "id";
request.UploadAsync(ctsUpload);
}

This is what you want:
await request.UploadAsync(ctsUpload);

Related

Getting Some Randam ID when Sending a file using MultipartContent() and HttpClient

I am trying to send a file via an API. I was able to receive the file in my API, but for some reason I am seeing random ID(could be content id) when I read the content in my API.
Previously I was using seeing info about content type and file info as well. I was using MultipartFormDataContent() at that time, then I switched to MultipartContent(). Now the content type and file info is gone, but I still see the id at the start and end of the content.
Code that I am using to send file
using (var formContent = new MultipartContent())
{
byte[] fileByteArray;
using (var binaryReader = new BinaryReader(file.OpenReadStream()))
{
fileByteArray = binaryReader.ReadBytes((int)file.Length);
}
var content = new ByteArrayContent(fileByteArray, 0, fileByteArray.Length);
formContent.Add(content);
// Add the file and it's content
formContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(file.ContentType);
formContent.Headers.ContentType.CharSet = string.Empty;
formContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("form-data");
HttpClient httpClient = new HttpClient();
var task = Task.Run(() => httpClient.PostAsync("MY_END_POINT", formContent));
task.Wait();
HttpResponseMessage response = task.Result;
response.EnsureSuccessStatusCode();
}
Code to read file
using (StreamReader reader = new StreamReader(fileUpload.FileContent))
{
string content = reader.ReadToEnd();
}
Any idea on how the id can be removed?

Want to download and upload file from a folder inside the blob using new sdk - Azure.Storage.Blobs package

I want to download and upload a json file in a folder by using path and jsonContent in string for in new sdk - Azure.Storage.Blobs package. I am able to do so using old library as per below code -
UploadCode -
`public async Task<bool> UploadToBlob(string path, string jsonContentString)
{
CloudBlobContainer container = _cloudBlobClient.GetContainerReference(Constant.ContainerName);
CloudBlockBlob blockBlob = container.GetBlockBlobReference("dose/NotificationDefinition/dose_dosedailyreport.json");
await blockBlob.UploadTextAsync(jsonContentString);
return true;
}`
Download Code -
public async Task<string> GetDataFromStorage()
{
CloudBlobContainer container = _cloudBlobClient.GetContainerReference(Constant.ContainerName);
var blockBlob = container.GetBlockBlobReference("dose/NotificationDefinition/dose_dosedailyreport.json");
return await blockBlob.DownloadTextAsync();
}
Try the following code. Basically we're creating an instance of BlockBlobClient and calling it's Upload and Download method for uploading and downloading.
static void UploadDownloadTest()
{
var blobName = "dose/NotificationDefinition/dose_dosedailyreport.json";
var containerName = "test";
var connectionString = "UseDevelopmentStorage=true";
var blockBlobClient = new BlockBlobClient(connectionString, containerName, blobName);
var jsonContentString = "This is the data I wish to upload";
using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonContentString)))
{
var httpHeaders = new BlobHttpHeaders()
{
ContentType = "application/json"
};
blockBlobClient.Upload(ms, httpHeaders);
}
Console.WriteLine("Upload Successful!");
var downloadResponse = blockBlobClient.Download().Value;
using (var stream = downloadResponse.Content)
{
byte[] buffer = new byte[downloadResponse.ContentLength];
stream.Read(buffer, 0, buffer.Length);
var responseData = Encoding.UTF8.GetString(buffer);
Console.WriteLine("Blob contents....");
Console.WriteLine(responseData);
}
}

Upload video on Twitter without 3rd library

I use Hammock in the project and I want to upload videos to Twitter. I also get the "media type unrecognized" error when I try with the following code. Where part am I doing wrong?
var restClient = new Hammock.RestClient
{
Authority = "https://upload.twitter.com",
Encoding = Encoding.UTF8,
};
var restRequest = new Hammock.RestRequest
{
Credentials = credentials,
Path = "/1.1/media/upload.json",
Method = Hammock.Web.WebMethod.Post,
Encoding = Encoding.UTF8,
};
Stream stream = new MemoryStream(images);
restRequest.AddFile("media", "test", stream);
var asyncResult = restClient.BeginRequest(restRequest);
var response = restClient.EndRequest(asyncResult);
var jsonData = JsonConvert.DeserializeObject<Image>(response.Content);

How to upload a Zip File using Octokit?

How to upload a zip file using Octokit.net? I am new to Octokit.net anyone could you possible provide code snippet?
The ocktokit.net docs are quite complete, read the docs well.
This is an example from the docs:
var client = new GitHubClient(new ProductHeaderValue("my-cool-app"));
var basicAuth = new Credentials("username", "password"); // NOTE: not real credentials
client.Credentials = basicAuth;
using(var archiveContents = File.OpenRead("output.zip")) { // TODO: better sample
var assetUpload = new ReleaseAssetUpload()
{
FileName = "my-cool-project-1.0.zip",
ContentType = "application/zip",
RawData = archiveContents
};
var release = client.Repository.Release.Get("octokit", "octokit.net", 1);
var asset = await client.Repository.Release.UploadAsset(release, assetUpload);
}

Document uploaded to MS Teams using graph API gets corrupted

I am trying to upload a document to Microsoft Teams using Microsoft Graph (beta version), but the document gets corrupted after a successful upload.
Using Graph, I'm first creating an Group, creating a Team based on the Group, adding some Team Members and finally uploading a document to the default channel.
All works fine except the uploaded document gets corrupted and the Office Online editor is not able to open it. We can however download the file and open in Microsoft Word after correcting the file.
Below is the code that I'm using for document upload->
FileInfo fileInfo =
new FileInfo(#"F:\Projects\TestProjects\MSTeamsSample\MSTeamsSample\Files\Test File.docx");
var bytes = System.IO.File.ReadAllBytes(fileInfo.FullName);
var endpoint = $"https://graph.microsoft.com/beta/groups/{groupId}/drive/items/root:/General/{fileInfo.Name}:/content";
var fileContent = new ByteArrayContent(bytes);
fileContent.Headers.ContentType =
MediaTypeHeaderValue.Parse("application/octet-stream");
var requestContent = new MultipartFormDataContent();
requestContent.Add(fileContent, "File", fileInfo.Name);
var request = new HttpRequestMessage(HttpMethod.Put, endpoint);
request.Headers.Authorization =
new AuthenticationHeaderValue("Bearer", "<Access Token>");
request.Content = requestContent;
var client = new HttpClient();
var response = client.SendAsync(request).Result;
I tried changing content type to application/vnd.openxmlformats-officedocument.wordprocessingml.document but no luck. I don't understand what could be wrong here. The code is pretty straight forward, based on the this documentation. Any help will be highly appreciated.
Please try this:
var filePath = #"F:\Projects\TestProjects\MSTeamsSample\MSTeamsSample\Files\Test File.docx";
var fileName = Path.GetFileName(filePath);
var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
var endpoint = $"https://graph.microsoft.com/beta/groups/{groupId}/drive/items/root:/General/{fileName}:/content";
using (var client = new HttpClient())
{
using (var content = new StreamContent(fileStream))
{
content.Headers.Add("Content-Type", MimeMapping.GetMimeMapping(fileName));
// Construct the PUT message towards the webservice
using (var request = new HttpRequestMessage(HttpMethod.Put, endpoint))
{
request.Content = content;
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", tokenResponse.Token);
// Request the response from the webservice
using (var response = await client.SendAsync(request))
{
// Check the response.
}
}
}
}
I am able to see Word document in Microsoft Teams editor.

Categories