OneNote API Create Notebook - c#

I'm getting a "Bad Request" when I try to create a new OneNote API Notebook.
private async Task<string> CreateSimpleNotebook(string notebookName, string apiRoute)
{
var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
try
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
}
catch (Exception ex)
{
string tempEx = ex.ToString();
}
var createMessage = new HttpRequestMessage(HttpMethod.Post, apiRoute )
{
Content = new StringContent("{ name : '" + WebUtility.UrlEncode(notebookName) + "' }", Encoding.UTF8, "application/json")
};
HttpResponseMessage response = await client.SendAsync(createMessage);
return response.Headers.Location.ToString();
}
And I call the method with the following:
string url = "https://graph.microsoft.com/v1.0/me/onenote/notebooks/";
// string url = "https://www.onenote.com/api/v1.0/me/notes/notebooks/";
string tempResponse = await CreateSimpleNotebook("EMRTest2", url);
Here is the response:
{StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
client-request-id: acacd4f5-8738-4c46-8150-17aa23413eb5
request-id: acacd4f5-8738-4c46-8150-17aa23413eb5
Transfer-Encoding: chunked
x-ms-ags-diagnostic: {"ServerInfo":{"DataCenter":"South Central US","Slice":"SliceB","Ring":"NA","ScaleUnit":"002","Host":"AGSFE_IN_10","ADSiteName":"SAN"}}
Duration: 772.4124
Cache-Control: private
Date: Sun, 19 Nov 2017 20:59:10 GMT
Content-Type: application/json
}}

You should use Content-Type JSON
The name of the property you are looking for is not "name", it is "displayName"
Additionally, crafting JSON by appending string is not best practice - I recommend using a JSON library, like NewtonSoft JSON.NET.

Related

Google Place Api does not return more than 20 results

I am learning Xamarin forms. I am using Google Place API for searching nearby
I have managed to call the API in .NET, but I only get 20 results as it is written in the Google document.
Here is my code :
string lati = location.Latitude.ToString().Replace(",", ".");
string longi = location.Longitude.ToString().Replace(",", ".");
string latitude = lati;
string longitude = longi;
string Myradius = "3000";
var URL = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?";
string urlParameters = "?location=" + latitude + "," + longitude + "&radius=" + Myradius + "&key=My_GOOGLE_KEY";
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(URL);
// Add an Accept header for JSON format.
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
// List data response.
HttpResponseMessage response = await client.GetAsync(urlParameters);
if (response.IsSuccessStatusCode)
{
JObject joResponse = JObject.Parse(await response.Content.ReadAsStringAsync());
JArray MyJsonResult = (JArray)joResponse["results"];
// I want to have the second page result of my API Call
string token = joResponse["next_page_token"].ToString(); // I have manage to get the token
JArray MyJsonResult2 = await GetnextPageData(latitude, longitude, Myradius, token); //no result
}
async Task<JArray> GetnextPageData(string latitude, string longitude, string Myradius , string token)
{
var URL = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?";
string urlParameters = "?location=" + latitude + "," + longitude + "&radius=" + Myradius + "&key=My_GOOGLE_KEY&pagetoken=" + token;
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(URL);
// Add an Accept header for JSON format.
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// List data response
HttpResponseMessage response = await client.GetAsync(urlParameters);
Console.WriteLine("MyPrint " + response);
if (response.IsSuccessStatusCode)
{
JObject joResponse = JObject.Parse(await response.Content.ReadAsStringAsync());
Console.WriteLine("MyPrint " + response);
JArray MyJsonResult = (JArray)joResponse["results"];
if (MyJsonResult != null)
{
return MyJsonResult;
}
else
{
return null;
}
}
return null;
}
I have found those link but still cannot add the parameter for the rest of the result:
Obtaining more than 20 results with Google Places API
How to get 20+ result from Google Places API?
Problem: I have manage to get the token but when I put it in the parameter I get no result - MyJsonResult2 is empty.
When I print "response" for the second call I have this :
StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.NSUrlSessionHandler+NSUrlSessionDataTaskStreamContent, Headers:
{
server-timing: gfet4t7; dur=30
Alt-Svc: h3=":443"; ma=2592000,h3-29=":443"; ma=2592000,h3-Q050=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000,quic=":443"; ma=2592000; v="46,43"
Server: scaffolding
Server: on
Server: HTTPServer2
x-xss-protection: 0
Cache-Control: public, max-age=300
Date: Sun, 13 Nov 2022 02:19:16 GMT
X-Frame-Options: SAMEORIGIN
Vary: Accept-Language
Content-Type: application/json; charset=UTF-8
server-timing: gfet4t7; dur=30
Alt-Svc: h3=":443"; ma=2592000,h3-29=":443"; ma=2592000,h3-Q050=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000,quic=":443"; ma=2592000; v="46,43"
Content-Encoding: gzip
x-xss-protection: 0
Expires: Sun, 13 Nov 2022 02:24:16 GMT
Content-Length: 86
X-Frame-Options: SAMEORIGIN
}
And when I print "joResponse" for the second call I have this :
{
"html_attributions": [],
"results": [],
"status": "INVALID_REQUEST"
}
Thanks for your help.
I have found the solution. I must add in my request the parameters :"hasNextPage=true&nextPage()=true"

Result from response.Content.ReadAsStringAsync() is empty string (Windows.Web.Http). How do I get response?

When I run this from a browser manually, it returns a response, that looks like this:
{"value":[{"ID":4}]}
Now, I am POSTing it from a Windows IoT Device, using the following code:
private async Task SendPostRequest(string username, string password, Dictionary<string, string> parameters)
{
try
{
// using Windows.Web.Http
HttpFormUrlEncodedContent formattedData = new HttpFormUrlEncodedContent(parameters);
using (HttpBaseProtocolFilter clientHandler = new HttpBaseProtocolFilter())
{
clientHandler.ServerCredential = GetCredentials(username, password);
using (HttpClient httpClient = new HttpClient(clientHandler))
{
//txtCommand.Text = "PostAsync";
HttpResponseMessage response = await httpClient.PostAsync(postUrl, formattedData);
txtResponse.Text = response.ToString();
response.EnsureSuccessStatusCode();
string responseString = await response.Content.ReadAsStringAsync();
txtResponse.Text += " responseString: " + responseString;
}
}
The result in responseString is an empty string.
The result of response.ToString() looks like this:
StatusCode: 200, ReasonPhrase: 'OK', Version: 2, Content: Windows.Web.Http.HttpStreamContent, Headers:
{
Persistent-Auth: true
Server: Microsoft-IIS/10.0
Transfer-Encoding: chunked
Date: Fri, 27 Aug 2021 15:16:38 GMT
X-Powered-By: ASP.NET
dbgate-version: 1.0
}{
Content-Type: text/plain
}

Unable to get json data from curl graph api using c#

I'm executing curl graph api using c#.
I took my curl query used this website and convert it into c#.
https://curl.olsh.me/
Api is able to give 200 ok status code and but output is below-
{
"extensions" : {
"requestId" : "123"
},
"data" : null,
"errors" : [ {
"message" : "Unable to process JSON",
"extensions" : {
"errorType" : "developer_error",
"errorClass" : "VALIDATION"
}
} ]
}
result string conv: StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Connection: keep-alive
Braintree-Version: 2016-10-07
Strict-Transport-Security: max-age=31536000; includeSubDomains
Vary: Braintree-Version
X-Cache: Miss from cloudfront
X-Amz-Cf-Pop: MIA3-C2
X-Amz-Cf-Id: 111
Date: Tue, 10 Sep 2019 16:13:54 GMT
Via: 1.1 demo.cloudfront.net (CloudFront)
Content-Length: 286
Content-Type: application/json
}
C# code -
HttpClientHandler handler = new HttpClientHandler()
{
UseProxy = false,
};
using (var httpClient = new HttpClient(handler))
{
using (var request = new HttpRequestMessage(new HttpMethod("POST"), "https://demo/graphql"))
{
// Prod token
request.Headers.TryAddWithoutValidation("Authorization", "Basic abc");
request.Headers.TryAddWithoutValidation("Braintree-Version", "2019-01-01");
request.Content = new StringContent("{\"query\": \"{ report { transactionLevelFees(date: \"2019-08-28\"){ url } } }\" }", Encoding.UTF8, "application/json");
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var response = await httpClient.SendAsync(request);
// Get the response content.
HttpContent responseContent = response.Content;
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
// Get the stream of the content.
using (var reader = new StreamReader(await responseContent.ReadAsStreamAsync()))
{
// Write the output.
Console.WriteLine((await reader.ReadToEndAsync()));
}
Console.WriteLine($"result string conv: {response }");
}
}
I expect in output i should get something in data json

Setting the If-Match in the Headers C#

I have the Odata service, in order to perform a PUT we need to set the Header with If-Match: * In Post man I giving like below and it works
How do I set this If-Match in the Odata Service call to perform a PUT operation.I tried the below
private async Task<HttpResponseMessage> PutJsonAsync(string messageBody,string B_Code)
{
string userName = ConfigurationManager.AppSettings["Username"];
string password = ConfigurationManager.AppSettings["Password"];
string BaseURL = ConfigurationManager.AppSettings["BaseURL"];
try
{
using (var httpClient = new HttpClient())
{
var request = new StringContent(messageBody, Encoding.UTF8, "application/json");
string apiUrl = "SAM('" + B_Code + "')";
request.Headers.ContentType = new MediaTypeHeaderValue("application/json");
request.Headers.TryAddWithoutValidation("If-Match", "*");
var url = string.Format("{0}{1}", BaseURL, apiUrl);
var creds = userName + ":" + password;
var credentials = Encoding.ASCII.GetBytes(creds);
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(credentials));
response = await httpClient.PutAsync(new Uri(url), request);
}
}
catch (Exception ex)
{
throw ex;
}
return response;
}
But it is not working and throws error 501:Not Implemented
`response {StatusCode: 501, ReasonPhrase: 'Not Implemented', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
OData-Version: 4.0
Date: Mon, 30 Oct 2017 20:42:28 GMT
Set-Cookie: JSESSIONID=XYZ; Path=/; Secure; HttpOnly
Set-Cookie: XYZ;PATH=/;SECURE;HTTPONLY
Server: Apache-Coyote/1.1
Vary: Accept-Encoding
Connection: keep-alive
Content-Length: 277
Content-Type: application/json; odata.metadata=minimal
}} System.Net.Http.HttpResponseMessage`
Your "request" object, is your content object, not the HttpRequestMessage object. How did I realise that? ContentType isn't available on the HttpRequestMessage.
If-Match is not a content-level header (I don't know why Microsoft make this distinction). You can't add it here, you have to add it to the request header. If you add it to the content object, it gets disregarded.
Something like this should work:
string apiUrl = "SAM('" + B_Code + "')";
var url = string.Format("{0}{1}", BaseURL, apiUrl);
var creds = userName + ":" + password;
var credentials = Encoding.ASCII.GetBytes(creds);
var request = new HttpRequestMessage(HttpMethod.Put, new Uri(url));
request.Content = new StringContent(messageBody, Encoding.UTF8, "application/json");
request.Headers.TryAddWithoutValidation("If-Match", "*");
request.Headers.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(credentials));
response = await httpClient.SendAsync(request);

