c# - expected name not found - c#

I have the following GraphQl query, which works fine in PostMan.
query getFirstName($id: String!) {
getFirstName(id: $id) {
myId
}
}
However, when I am executing using the traditional HttpClient module I get the error
code":400,"stacktrace":"Syntax Error: Expected Name, found \"$
My Code:
var queryObject = new
{
query = #"query {
getFirstName($id: String!) {
getFirstName(id: $id) {
myId
}
}
}",
variables = new { id = "132" }
};
httpClient.DefaultRequestHeaders.Accept.Clear();
var contentType = new MediaTypeWithQualityHeaderValue("application/json");
httpClient.DefaultRequestHeaders.Accept.Add(contentType);
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
var myContent = JsonConvert.SerializeObject(queryObject);
var buffer = System.Text.Encoding.UTF8.GetBytes(myContent);
var byteContent = new ByteArrayContent(buffer);
byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var responseTask = httpClient.PostAsync(myUri, byteContent);
responseTask.Wait();
var response = responseTask.Result;
I think my queryObject is not parsed correctly.

Related

Postman form-data: How to program it inside a HttpRequestMessage?

I am doing a request through postman to a specific url but I set the form-data type in order to get data to the site like this:
Now I want to program this request inside C# but everything I tried so far is returning a 400 Bad Request response. This is what I tried:
public async Task<CheckAccessTokenModel> CheckAccessTokenAsync(string accessToken)
{
string uriString = "someurl";
var uri = new Uri(uriString);
try
{
using(var httpClient = new HttpClient())
{
var request = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = uri
};
var ClientId = ConfigurationAccessor.Configuration["WebCredentials:ClientId"];
var Secret = ConfigurationAccessor.Configuration["WebCredentials:Secret"];
var authString = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{ClientId}:{Secret}"));
request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", authString);
MultipartFormDataContent content = new MultipartFormDataContent();
content.Add(new StringContent("token"), accessToken);
request.Content = content;
var response = await httpClient.SendAsync(request);
var checkTokenResponseData = await response.Content.ReadAsStringAsync();
//return new CheckAccessTokenModel { Active = true, Exp = 1647431224233 };
return JsonConvert.DeserializeObject<CheckAccessTokenModel>(checkTokenResponseData);
}
}
catch
{
return null;
}
}
I am doing it with the MultipartFormDataContent Object as suggested by many others here but it still won't work.
What can be the problem here?
EDIT: Wrong picture replaced
You can simply
request.Content = new StringContent($"token={accessToken}");
With form data I think it's something like this:
var data = new Dictionary<string, string>
{
{"token", acccessToken}
};
using var content = new FormUrlEncodedContent(data);
request.Content = content;

MS Graph API returns 400 Bad request

I am using HttpClient to call Microsoft Graph and create a new Team. I am using the Beta version.
string TeamsName = objTeam.TeamsName.ToString();
string TeamsDescription = objTeam.TeamsDescription.ToString();
var objJson = new CreateTeamsJson
{
templateodatabind = "https://graph.microsoft.com/beta/teamsTemplates(\'educationClass\')",
displayName = TeamsName,
description = TeamsDescription
};
var json = JsonConvert.SerializeObject(objJson, jsonSettings);
var modifiedjson = json.Replace("templateodatabind", "template#odata.bind");
StringContent postContent = new StringContent(modifiedjson, UnicodeEncoding.UTF8, "application/json");
if (!string.IsNullOrEmpty(TeamsName))
{
TokenHelper tokenHelper = new TokenHelper();
TokenResponse tokenResponse = tokenHelper.GetTokenAsync().Result;
using(HttpClient httpClient = new HttpClient())
{
var request = new HttpRequestMessage(HttpMethod.Post, "https://graph.microsoft.com/beta/teams");
request.Headers.Authorization = new AuthenticationHeaderValue("bearer", tokenResponse.access_token);
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
request.Content = postContent;
var response = httpClient.SendAsync(request).Result;
var createdTeamDetails = response.Headers.Location;
if (response.IsSuccessStatusCode)
{
responseMessage = string.Format("Successfully created team - details: '{0}'", createdTeamDetails);
}
else
{
responseMessage = "ERROR: Failed to create Team.";
}
}
}
else
{
log.Info("Please provide Teams Name");
responseMessage = "Please provide Teams Name";
IsError = true;
}
When I run the code I am getting a 400 - Bad Rrequest at the following line:
var response = httpClient.SendAsync(request).Result;
I tried the same endpoint and same JSON body request in Graph Explorer and I could create teams successfully. Can anybody help me?

