Autodesk forge viewer gives error after updation of tls1.2 - autodesk-forge

we have uploaded ipt and rvt files into autodesk forge bucket to view files into viewer.
Following segment show how we translate file to view into viewer.html.
Code is executed successfully but, when we open file into viewer, it gives error that file is not viewable.
HttpClient client = new HttpClient();
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + authToken);
client.DefaultRequestHeaders.Add("contenttype", "application/json");
string url = "https://developer.api.autodesk.com/modelderivative/v2/designdata/job";
JObject jsonbody = new JObject
(
new JProperty("input", new JObject
(
new JProperty("urn", urn)
)),
new JProperty("output", new JObject
(
new JProperty("formats", new JArray
(
new JObject
(
new JProperty("type", "svf"),
new JProperty("views", new JArray("3d", "2d"))
)
))
))
);
var ser = JsonConvert.SerializeObject(jsonbody);
StringContent insertString = new StringContent(ser, Encoding.UTF8, "application/json");
HttpResponseMessage response = client.PostAsync(url, insertString).Result;
string result = response.Content.ReadAsStringAsync().Result;
JObject jsonobject = JObject.Parse(result);
urn = (string)jsonobject["urn"];
Response.Redirect("Viewer.html?token=" + authToken + "&urn=" + urn);

Looks like you are redirecting to view the model immediately after calling the translation, while you should have polled for the job status and wait for its completion.
Note that any translation job with our Model Derivative service is asynchronous and will be queued for processing right after they are called. Jobs with large models might take minutes and even hours to complete. See here for API usage details to query the job status.
Also see below for sample .NET code to poll a web service:
Polling a web service

Related

2 step authentication C# Access JSON API via SSIS 2010

