0
votes

I'm trying to create some records on Dynamics 365/CRM using web-api. It works when doing GUID retrieves.

In my scenario I should use the web api from azure via webservices. Wdhen it is invoked it should query entity Lead Sources and set the GUID on entity Lead.

The error occurs when getting the query's result.

This is my code:

  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>();
    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 = "[email protected]";
        String pass = "********";
        String baseAddress = "https://crm-instance.api.crm.dynamics.com/api/data/";
        String baseAddressFull = baseAddress + "v8.2/";

        AuthenticationParameters ap = AuthenticationParameters.CreateFromResourceUrlAsync(
                    new Uri(baseAddress)).Result;

        //List<string> entityUris = new List<string>();

        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 = "[email protected]";
        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(); /*** outgoing 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("[email protected]", "/new_leadsources("+ LSId + ")");

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

      }
   }
}
1
What is the Exception you get? And what is the InnerException, if any?martijn_himself
Hi Martijn, i get this Message "Object reference not set to an instance of an object." string, and then the runconsole explotes :D :( the object it's line 81 when i'm retrieving the GUID on the LSId = lsRetreived["new_leadsourceid"].ToString();ProgressiveAlterego
Also returns the execption on here static void Main(string[] args) { Create.RunAsync().Wait(); }ProgressiveAlterego
Your query returns an array of entity objects. Therefore lsRetreived["new_leadsourceid"] returns null and .ToString() throws a NullReferenceException. Just set a breakpoint on the line and inspect object lsRetreived.Henk van Boeijen
Hi Henk, no it doesn't return null, it returns the GUID of the LeadSource variable that i sendProgressiveAlterego

1 Answers

1
votes

You are querying new_leadsources so you are not getting a single record, you are getting an Array of results. To be more precise, if you call:

http://apiurl/new_leadsources?$select=new_leadsourceid,new_name&$filter=new_name eq '" + LeadSource + "'"

results will look like this (this is simplified):

{
    value: [{
        new_leadsourceid: "guid",
        new_name: "somename"
    }]
}

Of course if you have more than one record with the same name, you will get more records in this Array, but it's still an Array.

So in this line:

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

you are trying to access "new_leadsourceid" property of object which has only "value" property. Having in mind the structure of the response you should do something like this:

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

Of course this code is awful and error prone (it assumes that there is always at leas one result and always takes the first result), but it should get you going in the right direction.

Also - use the debugger, it really helps to get the idea what's going on with your code, based on your comments I assume you did not take any time on debugging.