MS Dynamics 365 - Create records using ms dynamics Web API

Ankaprasad
Posted by Ankaprasad under C# category on | Points: 40 | Views : 2268
        public static string CreateLead(string accessToken , string countryid, string userid)
{
string leadUri = string.Empty;
try
{
JObject leadObj = new JObject { };
leadObj["firstname"] = "Prasad"; // text field
leadObj["lastname"] = "Testing"; // text field
leadObj["srin_leadsource"] = 1; // Option set
leadObj["srin_Country@odata.bind"] = "/srin_countries(" + countryid + ")"; // Set custom lookup value
leadObj["ownerid@odata.bind"] = "/systemusers(" + userid + ")"; // Set OOB lookup Value

leadUri= Task.Run(async () => await CallDynamicsAPI(accessToken, "leads", leadObj)).Result;
}
catch (Exception ex)
{

throw;
}
return leadUri;
}


To create access token/authToken please go through my previous post from the below URL.

http://www.dotnetfunda.com/codes/show/8371/ms-dynamics-365-consume-dynamics-web-api-from-csharp

Note : Copy entity and field names using CRM Rest Builder because web api will throw an error if we use entity display / schema names.


 public static async Task<string> CallDynamicsAPI(string accesToken, string entityName, JObject entityObject)
{

string apiUrl = "https://xyka12.api.crm8.dynamics.com/api/data/v9.1/";
string recordUri = "";
HttpClient client = new HttpClient();
client.Timeout = TimeSpan.FromSeconds(360);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accesToken);
client.BaseAddress = new Uri(apiUrl);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");
client.DefaultRequestHeaders.Add("OData-Version", "4.0");
client.DefaultRequestHeaders.Add("Cache-Control", "no-cache");

HttpRequestMessage createHttpRequest = new HttpRequestMessage(HttpMethod.Post, apiUrl + entityName);
createHttpRequest.Content = new StringContent(entityObject.ToString(), Encoding.UTF8, "application/json");
var response = await client.SendAsync(createHttpRequest);
response.EnsureSuccessStatusCode();

if (response.StatusCode == HttpStatusCode.NoContent)
{
recordUri = response.Headers.GetValues("OData-EntityId").FirstOrDefault();
Console.WriteLine("Record URI: {0}", recordUri);
Console.WriteLine("Record created in MS Dynamics.");
}
return recordUri;
}

Comments or Responses

Login to post response