Bad request when posting to OData Data Entity in Dynamics 365 - post

I've created a public Data Entity in dynamics with the following fields:
I keep getting a bad request response, but I'm not sure why.
I've tried to make a POST request in two ways:
1.
HireAction hireAction = new HireAction() { CompanyName = "DEMF", MovieId = "DEMF-000000014", HireActionStatus = "Created" };
string jsonMessage = JsonConvert.SerializeObject(hireAction);
using (HttpClient client = new HttpClient())
{
HttpRequestMessage requestMessage = new
HttpRequestMessage(HttpMethod.Post, "MyDynamicsEnvironmentName/data/HireActions?cross-company=true");
requestMessage.Content = new StringContent(jsonMessage, Encoding.UTF8, "application/json");
requestMessage.Headers.Add("Authorization", AuthResult.AuthorizationHeader);
HttpResponseMessage response = client.SendAsync(requestMessage).Result;
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
//Logic
}
}
var url = "MyDynamicsEnvironmentName/data/HireActions?cross-company=true";
var req = HttpWebRequest.Create(url);
req.Method = "POST";
req.ContentType = "application/json";
req.Headers["Authorization"] = AuthResult.AuthorizationHeader;
HireAction hireAction = new HireAction() { CompanyName = "DEMF", MovieId = "DEMF-000000014", HireActionId = "12345", HireActionStatus = "Created" };
var jsonSettings = new JsonSerializerSettings
{
DateTimeZoneHandling = DateTimeZoneHandling.Local
};
var postString = "CompanyName='DEMF'" + "&MovieId='DEMF-000000014'" + "&HireActionId=132&HireActionStatus='Created'";
var data = JsonConvert.SerializeObject(postString, jsonSettings);
var bytes = Encoding.Default.GetBytes(postString);
var newStream = req.GetRequestStream();
newStream.Write(bytes, 0, bytes.Length);
newStream.Close();
using (var resp = req.GetResponse())
{
var results = new StreamReader(resp.GetResponseStream()).ReadToEnd();
}
Some keypoints:
-Of course you'd replace MyDynamicsEnvironmentName with the URL for the environment. The URL is correct and verified however, by the fact that GET requests do work
-The Authresult.AuthorizationHeader contains a valid token, also validated by working GET requests
As said before, both of these result in a bad request. Does someone know what is wrong or missing?

Related

MS Graph create event 400 bad request

I have code that get's the default calendar and stores the id in a variable called calendar id. I then I then get a list of availabilities (which are events in our system) the end time and the start time are recorded in utc and I want to put those events into an office 365 calendar.
This is my code which is generating and 400 Bad request. Does anyone have any idea what I am doing wrong?
using (HttpClient httpClient = new HttpClient())
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", msBearerToken);
var callJson = new
{
Subject = "Booking",
Body = new ItemBody
{
ContentType = BodyType.Html,
Content = "Available"
},
Start = new DateTimeTimeZone
{
DateTime = availabilitySummery.StartDateUTC.ToString(),
TimeZone = "Europe/London"
},
End = new DateTimeTimeZone
{
DateTime = availabilitySummery.EndDateUTC.ToString(),
TimeZone = "Europe/London"
}
};
string path = $"/me/calendars/{calendarId}/events";
// string path = "/me/calendars/events";
path = "https://graph.microsoft.com/v1.0" + path;
HttpResponseMessage responseMessage = await httpClient.PostAsJsonAsync(path, callJson);}
Date should be ISO8601 formatted.
Replace .ToString() by .ToString("o") when you want to convert dates to string.
Ref: The round-trip ("O", "o") format specifier
And createdDateTime property of event object
Update: This worked:
using (HttpClient httpClient = new HttpClient())
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", msBearerToken);
var callJson = new
{
Subject = "Booking",
Body = new
{
ContentType = BodyType.Html.ToString(),
Content = "Available"
},
Start = new
{
DateTime = availabilitySummery.StartDateUTC.ToString("yyyy-MM-ddTHH:mm:ss"),
TimeZone = "GMT Standard Time"
},
End = new
{
DateTime = availabilitySummery.EndDateUTC.ToString("yyyy-MM-ddTHH:mm:ss"),
TimeZone = "GMT Standard Time"
}
};
string path = $"/me/calendars/{calendarId}/events";
string jsoncall = JsonConvert.SerializeObject(callJson);
path = "https://graph.microsoft.com/v1.0" + path;
HttpResponseMessage responseMessage = await httpClient.PostAsJsonAsync(path, callJson);
string content = await responseMessage.Content.ReadAsStringAsync();
if (!responseMessage.IsSuccessStatusCode)
{
return false;
}
}

NMI Create Subscription Giving Authentication Failed Error

