简体   繁体   中英

Exception using dynamics 365 web Api Console

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 = "new@organization.onmicrosoft.com";
        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 = "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(); /*** 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("new_leadsource@odata.bind", "/new_leadsources("+ LSId + ")");

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

      }
   }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM