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 CRM (Archived)

Insert data on lookupfield via WebApi dynamics 365

(1) ShareShare
ReportReport
Posted on by 1,257

Hi experts,

i have this question i'm tryingto set a record on dynamics 365 via web api using a console application on c# string data Works like a charm, but i need to insert data on a lookup field that is related to the lead entity and i don't know what the heck i should do :D...

Here the scenario, i call some variables, one of them its queried to CRM via web Api to return his GUID, when i receive the GUID i have to set it on the lookup field, but didn't know how to insert it... always get a brake on that action or the record is created without that data...

Here the code that i'm trying to run.

string LeadName = "Ville 2";
string LeadLastName = "Web Api Lead 2";
string LeadEmail = "3webapi@lead1.com";
string LeadTopic = "WebApi Lead 3";
string LeadSource = "Contact Us";
string queryLeadSource;
           
queryLeadSource = "new_leadsources?$select=new_leadsourceid&$filter=new_name eq '" + LeadSource + "'";          

HttpResponseMessage responsePost = await client.PostAsJsonAsync(queryLeadSource, true);

string leadSourceId = null;
          
if (responsePost.StatusCode == HttpStatusCode.OK){
   JObject lsRetreived = JsonConvert.DeserializeObject<JObject>(await
   responsePost.Content.ReadAsStringAsync());
   leadSourceId = lsRetreived["new_leadsourceid"].ToString();
}
else{
   Console.WriteLine("Error retrieving lead source ID!");
   throw new CrmHttpResponseException(responsePost.Content);
}
            
JObject newLead = new JObject();
newLead.Add("firstname", LeadName);
newLead.Add("lastname", LeadLastName);
newLead.Add("emailaddress1", LeadEmail);
newLead.Add("subject", LeadTopic);
newLead.Add("new_leadsource@odata.bind", "/new_leadsources("+ leadSourceId +")");

HttpResponseMessage response = await client.PostAsJsonAsync("leads", newLead);


*This post is locked for comments

I have the same question (0)
  • Suggested answer
    Aric Levin - MVP Profile Picture
    30,190 Moderator on at

    Take a look at this blog article, which might help you out:

    www.inogic.com/.../set-values-of-all-data-types-using-web-api-in-dynamics-crm

    Also, is new_leadsource the name of your custom entity that you are trying to reference or is this lead?

    Hope this helps.

  • Vile Andreas Rantala Profile Picture
    1,257 on at

    Hi, thanks for your response, that's other entity.

  • Vile Andreas Rantala Profile Picture
    1,257 on at

    But also my issue it's that i have to query the GUID based on the name of the related record on leads, but i don't know how to set it on the Lookupfield, i mean, how i should get the result to put the GUID on the lead new_leadsource related entity.

  • Aric Levin - MVP Profile Picture
    30,190 Moderator on at

    Not sure, but isn't this line supposed to be:

    newLead.Add("new_leadsourceid@odata.bind", "/new_leadsources("+ leadSourceId +")");

    You are retrieving it above as new_leadsourceid

  • Suggested answer
    Syed Ibrahim Profile Picture
    6,257 on at

    Refer the below as well.

    http://himbap.com/blog/?p=2043

  • Suggested answer
    Nithya Gopinath Profile Picture
    17,078 on at

    Hi Ville,

    Try to replace the lines as shown below.

    JObject newLead = new JObject();
    newLead["firstname"] = LeadName;
    newLead["lastname"] = LeadLastName;
    newLead["emailaddress1"] = LeadEmail;
    newLead["subject"] = LeadTopic;
    newLead["new_leadsource@odata.bind"] = "/new_leadsources("+ leadSourceId.Replace("{","").Replace("}","") +")";

    Hope this helps.

  • Vile Andreas Rantala Profile Picture
    1,257 on at

    Aric, when i do that the console crash down :(

  • Vile Andreas Rantala Profile Picture
    1,257 on at

    i replace the code for this one, but i'm getting a exception on the output line T_T

    using System;
    using System.Net;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using Microsoft.IdentityModel.Clients.ActiveDirectory;
    using System.Net.Http;
    using System.Net.Http.Headers;
    using Newtonsoft.Json.Linq;
    using Newtonsoft.Json;
    
    namespace Integration.Marketing_Activities_Creation
    {
        class Create
        {
            List<string> entityUris = new List<string>();
            //A set of variables to hold the state of and URIs for primary entity instances.
            string LeadSource1Uri;
    
            static void Main(string[] args)
            {
                Create.RunAsync().Wait();
            }
    
            public static async Task RunAsync()
            {
    
                String clientId = "0000000-0000-0000-0000-00000000";
                String redirectUrl = "http://localhost";
                String user = "new@organization.onmicrosoft.com";
                String pass = "********";
                String baseAddress = "crm-instance.api.crm.dynamics.com/.../data";
                String baseAddressFull = baseAddress + "v8.2/";
    
                AuthenticationParameters ap = AuthenticationParameters.CreateFromResourceUrlAsync(
                            new Uri(baseAddress)).Result;
    
                String authorityUrl = ap.Authority;
                String resourceUrl = ap.Resource;
    
                AuthenticationContext authContext = new AuthenticationContext(authorityUrl, false);
                UserCredential credentials = new UserCredential(user, pass);
                AuthenticationResult result;
                result = authContext.AcquireToken(resourceUrl, clientId, credentials);
                // = authContext.AcquireToken(resource, clientId, new Uri(redirectUrl));
                var token = result.AccessToken;
    
                var client = new HttpClient();
                client.BaseAddress = new Uri(baseAddressFull);
                client.Timeout = new TimeSpan(0, 2, 0);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
    
                /*** Create Leads ***/
    
                string LeadName = "Lead first Name";
                string LeadLastName = "Lead second Name";
                string LeadEmail = "3webapi@lead1.com";
                string LeadTopic = "WebApi Lead 3";
                string LeadSource = "Contact Us";
                HttpResponseMessage response;
    
                string queryLeadSource;
    
                queryLeadSource = "new_leadsources?$select=new_leadsourceid,new_name&$filter=new_name eq '" + LeadSource + "'";
    
                string LSId=null;
                response = await client.GetAsync(queryLeadSource,
                    HttpCompletionOption.ResponseContentRead);
                if (response.IsSuccessStatusCode)
                {
                    JObject lsRetreived = JsonConvert.DeserializeObject<JObject>(await
                        response.Content.ReadAsStringAsync());
                    LSId = lsRetreived["new_leadsourceid"].ToString(); /*** on this line i get an exception and the app crashes :( ***/
                }
                else
                {
                    Console.WriteLine("Error retrieving tracking Lead Source ID!");
                    throw new CrmHttpResponseException(response.Content);
                }
    
                JObject newLead = new JObject();
                newLead.Add("firstname", LeadName);
                newLead.Add("lastname", LeadLastName);
                newLead.Add("emailaddress1", LeadEmail);
                newLead.Add("subject", LeadTopic);
                newLead.Add("new_leadsource@odata.bind", "/new_leadsources("+ LSId + ")");
    
                HttpResponseMessage responsePost = await client.PostAsJsonAsync("leads", newLead);
    
            }
        }
    }
    


  • Suggested answer
    Nithya Gopinath Profile Picture
    17,078 on at

    Hi,

    Try replacing the lines as shown below.

    LSId = ((Guid)lsRetreived["new_leadsourceid"]).ToString();


  • Vile Andreas Rantala Profile Picture
    1,257 on at

    Hi Nithya, thanks for been so responsive and helpfull, i do that change but the exception break change now, show's this + InnerException {"Value cannot be null.\r\nParameter name: value"} System.Exception {System.ArgumentNullException}

    before was this Object reference not set to an instance of an object

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 CRM (Archived)

#1
SA-08121319-0 Profile Picture

SA-08121319-0 4

#1
Calum MacFarlane Profile Picture

Calum MacFarlane 4

#3
Alex Fun Wei Jie Profile Picture

Alex Fun Wei Jie 2

Last 30 days Overall leaderboard

Featured topics

Product updates

Dynamics 365 release plans