Skip to main content

Notifications

Announcements

No record found.

Microsoft Dynamics CRM (Archived)

Problem with C# Plugin Code that gets Money Field Value CRM 2011

Posted on by 1,579

I have a CRM 2011 plugin that executes Post-Operation on Update.

 

The plugin pulls data from each field on the form, and stores each field value in its own variable.

 

This data will later be manipulated and inserted into a newly created record, but I cannot do that or go that far until I can first get all the data from the fields and store them in variables without incident.

 

Now, I can get all my text box fields, and I can get the Guid values for all my lookup fields.

 

Some lookup fields may not have anything selected, so my code even handles that properly, and returns a “NULL” in place of what would be an exception/error.

 

My problem is that I am unable to get the value of the money field.

 

I have a function named GetFieldMoneyDataAsDecimal

 

And I pass it the following (service, localContext, new_s_checkstaging, "new_checkamount");


Using the following:


var CheckAmount = GetFieldMoneyDataAsDecimal(service, localContext, new_s_checkstaging, "new_checkamount");



GetFieldMoneyDataAsDecimal is then supposed to receive that information, and use it to GET the value of the money field. In a sample record, I have 3267.22 in the money field, so my expected result is that will ultimately be placed in CheckAmount is 3267.22

 

This isn’t happening and I am at a loss for how to proceed.

 

I already tried using the plugin profiler here -- https://support.microsoft.com/en-us/help/2778280/step-by-step-working-with-crm2011-plugin-profiler but I am not getting any useful information, and am instead getting even more error so I am clearly doing something very wrong.

 

My code is shown below

 

// TODO: Implement your custom Plug-in business logic.

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)
{
try
{ //Set Up Process
Entity new_s_checkstaging = (Entity)context.InputParameters["Target"];
//THERE IS A TON OF CODE HERE THAT I AM NOT SHOWING – BUT WILL SHOW LATERON IN THIS PROBLEM DESCRIPTION
//ALL THAT CODE WORKS PERFECTLY AND GETS ME THE VALUES OF ALL THE TEXT AND LOOKUP FIELDS I NEED
//AND RETURNS THOSE VALUES IN THE EXPECTED FORMAT, SO IT SEEMS I AM JUST HAVING PROBLEMS WITH THE 
//CODE THAT GETS THE CURRENCY VALUES FROM THE CURRENCY FIELDS AS SHOWN BELOW. 
//Get Field Data - CURRENCY
var CheckAmount = GetFieldMoneyDataAsDecimal(service, localContext, new_s_checkstaging, "new_checkamount");
//CODE TO TEST THE VALUE OBTAINED TO MAKE SURE ITS CORRECT
throw new Exception("CheckAmount is: " + CheckAmount);
}

catch (Exception ex) { throw new Exception("Error in top level at TRY housing UpdateCheckRecordsWithTransactionID: " + ex.Message); }
            }
            else
            {
throw new InvalidPluginExecutionException("ELSE Error - code went to ELSE inside the top level ExecutePostTestEntityCreate method when calling UpdateLicenseRecordsWithTransactionID(service,TransactionID); .");
            }
        }