I have managed in SSIS 2010 to access a JSON API with basic authentication ... Username and password, using the script below
I need to amend the script below to also include passing credentials of a Client Secret and Client ID
anyone know how to amend this for SSIS 2010. I have tried with no joy, so I have pasted the working code so far
Please help
WebRequest req = WebRequest.Create(#"https://sub.domain.com/api/operations? param=value&param2=value");
req.Method = "GET";
req.Headers["Authorization"] = "Basic " + Convert.ToBase64String (Encoding.Default.GetBytes("username:password"));
//req.Credentials = new NetworkCredential("username", "password");
HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
It may depend on how the API is set up and what it's expecting, but in my case, I did this in the creation of an HttpClientHandler:
using System.Net.Http;
using System.Configuration;
...
HttpClientHandler handler = new HttpClientHandler { Credentials = new NetworkCredential(ConfigurationManager.AppSettings["API.UserName"].ToString(), ConfigurationManager.AppSettings["API.Password"].ToString()) };
HttpClient apiClient = new HttpClient(handler);
OR, without using Configurations:
using System.Net.Http;
...
HttpClientHandler handler = new HttpClientHandler { Credentials = new NetworkCredential("MyUserName", "MyPassword") };
HttpClient apiClient = new HttpClient(handler);
Then use the Client to make calls. Here's how I do it:
HttpResponseMessage httpResponse = apiClient.GetAsync(curl).Result;

Salesforce Apex Google Drive API is creating new file with mimeType "application/json"

Trying to create a function in apex that will create Google Drive folders when creating a new record in Salesforce.
I have managed to authenticate and handle GET requests just fine. My issue is regarding the POST requests. The code below should create a folder with the label provided in the "title" parameter. The script executes and instead creates an extension-less file without a label.
public void getDriveFiles(HttpResponse authResponse) {
http h = new Http();
Httprequest req = new HttpRequest();
HttpResponse res = new HttpResponse();
Map<String, Object> responseObject = (Map<String, Object>) JSON.deserializeUntyped(authResponse.getBody());
req.setEndpoint('https://www.googleapis.com/upload/drive/v2/files');
req.setMethod('POST');
req.setHeader('Content-type', 'application/json');
req.setHeader('Authorization', 'Bearer '+responseObject.get('access_token'));
String jsonData = '{"title":"NewFolder", "mimeType":"application/vnd.google-apps.folder"}';
req.setBody(jsonData);
res = h.send(req);
system.debug('Response ='+ res.getBody() +' '+ res.getStatusCode());
}
I have a feeling it's my request body but I have no idea what to do to fix it.
You've used the wrong endpoint. Instead of the file endpoint, you're posting to the content endpoint.
So
req.setEndpoint('https://www.googleapis.com/upload/drive/v2/files');
should be (for the v2 API)
req.setEndpoint('https://www.googleapis.com/drive/v2/files');
or (for the v3 API)
req.setEndpoint('https://www.googleapis.com/drive/v3/files');
If you use v3 (which you probably should), your json should change thus
String jsonData = '{"name":"NewFolder", "mimeType":"application/vnd.google-apps.folder"}';

batch Google contact in dotnet

I cannot find any sample for batching contact insertions in dotnet.
We're using nuget package : Install-Package Google.GData.Contacts
For appointments we're batching in this way:
BatchRequest batch = new BatchRequest(service);
Google.Apis.Calendar.v3.EventsResource.InsertRequest ir = new EventsResource.InsertRequest(aservice, theEvent, userName);
batch.Queue<Google.Apis.Calendar.v3.Data.Event>(ir,
( error, i, message) =>
{
// code here
});
With the Google contacts apis, we do not find any InsertRequest object.
We're using the ContactRequest class for Oauth integration.
RequestSettings settings = new RequestSettings(ApplicationName);
string token = GetOauthAccessToken();
OAuth2Parameters oauth2 = new OAuth2Parameters();
oauth2.AccessToken = token;
settings.OAuth2Parameters = oauth2;
GetNextContactService = new ContactsRequest(settings);
Note: in the past, we were using the ContactService class with which we managed to batch inserts, but with this class we did not manage to attach an oauth token like in the code above.
old code:
PushContactService = new ContactsService("MigrationAsAService");
GOAuthRequestFactory requestFactory = new GOAuthRequestFactory("cl", "theappname");
requestFactory.ConsumerKey = this.ConnectorSettings.ConsumerKey;
requestFactory.ConsumerSecret = this.ConnectorSettings.ConsumerSecret;
PushContactService.RequestFactory = requestFactory;
ContactsFeed feed = new ContactsFeed(
new Uri(PushContactsURI),
PushContactService
);
feed.BatchData = new GDataBatchFeedData();
feed.BatchData.Type = GDataBatchOperationType.insert;
You should be able to use the ContactsService class with OAuth2, by creating a GOAuth2RequestFactory and setting that as the service's request factory.

HttpClient dosen't get data after update WP8

I have this code to get JSON data from an API for WP8:
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(mainURL.ToString());
HttpResponseMessage response = await client.GetAsync("");
string res = await response.Content.ReadAsStringAsync();
var root = await JsonConvert.DeserializeObjectAsync<Rootobject>(res);
Everything works perfectly, but when I update data on the web API from the web site and try to retrieve data again using this code it gets the old data even though accessing the URL in a browser it gets the new data.
When I debug line by line, I see that the "response" object contains the old data.
The only way I have found to fix this is to rebuild the project in this way it works.
How can I properly get the updated data?
There may be some caching involved. Tried adding some random string to the URL, like
client.BaseAddress = new Uri(mainURL.ToString()+"&random="+DateTime.Now.Ticks);
I have same kind of problem. I tried this this may be help you.
HttpWebRequest request = HttpWebRequest.CreateHttp(mainURL.ToString());
request.Method = "GET or Post";
request.BeginGetResponse(ResponseCallBack, request);
void ResponseCallBack(IAsyncResult asyncResult)
{
HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult);
using (Stream data = response.GetResponseStream())
{
using (var reader = new StreamReader(data))
{
string jsonString = reader.ReadToEnd();
MemoryStream memoryStream = new MemoryStream(Encoding.Unicode.GetBytes(jsonString));
DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(typeof(Rootobject));
Rootobject yourdata= dataContractJsonSerializer.ReadObject(memoryStream) as Rootobject;
}
}
}

