2011-10-02 2 views
3

이것은 CRM 2011에 대해 작성한 플러그인의 작동 예제입니다.이 플러그인의 플러그인 등록 도구에서 '만들기'단계를 만들었습니다. 이것은 잘 실행됩니다. 또한 플러그인에 대해 '업데이트'단계가 등록되어 있습니다. 반환 된 기본 연락처가 null이기 때문에이 작업을 실행할 수 없습니다. 이 단계는 모두 비동기로 등록됩니다.이 플러그인 코드에서 CRM 2011 Entity Relationship이 null 인 이유는 무엇입니까?

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using Microsoft.Xrm.Sdk; 
using System.ServiceModel; 
using System.IO; 
using System.Net; 

namespace CRMNewsletterPlugin 
{ 
    public class NewsletterSignup : IPlugin 
    { 
     public void Execute(IServiceProvider serviceProvider) 
     { 
      ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService)); 
      // Obtain the execution context from the service provider. 
      IPluginExecutionContext context = (IPluginExecutionContext) 
      serviceProvider.GetService(typeof(IPluginExecutionContext)); 

      tracingService.Trace("Begin load"); 
      // The InputParameters collection contains all the data passed in the message request. 
      if (context.InputParameters.Contains("Target") && 
      context.InputParameters["Target"] is Entity) 
      { 
       tracingService.Trace("We have a target."); 
       // Obtain the target entity from the input parmameters. 
       Entity entity = (Entity)context.InputParameters["Target"]; 
       IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory)); 
       IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId); 
       if (!entity.GetAttributeValue<bool>("new_receivesnewsletter")) 
       { 
        try 
        { 
         //check if the account number exist 
         string emailAddress = entity.GetAttributeValue<string>("emailaddress1"); 
         EntityReference primaryContact = entity.GetAttributeValue<EntityReference>("primarycontactid"); 

         // UPDATE STEP FAILS HERE 
         if (primaryContact == null) 
         { 
          tracingService.Trace("Primary Contact is null"); 
         } 
         Entity contact = service.Retrieve("contact", primaryContact.Id, new Microsoft.Xrm.Sdk.Query.ColumnSet(new string[] { "fullname" })); 
         string fullname = contact.GetAttributeValue<string>("fullname"); 
         string name = entity.GetAttributeValue<string>("name"); 
         WebRequest req = WebRequest.Create("http://localhost"); 
         string postData = "cm-name=" + fullname + "&cm-ddurhy-ddurhy=" + emailAddress + "&cm-f-jddkju=" + name; 
         tracingService.Trace(postData); 
         byte[] send = Encoding.Default.GetBytes(postData); 
         req.Method = "POST"; 
         req.ContentType = "application/x-www-form-urlencoded"; 
         req.ContentLength = send.Length; 
         tracingService.Trace("Sending info"); 

         Stream sout = req.GetRequestStream(); 
         sout.Write(send, 0, send.Length); 
         sout.Flush(); 
         sout.Close(); 
         tracingService.Trace("Info sent"); 
         WebResponse res = req.GetResponse(); 
         StreamReader sr = new StreamReader(res.GetResponseStream()); 
         string returnvalue = sr.ReadToEnd(); 
         tracingService.Trace(returnvalue); 

         entity.Attributes["new_receivesnewsletter"] = true; 
         service.Update(entity); 
         tracingService.Trace("Newsletter field set"); 

        } 
        catch (FaultException ex) 
        { 
         throw new InvalidPluginExecutionException("An error occurred in the plug-in.", ex); 
        } 

       } 
      } 

     } 
    }//end class 
} 

답변

10

InputParameters [ "대상"]에 포함 된 개체는 업데이트에 제출 된 변경된 필드, 모든 필드가 포함되어 있습니다. InputParameters [ "Target"]에는 Create 과정에서 항상 모든 필드가 포함되어 있기 때문에 플러그인은 Create에서 작동합니다.

이 문제를 해결하려면 primarycontactid 필드가 포함 된 PluginRegistrationTool의 단계에 PreImage를 추가해야합니다. PreImage는 업데이트 이전과 같이 항상 으로 지정한 필드의 값을 포함합니다.

트릭은 InputParameters [ "Target"]에서 primarycontactid를 확인하는 것이 가장 최근의 값을 포함하기 때문입니다 (예 : 사용자가 동일한 저장 중에 new_receivesnewsletter와 primarycontactid를 모두 업데이트 한 경우). InputParameters [ "대상은"] primarycontactid 포함하지 않는 경우, 다음 프리 이미지에 다시 가을이 같은 접근 뭔가 (에 "프리 이미지"당신이 당신의 프리 이미지의 별칭을 설정 가정) : 도움이

context.PreEntityImages["preimage"].GetAttributeValue<EntityReference>("primarycontactid") 

희망!

+0

너 대 남자 조쉬! 정보 주셔서 감사합니다. 이상하게도 사전 이미지 'account_preimage'의 이름을 지정했지만 컬렉션의 키는 '계정'인 계정 별칭이었습니다. – Nate

+0

흥미 롭습니다! 나는 일반적으로 이름과 별칭 모두에 "이미지"를 사용하므로 별칭이 실제 마법 키임을 알기에 좋습니다. 내 대답을 업데이트 할게. 감사! –

+1

지난 주 내 플러그인이 업데이트에 대해 효과가 없었던 이유를 알아 내려고했지만 작성한 시점에서 3 단락으로 답변했습니다. 건배 –

관련 문제