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 on State Change (Deactivate or Activate)

(0) ShareShare
ReportReport
Posted on by

I have a requirement to validate on change of state, so if a user deactivates a record and the end date is null an error should be thrown, i have registered the plugin at the pre-stage of setstate dynamic entity 

But I keep getting a null exception error

The code

using Microsoft.Xrm.Sdk;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Plugins.Event
{
    public class SetStatePreStage :  IPlugin
    {
        public void Execute(IServiceProvider serviceProvider)

        {
            PluginHelper helper = new PluginHelper();
            IPluginExecutionContext context = helper.PluginContext;

            const string entityname = "new_event";

            const string status =     "statecode";

            const string inactivedate = "new_enddate";

            // Initialize execution contexts
             helper.Init(this, serviceProvider);

             helper.Trace("Validating Primary entity context");
          
            if (context.InputParameters.Contains("Target") &&
               context.InputParameters["Target"] is EntityReference
                && context.PrimaryEntityName == entityname)
            {

                // Obtain the target business entity from the input parameters.
                helper.Trace("Obtaining the target business entity from input parameters");

                EntityReference new_event = (EntityReference)context.InputParameters["Target"];

                int statecode = ((OptionSetValue)context.InputParameters[status]).Value;

                DateTime enddate = ((DateTime)context.InputParameters[inactivedate]);

                //  int statecode = ((OptionSetValue)new_event[status]).Value;

               // DateTime enddate = ((DateTime)new_event[inactivedate]);

                //active is 0 inactive is 1

            if (statecode == 1)
                {
                if ( enddate == null)
                    {
                        throw new InvalidPluginExecutionException("You Cannot deactivate without setting end date time");
                    }
                else {
                        throw new InvalidPluginExecutionException("This did not work");
                    }

                }
            

            }


        }


    }

}


I initially used entity instead of entity reference but the code did nothing

but now the code gives and error and does not run either

exception-errorrr.PNG

user-error.PNG

Also whats the best way to achieve this task, use Pre-Image?

Also was the best way to check for a null field in date

if (enddate== null)

or

(!entity.Contains(enddate))

