使用动态365 web Api控制台的例外情况

时间:2017-11-28 15:44:43

标签: c# asp.net-web-api dynamics-crm

我尝试使用web-api在Dynamics 365 / CRM上创建一些记录。它在GUID检索时有效。

在我的场景中,我应该使用来自azure的web api通过webservices。如果调用它,它应该查询实体Lead Sources并在实体Lead上设置GUID。

获取查询结果时会发生错误。

这是我的代码:

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

      }
   }
}

1 个答案:

答案 0 :(得分:1)

您正在查询new_leadsources,因此您没有获得单个记录,而是获得了一系列结果。更确切地说,如果你打电话:

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

结果将如下所示(这是简化的):

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

当然,如果您有多个具有相同名称的记录,您将在此数组中获得更多记录,但它仍然是一个数组。

所以在这一行:

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

您正在尝试访问仅具有“value”属性的对象的“new_leadsourceid”属性。 考虑到响应的结构,你应该做这样的事情:

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

当然这段代码非常糟糕且容易出错(它假设总是有一个结果并且总是取得第一个结果),但它应该让你朝着正确的方向前进。

另外 - 使用调试器,根据您的评论,我认为您没有花时间进行调试,这有助于了解您的代码发生了什么。