Download Autodesk Forge viewables using C# - c#

I'am trying to download the Forge viewables in a C# application, but I'm having trouble downloading the svf file. The following code returns "The requested resource does not exist." If I run the same urn in the node.js extractor example it works fine. I'm not that familiar with using REST api's in C# and is probably missing a header or parameter. I have tried lots of combinations without success. Hopefully someone can point me in the right direction.
var urn = "urn:adsk.viewing:fs.file:<xxxxxURNxxxxxx>/output/0/0.svf";
var client = new RestClient("https://developer.api.autodesk.com");
var request = RestRequest("/derivativeservice/v2/derivatives/{" + urn + "}", Method.GET);
request.AddParameter("Authorization",string.Format("Bearer " + Configuration.Default.AccessToken),ParameterType.HttpHeader);
var result = client.Execute(request);

I think you just need to remove the curly braces from the URL, so use RestRequest("/derivativeservice/v2/derivatives/" + urn, Method.GET);

Related

How to "create the video" after file uploaded to DailyMotion using c#

Im following the instructions from here to publish a new video on DailyMotion, using c# and a WebClient.
i successfully got the auth-token, then an upload url, then the actual file to upload. im stuck at step 4, called: "create the video"
it states to POST url=<the url i got from previous step> to https://api.dailymotion.com/me/videos (with the Authorization token in the header), but all my attempts result in "bad request" - without further explanation.
any ideas?
using (var client = new WebClient())
{
var createRequest = $"url={videoUpload.url}";
client.Headers.Add("Authorization", $"Bearer {authToken.access_token}");
client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
var createVideo = client.UploadString("https://api.dailymotion.com/me/videos", "POST", createRequest);
}
also tried:
var createRequest = $"url={HttpUtility.UrlEncode(videoUpload.url)}";
I tried your code and my video was created successfully. As explained in our documentation a 400 error is related to a missing/invalid parameter.
I assume you are trying to send the upload url (returned in step 2) instead of the url returned by step 3 (url of your uploaded file).
You can find an article (with examples of returned values) which use a simplified way to upload on Dailymotion here.

upload feed to walmart

I am breaking my head trying to upload a feed to walmart, after many times trying i used postman to generate C# restsharp code for me, in postman it works, but when using the c# restsharp code it returns a mysterious error. like this:
"No message body writer has been found for response class FeedAcknowledgement"
what does that mean?
here is my code:
string requestUrl = "";
requestUrl = string.Format("https://marketplace.walmartapis.com/v2/feeds?feedType=inventory");
string method = "POST";
// string[] sig = getSig(method, requestUrl).Replace("\r", "").Split('\n');
var mySig = new Signature(ConsumerID, SecretKEY, requestUrl, method);
var s = mySig.TimeStamp;
var returendSigniture = mySig.GetSignature(s);
var client = new RestClient("https://marketplace.walmartapis.com/v2/feeds?feedType=inventory");
var request = new RestRequest(Method.POST);
//request.AddHeader("postman-token", "c325ba5f-813a-f990-7899-6bfc4b14aa1b");
request.AddHeader("cache-control", "no-cache");
request.AddHeader("content-type", "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW");
request.AddHeader("accept", "application/xml");
request.AddHeader("wm_consumer.id", "--");
request.AddHeader("wm_sec.auth_signature", returendSigniture);
request.AddHeader("wm_sec.timestamp", mySig.TimeStamp);
request.AddHeader("wm_qos.correlation_id", "123456abcdef");
request.AddHeader("wm_svc.name", "Walmart Marketplace");
request.AddParameter("multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW", "------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"BOUNDERY\"\r\n\r\n<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<wm:inventory xmlns:wm=\"http://walmart.com/\">\n <wm:sku>PP00500-2PC</wm:sku>\n <wm:quantity>\n <wm:unit>EACH</wm:unit>\n <wm:amount>120</wm:amount>\n </wm:quantity>\n <wm:fulfillmentLagTime>1</wm:fulfillmentLagTime>\n</wm:inventory>\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
I spent all day in figuring out how to request Walmart v3. I propose you the following two steps:
Use Walmart signer in order to generate signed token.
You will need to use HttpWebRequest for getting response from Walmart in a way similar to what is described here.
I have not been able to get this to work natively in C#, but I do have a work around.
The Java SDK can successfully submit multi-part requests to Walmart. I wrote a wrapper around the SDK functions that can accept basic command line input to read a text file and send the appropriate call with attached files. From here, you can just call the .jar file (I do it via dynamically generated batch file) from your C# program and receive responses back via text file. This is a sub-optimal system, but it works reliably and when the choice was between updating inventory on 2000 items every day and using some dirty code, I went with the Java wrapper method. This will be replaced as soon as the C# SDK comes out, but I believe this is one of the reasons why the C# SDK may be being delayed.
This solution was used, only after spending about a week trying to get boundaries / streams / attachments to work in C# and having zero success. Cases were also submitted to walmart and I was able to work with some of their top tier engineering support staff and this problem completely stumped them. I was able to trace the Java SDK execution all the way down to a built in Maven / Java function that constructed the web request so there's something under the hood that Java is doing with a multi-part request that isn't immediately clear in C#.

Sharepoint REST set metadata after document upload

I have a C# console application (which will ultimately be a windows service when it's finished). The purpose is to migrate a document store (500k+ documents) over to SharePoint 2013.
Note, this is a standalone C# app that will run on a server that does not have SharePoint installed. I am using pure REST via HttpClient calls.
Uploading a document and setting its metadata has 3 steps:
Upload the document (POST)
e.g. baseURL + "web/" + "GetFolderByServerRelativeUrl('/sites" + libPath + "')/Files/Add(url='" + filename + "',overwrite=true)";
Retrieve details for the list item associated with this document (GET)
e.g. baseURL + "web/lists/getbytitle('" + docLibName + "')/items?$filter=Title eq '" + filenameNoExt + "'"
These first 2 steps are working fine.
Update the metadata
This is the bit that's causing me sleepless nights now. I can't seem to figure out what exactly I should be sending to the web service, and anything I try just gives errors. I can't find any examples of anyone who's tried to do this; and the MS documentation is very sparse.
The MS documentation from http://msdn.microsoft.com/en-us/library/office/dn292552%28v=office.15%29.aspx says:
The following example shows how to update a list by using the MERGE method.
url: http: //siteurl/_api/web/lists(guid'list GUID')
method: POST
body: { '__metadata': { 'type': 'SP.List' }, 'Title': 'New title' }
Headers:
Authorization: "Bearer " + accessToken
X-RequestDigest: form digest value
IF-MATCH": etag or "*"
X-HTTP-Method: MERGE,
accept: "application/json;odata=verbose"
content-type: "application/json;odata=verbose"
content-length:length of post body
In my application, I have set the type in the query to SP.Data.CertificatesItem, which is what was returned in step 2; and I'm trying to set the Certificate Type field to the specified value, rather than the document title:
string body = "{ '__metadata': { 'type': '" + spItemType + "' }, 'CertificateType': 'Medical Certificate'}";
(there are several fields which need to be set; I am just hard-coding one field here for testing purposes. The fields which need to be set depend on the content type of the document library.)
Additionally, the URL is slightly different. Where the example had:
http: //siteurl/_api/web/lists(guid'list GUID')
I have (specific example, slightly anonymized):
http: //siteurl/_api/Web/Lists(guid'cdcbef76-8bc0-4a68-9279-f6f3b6cbd3c3')/Items(2)
Otherwise, my call is identical to the example above.
I am getting the error message:
{"error":{"code":"-1, Microsoft.SharePoint.Client.InvalidClientQueryException","message":{"lang":"en-US","value":"The parameter __metadata does not exist in method GetById."}}}
I don't understand what I'm doing wrong! And I can't find any concrete examples anywhere.
From the page: http://msdn.microsoft.com/en-us/library/office/dn292553%28v=office.15%29.aspx :
If you want to update a file's metadata, you'll have to construct an endpoint that reaches the file as a list item. You can do this because each folder is also a list, and each file is also a list item. Construct an endpoint that looks like this: https: //siteurl/_api/web/lists/getbytitle('Documents')/items(). Working with lists and list items with REST explains how to update a list item's metadata.
Can anyone provide any insight here?
UPDATE:
Seems the X-HTTP-Method wasn't getting set correctly. I fixed that, now I'm getting:
{"error":{"code":"-1, Microsoft.SharePoint.Client.InvalidClientQueryException","message":{"lang":"en-US","value":"An unexpected 'PrimitiveValue' node was found when reading from the JSON reader. A 'StartObject' node was expected."}}}
I came across your question while looking into this myself. I have documented how to do file uploads, creating, updating and retrieving list items including those with Termstore data all in .NET using the HttpClient with no JQuery required.
Example for updating a file from the HttpClient using REST:
client = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true });
client.BaseAddress = new System.Uri(url);
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Add("X-RequestDigest", digest);
client.DefaultRequestHeaders.Add("X-HTTP-Method", "MERGE");
client.DefaultRequestHeaders.Add("IF-MATCH", "*");
HttpContent strContent = new StringContent(String.Concat("{ '__metadata': { 'type': 'SP.List' }, 'Title': '", filename, "' }"));
strContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
strContent.Headers.ContentType.Parameters.Add(new NameValueHeaderValue("odata", "verbose"));
HttpResponseMessage updateResponse = await client.PostAsync(String.Concat("_api/web/lists/GetByTitle('Project Photos')/Items(", id, ")"), strContent);
updateResponse.EnsureSuccessStatusCode();
if (updateResponse.IsSuccessStatusCode)
{}
https://arcandotnet.wordpress.com/2015/04/01/sharepoint-2013-rest-services-using-c-and-the-httpclient-for-windows-store-apps/
Hopefully this helps.
Arcan.NET

How to create and redeem coupons in Recurly, programmatically?

