Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Microsoft Dynamics CRM (Archived)

Error during calling custom Action from API

(0) ShareShare
ReportReport
Posted on by

I get below error when i call custom action from API

{
"error": {
"code": "0x80040265",
"message": "Object reference not set to an instance of an object.",
"innererror": {
"message": "Object reference not set to an instance of an object.",
"type": "System.ServiceModel.FaultException`1[[Microsoft.Xrm.Sdk.OrganizationServiceFault, Microsoft.Xrm.Sdk, Version=9.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]",
"stacktrace": " at Microsoft.Crm.Extensibility.OrganizationSdkServiceInternal.Execute(OrganizationRequest request, InvocationContext invocationContext, CallerOriginToken callerOriginToken, WebServiceType serviceType, Boolean checkAdminMode, ExecutionContext executionContext, Dictionary`2 optionalParameters)\r\n at Microsoft.Crm.Extensibility.OData.CrmODataExecutionContext.Execute(OrganizationRequest request, ExecutionContext executionContext)\r\n at Microsoft.Crm.Extensibility.OData.CrmODataServiceDataProvider.ExecuteOperation(CrmODataExecutionContext context, EdmOperation edmOperation, Dictionary`2 parameters, Dictionary`2 boundParameters)\r\n at Microsoft.Crm.Extensibility.OData.ActionController.ProcessOperationRequest(String operationName, Dictionary`2 operationParameters, EntityReference entityReference, String boundEntityName, String boundEntityType)\r\n at Microsoft.Crm.Extensibility.OData.ActionController.<>c__DisplayClass9_0.<PostUnboundAction>b__0()\r\n at Microsoft.PowerApps.CoreFramework.ActivityLoggerExtensions.Execute[TResult](ILogger logger, EventId eventId, ActivityType activityType, Func`1 func, IEnumerable`1 additionalCustomProperties)\r\n at Microsoft.Xrm.Telemetry.XrmTelemetryExtensions.Execute[TResult](ILogger logger, XrmTelemetryActivityType activityType, Func`1 func)\r\n at Microsoft.Crm.Extensibility.OData.ActionController.PostUnboundAction(String operationName, ODataUntypedActionParameters parameters)\r\n at lambda_method(Closure , Object , Object[] )\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass10.<GetExecutor>b__9(Object instance, Object[] methodParameters)\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()"
}
}
}

Below is my code

public class CustomAction : CodeActivity
    {

        [Input("Entity Metadata Id")]
        public InArgument<string> MetadataId { get; set; }

        [Output("Entity Details")]
        public OutArgument<string> EntityInfo { get; set; }


        protected override void Execute(CodeActivityContext executionContext)
        {

             //Retrieve the id
            string accountId = this.MetadataId.Get(executionContext);

            //Create the tracing service
            ITracingService tracingService = executionContext.GetExtension<ITracingService>();

            //Create the context
            IWorkflowContext workflowContext = executionContext.GetExtension<IWorkflowContext>();
            IOrganizationServiceFactory serviceFactory = executionContext.GetExtension<IOrganizationServiceFactory>();
            IOrganizationService orgService = serviceFactory.CreateOrganizationService(workflowContext.UserId);
            var  output= new EntityInfo();

             //Get the Entity Metadata from the entityName
            var retrieveEntityRequest = new RetrieveEntityRequest
            {
                EntityFilters = EntityFilters.All,
                MetadataId = Guid.Parse(MetadataId.Get(context))
            };

            var entityResponse = (RetrieveEntityResponse)orgService.Execute(retrieveEntityRequest);
            var entityMetadata = entityResponse.EntityMetadata;
            var entityName = entityMetadata.LogicalName;
            output.EntityName = entityName;
            output.PrimaryIdAttributeName = entityMetadata.PrimaryIdAttribute;

             //Get the column name to be used to query the count of the entity.
            var columnName = string.IsNullOrEmpty(entityMetadata.PrimaryIdAttribute)
                ? entityMetadata.Attributes.FirstOrDefault()?.LogicalName
                : entityMetadata.PrimaryIdAttribute;

             //get the column Count
            output.ColumnCount = entityMetadata.Attributes.ToList().Count;


             //fetchXml to retrieve count of entity
            var entityCountXml =
                $"<fetch distinct='false' mapping='logical' aggregate='true'>" +
                $"<entity name='{entityName}'>" +
                $"<attribute name='{columnName}' alias='rowCount' aggregate='count'/>" +
                $"</entity>" +
                $"</fetch>";

             // Retrieving cases using fetchXml  
            var rowCount = 0;
            var result = orgService.RetrieveMultiple(new FetchExpression(entityCountXml));
            foreach (var c in result.Entities)
            {
                rowCount = (Int32)((AliasedValue)c["rowCount"]).Value;
            }

            output.RowCount = rowCount;
            var customColumns = entityMetadata.Attributes.Count(s => s.IsCustomAttribute != null && (bool) s.IsCustomAttribute);
            var systemColumns = entityMetadata.Attributes.Count(s => s.IsCustomAttribute != null && !(bool)s.IsCustomAttribute);

        }
    }


*This post is locked for comments

  • Suggested answer
    Community Member Profile Picture
    on at
    RE: Error during calling custom Action from API

    Faced the exact same error while calling custom action from Web Resource through a Process. Its late for reply but I struggled for sometime before solving it. Therefore adding the solution for others to benefit

    We should make sure that our custom action is added as the first step in the Process and subsequent steps (to assign value to variables) has that first step selected in Look for field as shown below

    pastedimage1593006456830v1.png
  • Suggested answer
    Ivan Ficko Profile Picture
    1,380 on at
    RE: Error during calling custom Action from API

    Drop some tracingService.Trace() every now and then and see which is the last message logged.

  • David Jennaway Profile Picture
    14,065 on at
    RE: Error during calling custom Action from API

    I can't see anything immediately wrong with the code, so I'd suggest putting in some tracing to see how far the code gets.

    Are you sure the MetadataId InputParameter is correct, and is there a reason why you use that rather than the LogicalName ? The LogicalName would seem less error prone, and deployment independent

  • Suggested answer
    Kokulan Profile Picture
    18,054 on at
    RE: Error during calling custom Action from API

    Hi

    I would first call this action in a Wokflow or Dialog and see if works as expected. Once you confirmed that your CWA works, you can isolate where the issue lies.

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

🌸 Community Spring Festival 2025 Challenge Winners! 🌸

Congratulations to all our community participants!

Adis Hodzic – Community Spotlight

We are honored to recognize Adis Hodzic as our May 2025 Community…

Kudos to the April Top 10 Community Stars!

Thanks for all your good work in the Community!

Leaderboard > Microsoft Dynamics CRM (Archived)

#1
Mohamed Amine Mahmoudi Profile Picture

Mohamed Amine Mahmoudi 83 Super User 2025 Season 1

#2
Community Member Profile Picture

Community Member 52

#3
dkrishna Profile Picture

dkrishna 6

Overall leaderboard

Featured topics

Product updates

Dynamics 365 release plans