Seeing the Http Response content in ServiceStack

I am using ServiceStack to create a C# client to a JSON RESTful service. I have this code that returns my DTO:
Search result = restClient.Get (search);
This works fine, but in order to effectively debug the search results coming back I need to output the text content from the underlying HTTP Response object. (I don't know all the elements in the response yet in order to add them to the DTO).
Is there any way I can get hold of the underlying HTTP response, and thus the full text content, from my result object?
Thanks in advance.
#adamfowleruk
When inheriting from ServiceStack's built-in Service you can access the underlying Request and Response directly from the Response class with:
public class MyService : Service
{
public object Get(Request request)
{
base.Request ...
base.Response ...
}
}
You won't see the response output in your service or filters since it writes directly to the response stream and is the last thing that ServiceStack does after executing your service and all response filters.
For diagnosing HTTP I recommend using Fiddler or WebInspector also ServiceStack's built-in Request Logger might help as well.
Consuming a ServiceStack service
If you're using the C# Service Clients you can simply ask for what you want, e.g. you can access the returned response as a raw string:
string responseJson = client.Get<string>("/poco/World");
Or as raw bytes:
byte[] responseBytes = client.Get<byte[]>("/poco/World");
Or as a Stream:
using (Stream responseStream = client.Get<Stream>("/poco/World")) {
var dto = responseStream.ReadFully().FromUtf8Bytes().FromJson<PocoResponse>();
}
Or even access the populated HttpWebResponse object:
HttpWebResponse webResponse = client.Get<HttpWebResponse>("/poco/World");
webResponse.Headers["X-Response"] //World
using (webResponse)
using (var stream = webResponse.GetResponseStream())
using (var sr = new StreamReader(stream)) {
string response = sr.ReadToEnd();
}
You can also introspect the HttpWebResponse by using Global and Local Response filters, e.g:
JsonServiceClient.HttpWebResponseFilter = httpRes => { .. };
Or using a Local filter:
var client = new JsonServiceClient(baseUrl) {
ResponseFilter = httpRes => { .. }
};
Consuming a 3rd Party Service
If you're consuming a 3rd Party REST/HTTP API you can use a responseFilter: in ServiceStack's HTTP Util extensions:
List<GithubRepo> repos = "https://api.github.com/users/{0}/repos".Fmt(user)
.GetJsonFromUrl(responseFilter: httpRes => {
var remaining = httpRes.Headers["X-Api-Remaining"];
})
.FromJson<List<GithubRepo>>();
I use Fiddler to debug my services. It gives you all sorts of cool HTTP debugging facilities.
http://www.fiddler2.com/fiddler2/
I like to use RestConsole. It is a Chrome Extension and you can easily submit POST requests and see the response. It is also handy to create sample data and then step into the ServiceStack code and see what's happening. The ServiceStack PluralSight course has a nice demo of how to use them together.
Thanks to the above help I found the right answer. Documenting here for others:-
SearchResponse result = null; // my ServiceStack DTO
HttpWebResponse webResponse = restClient.Get<HttpWebResponse>(
completePath("/v1/search",qp)); // builds the URL with parameters
using (var stream = webResponse.GetResponseStream())
using (var sr = new StreamReader(stream)) {
var text = sr.ReadToEnd();
log.log ("response text: " + text); // *** PRINTING STRING VALUE HERE FOR DEBUG
result = text.FromJson<SearchResponse>();
}
// Now do something useful with the result DTO object
log.log ("RESULT: " + result.ToString ());
for (int i = 0; i < result.Results.Length; i++) {
log.log ("Result " + i + ": " + result.Results[i].ToString());
}