++++++++++++++
Actual Scenario: I am working on a site (ASP.Net using C#) where the system will have 3 different subscription plans i.e. monthly, quarterly and yearly. All the subscription plans have their own cost and pricing. Now, if the system/admin wants to give any discounts to any subscribed user (regardless of subscription plan) on their on-going subscription based on some business logic (for example, for some user it may be $4 and for other it may be $25). How can I achieve this goal. I tried PayPal and Recurly, but stuck in-between.
++++++++++++++
I have to create a coupon and redeem the same using Recurly dynamically in C#. But, as per the code mentioned in "https://docs.recurly.com/api/v1/subscription-plans", we have to use Recurly API v2, but we don't have the code to create and redeem the coupon. So, please help me on how can I create coupons and redeem the same.
When we are using below code in mentioned URL "Recurly PUT request working but returning server error", it causes error while getting response.
uri = "https://" + subdomain + ".recurly.com/v2/subscriptions/" + uuid + "/reactivate";
try
{
string xml = "<subscription><timeframe>now</timeframe></subscription>"; //also tried with blank string.
byte[] arr = System.Text.Encoding.UTF8.GetBytes(xml);
HttpWebRequest renewRequest = (HttpWebRequest)WebRequest.Create(uri);
renewRequest.Headers.Add("Authorization", "Basic " + encodeB64);
renewRequest.Method = "PUT";
renewRequest.ContentType = "text/XML";
renewRequest.ContentLength = arr.Length;
Stream datastream = renewRequest.GetRequestStream();
datastream.Write(arr, 0, arr.Length);
datastream.Close();
HttpWebResponse renewResponse = (HttpWebResponse)renewRequest.GetResponse();
}
Looking for kind response and help...
We (recurly.com) just made available a release candidate of an all new API client for C# compatible with Recurly APIv2 that we highly recommend using. The client API is stable and this release will shortly become the final release pending new show-stopping bugs.
Here's how to get started using it.
Be sure set up your configuration.
Here's how to create a coupon.
Here's how to redeem coupons.
More examples are available here.
If you have further questions please don't hesitate to ask our support team! support#recurly.com.

Failing to retrieve access token in .NET desktop app

I'm writing a .NET app that runs on a Windows computer. It is not accessible through the browser. The problem is, I can't authenticate like I should. I'm currently coding in C# .NET, more specific in C#.
I have a webbrowser control on my form.
The user logs on to facebook through this webbrowser control.
After the logon, I start the authentication procedure.
I then retreive a code.
Here's where it goes wrong. With this code I want to obtain an access token.
The generated request URL looks like: https://graph.facebook.com/oauth/access_token?client_id=____MY_APP_ID______&redirect_uri=http://localhost/&client_secret=_____MY_APP_SECRET_____&code=____MY_RETREIVED_CODE_____ and is made through the code below.
Please note that my redirect URL is http://localhost. This should be okay, right?
Also, in my App Settings, I have the following information.
Site URL: http://localhost/
Site Domain: localhost
private String ExchangeCodeForToken(String code, Uri redirectUrl)
{
var TokenEndpoint = new Uri("https://graph.facebook.com/oauth/access_token");
var url = TokenEndpoint + "?" +
"client_id=" + _AppID + "&" +
"redirect_uri=" + redirectUrl + "&" +
"client_secret=" + _AppSecret + "&" +
"code=" + code;
var request = WebRequest.CreateDefault(new Uri(url));
using (var response = request.GetResponse())
{
using (var responseStream = response.GetResponseStream())
{
using (var responseReader = new StreamReader(responseStream))
{
var responseText = responseReader.ReadToEnd();
var token = responseText.Replace("access_token=", "");
return token;
}
}
}
}
When I execute this, I get this error:
error http://www.imageupload.org/getfile.php?id=50131&a=447f6fcc0ebd4d3f8e8a59a3a6e36ac3&t=4de0841c&o=0889D68FDC35508BA2C6F2689FCBAB7C30A8670CC9647EE598701D8BEC13ED278F0989D393&n=autherror.png&i=1
Webexception was unhandled by user code
The remote server returned an error: (400) Bad Request.
Here's where I think I might be going wrong:
Are my app settings correct?
Should my redirect url be http://localhost, even if there isn't actually a service listening there?
Most importantly:
how do I get rid of this error and retreive the access token?
Thanks in advance!
You get this error because you are not supposed to call this URL from a Desktop app : as far as I know, you can not use the token endpoint for Desktop app authentication. Also, you can get the access token directly (no need to ask for a code first). Here is what you have to do.
Load the following URL in your embedded web browser :
https://www.facebook.com/dialog/oauth?
client_id=YOUR_APP_ID&
redirect_uri=https://www.facebook.com/connect/login_success.html
The user will be asked to log in and will be redirected to this URL with the access token in the URL :
https://www.facebook.com/connect/login_success.html#access_token=...
So you have to detect the redirect and retrieve the access token from the URL.
Thanks quinten!
However, I've managed to solve my own problem by using the C# Facebook SDK.
This software development kit has been a really great help!
There are a lot of samples included (including authorisation)
Anyone who programs in .NET with facebook should check it out! Coding for facebook is now much easier.
http://facebooksdk.codeplex.com/

Categories