web
You’re offline. This is a read only version of the page.
close
Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
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

I have the same question (0)
  • Verified answer
    Naveen Ganeshe Profile Picture
    3,397 User Group Leader on at

    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"

  • Verified answer
    Bipin D365 Profile Picture
    28,983 Moderator on at

    Hello,

    Replace contactUri with _serviceUri in your code

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

  • King Lamarrr Profile Picture
    10 on at

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

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

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Neeraj Kumar – Community Spotlight

We are honored to recognize Neeraj Kumar as our Community Spotlight honoree for…

Leaderboard > Microsoft Dynamics 365 | Integration, Dataverse, and general topics

#1
#ManoVerse Profile Picture

#ManoVerse 93

#1
Siv Sagar Profile Picture

Siv Sagar 93 Super User 2025 Season 2

#3
Martin Dráb Profile Picture

Martin Dráb 62 Most Valuable Professional

Last 30 days Overall leaderboard

Product updates

Dynamics 365 release plans