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

Announcements

No record found.

News and Announcements icon
Community site session details

Community site session details

Session Id :
Microsoft Dynamics CRM (Archived)

Question regarding value variable that stores specific data pulled from an Entity Collection on RetrieveMultiple when no records are returned

(0) ShareShare
ReportReport
Posted on by 1,589

I have a Test Entity named "new_s_testentity"

I also have a plugin that executes in the Pre-Validation stage on creation of a record on the Test Entity above.

The plugin is supposed to get all the records from another entity called License Entity that have a specific value in Field X, and put those records into an EntityCollection named "MyReturnedRecords".

Then the value of the "new_licenseinfoId" attribute field from the very first record that was returned into the EntityCollection, is supposed to be placed in a string variable named mydata.

Next, that variable is returned to the main method via return mydata; where it is then accessed and checked as follows:

If there is data present, meaning at least one record was returned that matched the criteria,  the data is supposed to be placed in a field on the currently open Test Entity record (named "new_s_testentity" from above).

This works great!

However, if no records met the criteria with a certain value in Field X, then the words "No records exist" must be written to another field on the currently opened Test Entity record.

It is this second part that isn't happening.

I enabled tracing and am finding that when no records are returned, the focus of the plugin never starts the IF/Else section and immediately jumps to the CATCH {} section.

This is unexpected since I have an if/else if/else to help me understand what the value of mydata is if it’s not == null. I would have expected that it either executed the part where its == null or the final general else that serves as the "catch all" part of the if/else code section.

But it never gets there as it goes directly to the Catch part of the try/catch that contains the If/else

I can put the rest of my code in the catch as a work around, for when no records are returned, but I really want to understand what the value of the mydata variable is when no records are returned.

I tried to use the plugin profiler debugger as specified in the following KB Article

https://support.microsoft.com/en-us/kb/2778280 for this probelm since I have successfully used it in the past for a different problem but it doesn’t seem to work this time around. When I point to the ErrorDetails.txt file when the debug existing plugin window comes up, I get the following unhandled exception error shown below.

 

Unhandled Exception: System.ArgumentException: Unable to parse the OrganizationServiceFault.

Parameter name: serializedReport

   at PluginProfiler.Library.ProfilerUtility.ExtractReport(String serializedReport)

   at PluginProfiler.Library.ProfilerUtility.DeserializeProfilerReport(String assemblyFilePath, String logFilePath)

   at PluginProfiler.Library.ProfilerExecutionUtility.RetrieveReport(String logFilePath)

   at Microsoft.Crm.Tools.PluginRegistration.OrganizationHelper.ParseReportOrShowError(IWin32Window owner, FileBrowserControl profilePathControl, Boolean requireReportParse, ProfilerPluginReport& report)

Inner Exception: System.InvalidOperationException: Message does not contain a serialized value.

   at PluginProfiler.Library.ProfilerUtility.ExtractReportFromFault(OrganizationServiceFault fault)

   at PluginProfiler.Library.ProfilerUtility.ExtractReport(String serializedReport)

 

I am certain the problem centers around the following lines of code shown directly below when no records are returned. I even tried moving my if/else code immediately before return my data so that only valid information is returned when mydata has no records, but I can’t get that working.

  EntityCollection MyReturnedRecords = service.RetrieveMultiple(query);

  var mydata = MyReturnedRecords[0]["new_licenseinfoid"].ToString();

  return mydata;

I posted the entirety of my code below in the hope that someone can take a look at it, and might know right off the top of their head what is happening, why bypassing the if/else and jumping directly to the catch, and how I might say “if no records are returned” – as in what value occupies the mydata variable when no records are returned?

namespace ANumUpdate.Plugins
{
    using System;
    using System.Data;
    using System.ServiceModel;
    using Microsoft.Xrm.Sdk;
    using Microsoft.Xrm.Sdk.Query;
    using Microsoft.Xrm.Sdk.Client;
    using Microsoft.Xrm.Sdk.Discovery;
    using Microsoft.Xrm.Sdk.Linq;
    using Microsoft.Xrm.Sdk.Messages;
    using Microsoft.Xrm.Sdk.Metadata;
    using Microsoft.Xrm.Sdk.XmlNamespaces;

    public class PreValidateTestEntityCreate : Plugin
    {
          public PreValidateTestEntityCreate()
            : base(typeof(PreValidateTestEntityCreate))
        {
            base.RegisteredEvents.Add(new Tuple<int, string, string, Action<LocalPluginContext>>(10, "Create", "new_s_testentity", new Action<LocalPluginContext>(ExecutePreValidateTestEntityCreate)));

              }

