Skip to main content

Notifications

Announcements

No record found.

Microsoft Dynamics CRM (Archived)

Attempt by method x to access method y failed.

Posted on by 450

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

  • Albert_ Profile Picture
    Albert_ 450 on at
    RE: Attempt by method x to access method y failed.

    I just did that, Could you take a look at that?

  • Verified answer
    Albert_ Profile Picture
    Albert_ 450 on at
    RE: Attempt by method x to access method y failed.

    Finally I did that in this way,

    If you decompile All dependency .dll files into ILSPy and then Decompile the target project,It will decompile in a right way !

    So you should de-compile dependency .dll files first in the ILSPy and then decompile the target .dll file.

    Thanks to all

  • Suggested answer
    Temmy Wahyu Raharjo Profile Picture
    Temmy Wahyu Raharjo 2,914 on at
    RE: Attempt by method x to access method y failed.

    If you want to answer, better use reply so I will get notification to know that you are asking question to me.

    Actually I curious when you get salesOrderReceiptStep.TotalDetailAmount.Value this value. Seems like in the SalesOrderReceiptStepRepository you use early bound entity type. I also got this error when moving from on premise to 365. To solve it, actually we do the same with you.

    Put

    [assembly: SecurityTransparent()]

    [assembly: AllowPartiallyTrustedCallersAttribute]

    into our assembly.cs

    Then for  System.MethodAccessException:

    Attempt by method 'Microsoft.Xrm.Sdk.Entity.ToEntity<System.__Canon>()' to access method 'StepType..ctor()' failed. try to do for example:

    service.Update(entity.ToEntity<Canon>()) to become service.Update(entity.ToEntity<Entity>()).

    Because you choose Sandbox as your deployment type, it has different security level and I believe you've got serialization problem on it.

    Also usually if you change from None to database you need to merge all the dll that you used, include your entities dll. Can you show me your project reference?

  • RaviKashyap Profile Picture
    RaviKashyap 55,410 on at
    RE: Attempt by method x to access method y failed.

    Great Spirit Mate. All the best :)

  • Albert_ Profile Picture
    Albert_ 450 on at
    RE: Attempt by method x to access method y failed.

    Thank you Bro, I will let you know what was the problem.

  • RaviKashyap Profile Picture
    RaviKashyap 55,410 on at
    RE: Attempt by method x to access method y failed.

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

  • Albert_ Profile Picture
    Albert_ 450 on at
    RE: Attempt by method x to access method y failed.

    I Edited the question

    I do not thing the code has problem.

  • Suggested answer
    RaviKashyap Profile Picture
    RaviKashyap 55,410 on at
    RE: Attempt by method x to access method y failed.

    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
    Albert_ 450 on at
    RE: Attempt by method x to access method y failed.

    I also Edit the question.

  • Albert_ Profile Picture
    Albert_ 450 on at
    RE: Attempt by method x to access method y failed.

    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
                }));
            }
        }

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

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans