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

Community site session details

Session Id :
Microsoft Dynamics CRM (Archived)

Plugin throwing a null reference exception

(0) ShareShare
ReportReport
Posted on by 4,930

Hi,

I have written a birthday plugin, which fills 3 new fields birth day, birth month, birth year on create or update of a contact.

The plugin is registered via plugin registration tool as pre-operation for create and update contact. For the update step a pre-image for the "owningbusinessunit" is added.

The plugin runs fine, when I manually create or update a contact in the CRM 2011 GUI. But for all contacts created or update via the web service (daily import) the plugin fails with following error:

06-04-2015 13:09:01,883 ERROR [ 3] Unexpected exception from plug-in (Execute): BirthdayPlugin.BirthdayField: System.NullReferenceException: Object reference not set to an instance of an object. (File:131)
06-04-2015 13:09:01,883 ERROR [ 3] Code: -2147220956 (File:131)
06-04-2015 13:09:01,884 ERROR [ 3] Message: Unexpected exception from plug-in (Execute): BirthdayPlugin.BirthdayField: System.NullReferenceException: Object reference not set to an instance of an object. (File:131)
06-04-2015 13:09:01,884 ERROR [ 3] Plugin Trace:
[BirthdayPlugin: BirthdayPlugin.BirthdayField]
[xxxx: BirthdayPlugin.BirthdayField: Update of contact]

 

At first I thought it is related to this line in my code:

IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

Because the contact is created/updated by the "SYSTEM" user, so probably no UserId is being returned. But now I changed the plugin to run as a specific user instead of calling user and the problem still persists.

 

I would be grateful for any help.

thx in advance Thomas

 

Source code:

using

System;

using

System.Diagnostics;

using

System.Linq;

using

System.ServiceModel;

using

Microsoft.Xrm.Sdk;

using

Microsoft.Xrm.Sdk.Query;

using

Microsoft.Crm.Sdk;

using

Microsoft.Crm.Sdk.Messages;


namespace

BirthdayPlugin

{

   

public class BirthdayField : IPlugin

    {

       

public void Execute(IServiceProvider serviceProvider)

        {

       

IPluginExecutionContext context = (IPluginExecutionContext)

        serviceProvider.GetService(

typeof(IPluginExecutionContext));

       

IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));

       

IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

       

ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));

       

try

        {

           

if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)

            {

               

Entity entity = (Entity)context.InputParameters["Target"];

                tracingService.Trace(

"EntityName:" + entity.LogicalName);

               

// Verify that the target entity represents a contact.

               

// If not, this plug-in was not registered correctly.

               

if (entity.LogicalName == "contact")

                {

                   

// Image für Update Step --> enthält alle Felder des Contacts

                   

Entity prebirthdayimage;

                   

                   

if (context.MessageName == "Create")

                    {

                       

// Deklarierung des Namens der Owning Business Unit als Variable

                       

//Check ob die Owning Business Unit AT ist --> für CZ passiert kein Update der neuen Geburtstagsfelder

                       

EntityReference owningBusinessUnit = (EntityReference)entity.Attributes["owningbusinessunit"];

                       

Entity owningBU = service.Retrieve(owningBusinessUnit.LogicalName, owningBusinessUnit.Id, new ColumnSet(true));

                       

var atowner = owningBU.Attributes["name"].ToString();

                           

//Check if the plugin context contains the attribute birthday (=create or update of birthdate in CRM). If yes --> copy to new birthday/month/year fields                   

                           

if (entity.Attributes.Contains("birthdate") && atowner == "AT")

                            {

                               

//Neue Variable die den Geburtstag eines Contacts enthält

                               

DateTime birthday = (DateTime)entity["birthdate"];

                               

//Update bzw. Befüllung der 3 neuen Geburtstagsfelder am Contact

                                entity[

"new_birthday"] = birthday.ToLocalTime().Day;

                                entity[

"new_birthmonth"] = new OptionSetValue(birthday.ToLocalTime().Month);

                                entity[

"new_birthyear"] = birthday.ToLocalTime().Year;

                            }

                        }

                   

if (context.MessageName == "Update")

                    {

                       

// Deklarierung des Namens der Owning Business Unit als Variable

                        prebirthdayimage = (

Entity)context.PreEntityImages["ImageBirthday"];

                       

EntityReference UpdateOwningBusinessUnit = (EntityReference)prebirthdayimage.Attributes["owningbusinessunit"];

                       

Entity UpdateowningBU = service.Retrieve(UpdateOwningBusinessUnit.LogicalName, UpdateOwningBusinessUnit.Id, new ColumnSet(true));

                       

var UpdateAT = UpdateowningBU.Attributes["name"].ToString();

                        

//Check if the plugin context contains the attribute birthday (=create or update of birthdate in CRM). If yes --> copy to new birthday/month/year fields 

                        

//Check ob die Owning Business Unit AT ist --> für CZ passiert kein Update der neuen Geburtstagsfelder

                        

if (entity.Attributes.Contains("birthdate") && UpdateAT == "AT")

                            {

                               

//Neue Variable die den Geburtstag eines Contacts enthält

                               

DateTime birthday = (DateTime)entity["birthdate"];

                               

//Update bzw. Befüllung der 3 neuen Geburtstagsfelder am Contact

                                entity[

"new_birthday"] = birthday.ToLocalTime().Day;

                                entity[

"new_birthmonth"] = new OptionSetValue(birthday.ToLocalTime().Month);

                                entity[

"new_birthyear"] = birthday.ToLocalTime().Year;                               

                            }

                    }                   

                    }

                }

            }

       

