Skip to main content

Notifications

Announcements

No record found.

Customer experience | Sales, Customer Insights,...
Suggested answer

Help with plugin code

Posted on by 310

I have written a plugin based on Quotes entity that only fires on records returned by a query, however I get failed system jobs against quote records that i know do not meet the query in the plugin

The error I receive is:

Unexpected exception from plug-in (Execute): ClosePreviousWestQuote.ClosePreviousWestQuoteV2Plugin: System.NullReferenceException: Object reference not set to an instance of an object.

The plugin does work however, I just want to know why the plugin doesnt just skip if the record doesnt meet the query criteria? 

Here's my code:

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

namespace ClosePreviousWestQuote
{
    public class ClosePreviousQuoteV2Plugin : IPlugin
    {
        public void Execute(IServiceProvider serviceProvider)
        {
            // Extract the tracing service for use in debugging sandboxed plug-ins.
            ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));

            // Obtain the execution context from the service provider.
            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

            // The InputParameters collection contains all the data passed in the message request.
            if (context.InputParameters.Contains("Target")&&context.InputParameters["Target"] is Entity)
            {
                // Obtain the target entity from the input parameters.
                Entity entity = (Entity)context.InputParameters["Target"];

                // get the quote number and quote version from the quote record
                string new_quote_number = entity.GetAttributeValue("vendor_quote_number");
                string new_quote_ref = entity.GetAttributeValue("quote_ref");
                int new_quote_version = entity.GetAttributeValue("version_number");

                bool startsWithWQ = new_quote_ref.StartsWith("WQ-");

                // only fire this plugin if the entity is a quote and vendor quote number is not null and the version number is greater than 1
                if (entity.LogicalName == "quote" && new_quote_number != null && startsWithWQ == true && new_quote_version > 1)
                {
                    // Obtain the organization service reference which you will need for web service calls.
                    IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                    IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

                    try
                    {
                        // search for quotes with the same vendor quote number, the quote version is less than the newest quote version & alos they are not closed
                        string fetchxml = @"
                        
                            
                                
                                
                                
                                
                                
                                
                                
                                    
                                    
                                    
                                
                            
                        ";


                        EntityCollection result = service.RetrieveMultiple(new FetchExpression(fetchxml));

                        foreach (var c in result.Entities)
                        {
                            if (result != null && result.Entities.Count > 0)
                            {

                                foreach (Entity _entity in result.Entities)
                                {
                                    string QuoteID = c.Attributes["quoteid"].ToString();
                                    //string QuoteVersion = c.Attributes["version_number"].ToString();
                                    int QuoteStatus = ((OptionSetValue)(c.Attributes["statecode"])).Value;

                                    Guid _QuoteId = new Guid(QuoteID);

                                    // check the quote is not closed already
                                    if (QuoteStatus != 3)
                                    {
                                        // Create the Request Object
                                        SetStateRequest setStateRequest = new SetStateRequest();

                                        // In my case i'm Cancelling Task Activity
                                        var quoteReference = new EntityReference("quote", _QuoteId);

                                        try
                                        {
                                            // "statecode" Closed = "3"
                                            // "statuscode" Revised = "7"
                                            // Set the State and Status OptionSet Values to Closed / Revised
                                            CloseQuoteRequest closeQuoteRequest = new CloseQuoteRequest();
                                            Entity QuoteClose = new Entity("quoteclose");
                                            QuoteClose.Attributes["quoteid"] = new EntityReference("quote", _QuoteId);
                                            QuoteClose.Attributes["subject"] = "This quote has been closed due to a new version "   DateTime.Now.ToString();
                                            closeQuoteRequest.QuoteClose = QuoteClose;
                                            closeQuoteRequest.Status = new OptionSetValue(7);
                                            // Execute the Response
                                            service.Execute(closeQuoteRequest);

                                        }
                                        catch (Exception ex)
                                        {
                                            tracingService.Trace("WestQuoteV2Plugin: {0}", ex.ToString());
                                            throw;

                                        }
                                    }
                                    else
                                    {
                                        return;
                                    }
                                }
                            }
                            // skip plugin if no results
                            else
                            {
                                return;
                            }
                        }
                    }
                    catch (FaultException ex)
                    {
                        throw new InvalidPluginExecutionException("An error occurred in QuoteV2Plugin.", ex);
                    }

                    catch (Exception ex)
                    {
                        tracingService.Trace("QuoteV2Plugin: {0}", ex.ToString());
                        throw;
                    }
                }
                // skip plugin if it doesnt match
                else
                {
                    return;
                }
            }
            else
            {
                return;
            }
        }
    }
}

  • Suggested answer
    Bipin D365 Profile Picture
    Bipin D365 28,964 Super User 2024 Season 1 on at
    RE: Help with plugin code

    Hi,

    Replace below line in your code

    bool startsWithWQ = new_quote_ref.StartsWith("WQ-");

    with

    bool startsWithWQ=false;

    if(!string.IsNullOrEmpty(new_quote_ref))

    bool startsWithWQ = new_quote_ref.StartsWith("WQ-");

    Please mark my answer verified if i were helpful

  • Suggested answer
    Temmy Wahyu Raharjo Profile Picture
    Temmy Wahyu Raharjo 2,914 on at
    RE: Help with plugin code

    Hi G.Vetere

    First, do you know what is context.InputParameters["Target"] is? This is an object that contain all the changes for that entity. You can learn more in here: docs.microsoft.com/.../understand-the-data-context.

    From what I suspect, you want to run this plugin in update. Because of the "Target" only contains the data, then you will get null in below code because new_quote_ref don't have changes in UI (makes it null).

    bool startsWithWQ = new_quote_ref.StartsWith("WQ-");

    If your requirements is to get latest data, what u need to do is combine previous data in database (You can retrieve or using pre/post-image) + Target object.

    Also for more easy checking, I would suggest to you to use tracingService.Trace("message") to check your code run until which line instead of debugging.

    If you need any help, you can hit reply button so I can get notification.

  • Suggested answer
    sdfasdf Profile Picture
    sdfasdf 840 on at
    RE: Help with plugin code

    You got incorrect attribute names there: 

    string new_quote_number = entity.GetAttributeValue<string>("vendor_quote_number");
    string new_quote_ref = entity.GetAttributeValue<string>("quote_ref");
    int new_quote_version = entity.GetAttributeValue<int>("version_number");

    You might want to check the actual schema names for the fields you're trying to read.

  • Suggested answer
    Mahendar Pal Profile Picture
    Mahendar Pal 45,095 on at
    RE: Help with plugin code

    Hi,

    Best option is to debug your plugin and find out where it's failing, it will help you to fix the code as well as you have experience in debugging.

    dynamics365blocks.wordpress.com/.../

    Quick Tip: Also please make sure to check field is available in the entity collection or not before getting it using Contains.

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

December Spotlight Star - Muhammad Affan

Congratulations to a top community star!

Top 10 leaders for November!

Congratulations to our November super stars!

Tips for Writing Effective Suggested Answers

Best practices for providing successful forum answers ✍️

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 291,280 Super User 2024 Season 2

#2
Martin Dráb Profile Picture

Martin Dráb 230,235 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans