繁体   English   中英

使用Dynamics 365 Web Api控制台的异常

[英]Exception using dynamics 365 web Api Console

我正在尝试使用web-api在Dynamics 365 / CRM上创建一些记录。 在执行GUID检索时,它可以工作。

在我的场景中,我应该通过webservices使用来自Azure的Web API。 调用它时,应查询实体潜在顾客来源并在实体潜在顾客上设置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);

      }
   }
}

您正在查询new_leadsources因此您不会得到一条记录,而是得到一个结果数组。 更准确地说,如果您致电:

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

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

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

当然,如果您有多个同名记录,您将在此Array中获得更多记录,但是它仍然是一个Array。

所以在这一行:

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

您正在尝试访问仅具有“值”属性的对象的“ new_leadsourceid”属性。 考虑到响应的结构,您应该执行以下操作:

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

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

另外-使用调试器,根据您的评论,我认为您确实没有花任何时间进行调试,这确实有助于您了解代码的最新情况。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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