catch (FaultException<OrganizationServiceFault> ex)

        {

           

throw new InvalidPluginExecutionException("An error occurred in Birthday plugin", ex);

        }

        }

    }

}

*This post is locked for comments

I have the same question (0)
  • Suggested answer
    Bas van de Sande Profile Picture
    4,383 on at
    RE: Plugin throwing a null reference exception

    Hi Thomas,

    too bad, your code wasn't formatted that nicely ;).

    I looked at your source code and I spotted a possible point of failure:

    you declare:

    DateTime birthday = (DateTime)entity["birthdate"];

    Do you verify is the birthday is filled? because you do later on:

    entity["new_birthday"] = birthday.ToLocalTime().Day;

    if the birthday is null, then you have a null reference error because you call a function on a datetime object.

    Instead of working with DateTime, you should work with DateTime?

    then you can check if the DateTime has a value (with .HasValue)

    I hope this guides you into the right direction

    Bas

  • tpeschat Profile Picture
    4,930 on at
    RE: Plugin throwing a null reference exception

    Hi,

    yes I check if the birthday is filled:

    if (entity.Attributes.Contains("birthdate")  ...

    The code fails for contacts that carry a birthdate, so I believe that's not the point of failure.

    I guess it must be above the try / catch block because I don't have any warnings or errors in the event log.

    br Thomas

  • Aileen Gusni Profile Picture
    44,524 on at
    RE: Plugin throwing a null reference exception

    Thomas,

    Your code seems no problem.

    When you said 'specific user' are you using System Admin user or just common user?

    Thanks.

  • tpeschat Profile Picture
    4,930 on at
    RE: Plugin throwing a null reference exception

    Hi,

    I am using our CRM service account. It is a CRM user in the top business unit with security role "System Administrator".

    The contacts being created are in a different business unit then the user in whom's context the plugin is running.

    Top BU = BJ (this is the user), Contact BU = AT (1 level below BJ)

    br Thomas

  • Suggested answer
    Aileen Gusni Profile Picture
    44,524 on at
    RE: Plugin throwing a null reference exception

    Thomas,

    Okay,

    I see your code is good and you have validation.

    maybe also got smething missed out here.

    Okay, you triggered using filtered attribute?

    Worst case method, you can try to debug your plugin using Plugin profiler or you can just place this line:

    throw new InvalidPluginExecutionException("tested", ex);

    In specific line then we will see which one caused the error.

    You have registered the preImage with the exactly same case-sensitive alias right?

    Thanks.

  • tpeschat Profile Picture
    4,930 on at
    RE: Plugin throwing a null reference exception

    Hi,

    thx for your fast response.

    Yes I have registered the preImage with the exactly same case-sensitive alias. Otherwise it wouldn't work as well, when I create or update contacts via the CRM GUI. But there no error occurs.

    Unfortunately I haven't installed Visual Studio on our CRM Server, so the debugging of plugins is quite tricky for me, especially as I am completely new to this topic

    ;) Thomas

  • Suggested answer
    Mahadeo Matre Profile Picture
    17,021 on at
  • Bas van de Sande Profile Picture
    4,383 on at
    RE: Plugin throwing a null reference exception

    Hi Thomas,

    did you verify if the owningBusinessUnit is instantiated?

    Bas

  • tpeschat Profile Picture
    4,930 on at
    RE: Plugin throwing a null reference exception

    Hi,

    sorry for my late reply, had some other tasks to accomplish.

    I added now logging to my plugin and the error must be located in this part of the code:

    if (entity.Attributes.Contains("birthdate") && atowner == "AT")

    {

    //Neue Variable die den Geburtstag eines Contacts enthält

    DateTime birthday = (DateTime)entity["birthdate"];

    //Update bzw. Befüllung der 3 neuen Geburtstagsfelder am Contact

    entity["new_birthday"] = birthday.ToLocalTime().Day;

    entity["new_birthmonth"] = new OptionSetValue(birthday.ToLocalTime().Month);

    entity["new_birthyear"] = birthday.ToLocalTime().Year;

    But actually I have no clue what goes wrong? If I create or update a contact via the GUI the plugin works fine. But if a contact is created or updated via the webservice the plugin throws this null reference exception.

    Any idea?

    thx a lot

    Thomas

  • tpeschat Profile Picture
    4,930 on at
    RE: Plugin throwing a null reference exception

    Actually it must happen when declaring the birthday variable:

    WriteLog("atowner: " + atowner.ToString());  --> this part is written to the log

    if (entity.Attributes.Contains("birthdate") && atowner == "AT")

    {

    //Neue Variable die den Geburtstag eines Contacts enthält

    DateTime birthday = (DateTime)entity["birthdate"];

    WriteLog ("Birthday: " + birthday.ToString()); --> this line isn't part of the log anymore

    Any advice?

    thx Thomas

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…

Abhilash Warrier – Community Spotlight

We are honored to recognize Abhilash Warrier as our Community Spotlight honoree for…

Leaderboard > 🔒一 Microsoft Dynamics CRM (Archived)

#1
HR-09070029-0 Profile Picture

HR-09070029-0 2

#1
UllrSki Profile Picture

UllrSki 2

#3
ED-30091530-0 Profile Picture

ED-30091530-0 1

Last 30 days Overall leaderboard

Featured topics

Product updates

Dynamics 365 release plans