title: System.NullReferenceException: Object not set to an instance of an object?
body: <p>I am writing a plugin that deletes records between two dates when a contract is cancelled... The records to be deleted are from the cancellation date to the end of the contract. Here is the code I am using: </p>
  
  <pre class="lang-c# prettyprint-override"><code>using System;
  using System.Linq;
  using System.ServiceModel;
  using Microsoft.Xrm.Sdk;
  using Microsoft.Xrm.Sdk.Messages;
  using Microsoft.Xrm.Sdk.Query;
  
  
  /// &lt;summary&gt;
  /// This plugin will trimm off unit orders after a contract is cancelled before the end of the contract duration
  /// &lt;/summary&gt;
  
  namespace DCWIMS.Plugins
  {
  
      [CrmPluginRegistration(MessageNameEnum.Update,
      "contract",
      StageEnum.PostOperation,
      ExecutionModeEnum.Asynchronous,
      "statecode",
      "Post-Update On Cancel Contract",
      1000,
      IsolationModeEnum.Sandbox,
      Image1Name = "PreImage",
      Image1Type = ImageTypeEnum.PreImage,
      Image1Attributes = "")]
  
      public class UnitPluginOnCancel : IPlugin
      {
  
          public void Execute(IServiceProvider serviceProvider)
          {
              // Extract the tracing service for use in debugging sandboxed plug-ins.
              // Will be registering this plugin, thus will need to add tracing service related code.
  
              ITracingService tracing = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
  
              //obtain execution context from service provider.
              IPluginExecutionContext context = (IPluginExecutionContext)
                  serviceProvider.GetService(typeof(IPluginExecutionContext));
  
              // InputParameters collection contains all the data passed in the message request. 
  
              if (context.InputParameters.Contains("Target") &amp;&amp;
                  context.InputParameters["Target"] is Entity)
              {
  
                  Entity entity = (Entity)context.InputParameters["Target"];
  
                  //Get the before image of the updated contract
                  Entity PreImage = context.PreEntityImages["PreImage"];
  
  
                  //verify that the target entity represents the the contract entity has been cancelled
                  if (entity.LogicalName != "contract" || entity.GetAttributeValue&lt;OptionSetValue&gt;("statecode").Value != 4)
                      return;
  
  
                  //obtain the organization service for web service calls.
                  IOrganizationServiceFactory serviceFactory =
                      (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
  
                  IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
  
  
                  //Core Plugin code in Try Block
                  try
                  {
  
                      //Get Contract line start date
                      var startDate = entity.GetAttributeValue&lt;DateTime&gt;("cancelon");
  
                      //Get Contract Line End Date
                      DateTime endDate = (DateTime)PreImage["expireson"];
  
                      //Get Contract range into weekdays list
                      Eachday range = new Eachday();
                      var weekdays = range.WeekDay(startDate, endDate);
  
                      //Get Unit Order Lookup Id
                      EntityReference unitOrder = (EntityReference)PreImage.Attributes["new_unitorderid"];
                      var unitOrderId = unitOrder.Id;
  
                      var unitOrders = service.Retrieve(unitOrder.LogicalName, unitOrder.Id, new ColumnSet("new_name"));
  
                      var uiName = unitOrders.GetAttributeValue&lt;string&gt;("new_name");
  
                      //Get Entity Collection to delete 
  
                      string fetchXml = @" &lt;fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false' top='2000'&gt;
                          &lt;entity name='new_units'&gt;
                              &lt;link-entity name='new_alterunitorder' from ='new_orderlineid' to = 'new_unitsid' &gt;
                                  &lt;attribute name='new_alterunitorderid' /&gt;
                                  &lt;filter type='and'&gt;
                                      &lt;condition attribute='new_orderdate' operator='on-or-after' value='" + startDate.ToShortDateString() + @"' /&gt;
                                      &lt;condition attribute='new_orderdate' operator='on-or-before' value='" + endDate.ToShortDateString() + @"' /&gt;
                                      &lt;condition attribute='new_orderlineid' operator='eq' uiname='" + uiName + @"' uitype='new_units' value='" + unitOrderId + @"' /&gt;
                                  &lt;/filter&gt;
                              &lt;/link-entity&gt;
                          &lt;/entity&gt;
                      &lt;/fetch&gt;";
  
  
                      var result = service.RetrieveMultiple(new FetchExpression(fetchXml));
  
                      var entityRefs = result.Entities.Select(e =&gt; e.GetAttributeValue&lt;EntityReference&gt;("new_alterunitorderid"));
  
  
                      var batchSize = 1000;
                      var batchNum = 0;
                      var numDeleted = 0;
  
                      while (numDeleted &lt; entityRefs.Count())
                      {
                          var multiReq = new ExecuteMultipleRequest()
                          {
                              Settings = new ExecuteMultipleSettings()
                              {
                                  ContinueOnError = false,
                                  ReturnResponses = false
                              },
                              Requests = new OrganizationRequestCollection()
                          };
  
                          var currentList = entityRefs.Skip(batchSize * batchNum).Take(batchSize).ToList();
  
                          currentList.ForEach(r =&gt; multiReq.Requests.Add(new DeleteRequest { Target = r }));
  
                          service.Execute(multiReq);
  
                          numDeleted += currentList.Count;
                          batchNum++;
                      }
  
  
  
  
  
                  }
                  catch (FaultException&lt;OrganizationServiceFault&gt; ex)
                  {
                      throw new InvalidPluginExecutionException("An error occured.. Phil is responsible. ", ex);
                  }
                  catch (Exception ex)
                  {
                      tracing.Trace("An error occured: {0}", ex.ToString());
                      throw;
                  }
              }
  
  
          }
  
      }
  
  }
  </code></pre>
  
  <p>I am getting a NullReferenceException on line 55... I have literally used the same line for a previous plugin without any problems.. The statecode for a cancelled contract has a value of 4 and I only want the plugin to execute when the contract has been cancelled. Here is an image of the debugging.</p>
  
  <p><a href="https://i.stack.imgur.com/CONCV.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CONCV.jpg" alt="NullReference Exception"></a> </p>
  
  <p>I have used this statement before for another plugin that acts on the contract entity and it worked fine, I don't know why this time it's not working. Here is the statement:</p>
  
  <pre class="lang-c# prettyprint-override"><code>//verify that the target entity represents the the contract entity has been cancelled
                  if (entity.LogicalName != "contract" || entity.GetAttributeValue&lt;OptionSetValue&gt;("statecode").Value != 4)
                      return;
  </code></pre>