Исключение KeyNotFoundException истории аудита MS Dynamics 365 C#

#c# #visual-studio #microsoft-dynamics #keynotfoundexception

Вопрос:

Я пытаюсь извлечь историю аудита конкретной учетной записи, как показано на примере здесь:

введите описание изображения здесь

Мне конкретно нужно получить все результаты для Измененного поля под названием Кредитный лимит.

Для этого у меня есть следующий код на C#:

 using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Tooling.Connector;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PowerApps.Samples
{
    public partial class SampleProgram
    {
        [STAThread] // Added to support UX
        static void Main(string[] args)
        {
            CrmServiceClient service = null;
            service = SampleHelpers.Connect("Connect");
            if (!service.IsReady)
                Console.WriteLine("No Connection was Made.");
            Console.WriteLine("Connected");

            //Create a new RetrieveAttributeChangeHistoryRequest

            RetrieveAttributeChangeHistoryRequest req = new RetrieveAttributeChangeHistoryRequest();

            //Set the target Entity

            req.Target = new EntityReference("new_case", new Guid("468f8db5-4f98-eb11-57ee-0006ffc2587a"));

            //Set the attribute you want to retrieve specifically

            req.AttributeLogicalName = "credit_limit";

            //Execute the request against the OrgService

            RetrieveAttributeChangeHistoryResponse resp = (RetrieveAttributeChangeHistoryResponse)service.Execute(req);

            AuditDetailCollection details = resp.AuditDetailCollection;

            Console.WriteLine("Before the loop");
            //Iterate through the AuditDetails

            foreach (var detail in details.AuditDetails)

            {
                Console.WriteLine("Inside the loop");
                //Important: the AuditDetailCollection.AuditDetails doesn’t always contain the type of AttributeAuditDetail, so make sure it is of correct type before casting

                if (detail.GetType() == typeof(AttributeAuditDetail))
                {
                    AttributeAuditDetail attributeDetail = (AttributeAuditDetail)detail;

                    String oldValue = "(no value)", newValue = "(no value)";

                    if (attributeDetail.OldValue.Contains("credit_limit"))
                        Console.WriteLine("old value: " oldValue);

                    oldValue = attributeDetail.OldValue["credit_limit"].ToString();

                    if (attributeDetail.NewValue.Contains("credit_limit"))
                        Console.WriteLine("new value: " newValue);

                    newValue = attributeDetail.NewValue["credit_limit"].ToString();

                    //TODO: Use the old value and new value in the Business Logic

                }
            }
            Console.WriteLine("After the loop");
            Console.ReadLine();
        }
    }
}
 

Что происходит, так это то, что я получаю следующий результат в командной строке:

 Connected
Before the loop
Inside the loop
old value: (no value)
new value: (no value)
Inside the loop
 

А затем он прерывается при исключении, сообщая мне в Visual Studio, что

 System.Collections.Generic.KeyNotFoundExemption: The given key was not present in the dictionary.
 

Может ли кто-нибудь прояснить, что я делаю неправильно и что я могу сделать, чтобы это исправить?

Ответ №1:

Проблема в том, что вы проверяете, содержат ли «новое значение» и «старое значение» ваш атрибут, но затем пытаетесь использовать его, даже если он ложен.

Я внес небольшое изменение в ваш код, и он работает так, как ожидалось.

 //Create a new RetrieveAttributeChangeHistoryRequest

RetrieveAttributeChangeHistoryRequest req = new RetrieveAttributeChangeHistoryRequest();

//Set the target Entity

req.Target = new EntityReference("new_case", new Guid("468f8db5-4f98-eb11-57ee-0006ffc2587a"));

//Set the attribute you want to retrieve specifically

req.AttributeLogicalName = "credit_limit";

//Execute the request against the OrgService

RetrieveAttributeChangeHistoryResponse resp = (RetrieveAttributeChangeHistoryResponse)crmService.Execute(req);

AuditDetailCollection details = resp.AuditDetailCollection;

Console.WriteLine("Before the loop");
//Iterate through the AuditDetails

foreach (var detail in details.AuditDetails)

{
    Console.WriteLine("Inside the loop");
    //Important: the AuditDetailCollection.AuditDetails doesn’t always contain the type of AttributeAuditDetail, so make sure it is of correct type before casting

    if (detail.GetType() == typeof(AttributeAuditDetail))
    {
        AttributeAuditDetail attributeDetail = (AttributeAuditDetail)detail;

        String oldValue = "(no value)", newValue = "(no value)";

        if (attributeDetail.OldValue.Contains("credit_limit"))
            oldValue = attributeDetail.OldValue["credit_limit"].ToString();

        Console.WriteLine("old value: "   oldValue);

        if (attributeDetail.NewValue.Contains("credit_limit"))
            newValue = attributeDetail.NewValue["credit_limit"].ToString();

        Console.WriteLine("new value: "   newValue);
        
        //TODO: Use the old value and new value in the Business Logic

    }
}

Console.WriteLine("After the loop");
Console.ReadLine();
 

Ответ №2:

Вы должны сгруппировать операторы внутри {} , если для выполнения требуется более одного оператора в зависимости от if условия.

 if (attributeDetail.OldValue.Contains("credit_limit"))
{
        oldValue = attributeDetail.OldValue["credit_limit"].ToString();
        Console.WriteLine("old value: "   oldValue);
}