Saving data with the Dynamics Web Api

In my previous posts on using the Dynamics Web Api, I invested a significant amount of time in figuring out the connection protocols, querying and accessing data from the results (not being an Azure, Active Directory or JSON expert).

However, when it came to saving data, the hard work was over and I was able to do with relative ease.

To save data via the Dynamics Web API, the interface is quite similar to how you would access your controls via LateBinding except that instead of the Entity object you are consuming a JObject.

JObject phoneCall = new JObject();
 phoneCall["subject"] = "Here comes my call";
 phoneCall["phonenumber"] = "888-999-7777";
 phoneCall["scheduledend"] = DateTime.Now;
 phoneCall["description"] = "Who called me.";
//The Direction Code is always an incoming call.
 phoneCall["directioncode"] = false;

string recordId = string.Empty;
 try
 {
 HttpClient httpClient = new HttpClient();
 httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
 httpClient.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");
 httpClient.DefaultRequestHeaders.Add("OData-Version", "4.0");
 httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
 httpClient.BaseAddress = new Uri(dyanmicsTenant + "/api/data/v8.1/");
 HttpResponseMessage response = SendAsJsonAsync(httpClient, HttpMethod.Post, "phonecalls", phoneCall).Result;

//If the response is Successfully executed then it will return the value true
 if (response.StatusCode == System.Net.HttpStatusCode.NoContent)
 {

//Do something super cool here.

}
 }
 catch (Exception error)
 {

throw new Exception(error.Message);
 }

There is nothing crazy in that code except for the reference in our SendAsJsonAsync event that we are creating a phonecall, to our entity “phonecalls”.

You can access the full implementation of SendAsJsonAsync here on MSDN.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s