Uploading an image to a BIM 360 project using .NET - c#

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).

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

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);
}
}
}

How can I send or get a file through rest api

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

DocuSign API test demo - Faild to login demo

I try run the c# Hello world sample in visual studio - I'm jost trying the free DSA demo.
https://github.com/docusign/docusign-signature-appliance-api-recipes/blob/master/dsa-rest/Hello-World-examples/DSARestCsharpSample/Program.cs
I don't know if the parameters of :
dsa-user-password
dsa-user-name
When I change them to my username and password (username = email address??)
the response content is :
"Message: "Failed to login, check username, password and domain.",
"Module":"SAPIWS", "Code":-20, "InnerCode":-1878916813
maybe also need to change :
baseURL
resourcePath
What data should I put ??
According to your description, you want to run the DocuSign API test demo successfully.
I suggest that you register a new DSA account, it is not recommended to use the test account.
Registration link: https://go.docusign.com/signup/dsa-developer/
You can try the following codeļ¼š
Note://D:\\work\\PurchaseOrder.pdf is a self-created pdf
//D:\\work\\PurchaseOrder.DSA-REST-SIGNED.pdf code is generated pdf
static void Main(string[] args)
{
String baseURL = "https://prime-dsa-devctr.docusign.net:8081";
String resourcePath = "sapiws/v1/digital_signature";
String apiUrl = baseURL + "/" + resourcePath;
var client = new RestClient(apiUrl);
var request = new RestRequest(Method.PUT);
request.AddHeader("content-type", "application/json");
request.AddHeader("authorization", "Basic " + DSABasicAuthorizationString("Vtestdemo1#hotmail.com", "testpwd12"));
// "digital_signature" request body as Json formated String (use JavaScriptSerializer or Newtonsoft.Json to build from object)
String DigSigRequestBody =
"{ \"CreateAndSignField\" : " + //structure name specifies the operation / function
"{ \"file\": " + "\"" + File2Base64String("D:\\work\\PurchaseOrder.pdf") + "\", " +
"\"fileType\": \"PDF\", " +
"\"x\": \"91\", " +
"\"y\": \"164\", " +
"\"width\": \"113\", " +
"\"height\": \"38\", " +
"\"page\": \"1\", " +
"\"timeFormat\": \"h:mm:ss\", " +
"\"dateFormat\": \"dd/MM/yyyy\", " +
"\"appearance\": [\"GRAPHICAL_IMAGE\", \"SIGNED_BY\", \"TIME\"]" +
"}" +
"}";
request.AddParameter("application/json", DigSigRequestBody, ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
JObject joResponse = JObject.Parse(response.Content);
Base64String2Path(joResponse["signedFile"].Value<string>(), "D:\\work\\PurchaseOrder.DSA-REST-SIGNED.pdf");
Console.WriteLine("success");
Console.ReadKey();
}
private static void Base64String2Path(string Base64String, string FilePath)
{
Byte[] bytes = Convert.FromBase64String(Base64String);
File.WriteAllBytes(FilePath, bytes);
}
private static String File2Base64String(String FilePath)
{
Byte[] bytes = File.ReadAllBytes(FilePath);
String fileB64Data = System.Convert.ToBase64String(bytes);
return fileB64Data;
}
private static String DSABasicAuthorizationString(String username, string password)
{
var DSABasicAuthorizationBytes = System.Text.Encoding.UTF8.GetBytes(username + ":" + password);
return System.Convert.ToBase64String(DSABasicAuthorizationBytes);
}
Pdf file link:https://github.com/docusign/docusign-signature-appliance-api-recipes/blob/master/dsa-rest/Hello-World-examples/PurchaceOrder.pdf
Result:
You need a DSA sandbox account. See https://developers.docusign.com/dsa-api to signup.
Also, are you sure you want to be using the DocuSign Signing Appliance? It is an on-premises hardware digital signing solution.
Most use cases use the DocuSign cloud eSignature service. It has different APIs. See the Developer Center.

Sending a JSON request to ebay API

Ok so I'm having a bit of trouble getting these JSON requests through to the Ebay API.
Here is the json request:
string jsonInventoryRequest = "{" +
"\"requests\": [";
int commaCount = 1;
foreach (var ep in productsToProcess)
{
jsonInventoryRequest += "{\"offers\": [{" +
"\"availableQuantity\":" + ep.EbayProductStockQuantity + "," +
"\"offerId\":\"" + ep.EbayID.ToString() + "\"," +
"\"price\": {" +
"\"currency\": \"AUD\"," +
"\"value\":\"" + ep.EbayProductPrice.ToString() + "\"" +
"}" +
"}],";
jsonInventoryRequest += "\"shipToLocationAvailability\": " + "{" +
"\"quantity\":" + ep.EbayProductStockQuantity +
"},";
jsonInventoryRequest += "\"sku\": " + ep.EbayProductSKU.ToString() + "}";
if (commaCount < productsToProcess.Count())
jsonInventoryRequest += ",";
commaCount++;
sendEbayApiRequest = true;
}
jsonInventoryRequest +=
"]" +
"}";
And the Debug.WriteLine() output of the above JSON request is :
json string = {"requests": [{"offers": [{"availableQuantity":0,"offerId":"098772298312","price": {"currency": "AUD","value":"148.39"}}],"shipToLocationAvailability": {"quantity":0},"sku": 135779},{"offers": [{"availableQuantity":1,"offerId":"044211823133","price": {"currency": "AUD","value":"148.39"}}],"shipToLocationAvailability": {"quantity":1},"sku": 133607}]}
Here is the code in C# to send the request:
var ebayAppIdSetting = _settingService.GetSettingByKey(
"ebaysetting.appid", "");
var ebayCertIdSetting = _settingService.GetSettingByKey(
"ebaysetting.certid", "");
var ebayRuNameSetting = _settingService.GetSettingByKey(
"ebaysetting.appid", "");
var stringToEncode = ebayAppIdSetting + ":" + ebayCertIdSetting;
HttpClient client = new HttpClient();
byte[] bytes = Encoding.UTF8.GetBytes(stringToEncode);
var base64string = "Basic " + System.Convert.ToBase64String(bytes);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Authorization", base64string);
var stringContent = "?grant_type=client_credentials&" + "redirect_uri=" + ebayRuNameSetting + "&scope=https://api.sandbox.ebay.com/oauth/api_scope";
var requestBody = new StringContent(stringContent.ToString(), Encoding.UTF8, "application/json");
requestBody.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
var response = client.PostAsync("https://api.sandbox.ebay.com/identity/v1/oauth2/token", requestBody);
The output I get when I do Debug.WriteLine("response.Content = " + response.Result); is:
response.Content = StatusCode: 401, ReasonPhrase: 'Unauthorized',
Version: 1.1, Content: System.Net.Http.StreamContent, Headers: {
RlogId:
t6ldssk%28ciudbq%60anng%7Fu2h%3F%3Cwk%7Difvqn*14%3F0513%29pqtfwpu%29pdhcaj%7E%29fgg%7E%606%28dlh-1613f3af633-0xbd
X-EBAY-C-REQUEST-ID: ri=HNOZE3cmCr94,rci=6kMHBw5dW0vMDp8A
X-EBAY-C-VERSION: 1.0.0 X-EBAY-REQUEST-ID:
1613f3af62e.a096c6b.25e7e.ffa2b377!/identity/v1/oauth2/!10.9.108.107!r1esbngcos[]!token.unknown_grant!10.9.107.168!r1oauth-envadvcdhidzs5k[]
Connection: keep-alive Date: Mon, 29 Jan 2018 00:04:44 GMT
Set-Cookie: ebay=%5Esbf%3D%23%5E;Domain=.ebay.com;Path=/
WWW-Authenticate: Basic Content-Length: 77 Content-Type:
application/json }
Can anyone see where I'm going wrong. Cheers
Ok so the authentication was failing because I was sending wrong authentication token. Needed to get oauth token from application tokens.
So instead of base64 encoding token like this:
var base64string = "Basic " + System.Convert.ToBase64String(bytes);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Authorization", base64string);
I needed to do the following:
url = "https://api.sandbox.ebay.com/sell/inventory/v1/bulk_update_price_quantity";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
//request.ContentType = "application/json; charset=utf-8";
request.Headers.Add("Authorization", "Bearer **OAUTH TOKEN GOES HERE WITHOUT ASTERIKS**");
// Send the request
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
streamWriter.Write(jsonInventoryRequest);
streamWriter.Flush();
streamWriter.Close();
}
// Get the response
HttpWebResponse response = (HttpWebResponse) request.GetResponse();
if (response != null)
{
using (var streamReader = new StreamReader(response.GetResponseStream()))
{
// Parse the JSON response
var result = streamReader.ReadToEnd();
}
}

Categories

Resources