0
votes

I'm facing a problem in doing a plugin for the Dynamics CRM 365. I have 2 entities, Account and website, account entity have a text field called website and a subgrid related to website entity. My task is to do a plugin that runs on post-create of a new website entity from the subgrid in the account form. The plugin should copy a text field from the new created website record to the website text field in the account form.

I register the plugin for website entity as a primary entity, the code reads the guid of the account and the needed filed in the new created website, my problem is that I cannot update the website field in account.

My code:

var AccountId = entity.GetAttributeValue<EntityReference>("new_accountid");
var WebsiteDomain = entity.Attributes["new_url"].ToString();
   if (WebsiteDomain != null && WebsiteDomain != "" && AccountId != null && AccountId.Id!=null)
   {                    
      try
       {
          Entity obj = new Entity("account", new 
          Guid(AccountId.Id.ToString()));
          obj["websiteurl"] = WebsiteDomain;
          service.Update(obj);  
       }
       catch (Exception e)
       {                  
          throw;
       }
   }

The error when reaching the update statement: error

1
May be websiteurl is not the right schema name. It should start like new_ or any other prefix.. verify it.. - Arun Vinoth - MVP
no,, the schema name for this field is websiteurl - Alea
In this code, key from dictionary can be only 3. new_url new_accountid or websiteurl. It can be identified by debugging.. you know what to do next? - Arun Vinoth - MVP

1 Answers

1
votes

I overlooked it.

var WebsiteDomain = entity.Attributes["new_url"].ToString();

In this above line, you are assuming new_url key will be always there & converting .ToString(). This is highly error prone, as key may be wrong or it may be null.

Without null check or verifying Attributes.Contains don’t utilize the attribute key like this.

Safely you can use GetAttributeValue atleast. Read Tips