How do I delete a video in my Vimeo account using the Vimeo API using C# in .Net Core?
The following works if you have a Vimeo account (at least it works at the Plus level and above) and have created an app, given that app permission to delete, gotten an access token for that app, and have a video number for the video you want to delete.
Within a class put the following code:
HttpClient httpClient = new HttpClient();
public async Task deleteVideo(string videoNumber, string accessToken)
{
try
{
string vimeoApiUrl = "https://api.vimeo.com/videos/" + videoNumber; // Vimeo URL
var body = "{}";
HttpContent content = new StringContent(body);
using (var requestMessage = new HttpRequestMessage(HttpMethod.Delete, vimeoApiUrl))
{
requestMessage.Headers.Authorization =
new AuthenticationHeaderValue("Bearer", accessToken);
requestMessage.Headers.Add("Accept", "application/vnd.vimeo.*+json;version=3.4");
requestMessage.Headers.Add("ContentType", "application/x-www-form-urlencoded");
requestMessage.Content = content;
var response = await httpClient.SendAsync(requestMessage).ConfigureAwait(false);
response.EnsureSuccessStatusCode();
}
}
catch (Exception err)
{
var errMessage = err.Message;
Console.WriteLine("In deleteVideo() error: " + err.Message);
}
}
To call it from within that class:
await deleteVideo(videoNumber, accessToken).ConfigureAwait(false);
Related
Im trying to make a Discord C# Command That uses Discords new Timeout function using discord.NET
I tried using HTTP Requests instead cause i couldnt find a discord.NET function but It returns an unauthorized error
public static async Task PatchData(string url, string data, string token)
{
// Create a new HttpClient instance
using var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Authorization",token);
httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
var content = new StringContent(data, Encoding.UTF8, "application/json");
var response = await httpClient.PatchAsync(url, content);
if (response.IsSuccessStatusCode)
{
Console.WriteLine("Data patched successfully!");
}
else
{
Console.WriteLine(response.StatusCode);
}
}
and for the execution
await Patch.PatchData($"https://discord.com/api/v9/guilds/{Context.Guild.Id}/members/{user.Id}",
"{\"communication_disabled_until\": "
+ current_time + time_in_minutes + "}",botToken);
Im trying to connect to an API and get the data from the "User" table so that the credentials can be authenticated. However after executing GetAsync() the app stucks in a deadlock and doesnt do anything. I have tested the API with postman and it works.
public async Task<User> UserCredentialsGet(string name, string password)
{
var user = new User();
HttpClient client = new HttpClient();
string url = "https://xxx.xxx.xxx.xxx:xxxx/api/Users/username=" + name + "/" + "password=" + password ;
Uri uri = new Uri(url);
try
{
var response = await client.GetAsync(uri).ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
string content = response.Content.ReadAsStringAsync().Result;
user = JsonConvert.DeserializeObject<User>(content);
}
}
catch (Exception ex)
{
}
return user;
//return await Task.FromResult(user);
}
GetAsync is Idisposable so try to use something like
`using (HttpClient client = new HttpClient())
{
using (HttpResponseMessage response = await client.GetAsync(uri, cancellationToken))
{
var stringResponse = await response.Content.ReadAsStringAsync();
//todo process response
}
}
`
For me it works fine.
Do not for forget await response
So I am following Linkedin Documentation for implementing Create Image Share on Linkedin.
The documentation lists three steps:
Register your image to be uploaded.
Upload your image to LinkedIn.
Create the image share.
While I am able to do the first step to get the uploadUrl, I am getting 400 response error with blank error message while doing step 2.
The documentation list the second step as:
curl -i --upload-file /Users/peter/Desktop/superneatimage.png --header "Authorization: Bearer redacted" 'https://api.linkedin.com/mediaUpload/C5522AQGTYER3k3ByHQ/feedshare-uploadedImage/0?ca=vector_feedshare&cn=uploads&m=AQJbrN86Zm265gAAAWemyz2pxPSgONtBiZdchrgG872QltnfYjnMdb2j3A&app=1953784&sync=0&v=beta&ut=2H-IhpbfXrRow1'
Here's my step 2 in C# code:
private bool UploadImageBinaryFile(RequestUploadUrlResponse uploadDetails)
{
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", #access_token#);
client.DefaultRequestHeaders.Add("X-Restli-Protocol-Version", "2.0.0");
MultipartFormDataContent form = new MultipartFormDataContent();
string fileAddress = image_path + "image.png";
byte[] fileBytes = File.ReadAllBytes(fileAddress);
string name = "upload-file";
form.Add(new ByteArrayContent(fileBytes), name);
HttpResponseMessage response = client.PutAsync
(
uploadDetails.value.uploadMechanism.mediaUploadHttpRequest.uploadUrl,
form
).Result;
if (response.IsSuccessStatusCode)//<--getting 400 error Bad Request here
{
string responseBody = response.Content.ReadAsStringAsync().Result;
return true;
}
else
{
ErrorResponseHandler(response.Content.ReadAsStringAsync().Result);
return false;
}
}
}
I have ensured that I was successfully able to the uploadUrl from the first step. And when I used the URL https://api.linkedin.com/v2/assets/#id# to check the status, I was able the see the status as WAITING_UPLOAD.
Where am I going wrong?
I found the solution, basically we have to pass the binary in the content only, whereas I was passing it in the form.
using (HttpClient client = new HttpClient())
{
try
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accesstoken);
var content = new ByteArrayContent(File.ReadAllBytes(fileAddress));
HttpResponseMessage response = client.PutAsync(url, content).Result;
if (response.IsSuccessStatusCode)
{
//response is empty. Have to call the checkAssetStatus to see if the asset is 'AVAILABLE'
string responseBody = response.Content.ReadAsStringAsync().Result;
}
else
{
//handleError();
}
}
catch (HttpRequestException ex)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ", ex.Message);
}
}
I am trying to create a C# console application to download project details from a website which supports REST OAuth 2.0. How do I make a request/response call to the website using the Access Token?
Here is my code:
public string token = "4bjskfa2-b37d-6244-8413-3358b18c91b6";
public async Task GetProjectsAsync()
{
try
{
HttpClient client = new HttpClient();
var projects = "https://app.rakenapp.com/api/v2/projects?" + token;
client.CancelPendingRequests();
HttpResponseMessage output = await client.GetAsync(projects);
if (output.IsSuccessStatusCode)
{
string response = await output.Content.ReadAsStringAsync();
project proj = JsonConvert.DeserializeObject<project>(response);
if (proj != null)
{
Console.WriteLine(proj.name); // You will get the projects here.
}
}
}
catch (Exception ex)
{
//catching the exception
}
}
you need to add a header to your request:
string url = "https://app.rakenapp.com/api/v2/projects";
using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authorizationToken);
HttpResponseMessage response = await httpClient.GetAsync(url);
var contents = await response.Content.ReadAsStringAsync();
var model = JsonConvert.DeserializeObject<project>.contents);
return model;
}
UPDATE 1
I think I am using incorrect URL, this doc says to use "https://www.googleapis.com/drive/v2/files" & this doc says to use "https://www.googleapis.com/upload/drive/v2/files?uploadType=multipart". Though I am getting same 400 bad request.
Can I use Google Drive upload REST API in background uploader class?
I am following this doc from Google Drive to upload files but I am getting 400 - Bad request. What's wrong with my code?
public static async Task UploadFileAsync(Token AuthToken, StorageFile file, DriveFile objFolder)
{
try
{
if (!httpClient.DefaultRequestHeaders.Contains("Authorization"))
{
httpClient.DefaultRequestHeaders.Add("Authorization", AuthToken.TokenType + " " + AuthToken.AccessToken);
}
var JsonMessage = JsonConvert.SerializeObject(objFolder);
/*JsonMessage = {"title":"c4611_sample_explain.pdf","mimeType":"application/pdf","parents":[{"id":"root","kind":"drive#fileLink"}]}*/
var JsonReqMsg = new StringContent(JsonMessage, Encoding.UTF8, "application/json");
var fileBytes = await file.ToBytesAsync();
var form = new MultipartFormDataContent();
form.Add(new ByteArrayContent(fileBytes));
form.Add(JsonReqMsg);
form.Headers.ContentType = new MediaTypeHeaderValue("multipart/related");
var UploadReq = await httpClient.PostAsync(new Uri("https://www.googleapis.com/drive/v2/files?uploadType=multipart"), form);
if (UploadReq.IsSuccessStatusCode)
{
var UploadRes = await UploadReq.Content.ReadAsStringAsync();
}
else
{
}
}
catch (Exception ex)
{
}
}
You must use https://www.googleapis.com/upload/drive/v2/files
I have a working sample here (sorry, the JSON string is hard coded):
// Multipart file upload
HttpClient client = new HttpClient();
string uriString = "https://www.googleapis.com/upload/drive/v2/files?key=<your-key>&access_token=<access-token>&uploadType=multipart";
Uri uri = new Uri(uriString);
HttpContent metadataPart = new StringContent(
"{ \"title\" : \"My File\"}",
Encoding.UTF8,
"application/json");
HttpContent mediaPart = new StringContent(
"The naughty bunny ate all the cookies.",
Encoding.UTF8,
"text/plain");
MultipartContent multipartContent = new MultipartContent();
multipartContent.Add(metadataPart);
multipartContent.Add(mediaPart);
HttpResponseMessage response = await client.PostAsync(uri, multipartContent);
string responseString = await response.Content.ReadAsStringAsync();