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

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Microsoft Dynamics CRM (Archived)

Plugin Error

(0) ShareShare
ReportReport
Posted on by 2,139

Hi all! I'm facing an issue whit my public. Unfortunately, i cannot understand what's going wrong. Please see below my Code and Error getting from trace.

namespace Mangazeya_Plugins
{
    using System;
    using System.ServiceModel;
    using Microsoft.Xrm.Sdk;
    using Microsoft.Xrm.Sdk.Query;

    public class PostTisa_ArticleUpdateFurnishSum : Plugin
    {
        public PostTisa_ArticleUpdateFurnishSum()
            : base(typeof(PostTisa_ArticleUpdateFurnishSum))
        {
            base.RegisteredEvents.Add(new Tuple<int, string, string, Action<LocalPluginContext>>(40, "Update", "tisa_article", new Action<LocalPluginContext>(ExecutePostTisa_ArticleUpdateFurnishSum)));

        }

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

            IPluginExecutionContext context = localContext.PluginExecutionContext;
            IOrganizationService service = localContext.OrganizationService;
           
            if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
            {
                // Obtain the target entity from the input parmameters.
                Entity entity = (Entity)context.InputParameters["Target"];
                if (entity.LogicalName == "tisa_article")
                {
                    if (context.MessageName.ToUpper() == "UPDATE")
                    {
                        var pricewoFurnish = entity.Attributes["tisa_price"];
                        ColumnSet attributes = new ColumnSet(new string[] { "tisa_code", "tisa_addressid", "tisa_pricefurnishstandart", "tisa_pricefurnishdesign", "tisa_platformnumber", "tisa_quantity" });
                        var tisa_article = service.Retrieve(entity.LogicalName, entity.Id, attributes);

                        var tisa_addressid = ((EntityReference)tisa_article["tisa_addressid"]).Id;

                        string fetchxml = @"
                        <fetch distinct='false' mapping='logical' output-format='xml-platform' version='1.0'>
                            <entity name='tisa_costfurnishvariation'>
                                    <attribute name='tisa_costfurnishvariationid'/>
                                    <attribute name='tisa_isfurnishprice"+ tisa_article["tisa_platformnumber"] + @"'/>
                                    <attribute name='tisa_tisa_platformnumber" + tisa_article["tisa_platformnumber"] + @"'/>
                                    <attribute name='tisa_mainfurnish'/>
                                    <attribute name='tisa_addressid'/>
                                <order descending='false' attribute='tisa_addressid'/>
                                <filter type='and'>
                                    <condition attribute='tisa_addressid' value='" + tisa_addressid + @"' operator='eq'/>
                                </filter>
                            </entity>
                        </fetch>";

                        EntityCollection result = service.RetrieveMultiple(new FetchExpression(fetchxml));
                        foreach (var c in result.Entities) 
                        {
                            if (result != null && result.Entities.Count > 0) 
                            {
                                int value = ((OptionSetValue)c["tisa_mainfurnish"]).Value;

                                if (value == 1) 
                                {
                                    entity["tisa_pricefurnishstandart"] = ((Convert.ToDecimal(c["tisa_isfurnishprice" + tisa_article["tisa_platformnumber"]])) * (Convert.ToDecimal(tisa_article["tisa_quantity"]))) + Convert.ToDecimal(entity.GetAttributeValue<Money>("tisa_price").Value); ;
                                }
                                else if(value == 2)
                                {
                                    entity["tisa_pricefurnishdesign"] = ((Convert.ToDecimal(c["tisa_isfurnishprice" + tisa_article["tisa_platformnumber"]])) * (Convert.ToDecimal(tisa_article["tisa_quantity"]))) + Convert.ToDecimal(entity.GetAttributeValue<Money>("tisa_price").Value);
                                }
                            }
                        }

                        service.Update(entity);
                    }
                }
            }
        }
    }
}


I'm getting this error 