How to make POST request on BamBhooHr Api in C#

I want to add Employee on BamBhooHr using Bambhoohr REST API in MVC C#.
I have tried 2 content types to post as shown in the code but not succeed.
1==>
public async System.Threading.Tasks.Task<JsonResult> AddEmployee(string fn,string ln)
{
var _resultModel = new BBHEmployee();
var _bambhoohrApi = "https://epicsoftsandbox.bamboohr.com/api/gateway.php/epicsoftsandbox/v1/employees";
var _apiKey = "b2aef724a48603468bfe85dce9e417ac8cf15fdf";
var _url = $"{_bambhoohrApi}";
var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(_apiKey + ":x");
var base64encodedData = System.Convert.ToBase64String(plainTextBytes);
using (var _client = new HttpClient())
{
var _postData = new Dictionary<string, string>
{
{ "firstName", fn },
{ "lastName", ln }
};
_client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", base64encodedData);
var _response = await _client.PostAsync(_url, new FormUrlEncodedContent(_postData));
var _content = await _response.Content.ReadAsStringAsync();
_resultModel = JsonConvert.DeserializeObject<BBHEmployee>(_content);
}
return Json(_resultModel, JsonRequestBehavior.AllowGet);
}
2==>
public async System.Threading.Tasks.Task<JsonResult> AddEmployee(string fn,string ln)
{
var _resultModel = new BBHEmployee();
var _bambhoohrApi = "https://epicsoftsandbox.bamboohr.com/api/gateway.php/epicsoftsandbox/v1/employees";
var _apiKey = "b2aef724a48603468bfe85dce9e417ac8cf15fdf";
var _url = $"{_bambhoohrApi}";
var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(_apiKey + ":x");
var base64encodedData = System.Convert.ToBase64String(plainTextBytes);
using (var _client = new HttpClient())
{
_client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", base64encodedData);
_client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
var jsonString = "{\"firstName\":\"" + fn + "\",\"lastName\":\"" + ln + "\"}";
StringContent _contt = new StringContent(jsonString, Encoding.UTF8, "application/json");
var _response = await _client.PostAsync(_url, _contt);
var _content = await _response.Content.ReadAsStringAsync();
_resultModel = JsonConvert.DeserializeObject<BBHEmployee>(_content);
}
return Json(_resultModel, JsonRequestBehavior.AllowGet);
}
with both ways, it returns StatusCode 400(BadRequeest)
in that case, this BambhooHr API endpoint requires XML data to post,
so I use this and it's working fine.
var xmlString = "<employee><field id = \"firstName\">"+fn+"</field><field id = \"lastName\">"+ln+"</field></employee>";
var _contt = new StringContent(xmlString,Encoding.UTF8, "text/xml");
var _response = await _client.PostAsync(_url, _contt);

How to PATCH data using System.Net.Http