StatusCode 401 Reason Unauthorized when calling PostAsync WebRequest

I am new to the C# HttpClient class and I hope you guys & gals can help me out with my problem. I am getting the StatusCode 401 when trying to call the PostAsync Method. Here's my Code
public WebClient(HttpClient httpClient)
{
string webHost = ConfigurationManager.AppSettings["webHost"];
string webApiKey = ConfigurationManager.AppSettings["webApikey"];
_httpClient = httpClient;
_httpClient.BaseAddress = new Uri(webHost);
_httpClient.DefaultRequestHeaders.Accept.Clear();
_httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("x-coupa-api-key", "=" + ConfigurationManager.AppSettings["coupaApikey"]);
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
}
public Tuple<bool, Task<HttpResponseMessage>> Comment(comment comment)
{
try
{
string commentUrl = string.Format("{0}api/comments/", _webHost);
var responseMessage = _httpClient.PostAsync(commentUrl, CreateHttpContent(comment));
Log.Error("Response message: " + responseMessage.Result);
return new Tuple<bool, Task<HttpResponseMessage>>(responseMessage.Result.IsSuccessStatusCode, responseMessage);
}
catch (Exception ex)
{
Log.Error("Call to Web failed.", ex);
throw;
}
}
private static HttpContent CreateHttpContent(comment data)
{
var format = "application/xml";
return new StringContent(Common.SerializeUtf8(data), Encoding.UTF8, format);
}
So I am sending an xml with a POST to a webhost - and i get the following Result from PostAsync:
Response message:
StatusCode: 401, ReasonPhrase: 'Unauthorized', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Transfer-Encoding: chunked
Status: 401 Unauthorized
X-Frame-Options: SAMEORIGIN
X-XSS-Protection: 1; mode=block
X-Content-Type-Options: nosniff
X-Request-Id: 53e17930-f9fe-4ec4-ae5b-b772ce5f308e
X-Runtime: 0.025822
Cache-Control: no-cache
Date: Wed, 26 Apr 2017 06:07:39 GMT
Content-Type: text/html
}
Found the solution. Shouldn't have used the Authorization, just "add header":
_httpClient.DefaultRequestHeaders.Add("x-coupa-api-key", ConfigurationManager.AppSettings["webApikey"]);

Categories

Resources