Quantcast
Channel: Microsoft Dynamics CRM Forum - Recent Threads
Viewing all articles
Browse latest Browse all 55831

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

$
0
0

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;

        }

 
    
    }
 }

Viewing all articles
Browse latest Browse all 55831

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>