title: CRM Dynamics Plugin Error - Given Key not found in Dictionary
body: <p>Hi i developed a plugin and once deployed, i'm getting an error on save of a record. 
  Given key was not found in Dictionary. It's a pretty generic error, do you see anything or possibly know of a way to go about debugging ? `</p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.Data;
  using Microsoft.Xrm.Sdk;
  using Microsoft.Xrm.Sdk.Query;
  using Quad.SalesEstimating.MSCRMPlugins.PluginHelpers;
  using Sybase.Data.AseClient;
  
  namespace CRMSolution.Plugins
  {
      public class PreTitleUpdate : IPlugin
      {
  
          public void Execute(IServiceProvider serviceProvider)
          {
              IPluginExecutionContext context = (IPluginExecutionContext)
                  serviceProvider.GetService(typeof(IPluginExecutionContext));
  
              Entity entity;
  
              if (context.InputParameters.Contains("Target") &amp;&amp;
                  context.InputParameters["Target"] is Entity)
              {
                  // Obtain the target business entity from the input parmameters.
                  entity = (Entity)context.InputParameters["Target"];
  
                  // Verify that the entity represents an contact.);
                  if (entity.LogicalName != "qg_title") { return; }
              }
              else
              {
                  return;
              }
  
              try
              {
                  IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)
                      serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                  IOrganizationService service = serviceFactory.CreateOrganizationService(
                      context.UserId);
                  IOrganizationService elevatedService = serviceFactory.CreateOrganizationService(null);
  
                  Entity preImage = context.PreEntityImages["PreImage"];
                  //Entity postImage = context.PostEntityImages["PostImage"];
  
                  #region Variable Setup
  
                  const string PREMEDIA_PC = "100000000";
                  const string RETAIL_INSERTS_PC = "9";
                  const string COMMERCIAL_PC = "12";
                  const string DIRECT_MAIL_PC = "7";
                  const string INSTORE_PC = "13";
  
                  string creditAccountID = null;
                  string creditCustomerID = null;
                  //string previousTitleCode = null;
  
                  string accountId = null;
                  string creditId = null;
  
                  string productType = string.Empty;
                  int vertisId = 0;
                  string vertisCustId = string.Empty;
                  string vertisParentCustId = string.Empty;
                  string message = string.Empty;
  
                  #endregion
  
                  #region Get Entity Values
  
                  EntityReference titleidLookup = new EntityReference();
                  if (entity.Contains("qg_titleid"))
                  {
                      var titleGuid = (Guid)entity["qg_titleid"];
                      titleidLookup = (EntityReference)new EntityReference("qg_title", titleGuid);
                  }
                  else if (preImage.Contains("qg_titleid"))
                  {
                      var titleGuid = (Guid)preImage["qg_titleid"];
                      titleidLookup = (EntityReference)new EntityReference("qg_title", titleGuid);
                  }
  
  
                  EntityReference accountIdLookup = new EntityReference();
                  if (entity.Contains("qg_accountid"))
                  {
                      accountIdLookup = (EntityReference)entity["qg_accountid"];
                      accountId = accountIdLookup.Id.ToString();
                  }
                  else if (preImage.Contains("qg_accountid"))
                  {
                      accountIdLookup = (EntityReference)preImage["qg_accountid"];
                      accountId = accountIdLookup.Id.ToString();
                  }
  
                  EntityReference creditIdLookup = new EntityReference();
                  if (entity.Contains("qg_creditid"))
                  {
                      creditIdLookup = (EntityReference)entity["qg_creditid"];
  
                      if (creditIdLookup != null)
                      {
                          creditId = creditIdLookup.Id.ToString();
                      }
                      else
                      {
                          entity.SetValue("qg_customerid", string.Empty);
                      }
                  }
                  else if (preImage.Contains("qg_creditid"))
                  {
                      creditIdLookup = (EntityReference)preImage["qg_creditid"];
  
                      if (creditIdLookup != null)
                      {
                          creditId = creditIdLookup.Id.ToString();
                      }
                      else
                      {
                          entity.SetValue("qg_customerid", string.Empty);
                      }
                  }
  
                  //if (entity.Contains("qg_previoustitlecode"))
                  //{
                  //    previousTitleCode = entity.GetValue("qg_previoustitlecode");
                  //}
                  //else if (preImage.Contains("qg_previoustitlecode"))
                  //{
                  //    previousTitleCode = preImage.GetValue("qg_previoustitlecode");
                  //}
  
                  if (entity.Contains("qg_producttype"))
                  {
                      productType = entity.GetValue("qg_producttype");
                      //this.LogItemToFile("QG_TitlePreUpdate productType from entity.");
                  }
                  else if (preImage.Contains("qg_producttype"))
                  {
                      productType = preImage.GetValue("qg_producttype");
                      //this.LogItemToFile("QG_TitlePreUpdate productType from preImage.");
                  }
  
                  if (entity.Contains("qg_vertiscustomerid"))
                  {
                      vertisCustId = entity.GetValue("qg_vertiscustomerid");
                      //this.LogItemToFile("QG_TitlePreUpdate qg_vertiscustomerid from entity.");
                  }
                  else if (preImage.Contains("qg_vertiscustomerid"))
                  {
                      vertisCustId = preImage.GetValue("qg_vertiscustomerid");
                      //this.LogItemToFile("QG_TitlePreUpdate qg_vertiscustomerid from preImage.");
                  }
  
                  #endregion
  
                  if (accountId != null)
                  {
  
                      #region Credit Business Unit
  
                      if (creditId != null)
                      {
                          // get credit business unit
                          ColumnSet creditcolumns = new ColumnSet(new string[] {"qg_accountid", "qg_customerid"});
                          Guid creditIdGUID = new Guid(creditId);
                          Entity qg_credit = elevatedService.Retrieve("qg_credit", creditIdGUID, creditcolumns);
                          if (qg_credit.Attributes.Contains("qg_accountid"))
                          {
                              EntityReference creditAccount = (EntityReference)qg_credit["qg_accountid"];
                              creditAccountID = creditAccount.Id.ToString();
                          }
                          if (qg_credit.Attributes.Contains("qg_customerid"))
                          {
                              creditCustomerID = qg_credit.GetValue("qg_customerid").ToString();
                          }
                      }
  
                      #endregion
  
                      #region Validate Customer ID
  
                      // If the Customer has been selected, validate account and get the customer ID.
                      // Validate that the Credit record and Title are under the same Account
  
                      if (creditId != null)
                      {
  
                          if (creditAccountID != accountId)
                          {
                              throw new InvalidPluginExecutionException(" " +
                                                                        "Credit Record must be under the same Account as the Title.");
                          }
  
                          if (creditCustomerID != null)
                          {
                              // Set the customerid on the Title
                              entity.SetValue("qg_customerid", creditCustomerID);
                              // service.Update(entity);
                          }
                          else
                          {
                              // something went wrong so stop processing...
                              throw new InvalidPluginExecutionException(" " + "Could not update the Customer ID.");
                          }
                      }
  
                      #endregion
  
                      //#region Validate Previous Title Code
  
                      //// if a previous title code has been selected, validate that it exists...
                      //if (!String.IsNullOrEmpty(previousTitleCode))
                      //{
                      //    if (!TitleCodeExists(previousTitleCode))
                      //    {
                      //        throw new InvalidPluginExecutionException(" " + "Previous Title Code is not valid.  Please select a Title Code that previously existed.");
                      //    }
                      //}
  
                      //#endregion
  
                      #region Approved for QG Paper
  
                      try
                      {
  
                          string ownerDomainName = null;
                          string aprvdForQGPaper = "";
  
                          ColumnSet ownerColumns = new ColumnSet(new string[] { "businessunitid", "domainname", });
                          Entity systemuser = service.Retrieve("systemuser", context.InitiatingUserId, ownerColumns);
  
                          if (entity.Contains("qg_aprvdforqgppr"))
                          {
                              aprvdForQGPaper = entity.GetValue("qg_aprvdforqgppr");
                          }
  
                          if (systemuser.Attributes.Contains("domainname"))
                          {
                              ownerDomainName = systemuser.GetValue("domainname").ToString();
                          }
  
                          // Set the Approved for QG Paper last changed
                          if (aprvdForQGPaper == "1")
                          {
                              entity.SetValue("qg_aprvdforqgpprdt", DateTime.Now);
                              entity.SetValue("qg_aprvdforqgpprby", ownerDomainName);
                          }
  
                      }
                      catch (Exception ex)
                      {
                          throw new InvalidPluginExecutionException(
                              " " + "An error occurred in the plug-in." + ex.Message, ex);
                      }
  
                      #endregion
  
                      #region Validate Classification
  
                      //try
                      //{
                      //    if (entity.Contains("qg_producttype") &amp;&amp; preImage.Contains("qg_producttype"))
                      //    {
                      //        bool validateProdType = true;
  
                      //        // Allow Credit to change product type regardless of Sales Staff being assigned.
                      //        if (this.DoesUserHaveRole(context.InitiatingUserId, service, "Quad Credit") ||
                      //            this.DoesUserHaveRole(context.InitiatingUserId, service, "System Administrator"))
                      //        {
                      //            validateProdType = false;
                      //        }
  
                      //        if (validateProdType)
                      //        {
                      //            OptionSetValue preProdType = (OptionSetValue)preImage["qg_producttype"];
                      //            OptionSetValue postProdType = (OptionSetValue)entity["qg_producttype"];
  
                      //            if (preProdType.Value != postProdType.Value)
                      //            {
                      //                // The only valid Product Classification change is within MagCat/SIP.
                      //                List&lt;int&gt; validprodclasschangelist = new List&lt;int&gt;(new int[] { 2, 3, 5 });
  
                      //                List&lt;int&gt; salesRoles = new List&lt;int&gt;(new int[] { 52, 30, 33, 35, 41, 48 });
  
                      //                QueryExpression query = new QueryExpression();
                      //                query.NoLock = true;
                      //                ColumnSet columns = new ColumnSet(new string[] { "qg_titleid", "qg_employeerole" });
                      //                ConditionExpression condition = new ConditionExpression();
  
                      //                condition.AttributeName = "qg_employeerole";
                      //                condition.Operator = ConditionOperator.In;
                      //                foreach (var role in salesRoles)
                      //                {
                      //                    condition.Values.Add(role);
                      //                }
  
                      //                query.EntityName = "qg_titleemployeerole";
                      //                query.ColumnSet = columns;
                      //                query.Criteria.AddCondition("qg_titleid", ConditionOperator.Equal, titleidLookup.Id);
                      //                query.Criteria.AddCondition(condition);
  
                      //                EntityCollection resultSet = service.RetrieveMultiple(query);
  
                      //                if (resultSet.Entities.Count &gt; 0)
                      //                {
                      //                    if (!validprodclasschangelist.Contains(preProdType.Value) ||
                      //                        !validprodclasschangelist.Contains(postProdType.Value))
                      //                    {
                      //                        throw new InvalidPluginExecutionException("Product Classification change is not valid.");
                      //                    }
                      //                }
                      //            }
                      //        }
  
                      //    }                                                      
                      //}
                      //catch (Exception ex)
                      //{
                      //    throw new InvalidPluginExecutionException(
                      //        " " + "An error occurred in the plug-in." + ex.Message, ex);
                      //}
  
                      #endregion
  
                      #region Vertis Ids
  
  
                      string accountBUID = null;
                      string accountBUName = null;
  
                      // if the account doesn't have a VertisParentCustomerID get the last five digits of the VMAC ID 
                      //  to build the parent customer id 
                      ColumnSet accountcolumns = new ColumnSet(new string[] { "owningbusinessunit", "qg_vertisparentcustid" });
                      Guid accountIdGUID = new Guid(accountId);
                      Entity accountService = service.Retrieve("account", accountIdGUID, accountcolumns);
  
                      if (accountService.Attributes.Contains("owningbusinessunit"))
                      {
                          EntityReference accountBusinessUnit = (EntityReference)accountService["owningbusinessunit"];
                          accountBUID = accountBusinessUnit.Id.ToString();
                      }
  
                      if (accountService.Attributes.Contains("qg_vertisparentcustid"))
                      {
                          vertisParentCustId = accountService.GetValue("qg_vertisparentcustid");
                      }
  
                      ColumnSet buColumns = new ColumnSet(new string[] { "name" });
                      // GUID from above
                      Guid buIdGUID = new Guid(accountBUID);
                      Entity buService = service.Retrieve("businessunit", buIdGUID, buColumns);
                      if (buService.Attributes.Contains("name"))
                      {
                          accountBUName = buService.GetValue("name").ToString();
                      }
  
  
                      // if productClass has been selected, see if we need to pull VertisCustIds..
                      if (accountBUName.Equals("Corporate Print") &amp;&amp; string.IsNullOrEmpty(vertisCustId))
                      {
  
                          // if product class is 'Retail Inserts', 'Premedia', or 'Commercial' we need to pull Vertis Ids
                          if (productType.Equals(RETAIL_INSERTS_PC) || productType.Equals(DIRECT_MAIL_PC) ||
                              productType.Equals(COMMERCIAL_PC) || productType.Equals(PREMEDIA_PC) || productType.Equals(INSTORE_PC))
                          {
                              bool vertisIdResult = false;
  
                              // get the last five digits of the VMAC ID to build the customer id
                              vertisIdResult = this.GetNextId("VERTIS_CUST_ID", "TITLE", ref vertisId, ref message);
  
                              if (string.IsNullOrEmpty(vertisParentCustId))
                              {
                                  // get the last five digits of the VMAC ID to build the parent customer id
                                  //vertisIdResult = this.GetNextId("VERTIS_CUST_ID", "TITLE", ref vertisId, ref message);
  
                                  accountService.SetValue("qg_vertisparentcustid", "9" + vertisId.ToString());
                                  service.Update(accountService);
                              }
  
                              if (vertisIdResult)
                              {
                                  if (productType.Equals(DIRECT_MAIL_PC))
                                  {
                                      vertisCustId = "5" + vertisId.ToString();
                                  }
                                  else if (productType.Equals(RETAIL_INSERTS_PC))
                                  {
                                      vertisCustId = "0" + vertisId.ToString();
                                  }
                                  else { vertisCustId = "1" + vertisId.ToString(); }
  
                                  //this.LogItemToFile("TitlePreCreate vertisCustId: " + vertisCustId);
  
                                  entity.SetValue("qg_vertiscustomerid", vertisCustId);
                              }
                          }
                      }
                      else if (!string.IsNullOrEmpty(vertisCustId))
                      {
                          // if the product class changed, we may need to change the VertisCustomerID
                          if (entity.Contains("qg_producttype") &amp;&amp; preImage.Contains("qg_producttype"))
                          {
                              OptionSetValue preProdType = (OptionSetValue)preImage["qg_producttype"];
                              OptionSetValue postProdType = (OptionSetValue)entity["qg_producttype"];
  
                              if (preProdType.Value != postProdType.Value)
                              {
                                  //if (Convert.ToInt32(vertisCustId.Substring(1)) &lt; 67000)
                                  //{
                                  //    throw new InvalidPluginExecutionException(" " + "Product Class may not be changed for Customers that originated from Vertis.");
                                  //}
                                  //else
                                  //{
                                      // check the validity of the VertisId
                                      //    if (productType.Equals(DIRECT_MAIL_PC)) vertisCustId = "5" + vertisId.ToString();
                                      //    if (productType.Equals(RETAIL_INSERTS_PC)) vertisCustId = "0" + vertisId.ToString();
                                      //    else { vertisCustId = "1" + vertisId.ToString(); 
                                      if (productType.Equals(DIRECT_MAIL_PC) &amp;&amp; !vertisCustId.Substring(0, 1).Equals("5"))
                                      {
                                          vertisCustId = vertisCustId.Substring(1);
                                          vertisCustId = "5" + vertisCustId;
                                          entity.SetValue("qg_vertiscustomerid", vertisCustId);
                                      }
                                      else if (productType.Equals(RETAIL_INSERTS_PC) &amp;&amp; !vertisCustId.Substring(0, 1).Equals("0"))
                                      {
                                          vertisCustId = vertisCustId.Substring(1);
                                          vertisCustId = "0" + vertisCustId;
                                          entity.SetValue("qg_vertiscustomerid", vertisCustId);
                                      }
                                      else if (productType.Equals(PREMEDIA_PC) &amp;&amp; !vertisCustId.Substring(0, 1).Equals("1"))
                                      {
                                          vertisCustId = vertisCustId.Substring(1);
                                          vertisCustId = "1" + vertisCustId;
                                          entity.SetValue("qg_vertiscustomerid", vertisCustId);
                                      }
                                  //} 
                              }
                          }
                      }
  
                      #endregion
  
                  }
                  else
                  {
                      throw new InvalidPluginExecutionException(" " + "An error occurred in the plug-in. Owner ID, Account ID or Credit ID is Null.");
                  }
  
              }
              catch (Exception ex)
              {
                  throw new InvalidPluginExecutionException(" " + "An error occurred in the plug-in." + ex.Message, ex);
              }
          }
  
          /// &lt;summary&gt;
          /// Use Ase command to determine is title code exists
          /// &lt;/summary&gt;
          /// &lt;param name="titlecode"&gt;The title code to use in the select &lt;/param&gt;
          /// &lt;returns&gt;A true/false value indicating success or failure&lt;/returns&gt;
          public bool TitleCodeExists(string titlecode)
          {
              int TitleCodeCount = 0;
              string CmndText = "select count(*) as cnt from QUAD0024.dbo.TITLE_VW where _TITLE_CODE = '" + titlecode + "'";
  
              // connect to Sybase to see if Title Code exists in the Title View.
              try
              {
                  using (AseConnection dbcon = new AseConnection(this.GetSybaseDbConnectionString()))
                  {
  
                      dbcon.Open();
                      AseCommand cmd = new AseCommand(CmndText, dbcon);
                      IDataReader reader = cmd.ExecuteReader();
  
                      while (reader.Read())
                      {
                          TitleCodeCount = (int)reader["cnt"];
                      }
  
                      if (TitleCodeCount == 0)
                      {
                          //throw new InvalidPluginExecutionException(" " + " TitleCodeExists: Return False.");
                          return false; 
                      }
                      else
                      {
                          //throw new InvalidPluginExecutionException(" " + " TitleCodeExists: Return True.");
                          return true;
                      }
                  }
              }
              catch (Exception e)
              {
                  this.LogExceptionEvent(new Exception("Message", e));
                  throw new InvalidPluginExecutionException(" " + " TitleCodeExists Failed" + e.Message);
              }
          }
  
      }
  }
  
  `
  </code></pre>