//BUSINESS LOGIC FUNCTIONS
protected decimal GetFieldMoneyDataAsDecimal(IOrganizationService EntityService, LocalPluginContext EntityLocalContext, Entity PassedEntity, string PassedField)
        {
            IPluginExecutionContext context = EntityLocalContext.PluginExecutionContext;
            EntityService = EntityLocalContext.OrganizationService;
            ITracingService TracingSvc = EntityLocalContext.TracingService;
            if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
            {
                PassedEntity = (Entity)context.InputParameters["Target"];
                //Entity new_s_testentity = (Entity)context.InputParameters["Target"];
          try
                {
                    
                    //var TranscationID = PassedEntity.GetAttributeValue<string>("new_testentityinfoid");
                   //// if (String.IsNullOrEmpty(MyFieldValue))
                   // if (((Money)PassedEntity.Attributes[PassedField]).Value < 0)

                   // {
                   //     try
                   //     {
                            Money MyFieldValue = (Money)PassedEntity.GetAttributeValue<Money>(PassedField);
                            decimal actualAmount = MyFieldValue.Value;
                            return actualAmount;
                    //    }
                    //    catch (Exception ex) { throw new Exception("Error in IF/TRY TransactionID Check: " + ex.Message); }
                    //}
                    //else
                    //{
                    //    try
                    //    {
                    //        var result2 = 0;
                    //        return result2;
                    //    }
                    //    catch (Exception ex) { throw new Exception("Error in ELSE/TRY TransactionID Check: " + ex.Message); }

                    //}
                }
//THIS IS WHERE THE ERROR HAPPENS, AND THE CATCH EXCEPTION IS THROWN
                catch (Exception ex) { throw new Exception("Error in GetTransactionMethod: " + ex.Message); }            }
            return 0;
        }


 

Any assistance in helping me to identify the exact problem and how to rectify it would be greatly appreciated.

 

The code that does work, is the code that gets all of the values of the text fields as well as all of the Lookup Fields Guid values. I just need to do the same thing with all the money fields, and that’s my problem.

 

The get text and get Guid from Lookup fields code that works great is shown below.


//Get Field Data - TEXT
var CheckStagingID = GetFieldStringData(service, localContext, new_s_checkstaging, "new_chkstagenum");
var AddressLine1Pri = GetFieldStringData(service, localContext, new_s_checkstaging, "new_addressline1pri");
var AddressLine1Sec = GetFieldStringData(service, localContext, new_s_checkstaging, "new_addressline1sec");
var AddressLine2Pri = GetFieldStringData(service, localContext, new_s_checkstaging, "new_addressline2pri");
var AddressLine2Sec = GetFieldStringData(service, localContext, new_s_checkstaging, "new_addressline2sec");
var BankCode = GetFieldStringData(service, localContext, new_s_checkstaging, "new_bankcode");
var BusinessNamePri = GetFieldStringData(service, localContext, new_s_checkstaging, "new_businessname");
var BusinessNameSec = GetFieldStringData(service, localContext, new_s_checkstaging, "new_businessnamesec");
var CheckCatalogNum = GetFieldStringData(service, localContext, new_s_checkstaging, "new_checkcatalognumber");
var CheckNum = GetFieldStringData(service, localContext, new_s_checkstaging, "new_checknum");
var CheckYear = GetFieldStringData(service, localContext, new_s_checkstaging, "new_checkyear");
var CheckStagingNumber = GetFieldStringData(service, localContext, new_s_checkstaging, "new_chkstagenum");
var CityPri = GetFieldStringData(service, localContext, new_s_checkstaging, "new_citypri");
var CitySec = GetFieldStringData(service, localContext, new_s_checkstaging, "new_citysec");
var FirstNamePri = GetFieldStringData(service, localContext, new_s_checkstaging, "new_firstnamepri");
var FirstNameSec = GetFieldStringData(service, localContext, new_s_checkstaging, "new_firstnamesec");
var IssueReason = GetFieldStringData(service, localContext, new_s_checkstaging, "new_issuereasonlong");
var IssuingDepartment = GetFieldStringData(service, localContext, new_s_checkstaging, "new_issuingdepartmentlong");
var LastNamePri = GetFieldStringData(service, localContext, new_s_checkstaging, "new_lastnamepri");
var LastNameSec = GetFieldStringData(service, localContext, new_s_checkstaging, "new_lastnamesec");
var MiddleNamePri = GetFieldStringData(service, localContext, new_s_checkstaging, "new_middlenamepri");
var MiddleNameSec = GetFieldStringData(service, localContext, new_s_checkstaging, "new_middlenamesec");
var OwnerTypeDescriptionPri = GetFieldStringData(service, localContext, new_s_checkstaging, "new_otypelongpri");
var OwnerTypeDescriptionSec = GetFieldStringData(service, localContext, new_s_checkstaging, "new_otypelongsec");
var OwnerRelationshipPri = GetFieldStringData(service, localContext, new_s_checkstaging, "new_ownerrelationship");
var OwnerRelationshipSec = GetFieldStringData(service, localContext, new_s_checkstaging, "new_ownerrelationshipsec");
var OwnerStatusPri = GetFieldStringData(service, localContext, new_s_checkstaging, "new_ownerstatuslong");
var OwnerStatusSec = GetFieldStringData(service, localContext, new_s_checkstaging, "new_ownerstatuslongsec");
var CorporateStatusPri = GetFieldStringData(service, localContext, new_s_checkstaging, "new_ownertypelong");
var CorporateStatusSec = GetFieldStringData(service, localContext, new_s_checkstaging, "new_ownertypelongsec");
var PropertyOwnerType = GetFieldStringData(service, localContext, new_s_checkstaging, "new_potype");
var RecordOwner = GetFieldStringData(service, localContext, new_s_checkstaging, "new_recowner");
var StatusCode = GetFieldStringData(service, localContext, new_s_checkstaging, "new_scode");
var SSNTAXIDNum = GetFieldStringData(service, localContext, new_s_checkstaging, "new_ssntaxid");
var SSNTAXIDNumSec = GetFieldStringData(service, localContext, new_s_checkstaging, "new_ssntaxidsec");
var ZipCodePri = GetFieldStringData(service, localContext, new_s_checkstaging, "new_zipcodepri");
var ZipCodeSec = GetFieldStringData(service, localContext, new_s_checkstaging, "new_zipcodesec");
   