Exception: System.ServiceModel.FaultException`1[Microsoft.Xrm.Sdk.OrganizationServiceFault]: System.InvalidCastException: Microsoft Dynamics CRM has experienced an error.

From Trace

at MessageProcessor.Execute(PipelineExecutionContext context) ilOffset = 0x1C5
at InternalMessageDispatcher.Execute(PipelineExecutionContext context) ilOffset = 0xE4
at ExternalMessageDispatcher.ExecuteInternal(IInProcessOrganizationServiceFactory serviceFactory, IPlatformMessageDispatcherFactory dispatcherFactory, String messageName, String requestName, Int32 primaryObjectTypeCode, Int32 secondaryObjectTypeCode, ParameterCollection fields, CorrelationToken correlationToken, CallerOriginToken originToken, UserAuth userAuth, Guid callerId, Guid transactionContextId, Int32 invocationSource, Nullable`1 requestId, Version endpointVersion) ilOffset = 0x16E
at OrganizationSdkServiceInternal.ExecuteRequest(OrganizationRequest request, CorrelationToken correlationToken, CallerOriginToken callerOriginToken, WebServiceType serviceType, UserAuth userAuth, Guid targetUserId, OrganizationContext context, Boolean returnResponse, Boolean checkAdminMode) ilOffset = 0x1F1
at OrganizationSdkServiceInternal.ExecuteRequest(OrganizationRequest request, CorrelationToken correlationToken, CallerOriginToken callerOriginToken, WebServiceType serviceType, Boolean checkAdminMode) ilOffset = 0x2D
at OrganizationSdkServiceInternal.Execute(OrganizationRequest request, CorrelationToken correlationToken, CallerOriginToken callerOriginToken, WebServiceType serviceType, Boolean checkAdminMode) ilOffset = 0x26
at InprocessServiceProxy.ExecuteCore(OrganizationRequest request) ilOffset = 0x34
at PlatformCommand.XrmExecuteInternal() ilOffset = 0xF6
at UpdateCommand.Execute() ilOffset = 0x7
at DataSource.Update(EntityProxy entity, Boolean performDuplicateCheck, Guid auditingTransactionId, IOrganizationContext context) ilOffset = 0x11
at EntityProxy.Update(Boolean performDuplicateCheck, Guid auditingTransactionId) ilOffset = 0x0
at EntityProxy.Update(Boolean performDuplicateCheck) ilOffset = 0x7
at EntityProxy.UpdateAndRetrieve(String[] columnSet, Boolean performDuplicateCheck) ilOffset = 0x0
at CommandBase.UpdateEntity(Entity entity, Boolean retrieve) ilOffset = 0xD1
at SaveCommand.ExecuteCommand(String commandXml) ilOffset = 0x116
at CommandBase.Execute(String commandXml) ilOffset = 0x13
at InlineEditWebService.Execute(Int32 command, String commandXml) ilOffset = 0xD0
at RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor) ilOffset = 0xFFFFFFFF
at RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments) ilOffset = 0x25
at RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) ilOffset = 0xCF
at LogicalMethodInfo.Invoke(Object target, Object[] values) ilOffset = 0x4F
at WebServiceHandler.Invoke() ilOffset = 0xC3
at WebServiceHandler.CoreProcessRequest() ilOffset = 0x13E
at SyncSessionlessHandler.ProcessRequest(HttpContext context) ilOffset = 0x39
at HandlerWrapper.ProcessRequest(HttpContext context) ilOffset = 0x7
at CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() ilOffset = 0x18D
at HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) ilOffset = 0x15
at ApplicationStepManager.ResumeSteps(Exception error) ilOffset = 0x10A
at HttpApplication.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) ilOffset = 0x5C
at HttpRuntime.ProcessRequestInternal(HttpWorkerRequest wr) ilOffset = 0x16A
at ISAPIRuntime.ProcessRequest(IntPtr ecb, Int32 iWRType) ilOffset = 0x4B
MessageProcessor fail to process message 'Update' for 'tisa_article'.

*This post is locked for comments

