How can I send or get a file through rest api - c#

How can I move a file (for example: in pdf format) that is in a folder with me locally through an api call in a folder in a document management system?
This is a small cod section of the api call that takes over the task.
client = new RestClient("http://***.***.***.*");
client.Authenticator = new HttpBasicAuthenticator("******", "******");
client.Timeout = -1;
request = new RestRequest("/*****/api/*****/*****/371 ", Method.POST);
request.AddHeader("content-type", "multipart/form-data");
request.AlwaysMultipartFormData = true;
request.AddParameter("Object", "{" +
"\"****\":\"*****\"," +
"\"name\":\"*******\"," +
"\"******\":\"2\"," +
"\"fields\":{" +
"\"*******\":{\"value\":\"" + DateTime.Now.ToString("dd.MM.yyyy") + "\"}" +
"}" +
"}");
request.AddFile("File", "C:/Users/********/Documents/****/*****/pdf.pdf");
response = client.Execute(request);
Console.WriteLine(response.Content);
}
}
}
I would have to obscure a few places with stars
Thank You

Related

Empty value returned by RestSharp

The code block below returns me a emtpy value. But when I send a request on the postman side, the data reaches me without any problems. What do you think is the problem? Could you help? Thank you.
Code:
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var client = new RestClient("url");
client.Timeout = -1;
var request = new RestRequest(Method.GET);
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Authorization", "Basic mytoken");
var body = #"{" + "\n" +
#" ""size"": 1," + "\n" +
#" ""page"": 1," + "\n" +
#" ""start_date"": ""2022-01-02""," + "\n" +
#" ""end_date"": ""2022-01-03""" + "\n" +
#"}";
request.AddParameter("application/json", body, ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
MessageBox.Show(response.Content);
REST Return Emtpy Value
Try using AddJsonBody(), Instead of AddParameter() with anonymous object
//Kindly check the type of start_date and end_date property.
var body = new { Size = 1, Page = 1, start_date="2022-01-02", end_date="2022-01-03"};
request.AddJsonBody(body);
From Documentation:
AddParameter("application/json", ..., ParameterType.RequestBody) won't work, use AddBody() instead, or better, AddJsonBody

Unauthorized HTTP request .NET

I'm trying to make HTTP request with Bearer authorization. I have a token, token is valid. Tried to do it 3 different ways: App, that request must be implemented in, POSTMAN, console app with a code generated with POSTMAN (C# - RestSharp) from the same POSTMAN call:
App POST method:
public async Task<TResponse> Post<TRequest, TResponse>(string requestUri, TRequest data)
{
LogInit(requestUri, HttpMethod.Post, data);
using (var request = new HttpRequestMessage(HttpMethod.Post, requestUri))
{
var token = await GetToken(_httpClient);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token.AccessToken);
request.Content = new StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json");
using (var response = await _httpClient.SendAsync(request))
{
if (!response.IsSuccessStatusCode)
{
throw await HandleErrorResponse(response);
}
var responseObj = await response.Content.ReadAsJsonAsync<TResponse>();
return responseObj;
}
}
}
Console POST method:
static void Main(string[] args)
{
var client = new RestClient("http://***");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer xxx");
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Cookie", "ARRAffinity=xxx");
var body = #"{
" + "\n" +
#" ""amisPersonId"": ***,
" + "\n" +
#" ""name"": ""***"",
" + "\n" +
#" ""surname"": ""***"",
" + "\n" +
#" ""personalCode"": ""***"",
" + "\n" +
#" ""email"": ""***"",
" + "\n" +
#" ""phoneNumber"": ""***""
" + "\n" +
#"}";
request.AddParameter("application/json", body, ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
}
Requests tracked with debugger:
App request
Console app request
POSTMAN request
POSTMAN gets 200/400 reponses, App and Console app gets 401 (Unauthorized). BOTH Apps are .NET CORE apps.
assuming that you have correct token.AccessToken ,try to replace
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token.AccessToken);
with
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.AccessToken);

wrong format of json string in an api call?

I try to bring the pdf file into a standard software, wrote the code, an exception is issued because of wrong format with json although json string corresponds exactly to the specified json of api call of standard software. can you please take a look if I wrote something wrong here or if I forgot something?
I covered some information with a star
Many Thanks
IRestResponse response3;
client = new RestClient("http://***.***.***.*");
client.Authenticator = new HttpBasicAuthenticator("********", "*********");
client.Timeout = -1;
request = new RestRequest("/*****/api/******/*****/***", Method.POST);
request.AddHeader("content-type", "multipart/form-data");
request.AlwaysMultipartFormData = true;
request.AddParameter("Object", "{" +
"\"cabinet\":\"Posteingang\"," +
"\"name\":\"Posteingang\"," +
"\"objectTypeId\":\"2\"," +
"\"fields\":{" +
"\"Datum\":{\"value\":\"" + DateTime.Now.ToString("dd.MM.yyyy") + "\"}" +
"}" +
"}");
request.AddFile("file","C:/Users/*********/Documents/*********/Org.pdf","Org.pdf");
MultipartFormDataContent multipartForm = new MultipartFormDataContent();
byte[] file_bytes = File.ReadAllBytes("C:/Users/********/Documents/********/Org.pdf");
multipartForm.Add(new ByteArrayContent(file_bytes, 0, file_bytes.Length), "profile_pic", "hello1.jpg");
multipartForm.Add(new StringContent("Object"), "{" +
"\"cabinet\":\"Posteingang\"," +
"\"name\":\"Dokument\"," +
"\"objectTypeId\":\"******\"," +
"\"fields\":{" +
"\"Datum\":{\"MAIL_SUBMIT_TIME\":{\"value\":\"" + DateTime.Now.ToString("dd.MM.yyyy") + "\"},\"Typ\":" +
"{\"feld4\":{\"value\": \"Brief\"}},\"Absender\": {\"Mail_FROM\":{\"value\": \"*********\"}}}}}");
response3 = client.Execute(request);
Console.WriteLine(response3.Content);
}
}
}