//Get Field Data - LOOKUP
var Bank = GetLookupFieldGuid(service, localContext, new_s_checkstaging, "new_s_checkstaging", "new_bank");
var IssueReasonCode = GetLookupFieldGuid(service, localContext, new_s_checkstaging, "new_s_checkstaging", "new_issuereason");
var CheckID = GetLookupFieldGuid(service, localContext, new_s_checkstaging, "new_s_checkstaging", "new_checkmanagementid");
var IssuingDepartmentCode = GetLookupFieldGuid(service, localContext, new_s_checkstaging, "new_s_checkstaging", "new_issuingdepartment");
var PrefixPri = GetLookupFieldGuid(service, localContext, new_s_checkstaging, "new_s_checkstaging", "new_nameprefixpri");
var PrefixSec = GetLookupFieldGuid(service, localContext, new_s_checkstaging, "new_s_checkstaging", "new_nameprefixsec");
var SuffixPri = GetLookupFieldGuid(service, localContext, new_s_checkstaging, "new_s_checkstaging", "new_namesuffixpri");
var SuffixSec = GetLookupFieldGuid(service, localContext, new_s_checkstaging, "new_s_checkstaging", "new_namesuffixsec");
var NumofOwners = GetLookupFieldGuid(service, localContext, new_s_checkstaging, "new_s_checkstaging", "new_numberofowners");
var OwnerTypePri = GetLookupFieldGuid(service, localContext, new_s_checkstaging, "new_s_checkstaging", "new_otypecodepri");
var OwnerTypeSec = GetLookupFieldGuid(service, localContext, new_s_checkstaging, "new_s_checkstaging", "new_otypecodesec");
var OwnerRelationshipCodePri = GetLookupFieldGuid(service, localContext, new_s_checkstaging, "new_s_checkstaging", "new_ownerrelationshipcode");
var OwnerRelationshipCodeSec = GetLookupFieldGuid(service, localContext, new_s_checkstaging, "new_s_checkstaging", "new_ownerrelationshipcodesec");
var OwnerStatusCodeSec = GetLookupFieldGuid(service, localContext, new_s_checkstaging, "new_s_checkstaging", "new_ownerstatuscodesec");
var OwnerStatusCodePri = GetLookupFieldGuid(service, localContext, new_s_checkstaging, "new_s_checkstaging", "new_ownerstatuspri");
var CorporateStatusCodeSec = GetLookupFieldGuid(service, localContext, new_s_checkstaging, "new_s_checkstaging", "new_ownertypecodesec");
var CorporateStatusCodePri = GetLookupFieldGuid(service, localContext, new_s_checkstaging, "new_s_checkstaging", "new_ownertypepri");
var StatePri = GetLookupFieldGuid(service, localContext, new_s_checkstaging, "new_s_checkstaging", "new_statepri");
var StateSec = GetLookupFieldGuid(service, localContext, new_s_checkstaging, "new_s_checkstaging", "new_statesec");
var SubmissionStatus = GetLookupFieldGuid(service, localContext, new_s_checkstaging, "new_s_checkstaging", "new_submissionstatus");