In my project i am configuring NMI Payment gateway in which i create a plan and then customer and now creating subscription against that plan but client giving response of Authentication Failed below is the response of client
response=3&responsetext=Authentication Failed&authcode=&transactionid=0&avsresponse=&cvvresponse=&orderid=&type=&response_code=300
Below is my service code
var addsubscription = "add_subscription";
var date = DateTime.UtcNow;
var year = date.Year.ToString();
var month = date.Month.ToString();
var padedmonth = month.PadLeft(2, '0');
var day = date.Day.ToString();
var padedday = day.PadLeft(2, '0');
var startdate = year + padedmonth + padedday;
string option = $"plan_id={model.Data.StripePlanId}&recurring={addsubscription}&payment_token={model.Data.StripePaymentToken}&ccnumber={model.Data.CCNumber}&ccexp={model.Data.CCExpiry}&start_date={startdate}";
var requester = new NMIGatewayRequester();
var relativeUrl = "https://secure.networkmerchants.com/api/transact.php";
var response = requester.Request(relativeUrl, RestSharp.Method.POST, option);
var customerResponseObj = GetPaymentApiResponseValues(response.Split('&').Select(x => x.Split('=')).ToDictionary(x => x[0], x => x[1]));
public class NMIGatewayRequester
{
private RestClient client;
public string Request(string relativeUrl, RestSharp.Method verb, string option)
{
client = new RestSharp.RestClient($"{relativeUrl}") { Timeout = -1 };
var request = new RestRequest(verb);
request.AddParameter("application/x-www-form-urlencoded", option, ParameterType.RequestBody);
var subResponse = client.Execute(request);
if (!subResponse.IsSuccessful)
{
throw new Exception("Unable to Process Request");
}
return subResponse.Content;
}
}
You need to include a security key in your options:
string option = $"security_key=[...]&plan_id={model.Data.StripePlanId}&[...]";
See documentation here.

Using webforms with API - returns null values

Can anybody help me?
This code work fine with no parameter:
private void PopulateGridView()
{
string apiUrl = apiurl + "local_stud_listgrupmenu";
string inputJson = (new JavaScriptSerializer()).Serialize(input);
WebClient client = new WebClient();
client.Headers["Content-type"] = "application/json";
client.Headers[HttpRequestHeader.ContentType] = "application/json";
client.Encoding = Encoding.UTF8;
string json2 = client.UploadString(apiUrl,"POST");
Response.Write("output:" + json2.ToString());
}
but this code below return null with post parameter, what wrong my code :)
private void crudinsert()
{
string data;
string apiUrl = apiurl + "ins_rec_crudparentmenu";
string x = "";
var vm = new { mod = "0", moduldesc ="test'", modulurl = "tesx.aspx", idparent= "0" };
using (var clien2 = new WebClient())
{
var dataString = (new JavaScriptSerializer()).Serialize(vm);
client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
x = client.UploadString(new Uri(apiUrl), "POST", dataString);
}
Response.Write("output:"+x);
}

Send HTTP Post with .Net Core

how can I set up an HTTP call in asp.net core mvc
$url = "https://prod-25.northeurope.logic.azure.com:443/..."
$parms = #{
Uri = $url
Method = 'post'
ContentType = 'application/json'
body = '{"recipient": "stefan.","body":"Test"}'
}
curl #parms
using
using System.Net.Http;
and your code will be
var url = "http://yoursite.com/Home/Insert";
var data = new {"recipient"= "stefan.", "body"="Test"};
using(var client = new HttpClient())
{
var response = await client.PostAsJsonAsync(url, data);
string responseContent = await response.Content.ReadAsStringAsync(); // only to see response as text ( debug perpose )
var result = await ProcessedResult<TResult>(response); // cast it to TResult or any type that you expect to retrieve
}

AcquireTokenByAuthorizationCodeAsync does not complete

Here is my code. It's been over a month I'm trying to add calendars in Outlook but nothing is working :( please help. The function AcquireTokenByAuthorizationCodeAsync never completes. And the token.Result is always null
string authority = ConfigurationManager.AppSettings["authority"];
string clientID = ConfigurationManager.AppSettings["clientID"];
Uri clientAppUri = new Uri(ConfigurationManager.AppSettings["clientAppUri"]);
string serverName = ConfigurationManager.AppSettings["serverName"];
var code = Request.Params["code"];
AuthenticationContext ac = new AuthenticationContext(authority, true);
ClientCredential clcred = new ClientCredential(clientid, secretkey);
//ac = ac.AcquireToken(serverName, clientID, clientAppUri, PromptBehavior.Auto);
//string to = ac.AcquireToken(serverName, clientID, clientAppUri, PromptBehavior.Auto).AccessToken;
var token = ac.AcquireTokenByAuthorizationCodeAsync(code, new Uri("http://localhost:2694/GetAuthCode/Index/"), clcred, resource: "https://graph.microsoft.com/");
string newtoken = token.Result.AccessToken;
ExchangeService exchangeService = new ExchangeService(ExchangeVersion.Exchange2013);
exchangeService.Url = new Uri("https://outlook.office365.com/" + "ews/exchange.asmx");
exchangeService.TraceEnabled = true;
exchangeService.TraceFlags = TraceFlags.All;
exchangeService.Credentials = new OAuthCredentials(token.Result.AccessToken);
exchangeService.FindFolders(WellKnownFolderName.Root, new FolderView(10));
Appointment app = new Appointment(exchangeService);
app.Subject = "";
app.Body = "";
app.Location = "";
app.Start = DateTime.Now;
app.End = DateTime.Now.AddDays(1);
app.Save(SendInvitationsMode.SendToAllAndSaveCopy);
I have experienced this issue when I call the AcquireTokenByAuthorizationCodeAsync using result instead of using await key words and all these code was in a asynchronously controller in the MVC.
If you are in the same scenario, you can fix this issue by two ways:
1.Always using the async, await like code below:
public async System.Threading.Tasks.Task<ActionResult> About()
{
...
var result =await ac.AcquireTokenByAuthorizationCodeAsync(code, new Uri("http://localhost:2694/GetAuthCode/Index/"), clcred, resource: "https://graph.microsoft.com/");
var accessToken = result.AccessToken;
...
}
2.Use the synchronization controller:
public void About()
{
...
var result =ac.AcquireTokenByAuthorizationCodeAsync(code, new Uri("http://localhost:2694/GetAuthCode/Index/"), clcred, resource: "https://graph.microsoft.com/").Result;
var accessToken = result.AccessToken;
...
}

Resources