I have the same question (0)
  • Suggested answer
    Community Member Profile Picture
    on at

    Hi,

    It seems like it is a datatype issue.

    Thanks,

    Ridhima

  • Suggested answer
    gdas Profile Picture
    50,091 Moderator on at

    Hi Oscar,

    In which message and stage your plugin has registered ?

    Try to register plugin in post operation and set execution mode asynchronous . In addition I would suggest try to debug or write trace log to understand the data you are passing for update is correct or not .

  • Suggested answer
    RaviKashyap Profile Picture
    55,410 Moderator on at

    Hi,

    The error you are getting is Invalid Type Cast whichraised from s type conversion. In your code, you are converting value to decimal, check if you reslly have any value which you are converting.

    Hope this helps.

  • betlejuice Profile Picture
    2,139 on at

    Hi Ravi. I'm getting values. There is not any null field. How can i check if i paassing the correct value? I'm new in C#

  • Community Member Profile Picture
    on at

    Hi,

    docs.microsoft.com/.../watch-and-quickwatch-windows

    Hope it helps

    Thanks

  • AllanDeCastro Profile Picture
    156 on at

    Hey !

    Have a look on this (I just modified your code during my coffee break so it's really not perfect but will help you ) :

           protected void ExecutePostTisa_ArticleUpdateFurnishSum(LocalPluginContext localContext)

           {

               IPluginExecutionContext context = localContext.PluginExecutionContext;

               IOrganizationService service = localContext.OrganizationService;

               //Create the tracingService

               ITracingService tracingService = (ITracingService)ServiceProvider.GetService(typeof(ITracingService));

               // now you can use tracingService.Trace("MESSAGE");

               //add a try catch !!

               try

               {

                   if (localContext == null)

                   {

                       throw new InvalidPluginExecutionException("LocalContext is null");

                   }

                   if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)

                   {

                       // Obtain the target entity from the input parmameters.

                       Entity entity = (Entity)context.InputParameters["Target"];

                       if (entity.LogicalName == "tisa_article")

                       {

                           if (context.MessageName.ToUpper() == "UPDATE")

                           {

                               if (entity.Contains("tisa_price"))

                               {

                                   tracingService.Trace("tisa_price is ok");

                                   Money pricewoFurnish = entity.GetAttributeValue<Money>("tisa_price");

                                   ColumnSet attributes = new ColumnSet(new string[] { "tisa_code", "tisa_addressid", "tisa_pricefurnishstandart", "tisa_pricefurnishdesign", "tisa_platformnumber", "tisa_quantity" });

                                   Entity tisa_article = service.Retrieve(entity.LogicalName, entity.Id, attributes);

                                   if (tisa_article != null)

                                   {

                                       tracingService.Trace("tisa_article not null");

                                       Guid tisa_addressid = tisa_article.GetAttributeValue<EntityReference>("tisa_addressid") != null ? tisa_article.GetAttributeValue<EntityReference>("tisa_addressid").Id : Guid.Empty;

                                       if (tisa_article.Contains("tisa_platformnumber") && tisa_addressid != Guid.Empty)

                                       {

                                           tracingService.Trace("fields ok");

                                           //BE SURE OF THE VAR TYPE !!!

                                           // i think tisa_isfurnishprice is a boolean, no ?

                                           // i think

                                           string fetchxml = @"

                                                       <fetch distinct='false' mapping='logical' output-format='xml-platform' version='1.0'>

                                                           <entity name='tisa_costfurnishvariation'>

                                                                   <attribute name='tisa_costfurnishvariationid'/>

                                                                   <attribute name='tisa_isfurnishprice" + tisa_article.GetAttributeValue<Decimal>("tisa_platformnumber") + @"'/>

                                                                   <attribute name='tisa_tisa_platformnumber" + tisa_article.GetAttributeValue<Decimal>("tisa_platformnumber") + @"'/>

                                                                   <attribute name='tisa_mainfurnish'/>

                                                                   <attribute name='tisa_addressid'/>

                                                               <order descending='false' attribute='tisa_addressid'/>

                                                               <filter type='and'>

                                                                   <condition attribute='tisa_addressid' value='" + tisa_addressid + @"' operator='eq'/>

                                                               </filter>

                                                           </entity>

                                                       </fetch>";

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

                                           if (result != null && result.Entities.Count > 0)

                                           {

                                               tracingService.Trace("result >0");

                                               foreach (var c in result.Entities)

                                               {

                                                   if (c.Contains("tisa_mainfurnish"))

                                                   {

                                                       int value = 0;

                                                       if ((OptionSetValue)c["tisa_mainfurnish"] != null)

                                                           value = ((OptionSetValue)c["tisa_mainfurnish"]).Value;

                                                       tracingService.Trace("Value = " + value);

                                                       // You have to test if all the fields used below are ok (X.contains)

                                                       if (value == 1)

                                                       {

                                                           entity["tisa_pricefurnishstandart"] = (Convert.ToDecimal(c.GetAttributeValue<Decimal>("tisa_isfurnishprice") + c.GetAttributeValue<Decimal>("tisa_platformnumber")) * (Convert.ToDecimal(tisa_article.GetAttributeValue<Decimal>("tisa_quantity"))) + Convert.ToDecimal(entity.GetAttributeValue<Money>("tisa_price").Value)); ;

                                                           service.Update(entity);

                                                       }

                                                       else if (value == 2)

                                                       {

                                                           entity["tisa_pricefurnishdesign"] = (Convert.ToDecimal(c.GetAttributeValue<Decimal>("tisa_isfurnishprice") + tisa_article.GetAttributeValue<Decimal>("tisa_platformnumber")) * (Convert.ToDecimal(tisa_article.GetAttributeValue<Decimal>("tisa_quantity"))) + Convert.ToDecimal(entity.GetAttributeValue<Money>("tisa_price").Value));

                                                           service.Update(entity);

                                                       }

                                                   }

                                                   else

                                                       throw new InvalidPluginExecutionException("Field not present");

                                               }

                                           }

                                       }

                                       else

                                           throw new InvalidPluginExecutionException("platnumber and guid not valid");

                                   }

                                   else

                                       throw new InvalidPluginExecutionException("tisa article is null");

                               }

                           }

                       }

                   }

                   else

                       throw new InvalidPluginExecutionException("Target Entity is null");

               }

               catch (Exception ex)

               {

                   //always use InvalidPluginExecutionException to throw exception

                   throw new InvalidPluginExecutionException("Erreur sur on PostTisa_ArticleUpdateFurnishSum : " + ex.Message);

               }

           }

  • Verified answer
    AllanDeCastro Profile Picture
    156 on at

    Hey !

    Have a look on this (I just modified your code during my coffee break so it's really not perfect but will help you ) :

           

    protected void ExecutePostTisa_ArticleUpdateFurnishSum(LocalPluginContext localContext)
    
           {
    
               IPluginExecutionContext context = localContext.PluginExecutionContext;
    
               IOrganizationService service = localContext.OrganizationService;
    
               //Create the tracingService
    
               ITracingService tracingService = (ITracingService)ServiceProvider.GetService(typeof(ITracingService));
    
               // now you can use tracingService.Trace("MESSAGE");
    
               //add a try catch !!
    
               try
    
               {
    
                   if (localContext == null)
    
                   {
    
                       throw new InvalidPluginExecutionException("LocalContext is null");
    
                   }
    
                   if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
    
                   {
    
                       // Obtain the target entity from the input parmameters.
    
                       Entity entity = (Entity)context.InputParameters["Target"];
    
                       if (entity.LogicalName == "tisa_article")
    
                       {
    
                           if (context.MessageName.ToUpper() == "UPDATE")
    
                           {
    
                               if (entity.Contains("tisa_price"))
    
                               {
    
                                   tracingService.Trace("tisa_price is ok");
    
                                   Money pricewoFurnish = entity.GetAttributeValue<Money>("tisa_price");
    
                                   ColumnSet attributes = new ColumnSet(new string[] { "tisa_code", "tisa_addressid", "tisa_pricefurnishstandart", "tisa_pricefurnishdesign", "tisa_platformnumber", "tisa_quantity" });
    
                                   Entity tisa_article = service.Retrieve(entity.LogicalName, entity.Id, attributes);
    
                                   if (tisa_article != null)
    
                                   {
    
                                       tracingService.Trace("tisa_article not null");
    
                                       Guid tisa_addressid = tisa_article.GetAttributeValue<EntityReference>("tisa_addressid") != null ? tisa_article.GetAttributeValue<EntityReference>("tisa_addressid").Id : Guid.Empty;
    
                                       if (tisa_article.Contains("tisa_platformnumber") && tisa_addressid != Guid.Empty)
    
                                       {
    
                                           tracingService.Trace("fields ok");
    
                                           //BE SURE OF THE VAR TYPE !!!
    
                                           // i think tisa_isfurnishprice is a boolean, no ?
    
                                           // i think
    
                                           string fetchxml = @"
    
                                                       <fetch distinct='false' mapping='logical' output-format='xml-platform' version='1.0'>
    
                                                           <entity name='tisa_costfurnishvariation'>
    
                                                                   <attribute name='tisa_costfurnishvariationid'/>
    
                                                                   <attribute name='tisa_isfurnishprice" + tisa_article.GetAttributeValue<Decimal>("tisa_platformnumber") + @"'/>
    
                                                                   <attribute name='tisa_tisa_platformnumber" + tisa_article.GetAttributeValue<Decimal>("tisa_platformnumber") + @"'/>
    
                                                                   <attribute name='tisa_mainfurnish'/>
    
                                                                   <attribute name='tisa_addressid'/>
    
                                                               <order descending='false' attribute='tisa_addressid'/>
    
                                                               <filter type='and'>
    
                                                                   <condition attribute='tisa_addressid' value='" + tisa_addressid + @"' operator='eq'/>
    
                                                               </filter>
    
                                                           </entity>
    
                                                       </fetch>";
    
                                           EntityCollection result = service.RetrieveMultiple(new FetchExpression(fetchxml));
    
                                           if (result != null && result.Entities.Count > 0)
    
                                           {
    
                                               tracingService.Trace("result >0");
    
                                               foreach (var c in result.Entities)
    
                                               {
    
                                                   if (c.Contains("tisa_mainfurnish"))
    
                                                   {
    
                                                       int value = 0;
    
                                                       if ((OptionSetValue)c["tisa_mainfurnish"] != null)
    
                                                           value = ((OptionSetValue)c["tisa_mainfurnish"]).Value;
    
                                                       tracingService.Trace("Value = " + value);
    
                                                       // You have to test if all the fields used below are ok (X.contains)
    
                                                       if (value == 1)
    
                                                       {
    
                                                           entity["tisa_pricefurnishstandart"] = (Convert.ToDecimal(c.GetAttributeValue<Decimal>("tisa_isfurnishprice") + c.GetAttributeValue<Decimal>("tisa_platformnumber")) * (Convert.ToDecimal(tisa_article.GetAttributeValue<Decimal>("tisa_quantity"))) + Convert.ToDecimal(entity.GetAttributeValue<Money>("tisa_price").Value)); ;
    
                                                           service.Update(entity);
    
                                                       }
    
                                                       else if (value == 2)
    
                                                       {
    
                                                           entity["tisa_pricefurnishdesign"] = (Convert.ToDecimal(c.GetAttributeValue<Decimal>("tisa_isfurnishprice") + tisa_article.GetAttributeValue<Decimal>("tisa_platformnumber")) * (Convert.ToDecimal(tisa_article.GetAttributeValue<Decimal>("tisa_quantity"))) + Convert.ToDecimal(entity.GetAttributeValue<Money>("tisa_price").Value));
    
                                                           service.Update(entity);
    
                                                       }
    
                                                   }
    
                                                   else
    
                                                       throw new InvalidPluginExecutionException("Field not present");
    
                                               }
    
                                           }
    
                                       }
    
                                       else
    
                                           throw new InvalidPluginExecutionException("platnumber and guid not valid");
    
                                   }
    
                                   else
    
                                       throw new InvalidPluginExecutionException("tisa article is null");
    
                               }
    
                           }
    
                       }
    
                   }
    
                   else
    
                       throw new InvalidPluginExecutionException("Target Entity is null");
    
               }
    
               catch (Exception ex)
    
               {
    
                   //always use InvalidPluginExecutionException to throw exception
    
                   throw new InvalidPluginExecutionException("Erreur sur on PostTisa_ArticleUpdateFurnishSum : " + ex.Message);
    
               }
    
           }
  • betlejuice Profile Picture
    2,139 on at

    AllanDeCastro, thank you for your help. I put your code and i'm having an error. Can you please say me where i need to declare serviceProvider?

    3731._21043D0438043C043E043A04_.JPG

  • betlejuice Profile Picture
    2,139 on at

    Allan de Castro, i have implemented thew code. Now, i'm tracing the error. My error is below. I will try to resolve the issue. Thank you again

    Unhandled Exception: System.ServiceModel.FaultException`1[[Microsoft.Xrm.Sdk.OrganizationServiceFault, Microsoft.Xrm.Sdk, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]: Erreur sur on PostTisa_ArticleUpdateFurnishSum : Specified cast is not valid.Detail:

    <OrganizationServiceFault xmlns:i="www.w3.org/.../XMLSchema-instance&quot; xmlns="schemas.microsoft.com/.../Contracts&quot;>

     <ErrorCode>-2147220891</ErrorCode>

     <ErrorDetails xmlns:d2p1="schemas.datacontract.org/.../System.Collections.Generic&quot;>

       <KeyValuePairOfstringanyType>

         <d2p1:key>OperationStatus</d2p1:key>

         <d2p1:value xmlns:d4p1="www.w3.org/.../XMLSchema&quot; i:type="d4p1:string">0</d2p1:value>

       </KeyValuePairOfstringanyType>

       <KeyValuePairOfstringanyType>

         <d2p1:key>SubErrorCode</d2p1:key>

         <d2p1:value xmlns:d4p1="www.w3.org/.../XMLSchema&quot; i:type="d4p1:string">-2146233088</d2p1:value>

       </KeyValuePairOfstringanyType>

     </ErrorDetails>

     <Message>Erreur sur on PostTisa_ArticleUpdateFurnishSum : Specified cast is not valid.</Message>

     <Timestamp>2018-12-12T16:16:05.168356Z</Timestamp>

     <InnerFault i:nil="true" />

     <TraceText>

    [Mangazeya_Plugins: Mangazeya_Plugins.PostArticleUpdateFurnishSum]

    [ec2ee133-29fe-e811-9437-00155d469803: Mangazeya_Plugins.PostArticleUpdateFurnishSum: Update of tisa_article]

    tisa_price is ok

    tisa_article not null

    fields ok

    </TraceText>

    </OrganizationServiceFault>

  • AllanDeCastro Profile Picture
    156 on at

    My bad :(

    Try to replace the whole line with :

               ITracingService tracingService = localContext.tracingService;

    Or directly to use : localContext.Trace("your trace message"); instead of my tracingService.Trace("");

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…

Neeraj Kumar – Community Spotlight

We are honored to recognize Neeraj Kumar as our Community Spotlight honoree for…

Leaderboard > 🔒一 Microsoft Dynamics CRM (Archived)

#1
SA-08121319-0 Profile Picture

SA-08121319-0 4

#1
Calum MacFarlane Profile Picture

Calum MacFarlane 4

#3
Alex Fun Wei Jie Profile Picture

Alex Fun Wei Jie 2

Last 30 days Overall leaderboard

Featured topics

Product updates

Dynamics 365 release plans