web
You’re offline. This is a read only version of the page.
close
Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Microsoft Dynamics CRM (Archived)

System.NullReferenceException: Object not set to an instance of an object?!!

(0) ShareShare
ReportReport
Posted on by

Hello, 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: 

using System;
using System.Linq;
using System.ServiceModel;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Query;


/// <summary>
/// This plugin will trimm off unit orders after a contract is cancelled before the end of the contract duration
/// </summary>

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") &&
                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<OptionSetValue>("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<DateTime>("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<string>("new_name");

                    //Get Entity Collection to delete 

                    string fetchXml = @" <fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false' top='2000'>
                        <entity name='new_units'>
                            <link-entity name='new_alterunitorder' from ='new_orderlineid' to = 'new_unitsid' >
                                <attribute name='new_alterunitorderid' />
                                <filter type='and'>
                                    <condition attribute='new_orderdate' operator='on-or-after' value='" + startDate.ToShortDateString() + @"' />
                                    <condition attribute='new_orderdate' operator='on-or-before' value='" + endDate.ToShortDateString() + @"' />
                                    <condition attribute='new_orderlineid' operator='eq' uiname='" + uiName + @"' uitype='new_units' value='" + unitOrderId + @"' />
                                </filter>
                            </link-entity>
                        </entity>
                    </fetch>";


                    var result = service.RetrieveMultiple(new FetchExpression(fetchXml));

                    var entityRefs = result.Entities.Select(e => e.GetAttributeValue<EntityReference>("new_alterunitorderid"));


                    var batchSize = 1000;
                    var batchNum = 0;
                    var numDeleted = 0;

                    while (numDeleted < 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 => multiReq.Requests.Add(new DeleteRequest { Target = r }));

                        service.Execute(multiReq);

                        numDeleted += currentList.Count;
                        batchNum++;
                    }





                }
                catch (FaultException<OrganizationServiceFault> ex)
                {
                    throw new InvalidPluginExecutionException("An error occured.. Phil is responsible. ", ex);
                }
                catch (Exception ex)
                {
                    tracing.Trace("An error occured: {0}", ex.ToString());
                    throw;
                }
            }


        }

    }

}


I am getting a NullReferenceException here on line 55, why?!

Null.JPG

*This post is locked for comments

I have the same question (0)
  • Radu Chiribelea Profile Picture
    6,667 on at

    Hi Alan,

    Have you checked if the entity contains the statecode attribute?

    if(entity.Contains("statecode")

    I would start from here

    Hope this helps

    Radu

  • Community Member Profile Picture
    on at

    I have used this in another plugin for the same entity... I know it has statecode attribute!

  • Radu Chiribelea Profile Picture
    6,667 on at

    If you look in the debugger, which object appears to be null?

  • Community Member Profile Picture
    on at

    Line 55:

                    //verify that the target entity represents the contract entity and has been cancelled
                    if (entity.LogicalName != "contract" || entity.GetAttributeValue<OptionSetValue>("statecode").Value != 4)
                        return;
  • Radu Chiribelea Profile Picture
    6,667 on at

    Have you checked the targeted .NET Framework and the CRM SDK dll version?

  • Community Member Profile Picture
    on at

    All my plugins are under the same namespace.....

  • Radu Chiribelea Profile Picture
    6,667 on at

    In addition if you add a watch for entity.LogicalName and entity.GetAttributeValue<OptionSetValue>("statecode").Value what do you get?

  • Community Member Profile Picture
    on at

    for GetAttributeValue in entity.GetAttributeValue<OptionSetValue>("statecode").Value, I get error CS0103: The name 'GetAttributeValue' does not exist in the current context..

    debugging.JPG

  • Radu Chiribelea Profile Picture
    6,667 on at

    if you try instead ((OptionSetValue)entity["statecode"]).Value -> does that work?

  • Radu Chiribelea Profile Picture
    6,667 on at

    Also, from the print screen you shared above, you are trying to set a watch on a method - the error is expected.

    Please set the watch to entity.GetAttributeValue<OptionSetValue>("statecode").Value

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Neeraj Kumar – Community Spotlight

We are honored to recognize Neeraj Kumar as our Community Spotlight honoree for…

Leaderboard > 🔒一 Microsoft Dynamics CRM (Archived)

#1
SA-08121319-0 Profile Picture

SA-08121319-0 4

#1
Calum MacFarlane Profile Picture

Calum MacFarlane 4

#3
Alex Fun Wei Jie Profile Picture

Alex Fun Wei Jie 2

Last 30 days Overall leaderboard

Featured topics

Product updates

Dynamics 365 release plans