Uploading an image to a BIM 360 project using .NET

How do you upload an image to a BIM 360 Project using .NET? I have successfully been able to upload an image to a BIM 360 Project using Postman but when using the same code to perform the same function I get an error message saying:
"{\"code\":1001,\"message\":\"image has contents that are not what they are reported to be; image_content_type is invalid; \"}"
The code I used inside of .NET is the following:
var client3 = new RestClient("https://developer.api.autodesk.com/hq/v1/accounts/" + accountId + "/projects/" + targetProject + "/image");
var request3 = new RestRequest(Method.PATCH);
request3.AddHeader("cache-control", "no-cache");
request3.AddHeader("Authorization", "Bearer " + bearer.access_token);
request3.AddHeader("Content-Type", "multipart/form-data");
request3.AddHeader("content-type", "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW");
request3.AddParameter("multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW",
"------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"chunk\"; filename=\"C:\\Users\\Nathan\\Desktop\\logo.png\"\r\n" +
"Content-Type: image/png\r\n\r\n\r\n" +
"------WebKitFormBoundary7MA4YWxkTrZu0gW\r\n" +
"Content-Disposition: form-data; name=\"type\"\r\n\r\nimage/png\r\n" +
"------WebKitFormBoundary7MA4YWxkTrZu0gW--",
ParameterType.RequestBody);
IRestResponse response3 = client3.Execute(request3);
string updatedProjectImage = response3.Content;
I used the source code here as a reference to create a PrepareRequest() function that performs all my requests. The parameters I used to complete the function are as follows:
string updatedProjectImage = PrepareRequest(
"https://developer.api.autodesk.com/hq/v1/accounts/" + accountId + "/projects/" + targetProjectId + "/image",
Method.PATCH,
new Dictionary<string, string>(),
null,
headerParams,
formParams,
fileParams,
new Dictionary<string, string>(),
"multipart/form-data");
headerParams: "Authorization", "Bearer " + bearer.access_token
formParams: "type", "image/png" (Format can change depending on the image)
fileParams: "file", fileParam
fileParam:
FileParameter fileParam = FileParameter.Create(
"chunk",
GetBytesFromFile(fileName),
Path.GetFileName(fileName),
"multipart/form-data");`
(A reference to how the GetBytesFromFile() function was made can be found in the source code. Lastly fileName includes the full address path).

.ics Calendar. Appointment Via Email API Emailing Method

Hello every one I am creating a system that creates a event like an Appointment.Then it sends it to a receiver via Email using This method
It creates a Calendar like this.
string[] contents = { "BEGIN:VCALENDAR",
"PRODID:-//Flo Inc.//FloSoft//EN",
"BEGIN:VEVENT",
"DTSTART:" + schBeginDate.ToUniversalTime().ToString("yyyyMMdd\\THHmmss\\Z"),
"DTEND:" + schEndDate.ToUniversalTime().ToString("yyyyMMdd\\THHmmss\\Z"),
"LOCATION:" + schLocation,
"ORGANIZER:" + "Haseeb",
"DESCRIPTION;ENCODING=QUOTED-PRINTABLE:" + schDescription,
"SUMMARY:" + schSubject, "PRIORITY:3",
"END:VEVENT", "END:VCALENDAR" };
System.IO.File.WriteAllLines(Server.MapPath("Calendar's//" + txtCelenderName.Text + ".ics"),
contents);
It works all good and sends Email but every time it creates a Event it downloads a file which is a big data a company with 400 users and meetings with customers is going to be over load. Is there any other method to send Calendar reminders without saving it into a path.
This is how i send the Attachment.
RestClient client = new RestClient();
client.BaseUrl = new Uri("https://api.mailgun.net");
client.Authenticator = new HttpBasicAuthenticator("api", "key-key");
RestRequest request = new RestRequest();
request.AddParameter("domain", "email.com", ParameterType.UrlSegment);
request.Resource = "{domain}/messages";
if (!string.IsNullOrEmpty(sFromAlias))
request.AddParameter("from", sFromAlias + " <" + sFrom + ">");
else
request.AddParameter("from", "<" + sFrom + ">");
request.AddParameter("subject", sSubject);
request.AddParameter("html", sBody);
request.AddFile("attachment", Path, "text/calendar"); // This is the Celender that goes along the Email
request.Method = Method.POST;

Categories

Resources