2016-10-31 91 views
0

我是新來的c#和動態插件。爲了學習和測試,我已經成功創建了一對非常簡單的插件。現在,我試圖進一步瞭解我實際需要使用插件的方式 - 我試圖獲取自定義實體上的字段值,並使用該值更新相關自定義的屬性實體。c# - dynamics crm在線插件 - 使用字段值來填充相關實體的屬性

我的插件是在自定義實體的更新消息(稱爲new_registration)上註冊的。它以異步方式運行後操作。更新並觸發插件的字段(選項集「狀態」字段)不會在任何地方的代碼中使用。

這裏是我的代碼:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 

using System.ServiceModel; 
using Microsoft.Xrm.Sdk; 

namespace PlugInTests 
{ 
    public class AdjustTimeSlots: IPlugin 
    { 
     public void Execute(IServiceProvider serviceProvider) 
     { 
      //Extract the tracing service for use in debugging sandboxed plug-ins. 
      ITracingService tracingService = 
       (ITracingService)serviceProvider.GetService(typeof(ITracingService)); 

      // Obtain the execution context from the service provider. 
      IPluginExecutionContext context = (IPluginExecutionContext) 
       serviceProvider.GetService(typeof(IPluginExecutionContext)); 

      if (context.InputParameters != null) 
      { 
       Entity entity = (Entity)context.InputParameters["Target"]; 
       Guid id = entity.Id; 
       tracingService.Trace("got input parameters"); 

       //get time slot 
       string slot = (string)entity.Attributes["new_yourtimeslot"]; 
       EntityReference eventclass = (EntityReference)entity.Attributes["new_eventregistrationrelationshipid"]; 
       tracingService.Trace("got time slot"); 

       //set updated entity (event/class) 
       Entity parentevent = new Entity("new_eventclass"); 
       parentevent.Id = eventclass.Id; 
       parentevent.Attributes["new_timeslotsfordelete"] = slot; 


       // Obtain the organization service reference. 
       IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory)); 
       IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId); 

       //update event record 
       tracingService.Trace("Update time slot plugin"); 
       service.Update(parentevent); 
      } 
     } 
    } 
} 

通過測試,我已經縮小,這是在這條線失敗(至少在初期):

string slot = (string)entity.Attributes["new_yourtimeslot"]; 

的錯誤我得到在插件跟蹤日誌中是:

給定的鍵不在字典中。

我檢查並重新檢查,我知道我得到的字段名稱正確。我在如何從輸入參數中獲取值時做錯了什麼?或者我搞砸了什麼,我甚至沒有意識到我可能會搞砸了?任何幫助表示讚賞,謝謝。

回答

3

總是嘗試以安全的方式獲取屬性值(檢查屬性集合中的屬性或使用下面的SDK方法)。如果屬性值爲null,則該屬性不會作爲屬性集合的一部分返回。

var slot = entity.GetAttributeValue<string>("new_yourtimeslot"); 

下面的代碼片段看起來不正確

EntityReference eventclass = (EntityReference)entity.Attributes["new_eventregistrationrelationshipid"]; 

屬性名稱和關係名稱是很少相同。關係名稱通常包括目標實體和相關實體,並且通常最終作爲查找的屬性命名有所不同new_eventregistrationid也許?仔細查看Customization - Field Properties

此外,安全地獲得相關的屬性:

var eventclass = entity.GetAttributeValue<EntityReference>("new_eventregistrationid"); 
+0

感謝。這非常有幫助。獲取這些屬性值的調整工作。你的語法參考在哪裏?我一直在閱讀MSDN文檔,我不相信我看過這種語法?我可能會混淆的是,舊的在線示例已經過時了。謝謝你的幫助。 –

相關問題