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);
}
Related
I am attempting to update the RestSharp file download portion code in one of my applications. Apparently the .SaveAs() is being depricated, so I'm trying to follow their updated example for working with files. However, my response is always null, and the temp file that is created doesn't seem to be filled with the data I'm attempting to save.
Here's what I have so far:
var tempFile = Path.GetTempFileName();
using var writer = File.OpenWrite(tempFile);
var client = new RestClient("https://provider-api.spotify.com/v1/analytics");
var request = new RestRequest("{licensor}/enhanced/tracks/{year}/{month}/{day}", Method.GET);
request.AddHeader("Authorization", $#"Bearer {token}");
request.AddUrlSegment("licensor", "licensor_name");
request.AddUrlSegment("year", 2021);
request.AddUrlSegment("month", 1);
request.AddUrlSegment("day", 10);
var checkResponse = client.Execute<SpotifyTracksResourceModel>(request);
if (checkResponse.Content == "")
{
Console.WriteLine("No data");
}
request.ResponseWriter = responseStream =>
{
using (responseStream)
{
responseStream.CopyTo(writer);
}
};
var response = client.DownloadData(request);
I threw in the checkResponse code to ensure that I am actually getting data back, and I am in fact getting data. But as I said, once it gets to the var response = ... line, it comes back NULL, and nothing has been written to that temp file.
Thank you in advance for any help with this!
So it ended up being a combination of a few little things I needed to tweak. But the biggest things were updating the RestSharp NuGet package, and closing off the writer FileStream.
var tempFile = Path.GetTempFileName();
using var writer = File.OpenWrite(tempFile);
var client = new RestClient("https://provider-api.spotify.com/v1/analytics");
var request = new RestRequest("{licensor}/enhanced/tracks/{year}/{month}/{day}", DataFormat.Json)
.AddUrlSegment("licensor", "licensor_name")
.AddUrlSegment("year", "2021")
.AddUrlSegment("month", "1")
.AddUrlSegment("day", "10");
spotifyRequest.AddHeader("Authorization", $#"Bearer {token}");
var checkResponse = spotifyClient.Get<SpotifyTracksResourceModel>(spotifyRequest);
request.ResponseWriter = responseStream =>
{
using (responseStream)
{
responseStream.CopyTo(writer);
}
};
var response = client.DownloadData(request);
writer.Close();
I have write a mail sending functionality using sendGrid in c#. It works properly but when attaching the generated pdf as attachement, it's not working.
var client = new SendGridClient(apiKey);
var msg = new SendGridMessage()
{
From = new EmailAddress(senderMailID, senderName),
Subject = "ABCD",
};
var attach = new Attachment();
attach.Filename = "ABC.pdf";
attach.Content = "~/Templates/output.pdf";
msg.AddAttachment(attach);
msg.AddTo(new EmailAddress(receiverMailID,receiverName));
var result = await client.SendEmailAsync(msg);
}
You should be converting the file to a base64 representation (as seen in examples here) of the file rather than adding a path to it.
A sample of the code needed:
var client = new SendGridClient(apiKey);
var msg = new SendGridMessage()
{
From = new EmailAddress(senderMailID, senderName),
Subject = "ABCD",
};
var bytes = File.ReadAllBytes("~/Templates/output.pdf");
var file = Convert.ToBase64String(bytes);
msg.AddAttachment("ABC.pdf", file);
var response = await client.SendEmailAsync(msg);
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.
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);
I've read the S3 documentation several times and I'm adding metadata to an S3 object with this code...
PutObjectRequest titledRequest = new PutObjectRequest();
titledRequest.WithTimeout(3600000)
.WithMetaData("outputfolder", outputFolder)
.WithBucketName(AWS_BUCKET_NAME)
.WithKey(objectKey)
.WithAutoCloseStream(true)
.WithInputStream(fs);
When reading the object from the S3 bucket I'm using this code....
string outputFolder = response.Metadata["x-amz-meta-outputfolder"];
But I'm getting an empty string every time even though the outputFolder variable definitely has a value.
Am I doing something really silly wrong here? As far as I can tell this is consistent with the documentation
string outputFolder = response.Metadata["outputfolder"];
will do.
use this instead of reading the meta from putobject response
GetObjectMetadataRequest request = new GetObjectMetadataRequest()
.WithKey("Key")
.WithBucketName("");
GetObjectMetadataResponse response = s3Client.GetObjectMetaData(request);
response."choose properety to retrieve"
hope this may help
Codes verified to work.
// upload & add outputfolder to metadata
var S3Client = new AmazonS3Client();
var Request = new PutObjectRequest {
BucketName = bucketname,Key = S3Name,FilePath = Filepath };
Request.Metadata.Add("outputfolder",#"C:\test");
PutObjectResponse Response = S3Client.PutObject(Request);
// download and retrieve metadata
var S3Client = new AmazonS3Client();
var Request = new GetObjectRequest { BucketName = bucketname,Key = S3Name };
GetObjectResponse Response = S3Client.GetObject(Request);
// this works
string outputFolder = Response.Metadata["x-amz-meta-outputfolder"];
// so does this - no need for the x-amz-meta- prefix
string outputFolder = Response.Metadata["outputfolder"];