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)

Attempt by method x to access method y failed.

(0) ShareShare
ReportReport
Posted on by 458

Hi there all
I have a class library And wanna import that.
The CRM has some other plugins that I do not know about them.
It is almost a mirror of another .dll file that I wanna insert.
Anyways,  In customization of CRM, I have disabled All steps of previous Plugin ( the main one that I have created a mirror from that) insert new Plugin via Plugin Registration.
I build my class library,  VS  makes a .dll file in /bin/Debug folder of project.
I select insert that .dll as Register new assembly.
I chose Sandbox as Isolation mode.
And then database as location ( Not disk or GAC ).
It successfully updated my selected Plugin.
After that, I insert my steps( Just like the mirror ).
But in one the create methods, I get this Error :

Unhandled Exception: System.ServiceModel.FaultException`1[[Microsoft.Xrm.Sdk.OrganizationServiceFault,
 Microsoft.Xrm.Sdk, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]: 
Unexpected exception from plug-in (Execute): OrderReceiptStepPlugin: System.MethodAccessException:
 Attempt by method 'Microsoft.Xrm.Sdk.Entity.ToEntity<System.__Canon>()' to access method 'StepType..ctor()' failed.Detail: 
<OrganizationServiceFault xmlns:i="www.w3.org/.../XMLSchema-instance" 
xmlns="schemas.microsoft.com/.../Contracts">
  <ErrorCode>-2147220956</ErrorCode>
  <ErrorDetails xmlns:d2p1="schemas.datacontract.org/.../System.Collections.Generic" />
  <Message>Unexpected exception from plug-in (Execute): OrderReceiptStepPlugin: System.MethodAccessException: 
Attempt by method 'Microsoft.Xrm.Sdk.Entity.ToEntity&lt;System.__Canon&gt;()' to access method 'StepType..ctor()' failed.</Message>
  <Timestamp>2018-10-29T10:57:37.4628797Z</Timestamp>
  <InnerFault i:nil="true" />
  <TraceText>

[OrderReceiptStep: OrderReceiptStepPlugin]
[xxxxxx-xxxx-xxxx11-xxx-xxxxxxxxxxxx: OrderReceiptStepPlugin: Create of bmsd_orderreceiptstep]

Entered .Execute(), Correlation Id: 47c5ddcb-9290-4945-9ac0-fd88925480b1, Initiating User: 5b6b27be-ca0f-e811-bebe-000c2964dd77
 is firing for Entity: bmsd_orderreceiptstep, Message: Create, Correlation Id: 47c5ddcb-9290-4945-9ac0-fd88925480b1, Initiating User: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxx
Exiting .Execute(), Correlation Id: xxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx, Initiating User: xxxxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxx


</TraceText>
</OrganizationServiceFault>

I googled about MethodAccessException Find out that this method occurs because of .Net version 4 and later,
And some code you can add in your Assebmly.cs to avoid this exception, according to this thread.
But in my case no success.

I added the code below to my assembly.cs but no success :

[assembly: SecurityTransparent()]
[assembly: AllowPartiallyTrustedCallersAttribute]



Here is the code that cause the error, It is in pre-Create of custom entity :

    private void OrderReceiptStepPreCreateEventHandler(LocalPluginContext context)
    {
        SalesOrderReceiptStepRepository salesOrderReceiptStepRepository = new SalesOrderReceiptStepRepository(context);
        SalesOrderReceiptStep salesOrderReceiptStep = salesOrderReceiptStepRepository.CreateInstance();
        salesOrderReceiptStep.TotalAmountWithoutTax = new Money(salesOrderReceiptStep.TotalAmountWithoutTax.Value + salesOrderReceiptStep.FreightAmount.Value);
        salesOrderReceiptStep.TotalAmountWithoutTax = new Money(salesOrderReceiptStep.TotalAmountWithoutTax.Value - salesOrderReceiptStep.DiscountAmount.Value);
        switch (salesOrderReceiptStep.ReceiptStepType)
        {
            case ReceiptStepType.TimeOriented:
            case ReceiptStepType.PrePayment:
            case ReceiptStepType.Others:
                salesOrderReceiptStep.TotalAmountWithoutTax = new Money(salesOrderReceiptStep.TotalDetailAmount.Value + salesOrderReceiptStep.FreightAmount.Value - salesOrderReceiptStep.DiscountAmount.Value);
                salesOrderReceiptStep.TotalAmount = new Money(salesOrderReceiptStep.TotalAmountWithoutTax.Value + salesOrderReceiptStep.TotalTax.Value);
                break;
        }
        OrderReceiptStepCalculationPlugin orderReceiptStepCalculationPlugin = new OrderReceiptStepCalculationPlugin();
        orderReceiptStepCalculationPlugin.CreateORderReceiptStep(context, salesOrderReceiptStep);
        if (salesOrderReceiptStep.Contains("bmsd_totallineitemamount") && salesOrderReceiptStep.Contains("bmsd_orderid"))
        {
            EntityReference attributeValue = salesOrderReceiptStep.GetAttributeValue<EntityReference>("bmsd_orderid");
            if (attributeValue != null)
            {
                SalesOrderAdapter salesOrderAdapter = new SalesOrderAdapter();
                OrganizationServiceContext context2 = new OrganizationServiceContext(context.OrganizationService);
                Entity ordersById = salesOrderAdapter.GetOrdersById(context2, attributeValue.Id);
                if (ordersById != null)
                {
                    CalculationHelper calculationHelper = new CalculationHelper();
                    Entity entity = calculationHelper.CalculateOrdersAndReturnEntity(context, ordersById, ordersById);
                    entity.Attributes["statuscode"] = null;
                    entity.Attributes["statecode"] = null;
                    context.OrganizationService.Update(entity);
                }
            }
        }
        if (salesOrderReceiptStep.Contains("bmsd_invoiceid") || salesOrderReceiptStep.Contains("statuscode") || salesOrderReceiptStep.Contains("statecode") || salesOrderReceiptStep.Contains("bmsd_totallineitemamount"))
        {
            EntityReference attributeValue2 = salesOrderReceiptStep.GetAttributeValue<EntityReference>("bmsd_invoiceid");
            if (attributeValue2 != null)
            {
                OrganizationServiceContext context2 = new OrganizationServiceContext(context.OrganizationService);
                OrderReceiptItemAdapter orderReceiptItemAdapter = new OrderReceiptItemAdapter();
                Entity invoiceById = orderReceiptItemAdapter.GetInvoiceById(context2, attributeValue2.Id);
                if (invoiceById != null)
                {
                    CalculationHelper calculationHelper = new CalculationHelper();
                    Entity entity2 = calculationHelper.CalculateInvoiceAndReturnEntity(context, invoiceById, invoiceById);
                    entity2.Attributes["statuscode"] = null;
                    entity2.Attributes["statecode"] = null;
                    context.OrganizationService.Update(entity2);
                }
            }
        }
    }


I know this is not a syntax or logical error in development ( Cause the mirror is working correctly).
What other reasons can make this error?


Also here is the Execute medthod :

    public void Execute(IServiceProvider serviceProvider)
    {
        if (serviceProvider == null)
        {
            throw new ArgumentNullException("serviceProvider");
        }
        LocalPluginContext localcontext = new LocalPluginContext(serviceProvider);
        localcontext.Trace(string.Format(CultureInfo.InvariantCulture, "Entered {0}.Execute()", new object[1]
        {
            ChildClassName
        }));
        try
        {
            Action<LocalPluginContext> action = (from a in RegisteredEvents
                                                 where a.Item1 == localcontext.PluginExecutionContext.Stage && a.Item2 == localcontext.PluginExecutionContext.MessageName &&
                                                 (string.IsNullOrWhiteSpace(a.Item3) || a.Item3 == localcontext.PluginExecutionContext.PrimaryEntityName)
                                                 select a.Item4).FirstOrDefault();
            if (action != null)
            {
                localcontext.Trace(string.Format(CultureInfo.InvariantCulture, "{0} is firing for Entity: {1}, Message: {2}", new object[3]
                {
                    ChildClassName,
                    localcontext.PluginExecutionContext.PrimaryEntityName,
                    localcontext.PluginExecutionContext.MessageName
                }));
                action(localcontext);
            }
        }
        catch (FaultException<OrganizationServiceFault> ex)
        {
            localcontext.Trace(string.Format(CultureInfo.InvariantCulture, "Exception: {0}", new object[1]
            {
                ex.ToString()
            }));
            throw;
        }
        finally
        {
            localcontext.Trace(string.Format(CultureInfo.InvariantCulture, "Exiting {0}.Execute()", new object[1]
            {
                ChildClassName
            }));
        }
    }




*This post is locked for comments

I have the same question (0)
  • Suggested answer
    Temmy Wahyu Raharjo Profile Picture
    2,916 on at

    Hi, you are using Early Bound, do you already merge your dll? I think this one because of u use sandbox mode. Little bit tricky to solve from non sandbox to sandbox mode. You can try to remove all the toEntity<entityType> as generic Entity.

  • Albert_ Profile Picture
    458 on at

    No, I did not merge my own .dll with the real one inside the CRM.

    In real, plugin of the CRM is not in Sandbox, also is in the file( Not database ).

    But mine is in Sandbox and also in DB.

    Whats the point?

  • Albert_ Profile Picture
    458 on at

    Could you explain more?

  • Albert_ Profile Picture
    458 on at

    Any suggestion?

  • RaviKashyap Profile Picture
    55,410 Moderator on at

    Where is the plugin execute method? could you please share the full code?

  • Albert_ Profile Picture
    458 on at

    Here is the Execute method :

        public void Execute(IServiceProvider serviceProvider)
        {
            if (serviceProvider == null)
            {
                throw new ArgumentNullException("serviceProvider");
            }
            LocalPluginContext localcontext = new LocalPluginContext(serviceProvider);
            localcontext.Trace(string.Format(CultureInfo.InvariantCulture, "Entered {0}.Execute()", new object[1]
            {
                ChildClassName
            }));
            try
            {
                Action<LocalPluginContext> action = (from a in RegisteredEvents
                                                     where a.Item1 == localcontext.PluginExecutionContext.Stage && a.Item2 == localcontext.PluginExecutionContext.MessageName &&
                                                     (string.IsNullOrWhiteSpace(a.Item3) || a.Item3 == localcontext.PluginExecutionContext.PrimaryEntityName)
                                                     select a.Item4).FirstOrDefault();
                if (action != null)
                {
                    localcontext.Trace(string.Format(CultureInfo.InvariantCulture, "{0} is firing for Entity: {1}, Message: {2}", new object[3]
                    {
                        ChildClassName,
                        localcontext.PluginExecutionContext.PrimaryEntityName,
                        localcontext.PluginExecutionContext.MessageName
                    }));
                    action(localcontext);
                }
            }
            catch (FaultException<OrganizationServiceFault> ex)
            {
                localcontext.Trace(string.Format(CultureInfo.InvariantCulture, "Exception: {0}", new object[1]
                {
                    ex.ToString()
                }));
                throw;
            }
            finally
            {
                localcontext.Trace(string.Format(CultureInfo.InvariantCulture, "Exiting {0}.Execute()", new object[1]
                {
                    ChildClassName
                }));
            }
        }
  • Albert_ Profile Picture
    458 on at

    I also Edit the question.

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

    Unfortunately I am unable to understand the code :( it is high level :)

    I know when plugin executes, it calls the Execute method, and we write all the business logic under that. But the code you have shared for the execute method is not calling your actual method OrderReceiptStepPreCreateEventHandler. I may be wrong or you may have some other pieces of your code which I am not aware off.

    Do you need it the way it is currently written or you can change it in a simple way, like below-

    ============

    public void Execute(IServiceProvider serviceprovider)

           {

               if (serviceprovider == null)

                   throw new ArgumentNullException("serviceProvider");

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

               IPluginExecutionContext context = (IPluginExecutionContext)serviceprovider.GetService(typeof(IPluginExecutionContext));            

               IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceprovider.GetService(typeof(IOrganizationServiceFactory));

               IOrganizationService service = factory.CreateOrganizationService(context.UserId);

               IOrganizationService adminService = factory.CreateOrganizationService(null);            

               string message = context.MessageName.ToLowerInvariant();

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

               {                

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

                  // Add your business logic here

               }

           }

    ============

    Hope this helps.

  • Albert_ Profile Picture
    458 on at

    I Edited the question

    I do not thing the code has problem.

  • RaviKashyap Profile Picture
    55,410 Moderator on at

    Sorry Albert but I have no idea wof this code. You can try debugging to see if you can find anything.

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