I have uploaded a file to SharePoint and found out what id it has. Now I need to update some of the other columns on that listitem. The problem is that System.Net.Http.HttpMethod.Patch doesn't exist.
public static async Task<string> UpdateFileData()
{
var (authResult, message) = await Authentication.AquireTokenAsync();
string updateurl = MainPage.rooturl + "lists/edd49389-7edb-41db-80bd-c8493234eafa/items/" + fileID + "/";
var httpClient = new HttpClient();
HttpResponseMessage response;
try
{
var root = new
{
fields = new Dictionary<string, string>
{
{ "IBX", App.IBX }, //column to update
{ "Year", App.Year}, //column to update
{ "Month", App.Month} //column to update
}
};
var s = new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.MicrosoftDateFormat };
var content = JsonConvert.SerializeObject(root, s);
var request = new HttpRequestMessage(HttpMethod.Put, updateurl);
request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", authResult.AccessToken);
request.Content = new StringContent(content, Encoding.UTF8, "application/json");
response = await httpClient.SendAsync(request);
var responseString = await response.Content.ReadAsStringAsync();
return responseString;
}
catch (Exception ex)
{
return ex.ToString();
}
}
Modify the code as below.
public static async Task<string> UpdateFileData()
{
var (authResult, message) = await Authentication.AquireTokenAsync();
string updateurl = MainPage.rooturl + "lists/edd49389-7edb-41db-80bd-c8493234eafa/items/" + fileID + "/";
var httpClient = new HttpClient();
HttpResponseMessage response;
try
{
var root = new
{
fields = new Dictionary<string, string>
{
{ "IBX", App.IBX }, //column to update
{ "Year", App.Year}, //column to update
{ "Month", App.Month} //column to update
}
};
var s = new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.MicrosoftDateFormat };
var content = JsonConvert.SerializeObject(root, s);
var request = new HttpRequestMessage(new HttpMethod("PATCH"), updateurl);
request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", authResult.AccessToken);
request.Content = new StringContent(content, System.Text.Encoding.UTF8, "application/json;odata=verbose");
response = await httpClient.SendAsync(request);
var responseString = await response.Content.ReadAsStringAsync();
return responseString;
}
catch (Exception ex)
{
return ex.ToString();
}
}
Or we can also use REST API to update list item by ID.
Refer to: SharePoint 2013 REST Services using C# and the HttpClient
It dependents whether .NET Core or .NET Framework is utilized, in case of `.NET Core HttpClient.PatchAsync Method could be utilized.
In case of .NET Framework ListItem could be updated like this:
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
client.BaseAddress = new Uri("https://graph.microsoft.com");
var listItemPayload = new Dictionary<string, object>
{
{"Color", "Fuchsia"},
{"Quantity", 934}
};
var requestContent = new StringContent(JsonConvert.SerializeObject(listItemPayload));
requestContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
var response = await client.PatchAsync(new Uri($"https://graph.microsoft.com/v1.0/sites/{siteId}/lists/{listId}/items/{itemId}/fields"), requestContent);
var data = response.Content.ReadAsStringAsync().Result.ToString();
}
where PatchAsync is the extension method for HttpClient class:
public static class HttpClientExtensions
{
public static async Task<HttpResponseMessage> PatchAsync(this HttpClient client, Uri requestUri, HttpContent iContent)
{
var method = new HttpMethod("PATCH");
var request = new HttpRequestMessage(method, requestUri)
{
Content = iContent
};
HttpResponseMessage response = new HttpResponseMessage();
try
{
response = await client.SendAsync(request);
}
catch (TaskCanceledException e)
{
Debug.WriteLine("ERROR: " + e.ToString());
}
return response;
}
}
All the credits for extension method go to the author of this answer
Can't you just use the HttpMethod class constructor?
new HttpMethod("PATCH");
Source: https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpmethod.-ctor?view=netframework-4.7.2#System_Net_Http_HttpMethod__ctor_System_String_

How to reconstruct return type object in web api

Given that I have the following web api method in my controller
public HttpResponseMessage PostGrantAccess(GrantAccessRequest grantAccessRequest)
{
var deviceId = grantAccessRequest.DeviceId;
var grantAccessResponse = new GrantAccessResponse()
{
Status = "OK"
};
var response = Request.CreateResponse<GrantAccessResponse>(HttpStatusCode.OK, grantAccessResponse);
return response;
}
Client calling code:
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:55208/");
var request = new GrantAccessRequest { DeviceId = "bla" };
var response = client.PostAsJsonAsync("api/accesspanel", request).Result;
if (response.IsSuccessStatusCode)
{
var uri = response.Headers.Location;
}
}
How do I get back GrantAccessResponse at the client?
response.Content.ReadAsAsync<GrantAccessResponse>()

Categories