//Get Field Data - MEMO
var AdditionalInformationSec = GetFieldStringData(service, localContext, new_s_checkstaging, "new_additionalInformationasec");
var AdditionalInformationPri = GetFieldStringData(service, localContext, new_s_checkstaging, "new_additionalInformationpri");

                    //throw new Exception("The Bank GUID is: " + Bank +
                    //                   " ,the Issue Reason Code is: " + IssueReasonCode +
                    //                   ", the Check ID is: " + CheckID +
                    //                   ", the Issuing Dept Code is: " + IssuingDepartmentCode +
                    //                   ", the Prefix(Pri) is: " + PrefixPri +
                    //                   ", the Prefix(Sec) is: " + PrefixSec +
                    //                   ", the Suffix(Pri) is: " + SuffixPri +
                    //                   ", the Suffix(Sec) is: " + SuffixSec +
                    //                   ", the NumofOwners is: " + NumofOwners +
                    //                   ", the OwnerType(Pri) is: " + OwnerTypePri +
                    //                   ", the OwnerType(Sec) is: " + OwnerTypeSec +
                    //                   ", the OwnerRelationshipCode(Pri) is: " + OwnerRelationshipCodePri +
                    //                   ", the OwnerRelationshipCode(Sec) is: " + OwnerRelationshipCodeSec +
                    //                   ", the OwnerStatusCode(Pri) is: " + OwnerStatusCodePri +
                    //                   ", the OwnerStatusCode(Sec) is: " + OwnerStatusCodeSec +
                    //                   ", the CorporateStatusCode(Pri) is: " + CorporateStatusCodePri +
                    //                   ", the CorporateStatusCode(Sec) is: " + CorporateStatusCodeSec +
                    //                   ", the State(Pri) is: " + StatePri +
                    //                   ", the State(Sec) is: " + StateSec +
                    //                   ", the SubmissionStatus is: " + SubmissionStatus +
                    //                   ", the AdditionalInformationPri is: " + AdditionalInformationPri +
                    //                   ", the AdditionalInformationSec is: " + AdditionalInformationSec);

  //BUSINESS LOGIC FUNCTIONS

        protected string GetLookupFieldGuid(IOrganizationService EntityService, LocalPluginContext EntityLocalContext, Entity PassedEntity, string CurrentEntity, string LookupFieldName) 
        {
           IPluginExecutionContext context = EntityLocalContext.PluginExecutionContext;
           EntityService = EntityLocalContext.OrganizationService;
           ITracingService TracingSvc = EntityLocalContext.TracingService;

           // Get the context
           
              if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
            {
                //PassedEntity = (Entity)context.InputParameters["Target"];
                //Entity new_s_testentity = (Entity)context.InputParameters["Target"];
                 
                try
                {
                    //Lookup Attribute: new_MyLookupattribute,
                    //Current Entity: new_myentity,

                    ColumnSet myAttributes = new ColumnSet(new String[] { LookupFieldName });
                    Entity myEntityHavingLookup = EntityService.Retrieve(CurrentEntity, PassedEntity.Id, myAttributes);

                    if (((Microsoft.Xrm.Sdk.EntityReference)(myEntityHavingLookup.Attributes[LookupFieldName])).Id != null)
                        {
                        var myLookupId = ((Microsoft.Xrm.Sdk.EntityReference)(myEntityHavingLookup.Attributes[LookupFieldName])).Id;
                        var myLookupName = ((Microsoft.Xrm.Sdk.EntityReference)(myEntityHavingLookup.Attributes[LookupFieldName])).Name;
                        var MyGUIDAsString = myLookupId.ToString();
                        return MyGUIDAsString;
                        }

                    else { return "NULL"; }
                        

                     }

                //catch (Exception ex) { throw new Exception("Error in GetTransactionMethod: " + ex.Message); }
                catch {return "NULL"; }
              }
              else
                    {
                        try
                        {
                            var result2 = "BLANK";
                            return result2;
                        }
                        catch (Exception ex) { throw new Exception("Error in ELSE/TRY TransactionID Check: " + ex.Message); }
                    }   
        }
        
  

        protected string GetFieldStringData(IOrganizationService EntityService, LocalPluginContext EntityLocalContext, Entity PassedEntity, string PassedField)
        {
            IPluginExecutionContext context = EntityLocalContext.PluginExecutionContext;

            EntityService = EntityLocalContext.OrganizationService;

            ITracingService TracingSvc = EntityLocalContext.TracingService;

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

                try
                {
                    var MyFieldValue = PassedEntity.GetAttributeValue<string>(PassedField);
                    //var TranscationID = PassedEntity.GetAttributeValue<string>("new_testentityinfoid");
                    if (String.IsNullOrEmpty(MyFieldValue))
                    {
                        try
                        {
                            var result = "NULL";
                            return result;
                        }
                        catch (Exception ex) { throw new Exception("Error in IF/TRY TransactionID Check: " + ex.Message); }
                    }
                    else
                    {
                        try
                        {
                            var result2 = MyFieldValue;
                            return result2;
                        }
                        catch (Exception ex) { throw new Exception("Error in ELSE/TRY TransactionID Check: " + ex.Message); }

                    }
                }

                catch (Exception ex) { throw new Exception("Error in GetTransactionMethod: " + ex.Message); }

            }
            return null;
        }



