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();
}
}
}
Console
"logging" unless the intent is really to continue: the program should happily terminate with a useful trace. (Run the program in an already opened terminal.) – user2864740