            protected void ExecutePreValidateTestEntityCreate(LocalPluginContext localContext)
        {
            if (localContext == null)
            {
                throw new ArgumentNullException("localContext");
            }

            // Custom Plug-in business logic implemented below.

           
            IPluginExecutionContext context = localContext.PluginExecutionContext;

            IOrganizationService service = localContext.OrganizationService;

            ITracingService TracingSvc = localContext.TracingService;

            TracingSvc.Trace("Plugin has started.");

            if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
            {
                Entity new_s_testentity = (Entity)context.InputParameters["Target"];

                try
                {
                    string Last2DigitsOfyear = getCurrentYearAndStartTheProcess();

                    TracingSvc.Trace("Function getCurrentYearAndStartTheProcess has just completed and returned a value of " + Last2DigitsOfyear + "to the main function");

                    var mydta = DoRecsOfSpecifiedYearExist(service, Last2DigitsOfyear);

                    new_s_testentity["new_testwritefield1"] = mydta;

                    if (mydta != null)
                    {
                        TracingSvc.Trace("The value of mydta is: " + mydta +" ." );
                        new_s_testentity["new_testwritefield2"] = "Don't reset autonumber because data exists";
                        

                    }
                    else if (mydta == null)
                    {	//when no records are returned, i would expect this to happen or what's in the unconditional else statement below if no records were returned
                        TracingSvc.Trace("The value of mydta is: " + mydta + " .");
                        new_s_testentity["new_testwritefield2"] = "No records exist. RESET the autoincrementor!";

                    }

                    else
                    {
                        var probelmdta = "This didn't work as expected. The value is " + mydta + " .";
                        TracingSvc.Trace("This didn't work as expected. The value is " + mydta + " .");                        
                        new_s_testentity["new_testwritefield2"] = probelmdta;
                    }
                    
                }
                catch
                {
                    throw new InvalidPluginExecutionException("Catch Error - code went to catch.");
//when the no records are returned, it skips down here and does not 
                }

                throw new InvalidPluginExecutionException("Fake Error to get trace into.");
                //End the plugin, no update neeeded. Business as usual
                return;
            }
           
            
           
        }
            
                
        //CUSTOM FUNCTIONS USED BY BUSINESS LOGIC ABOVE

        protected string Test2017()
        {
        string myyr = "17";
            return myyr;
        }

        protected string getCurrentYearAndStartTheProcess()
        {   
            DateTime DateOfToday = DateTime.Today;
            string lastTwoDigitsOfYear = DateOfToday.ToString("yy");
            return lastTwoDigitsOfYear;
        }

        protected string DoRecsOfSpecifiedYearExist(IOrganizationService service, string year) 
        {
            QueryExpression query = new QueryExpression();
            query.EntityName = "new_s_licenseinformation";
            query.ColumnSet = new ColumnSet() { AllColumns = true };

            query.Criteria = new FilterExpression();
            query.Criteria.FilterOperator = LogicalOperator.And;
            query.Criteria.Conditions.Add
            (
                new ConditionExpression("new_licenseyear", ConditionOperator.Equal, year)
            );
            EntityCollection MyReturnedRecords = service.RetrieveMultiple(query);

            var mydata = MyReturnedRecords[0]["new_licenseinfoid"].ToString();

            return mydata;

        }

 
    
    }
 }

*This post is locked for comments

I have the same question (0)
  • Suggested answer
    ScottDurow Profile Picture
    21 on at

    I suspect that the issue is with the line:

    var mydata = MyReturnedRecords[0]["new_licenseinfoid"].ToString();

    You should first check that there are any records before you access the first record. This line will throw an exception if no records are returned.

    It should be something like

    if (MyReturnedRecords.Count>0)

    {

    ....

    }

    else

    return null;

    Hope this helps,

  • Verified answer
    Aiden Kaskela Profile Picture
    19,696 on at

    Hi Jim,

    In C# when you're accessing a collection, you need to make sure there's an item in the collection before you get it:

    If MyReturnedRecords has 5 items and you try to get the tenth one like MyReturnedRecords[9], you'll get an error. This is what's happening when you try to get the first result when there are none. You can check the size of the Entities property before you access it to make sure it's the right size:

    EntityCollection MyReturnedRecords = service.RetrieveMultiple(query);
    string returnValue = "No records exist";
    if (MyReturnedRecords.Entities.Count > 0 && MyReturnedRecords.Entities[0].Contains("new_licenseinfoid"))
    {
      returnValue = MyReturnedRecords[0]["new_licenseinfoid"].ToString();
    }
    return returnValue;

    Note: I'm at home so the properties are from memory so the spelling may be off. In this code, it's checking the Entities collection Count (or Length) to make sure there's at least one record, and it has the new_licenseinfoid property before it tries to get it. This way, it'll only get the first item if it exists, and only get the property if it exists.

    Hope this helps! Let me know if I explained something poorly and I'd be happy to try and clarify. If this helps I'd appreciate if you'd mark this as a Verified answer.

    Thanks,

      Aiden

  • ACECORP Profile Picture
    1,589 on at

    Aiden - worked perfect. Thanks so much!

    Scott - your info was also valid.. just less detail.

    Thanks again for the assistance!

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

Introducing the 2026 Season 1 community Super Users

Congratulations to our 2026 Super Stars!

Meet the Microsoft Dynamics 365 Contact Center Champions

We are thrilled to have these Champions in our Community!

Congratulations to the March Top 10 Community Leaders

These are the community rock stars!

Leaderboard > 🔒一 Microsoft Dynamics CRM (Archived)

Last 30 days Overall leaderboard

Featured topics

Product updates

Dynamics 365 release plans