*This post is locked for comments

  • Saddamk206 Profile Picture
    Saddamk206 777 on at
    RE: Problem with C# Plugin Code that gets Money Field Value CRM 2011

    Get and Set Currency(Money) using C#

    Get : -

    var moneyValue = ((Money)item.Attributes[attributeName]).Value;

    Post : -

    newSalesOrder[attributeName] = new Money((decimal)moneyValue);

  • ACECORP Profile Picture
    ACECORP 1,579 on at
    RE: Problem with C# Plugin Code that gets Money Field Value CRM 2011

    Got it! That worked! Thanks so much for all your help!

  • Verified answer
    ashlega Profile Picture
    ashlega 34,475 on at
    RE: Problem with C# Plugin Code that gets Money Field Value CRM 2011

    Hi Jim,

     If everything is correct with the postimage(if that postimage variable is not null), you just need to replace passedentity with postimage in that code

  • ACECORP Profile Picture
    ACECORP 1,579 on at
    RE: Problem with C# Plugin Code that gets Money Field Value CRM 2011

    Great! So once I get the post image using var postImage =   context.PostEntityImages["PostImageAddImportCheckToCheckRegister"];

    What do I do to actually pull the data from the post image for a particular field?

    The code below works when I don't use the post image.

    Money MyFieldValue = (Money)PassedEntity.GetAttributeValue<Money>(PassedField);

                                if (MyFieldValue != null)

                               {

                                   decimal actualAmount = MyFieldValue.Value;

                                   return actualAmount;

                               }

                               else { return 0; }

    How would I need to change that to utilize the post image?

  • Verified answer
    ashlega Profile Picture
    ashlega 34,475 on at
    RE: Problem with C# Plugin Code that gets Money Field Value CRM 2011

    Hi Jim,

     that post image is a copy of the record that has all the fields (if some of them were updated, it will have updated fields. If some of them were not updated, it will just get them from the database)

     To access post image in the code, you just need to get it from the context:

     var postImage =   context.PostEntityImages["PostImageAddImportCheckToCheckRegister"];

     Once you have that, you don't have to worry about submit mode etc..

     BUT some of the fields may still be missing (in case they were never entered), so you may still have to check for nulls

  • ACECORP Profile Picture
    ACECORP 1,579 on at
    RE: Problem with C# Plugin Code that gets Money Field Value CRM 2011

    Alex, I got your code working. And I see what you mean, if the end user doesn't change the contents of the money field, the returned result is 0 -- which is a problem. I need to get the new value of this field if its changed, but I also need to get the value of this field if it is NOT changed.

    Can I get around the issue by simply setting the money field to "submit mode = always" via JavaScript? Will that enable the plugin to always get the value of that money field, even if it wasn't changed during update?

    If I want to go the "post image" route, what must I do in my code exactly?

    I already registered the plugin with a post image named PostImageAddImportCheckToCheckRegister

    But what I don't quite understand what I need to do in the code.

    Must I change all my field collection to happen inside the PostImage? Or instead of where it is happening currently?  

  • Verified answer
    ashlega Profile Picture
    ashlega 34,475 on at
    RE: Problem with C# Plugin Code that gets Money Field Value CRM 2011

    Also, if there is no value at all, you'll get an exception there beause you are not testing for null..

    Should be something along these lines:

    Money MyFieldValue = (Money)PassedEntity.GetAttributeValue<Money>(PassedField);

    if(MyFieldValue != null)

    {

    decimal actualAmount = MyFieldValue.Value;

    return actualAmount;

    }

    else return 0;

    But.. you should be using a post image instead. You won't have to do this then to retrieve those fields - they will all be added to the post image by CRM:

    EntityService.Retrieve

    crmbook.powerobjects.com/.../plug-in-images-pre-vs-post

  • Suggested answer
    ashlega Profile Picture
    ashlega 34,475 on at
    RE: Problem with C# Plugin Code that gets Money Field Value CRM 2011

    Hi Jim,

     Are you updating all form fields every time? Including that money field? I mean.. are you changing the value of that field or are you just trying to get access to whatever is there, already?

     You won't have an attribute in the target if it has not been updated on the client side - only modified fields will be added to the target entity.

     If you want to have access to everything.. the easiest method would be to register a post image for that plugin step. It will be available through context.PostEntityImages

  • Suggested answer
    Guido Preite Profile Picture
    Guido Preite 54,081 Super User 2024 Season 1 on at
    RE: Problem with C# Plugin Code that gets Money Field Value CRM 2011

    please read this post I wrote on how to use GetAttributeValue to retrieve values.

    your GetFieldMoneyDataAsDecimal can be reduced to just one line.

    www.crmanswers.net/.../getattributevalue-demystified.html

  • Suggested answer
    Gopalan Bhuvanesh Profile Picture
    Gopalan Bhuvanesh 11,397 on at
    RE: Problem with C# Plugin Code that gets Money Field Value CRM 2011

    Hi

    Your condition could be > instead of <.

    Also try changing the code as below, if you are not able to get the value after changing the condition:

    if (PassedEntity.Contains(PassedField)&&
    ((Money)PassedEntity.Attributes[PassedField]).Value > 0) { try { Money MyFieldValue = (Money)PassedEntity.Attributes[PassedField]; //Money MyFieldValue = (Money)PassedEntity.GetAttributeValue<Money>(PassedField); decimal actualAmount = MyFieldValue.Value; return actualAmount; } catch (Exception ex) { throw new Exception("Error in IF/TRY TransactionID Check: " + ex.Message); } }

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,214 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans