Quantcast
Channel: Microsoft Dynamics CRM Forum - Recent Threads
Viewing all articles
Browse latest Browse all 82002

WebApi to create record in console application failing due to bad request error

$
0
0

Hello everyone,

I need your help in resolving an issue. I have created a console application which talks to the Dynamics 365 9.2 online instance, creates a record. I have created the app, secret and established the connection with the environment. However, I am not able to create the record. It says bad request. Please help.

using System;
using System.Configuration;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Crm.Sdk.Messages;
using System.Net;
using System.ServiceModel.Description;
using Microsoft.Xrm.Tooling.Connector;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System.Net.Http.Headers;
using System.Net.Http;
using Newtonsoft.Json.Linq;

namespace GMG_QB_Integration
{
    class Program
    {
        static void Main(string[] args)
        {
            String url = "orgname.crm.dynamics.com";
            string clientId = "00000000-0000-0000-0000-000000000000";
            string secret = "zzzzzzzzzzzzzzzzzzzzzzzzz";
            AuthenticationContext authContext = new AuthenticationContext("login.microsoftonline.com/00000000-0000-0000-0000-000000000000");
            ClientCredential credential = new ClientCredential(clientId, secret);
            AuthenticationResult authResult = authContext.AcquireToken(url, credential);
            string apiVersion = "9.2";
            string webApiUrl = $"{url}/api/data/v{apiVersion}/";
            var authHeader = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);

            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(webApiUrl);
                client.DefaultRequestHeaders.Authorization = authHeader;
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                client.DefaultRequestHeaders.Add("Prefer", "odata.include-annotations = *");
                // Use the WhoAmI function
                var response = client.GetAsync("WhoAmI").Result;

                if (response.IsSuccessStatusCode)
                {
                    //Get the response content and parse it.  
                    JObject body = JObject.Parse(response.Content.ReadAsStringAsync().Result);
                    Guid userId = (Guid)body["UserId"];
                    Console.WriteLine("Your UserId is {0}", userId);
                    Task.WaitAll(Task.Run(async () => await CreateContactOld(client)));

                }
                else
                {
                }               

            }

        }
        static async Task CreateContactOld(HttpClient httpClient)
        {
            string jobCreateuri = string.Empty;
            JObject jobCreate = new JObject();
            jobCreate.Add("sa_name", "Test");
            HttpRequestMessage request1 = new HttpRequestMessage(HttpMethod.Post, ".../sa_jobs");
            request1.Content = new StringContent(jobCreate.ToString(), System.Text.Encoding.UTF8, "application/json");
            HttpResponseMessage response1 = await httpClient.SendAsync(request1);
            if (response1.StatusCode == HttpStatusCode.NoContent)
            {
                Console.WriteLine("Job created" + jobCreate.GetValue("sa_name"));
                HttpResponseHeaders responseheaders = response1.Headers;
                jobCreateuri = responseheaders.Location.AbsoluteUri;
            }
            else
            {
                Console.WriteLine("failed to create job");
            }

        }
    }

}

Viewing all articles
Browse latest Browse all 82002

Latest Images

Trending Articles



Latest Images