[英]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.