*This post is locked for comments

  • Suggested answer
    Aric Levin - MVP Profile Picture
    on at
    RE: Plugin on State Change (Deactivate or Activate)

    Take a look at the following article:

    thomasthankachan.wordpress.com/.../plugin-usage-of-setstate-and-statestatedynamicentity-message

    I am not sure if this has changed, you should be using EntityMoniker instead of Target:

    if (context.InputParameters.Contains("EntityMoniker") && context.InputParameters["EntityMoniker"] is EntityReference)

    Hope this helps.

  • Verified answer
    ashlega Profile Picture
    on at
    RE: Plugin on State Change (Deactivate or Activate)

    Or you can try an "Update" message instead

    PS. If the error is really happening in that line, that's kind of strange since you are not type casting anything there.

  • lawix10 Profile Picture
    on at
    RE: Plugin on State Change (Deactivate or Activate)

    Thanks Aric , I still get the same error , will read more about it and debug debug debug (that helps a lot), also generally how do i achieve the task using pre image or using context.input parameters ... also on the checking of null date..and finally i registered it on SetStateDynamic entity alone..because set state did not trigger the plugin..should i register on both.

  • lawix10 Profile Picture
    on at
    RE: Plugin on State Change (Deactivate or Activate)

    Thanks Alex , new experience, have not worked on SetState before now but thanks to debugging and am sure it is the same concept.

    What do u mean by update message, the plugin should only trigger when deactivate button is clicked or activate ...Just finding out about the entitymoniker....aside from that its a very easy task..was wondering if using preimage is better than using

    context.inputparameters...

    but since the code fails from the first step without the logic will keep working on it...

    also was the best way to check for null in a date field or was the difference between.

    if (enddate== null)

    or

    (!entity.Contains(enddate))

  • ashlega Profile Picture
    on at
    RE: Plugin on State Change (Deactivate or Activate)

    Well, register on Update and see what happens - usually works fine. If you want to filter by statecode/statuscode attributes, add those attribute to the step.

    Besides, SetStateRequest has been deprecated:

    msdn.microsoft.com/.../microsoft.crm.sdk.messages.setstaterequest.aspx

  • lawix10 Profile Picture
    on at
    RE: Plugin on State Change (Deactivate or Activate)

    Thanks this makes a lot of sense, its the same functionality as long as it it registered in the pre event stage ..thanks will consider all.

  • lawix10 Profile Picture
    on at
    RE: Plugin on State Change (Deactivate or Activate)

    Thanks Alex you were right from the start, the context from the helper class was returning null, so that was thy the error was at that stage.

    I changed the context to 

     IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));


    Now the logic behind the codes work , but I still get and error with the code. 

    On the date field.

    The Code is now like this

    if (context.InputParameters.Contains("EntityMoniker") && context.PrimaryEntityName == entityname)
    			
    	{ 
    	    // Obtain the target business entity from the input parameters.
    		helper.Trace("Obtaining the target business entity from input parameters");
    		int statecode = ((OptionSetValue)context.InputParameters[status]).Value;
    		string enddate = null;
    		
    		//   DateTime enddate = ((DateTime)context.InputParameters[inactivedate]) ;  // this throws an error
    
    		//active is 0 inactive is 1
    		if (statecode == 1)
    		{
    		if (enddate == null)
    			 {
    					throw new InvalidPluginExecutionException("You Cannot Deactivate the record without setting end date");
    			 }
    			 
    		else {
    			throw new InvalidPluginExecutionException("This did not work");
    		     }
    
    		}
    
    	}


    The Date Field throws an error 

     DateTime enddate = ((DateTime)context.InputParameters[inactivedate]) ;

     I also found out that for Status you use the Schema name State and not StateCode, I fixed that already.

    So please How can I properly get the date field and also check for null.

    and finally if the field was set to active from inactive how can i clear out the date field or set it to null.

    Regards.

  • lawix10 Profile Picture
    on at
    RE: Plugin on State Change (Deactivate or Activate)

    Thanks Aric


    Now the logic behind the codes work , but I still get and error with the code. 

    On the date field.

    The Code is now like this

    if (context.InputParameters.Contains("EntityMoniker") && context.PrimaryEntityName == entityname)
    
    { 
    	// Obtain the target business entity from the input parameters.
    	helper.Trace("Obtaining the target business entity from input parameters");
    	int statecode = ((OptionSetValue)context.InputParameters[status]).Value;
    	string enddate = null;
    
    	//   DateTime enddate = ((DateTime)context.InputParameters[inactivedate]) ;  // this throws an error
    
    	//active is 0 inactive is 1
    	if (statecode == 1)
    	{
    	if (enddate == null)
    	{
    	throw new InvalidPluginExecutionException("You Cannot Deactivate the record without setting end date");
    	}
    
    	else {
    	throw new InvalidPluginExecutionException("This did not work");
    	}
    
    	}
    
    }

    The Date Field throws an error 

    DateTime enddate = ((DateTime)context.InputParameters[inactivedate]);

     I also found out that for Status you use the Schema name State and not StateCode, I fixed that already.

    So please How can I properly get the date field and also check for null.

    and finally if the field was set to active from inactive how can i clear out the date field or set it to null.

    Regards.

  • Verified answer
    Aric Levin - MVP Profile Picture
    on at
    RE: Plugin on State Change (Deactivate or Activate)

    Hi Adeyemi,

    You are correct. The Input Parameter name is State, not State Code.

    Regarding the date issue.

    The SetState messages do not pass any input parameters that are field related, so the inactive date (new_enddate) will not be retrieved with the Set State Message.

    You will need to call a retrieve method to get the new_enddate field and do your validation then...

    Guid eventId = (Guid)context.PrimaryEntityId;

    Entity evt = service.Retrieve(entityName, entityId, new ColumnSet("new_enddate"));

    DateTime endDate = evt.Contains("new_enddate") ? evt.GetAttributeValue<DateTime>("new_enddate") : DateTime.MinValue;

    if (endDate == DateTime.MinValue)

    {

     // No Date Provided

    }

    else

    {

     // Ok to deactivate

    }

  • lawix10 Profile Picture
    on at
    RE: Plugin on State Change (Deactivate or Activate)

    Thanks issue solved, already marked as the answer. what if am setting from deactive to activate how do i clear the end-date field

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…

Pallavi Phade – Community Spotlight

We are honored to recognize Pallavi Phade as our Community Spotlight honoree for…

Leaderboard > 🔒一 Microsoft Dynamics CRM (Archived)

Last 30 days Overall leaderboard

Featured topics

Product updates

Dynamics 365 release plans