Skip to main content

Notifications

Announcements

No record found.

Microsoft Dynamics 365 | Integration, Dataverse...
Answered

I am trying to build a WEB API to update entity records on CRM2016 but i got an errorr which said "the name contactUri does not exist in this context" please what do i do? the code is below.

(1) ShareShare
ReportReport
Posted on by 10

using System;

using System.Collections.Generic;

using System.Linq;

using System.Threading.Tasks;

using Microsoft.AspNetCore.Http;

using Microsoft.AspNetCore.Mvc;

using Newtonsoft.Json;

using System.Net.Http.Headers;

using Newtonsoft.Json.Linq;

using System.Text;

using System.Net;

using System.Net.Http;

using LHOnBoardingAndCaseManagement.Resources;

namespace LHOnBoardingAndCaseManagement.Controllers

{

    [ApiController]

    [Route("[controller]")]

    public class UpdateEnrolleeController : Controller

    {

        private string _userName = Properties.Resources.UserName;

        private string _passWord = Properties.Resources.Password;

        private string _domain = Properties.Resources.Domain;

        private string _serviceUri = Properties.Resources._serviceURI;

        private string DateTimeFormat = "yyyy-MM-dd";

        HttpMessageHandler messageHandler;

        HttpClient httpClient;

        [HttpPost]

        public async Task<PrognosisResponse> Post([FromBody] UpdateEnrolleeResource resource)

        {

            PrognosisResponse MethodResponse = new PrognosisResponse();

            string crmid = " ", status = " ", statusMessage = " ", corporateClientId = " ";

            NetworkCredential credentials = new NetworkCredential(_userName, _passWord, _domain);

            messageHandler = new HttpClientHandler() { Credentials = credentials };

            try

            {

                using (this.httpClient = new HttpClient(messageHandler))

                {

                    httpClient.BaseAddress = new Uri(_serviceUri);

                    httpClient.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"));

                        //get crm id

                        string queryOptions = "?$select=contactid&$filter=new_enrolleeid eq " +resource.enrolleeid;

                    HttpResponseMessage response = await SendCrmRequestAsync(HttpMethod.Get, contactUri +  queryOptions, true);                    

                    JObject retrievedRecord = JsonConvert.DeserializeObject<JObject>(await response.Content.ReadAsStringAsync());

                    crmid = retrievedRecord["contactid"].ToString();

                        //     status = "success";

                    // define UpdateEnrollee variable

                    JObject UpdateEnrollee = new JObject

                       {

                        {"new_enrolleeid", resource.enrolleeid },

                        {"new_cifno", resource.cifno },

                        {"firstname", resource.firstname},

                        {"lastname", resource.lastname},

                        {"emailaddress1", resource.email},

                        {"mobilephone", resource.mobilephone},

                        {"address1_composite", resource.address1_composite },

                       };

                    // Send request to update the enrollee in the CRM system

                    HttpRequestMessage request = new HttpRequestMessage();

                    request = new HttpRequestMessage(HttpMethod.Patch, _serviceUri + "api/data/v8.1/contacts(" + resource.enrolleeid + ")");

                    request.Content = new StringContent(UpdateEnrollee.ToString(), Encoding.UTF8, "application/json");

                    HttpResponseMessage queryResponse = await httpClient.SendAsync(request);

                    if (queryResponse.IsSuccessStatusCode)

                    {

                        status = "Success";

                        statusMessage = "Enrollee information updated successfully.";

                    }

                    else

                    {

                        status = "Failed";

                        statusMessage = "Failed to update enrollee information. Error: " + queryResponse.ReasonPhrase;

                    }

                    MethodResponse.ID = crmid;

                    MethodResponse.Status = status;

                    MethodResponse.Message = statusMessage;

                    return MethodResponse;

                }

            }

            catch (Exception ex)

            {

                status = "Failed";

                statusMessage = ex.Message;

                MethodResponse.ID = crmid;

                MethodResponse.Status = status;

                MethodResponse.Message = statusMessage;

                return MethodResponse;

            }

        }

        private async Task<HttpResponseMessage> SendCrmRequestAsync(HttpMethod method, string query, Boolean formatted = false, int maxPageSize = 10)

        {

            HttpRequestMessage request = new HttpRequestMessage(method, query);

            request.Headers.Add("Prefer", "odata.maxpagesize=" + maxPageSize.ToString());

            

            if (formatted)

                request.Headers.Add("Prefer", "odata.include-annotations=OData.Community.Display.V1.FormattedValue");

            return await httpClient.SendAsync(request);

        }

    }

    

}3386.ERROR-1.png

  • King Lamarrr Profile Picture
    King Lamarrr 10 on at
    RE: I am trying to build a WEB API to update entity records on CRM2016 but i got an errorr which said "the name contactUri does not exist in this context" please what do i do? the code is below.

    Thank you, i have done that but I still got another error after running with POSTMAN. The error is "No such host is known"

  • Verified answer
    Bipin D365 Profile Picture
    Bipin D365 28,964 Super User 2024 Season 1 on at
    RE: I am trying to build a WEB API to update entity records on CRM2016 but i got an errorr which said "the name contactUri does not exist in this context" please what do i do? the code is below.

    Hello,

    Replace contactUri with _serviceUri in your code

    You have used ContactUri in your code but never defined anywhere in your code...

  • Verified answer
    Naveen Ganeshe Profile Picture
    Naveen Ganeshe 3,393 User Group Leader on at
    RE: I am trying to build a WEB API to update entity records on CRM2016 but i got an errorr which said "the name contactUri does not exist in this context" please what do i do? the code is below.

    Hello,

    Looks like you haven't defined the "contactUri" in your code. Please declare a variable on top something like:

    string contactUri= "https:// <your org>/api/data/v8.1/contacts"

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

December Spotlight Star - Muhammad Affan

Congratulations to a top community star!

Top 10 leaders for November!

Congratulations to our November super stars!

Tips for Writing Effective Verified Answers

Best practices for providing successful forum answers ✍️

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 291,391 Super User 2024 Season 2

#2
Martin Dráb Profile Picture

Martin Dráb 230,445 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Product updates

Dynamics 365 release plans