Create records using Web api C# in Dynamics 365

Here is the code to create records using C# + Web Api in Dynamics 365

private static async Task CreateRecord()
        {
            JObject contact1 = new JObject{
                        { "firstname", "Bangar" },
                        { "lastname", "Raju" },
                        { "annualincome", 80000 }
                        };

            contact1["jobtitle"] = "Junior Developer";
            //for Custom data type for Account entity. if you want contat then "parentcustomerid_contact@odata.bind"
            contact1.Add("parentcustomerid_account@odata.bind", "/accounts(475B158C-541C-E511-80D3-3863BB347BA8)");
            //For Custom Attribute
            /*
             Data Type: Customer
             field Name: new_name
             */
            contact1.Add("new_Account_account@odata.bind", "/accounts(475B158C-541C-E511-80D3-3863BB347BA8)");
            //Custom lookup
            contact1.Add("new_Lead@odata.bind", "/leads(E9975EA3-531C-E511-80D8-3863BB3CE2C8)");
            //OOB lookup
            contact1.Add("originatingleadid@odata.bind", "/leads(494FA496-3FF2-E311-9864-A45D36FC5F1C)");

            var httpClient = new HttpClient
            {
                BaseAddress = new Uri(serviceUrl + "/api/data/v9.0/"),
                Timeout = new TimeSpan(0, 2, 0)
            };
            httpClient.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");
            httpClient.DefaultRequestHeaders.Add("OData-Version", "4.0");
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);

            // Add this line for TLS complaience
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "contacts")
            {
                Content = new StringContent(contact1.ToString(), Encoding.UTF8, "application/json")
            };

            HttpResponseMessage response = await httpClient.SendAsync(request);
            if (response.StatusCode == HttpStatusCode.NoContent)
            //204
            {
                Console.WriteLine("POST succeeded, entity created!");
                //optionally process response message headers or body here, for example:
                var entityUri = response.Headers.GetValues("OData - EntityId").FirstOrDefault();
            }
            else
            {
                Console.WriteLine("Operation failed: {0}", response.ReasonPhrase);
            }
        }

Comments

Popular posts from this blog

Connecting Dynamics 365 Web api using external HTML page

Get azure blob files inside Sub Directories

Interview questions on MS CRM