dynamics-crmmicrosoft-dynamicsdynamics-crm-2016webapidynamics-crm-webapi

Dynamics 2016 Web API C# Create Products


I am working to add Products to our Dynamics 2016 CRM using the Web Api and C#.

Here is the code - it returns an Internal Server Error. I know that the code works when I do this for a Contact Entity, so it is a matter of what to pass in to the call. I am not sure where to go from here so any help would be great.

Many thanks!


using Newtonsoft.Json.Linq;
using System;
using System.Net;
using System.Configuration;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System.IO;

namespace ProductsToCrm {
    public partial class InsertProducts {
        static void Main(string[] args) {
            Task.WaitAll(Task.Run(async () => await Create_Products()));
        }

        static async Task Create_Products() {
            Console.WriteLine("--Section Products started--");
            try {
                HttpClient httpClient = new HttpClient(new HttpClientHandler() { Credentials = new NetworkCredential("uName", "uPassword", "uDomain") });
                httpClient.BaseAddress = new Uri("http://this.orgname.org:port/orgname/api/data/v8.2/");
                httpClient.Timeout = new TimeSpan(0, 1, 0);
                httpClient.DefaultRequestHeaders.Add("User-Agent", "C# console program");

                JObject jProduct = new JObject();
                jProduct.Add("name", "testing_a_product1");
                jProduct.Add("description", "I am testing");

                string opportunity1Uri;
                List<string> entityUris = new List<string>();

                HttpRequestMessage createRequest1 =
                    new HttpRequestMessage(HttpMethod.Post, "products");
                createRequest1.Content = new StringContent(jProduct.ToString(),
                    Encoding.UTF8, "application/json");
                HttpResponseMessage createResponse1 =
                    await httpClient.SendAsync(createRequest1);
                if(createResponse1.StatusCode == HttpStatusCode.NoContent) {
                    Console.WriteLine("Product '{0} {1}' created.", jProduct.GetValue("name"), jProduct.GetValue("description"));
                    opportunity1Uri = createResponse1.Headers.GetValues("OData-EntityId").FirstOrDefault();
                    entityUris.Add(opportunity1Uri);
                    Console.WriteLine("Created Entity URI: {0}", opportunity1Uri);
                } else {
                    Console.WriteLine("Failed to create Entity for reason: {0} == {1} == {2}",
                        createResponse1.ReasonPhrase, createRequest1, "test");
                }
            } catch(Exception ex) {
                Console.WriteLine(ex.ToString());
            }
            Console.ReadLine();
        }
    }
}

Solution

  • There are some required attributes like name, productnumber, defaultuomscheduleid (Unit Group), defaultuomid (Default Unit), and quantitydecimal (Decimals supported) while creating Product record, even in CRM UI. You have to pass all for successful transaction.

    You can use postman or CRM REST builder for dev/test purpose.

    The basic payload for creating a product is as below: Reference

    {
    
       "name": "new product",
    
       "productnumber": "12345",
    
       "defaultuomscheduleid@odata.bind": "/uomschedules(54692a01-4c22-45eb-a224-a157b9a6a0b3)",
    
       "defaultuomid@odata.bind": "/uoms(d41f6ab2-6087-477b-a7f1-c4d1df10a57e)",
    
       "quantitydecimal": 0
    
    }