locked
Whay am I getting an 'Object Reference not set to an instance of an object' error? RRS feed

  • Question

  • I've got a plugin that is triggered when a status on a form is changed. When I change the status and click save on the form, I'm getting an 'Object reference not set to an instance of an object' error. I have tracing set up, and have trace messages in my code, but I'm not even seeing the first trace message in the resulting log file.

    The plugin in registered for create & update. The create step has a post image and is a post-operation, and the update step has a pre & post image and is also a post-operation.

    Any ideas?

    Thanks.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Diagnostics;
    
    using Microsoft.Xrm.Sdk;
    using Microsoft.Crm.Sdk.Messages;
    
    namespace MyRules
    {
        public class StatusChange : PluginBase, IPlugin
        {
            public enum formStatus
            {
                InProcess = 717770000,
                SentForApproval = 717770001,
                Approved = 717770002,
                Rejected = 717770003
            }   
    
            public void Execute(IServiceProvider serviceProvider)
            {
                try
                {	// I'm not even seeing this trace message in the log file
                    Trace("Here 1");
                    if (ContextContainsRequiredImages())
                    {
                        Trace("Here 2");
                        // Get updated status
                        // If it's 'Sent for Approval', email is sent 
                        if (postImage.Attributes.Contains("new_status"))
                        {
                            Trace("postImage.Attributes.Contains('new_status')");
                            Trace("postImage['new_status'].ToString()" + postImage["new_status"].ToString());
                            if (postImage["vs_status"].ToString() == formStatus.SentForApproval.ToString())
                            {
                                Trace("Here 3");
                                // Send email x
                            }
                            else if (postImage["new_status"].ToString() == formStatus.Approved.ToString())
                            {
                                Trace("Here 4");
                                // Send email y
                            }
                        }
                        
                    }
    
                    throw new InvalidPluginExecutionException();
    
                }
                catch (Exception ex)
                {
                    throw new InvalidPluginExecutionException("An error occurred in the formStatus.StatusChange.Execute plug-in." + ex.Message, ex);
                }
    
            }
    
            private bool ContextContainsRequiredImages()
            {
                if ((IsUpdate() && PreImage != null && PostImage != null) || (IsCreate() && PostImage != null))
                {
                    return true;
                }
                else
                    return false;
            }
        }
    }

    Here's the error log:

    Unhandled Exception: System.ServiceModel.FaultException`1[[Microsoft.Xrm.Sdk.OrganizationServiceFault, Microsoft.Xrm.Sdk, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]: An error occurred in the MyRules.StatusChange: .StatusChange.Execute plug-in.Object reference not set to an instance of an object.Detail: 
    <OrganizationServiceFault xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/xrm/2011/Contracts">
      <ErrorCode>-2147220891</ErrorCode>
      <ErrorDetails xmlns:d2p1="http://schemas.datacontract.org/2004/07/System.Collections.Generic">
        <KeyValuePairOfstringanyType>
          <d2p1:key>OperationStatus</d2p1:key>
          <d2p1:value xmlns:d4p1="http://www.w3.org/2001/XMLSchema" i:type="d4p1:string">0</d2p1:value>
        </KeyValuePairOfstringanyType>
      </ErrorDetails>
      <Message>An error occurred in the formStatus.StatusChange.Execute plug-in.Object reference not set to an instance of an object.</Message>
      <Timestamp>2013-06-28T10:53:33.7969759Z</Timestamp>
      <InnerFault i:nil="true" />
      <TraceText>
    
    [MyRules: MyRules.StatusChange]
    [012e3533-3fdf-e211-8c38-3c4a92dbc855: MyRules.StatusChange: Create of new_assessmentform]
    
    
    </TraceText>
    </OrganizationServiceFault>
    

    Friday, June 28, 2013 10:56 AM

All replies

  • Are you sure the Trace instance has been instantiated ? It's not instantiated in anywhere in the code you posted - it might be instantiated in the PluginBase class


    Microsoft CRM MVP - http://mscrmuk.blogspot.com/ http://www.excitation.co.uk

    Friday, June 28, 2013 12:24 PM
    Moderator
  • Hi, thanks for your reply.

    Yes, the Trace instance has been instantiated in the PluginBase class (I think!). However, the PluginBase class was in a different namespace (it was the same code that I used in a different project). So I changed the namespace of the PluginBase class to the same one as the file above (ie. MyRules), but I'm still getting the error message.

    Here's the pluginbase code:

    using System;
    
    // Microsoft Dynamics CRM namespace(s)
    using Microsoft.Xrm.Sdk;
    using Microsoft.Crm.Sdk.Messages;
    
    namespace NCIRules
    {
        public class PluginBase
        {
            private const string CreateMessage = "Create";
            private const string UpdateMessage = "Update";
    
            protected internal void Trace(string details)
            {
                if (tracingService != null)
                    tracingService.Trace(details);
            }
    
            protected internal void TraceMethodStart(string MethodName)
            {
                if (tracingService != null)
                    tracingService.Trace(string.Format("{0} Started", MethodName));
            }
    
            protected internal void TraceMethodExit(string MethodName)
            {
                if (tracingService != null)
                    tracingService.Trace(string.Format("{0} Exit", MethodName));
            }
    
            protected internal Microsoft.Xrm.Sdk.IPluginExecutionContext context;
            protected internal const string PreImage = "PreImage";
            protected internal const string PostImage = "PostImage";
    
            protected internal Entity postImage;
            protected internal Entity preImage;
            protected internal Entity target;
            protected internal IOrganizationService service;
            protected internal IOrganizationServiceFactory serviceFactory;
            protected internal ITracingService tracingService;
    
    
            protected internal bool IsCreate()
            {
                return context.MessageName == CreateMessage;
            }
    
            protected internal bool IsUpdate()
            {
                return context.MessageName == UpdateMessage;
            }
    
    
            protected internal void PluginSetup(IServiceProvider serviceProvider)
            {
                try
                {
                    SetupTracing(serviceProvider);
    
                    GetContext(serviceProvider);
    
                    GetService(serviceProvider);
    
                    GetImages();
                }
                catch (Exception ex)
                {
                    throw new InvalidPluginExecutionException("MyRules.PluginBase exception: ", ex);
                }
            }
    
            private void SetupTracing(IServiceProvider serviceProvider)
            {
                tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
                if (tracingService == null)
                    throw new InvalidPluginExecutionException("MyRules.PluginBase exception: Failed to retrieve the tracing service.");
            }
    
    
            private void GetContext(IServiceProvider serviceProvider)
            {
                context = (Microsoft.Xrm.Sdk.IPluginExecutionContext)serviceProvider.GetService(typeof(Microsoft.Xrm.Sdk.IPluginExecutionContext));
            }
    
            private void GetService(IServiceProvider serviceProvider)
            {
                serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                service = serviceFactory.CreateOrganizationService(context.UserId);
    
            }
    
    
            private void GetImages()
            {
    
                if ((context.InputParameters != null) && (context.InputParameters.Count > 0) && (context.InputParameters.Contains("Target")) && (context.InputParameters["Target"] is Entity))
                {
                    // Obtain the target entity from the input parameters.
                    target = (Entity)context.InputParameters["Target"];
                    Trace("PluginBase attribute count: " + target.Attributes.Count);
                }
    
                if (context.MessageName == CreateMessage)
                {
                    if ((context.PostEntityImages != null) && (context.PostEntityImages.Count > 0) && (context.PostEntityImages.Contains(PostImage)) && (context.PostEntityImages[PostImage] is Entity))
                    {
                        postImage = (Entity)context.PostEntityImages[PostImage];
                    }
                    Trace("CreateMessage");
    
                }
                else if (context.MessageName == UpdateMessage)
                {
                    if ((context.PreEntityImages != null) && (context.PreEntityImages.Count > 0) && (context.PreEntityImages.Contains(PreImage) &&
                                 context.PreEntityImages[PreImage] is Entity))
                    {
                        preImage = (Entity)context.PreEntityImages[PreImage];
                    }
    
                    Trace("UpdateMessage");
                    if ((context.PostEntityImages != null) && (context.PostEntityImages.Count > 0) && (context.PostEntityImages.Contains(PostImage)) && (context.PostEntityImages[PostImage] is Entity))
                    {
                        postImage = (Entity)context.PostEntityImages[PostImage];
                    }
                }
            }
    
    
            protected internal bool HasAttributeChanged(string attributeName)
            {
                object oldAttributeValue = new object();
                object currentAttributeValue = new object();
                bool isUpdated = false;
                try
                {
                    Trace("MyRules.PluginBase: Entering HasAttributeChanged.");
                    if (context != null)
                    {
                        isUpdated = ProcessAttributeChangeCheck(attributeName, ref currentAttributeValue, ref oldAttributeValue);
                    }
                    else
                    {
                        throw new InvalidPluginExecutionException("The PluginBase has not been Intialised");
                    }
                }
                catch (Exception ex)
                {
                    throw new InvalidPluginExecutionException(String.Format("An error occurred in MyRules.PluginBase.HasAttributeUpdatedInPresentContext. " + ex.ToString()
                        , context.GetType().ToString()), ex);
                }
                finally
                {
                }
                return isUpdated;
    
            }
    
            /// <summary>
            /// Method used to Process the update check for IsAttributeChanged methods
            /// </summary>
            /// <param name="attributeName">Schema Name of the Attribute</param>
            /// <param name="currentAttributeValue">Outputting CurrentAttribute Value</param>
            /// <param name="preAttributeValue">Outputting old attribute Value</param>
            /// <returns>Yes/No value indicating if the value was updated</returns>
            private bool ProcessAttributeChangeCheck(string attributeName, ref object currentAttributeObj, ref object preAttributeObj)
            {
                bool isUpdated = false;
                string currentAttributeValue = string.Empty;
                string preAttributeValue = string.Empty;
                try
                {
                    if (context != null)
                    {
                        Trace("MyRules.PluginBase: Entering ProcessAttributeChangeCheck.");
    
                        //Context will either be a postImage, preImage or target
                        if (postImage != null && postImage.Attributes.Contains(attributeName))
                        {
                            currentAttributeObj = postImage.Attributes[attributeName];
                            currentAttributeValue = postImage.Attributes[attributeName].ToString();
    
                        }
                        else
                        {
                            if (target != null && target.Attributes.Contains(attributeName))
                            {
                                currentAttributeObj = target.Attributes[attributeName];
                                currentAttributeValue = target.Attributes[attributeName].ToString();
                            }
                        }
    
                        if (preImage != null && preImage.Attributes.Contains(attributeName))
                        {
                            preAttributeObj = preImage.Attributes[attributeName];
                            preAttributeValue = preImage.Attributes[attributeName].ToString();
                        }
    
                        switch (context.MessageName)
                        {
                            case "Delete":
                                isUpdated = true;
                                currentAttributeObj = preAttributeObj;  //// nothing gets updated so set current value to last value
                                break;
                            case "Create":
                                if (currentAttributeValue != preAttributeValue)// extra check for crud current value will always be latest for create
                                {
                                    isUpdated = true;
                                }
                                break;
                            case "Update":
                                if (target != null && target.Contains(attributeName)) // for update check if its in target
                                {
                                    if (currentAttributeValue != preAttributeValue)// extra check for crud 
                                    {
                                        isUpdated = true;
                                    }
                                }
                                else
                                {
                                    currentAttributeObj = preAttributeObj;
                                }
                                break;
                            default:
                                break;
                        }
                    }
                    else
                    {
                        throw new InvalidPluginExecutionException("The PluginBase has not been Intialised");
                    }
                }
                catch (Exception ex)
                {
                    throw new InvalidPluginExecutionException(
                       String.Format("An error occurred in MyRules.ProcessAttributeChangeCheck of the {0} plug-in." + ex.ToString(), context.GetType().ToString()), ex);
                }
                finally
                {
                }
                Trace("MyRules.PluginBase: Exiting ProcessAttributeChangeCheck.");
                return isUpdated;
            }
    
        }
    }


    • Edited by crmNewbie1978 Friday, June 28, 2013 12:38 PM Misspelling
    Friday, June 28, 2013 12:36 PM