Skip to main content

Notifications

Announcements

No record found.

Microsoft Dynamics CRM (Archived)

Insert data on lookupfield via WebApi dynamics 365

(1) ShareShare
ReportReport
Posted on by 1,255

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

  • Suggested answer
    Nithya Gopinath Profile Picture
    Nithya Gopinath 17,074 on at
    RE: Insert data on lookupfield via WebApi dynamics 365

    Hi Vile,

    Are you sure the IsRetrived["new_leadsourceid"] contains value?

  • Vile Andreas Rantala Profile Picture
    Vile Andreas Rantala 1,255 on at
    RE: Insert data on lookupfield via WebApi dynamics 365

    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

  • Suggested answer
    Nithya Gopinath Profile Picture
    Nithya Gopinath 17,074 on at
    RE: Insert data on lookupfield via WebApi dynamics 365

    Hi,

    Try replacing the lines as shown below.

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


  • Vile Andreas Rantala Profile Picture
    Vile Andreas Rantala 1,255 on at
    RE: Insert data on lookupfield via WebApi dynamics 365

    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);
    
            }
        }
    }
    


  • Vile Andreas Rantala Profile Picture
    Vile Andreas Rantala 1,255 on at
    RE: Insert data on lookupfield via WebApi dynamics 365

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

  • Suggested answer
    Nithya Gopinath Profile Picture
    Nithya Gopinath 17,074 on at
    RE: Insert data on lookupfield via WebApi dynamics 365

    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.

  • Suggested answer
    Syed Ibrahim Profile Picture
    Syed Ibrahim 6,257 on at
    RE: Insert data on lookupfield via WebApi dynamics 365

    Refer the below as well.

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

  • Aric Levin Profile Picture
    Aric Levin 30,188 on at
    RE: Insert data on lookupfield via WebApi dynamics 365

    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

  • Vile Andreas Rantala Profile Picture
    Vile Andreas Rantala 1,255 on at
    RE: Insert data on lookupfield via WebApi dynamics 365

    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.

  • Vile Andreas Rantala Profile Picture
    Vile Andreas Rantala 1,255 on at
    RE: Insert data on lookupfield via WebApi dynamics 365

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

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

Congratulations 2024 Spotlight Honorees

Kudos to all of our 2024 community stars! 🎉

Meet the Top 10 leaders for December

Congratulations to our December super stars! 🥳

Start Your Super User Journey

Join the ranks of our community heros! 🦹

Leaderboard

#1
André Arnaud de Calavon Profile Picture

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

#2
Martin Dráb Profile Picture

Martin Dráb 230,466 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans