locked
Account Id ="" Doesn not exist with error code:-2147220970 RRS feed

  • Question

  • Hi ,

    My Plugin is not working properly.I regsitered the plugin through plugin registration tool.

    Basically i am doing check on account number in account entity

    if account number is null

    then creating a task

    Below is the Code which i have written:

    ////////////////////////////////////////////////////////////////

    // <copyright file="Plugin.cs" company="Microsoft">
    // Copyright (c) 2012 All Rights Reserved
    // </copyright>
    // <author>Microsoft</author>
    // <date>9/29/2012 1:24:40 PM</date>
    // <summary>Implements the Plugin Workflow Activity.</summary>
    // <auto-generated>
    //     This code was generated by a tool.
    //     Runtime Version:4.0.30319.1
    // </auto-generated>
    namespace CRMPlugins1
    {
        using System;
        using System.Collections.ObjectModel;
        using System.Globalization;
        using System.Linq;
        using System.ServiceModel;
        using Microsoft.Xrm.Sdk;

        /// <summary>
        /// Base class for all Plugins.
        /// </summary>   
        public class Plugin : IPlugin
        {
           /* protected class LocalPluginContext
            {
                internal IServiceProvider ServiceProvider
                {
                    get;

                    private set;
                }

                internal IOrganizationService OrganizationService
                {
                    get;

                    private set;
                }

                internal IPluginExecutionContext PluginExecutionContext
                {
                    get;

                    private set;
                }

                internal ITracingService TracingService
                {
                    get;

                    private set;
                }

                private LocalPluginContext()
                {
                }

                internal LocalPluginContext(IServiceProvider serviceProvider)
                {
                    if (serviceProvider == null)
                    {
                        throw new ArgumentNullException("serviceProvider");
                    }

                    // Obtain the execution context service from the service provider.
                    this.PluginExecutionContext = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

                    // Obtain the tracing service from the service provider.
                    this.TracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));

                    // Obtain the Organization Service factory service from the service provider
                    IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));

                    // Use the factory to generate the Organization Service.
                    this.OrganizationService = factory.CreateOrganizationService(this.PluginExecutionContext.UserId);
                }

                internal void Trace(string message)
                {
                    if (string.IsNullOrWhiteSpace(message) || this.TracingService == null)
                    {
                        return;
                    }

                    if (this.PluginExecutionContext == null)
                    {
                        this.TracingService.Trace(message);
                    }
                    else
                    {
                        this.TracingService.Trace(
                            "{0}, Correlation Id: {1}, Initiating User: {2}",
                            message,
                            this.PluginExecutionContext.CorrelationId,
                            this.PluginExecutionContext.InitiatingUserId);
                    }
                }
            }

            private Collection<Tuple<int, string, string, Action<LocalPluginContext>>> registeredEvents;

            /// <summary>
            /// Gets the List of events that the plug-in should fire for. Each List
            /// Item is a <see cref="System.Tuple"/> containing the Pipeline Stage, Message and (optionally) the Primary Entity.
            /// In addition, the fourth parameter provide the delegate to invoke on a matching registration.
            /// </summary>
            protected Collection<Tuple<int, string, string, Action<LocalPluginContext>>> RegisteredEvents
            {
                get
                {
                    if (this.registeredEvents == null)
                    {
                        this.registeredEvents = new Collection<Tuple<int, string, string, Action<LocalPluginContext>>>();
                    }

                    return this.registeredEvents;
                }
            }

            /// <summary>
            /// Gets or sets the name of the child class.
            /// </summary>
            /// <value>The name of the child class.</value>
            protected string ChildClassName
            {
                get;

                private set;
            }

            /// <summary>
            /// Initializes a new instance of the <see cref="Plugin"/> class.
            /// </summary>
            /// <param name="childClassName">The <see cref=" cred="Type"/> of the derived class.</param>
            internal Plugin(Type childClassName)
            {
                this.ChildClassName = childClassName.ToString();
            }

            /// <summary>
            /// Executes the plug-in.
            /// </summary>
            /// <param name="serviceProvider">The service provider.</param>
            /// <remarks>
            /// For improved performance, Microsoft Dynamics CRM caches plug-in instances.
            /// The plug-in's Execute method should be written to be stateless as the constructor
            /// is not called for every invocation of the plug-in. Also, multiple system threads
            /// could execute the plug-in at the same time. All per invocation state information
            /// is stored in the context. This means that you should not use global variables in plug-ins.
            /// </remarks>*/
            public void Execute(IServiceProvider serviceProvider)
            {
                if (serviceProvider == null)
                {
                    throw new ArgumentNullException("serviceProvider");
                }

                // Construct the Local plug-in context.
                //LocalPluginContext localcontext = new LocalPluginContext(serviceProvider);

                // localcontext.Trace(string.Format(CultureInfo.InvariantCulture, "Entered {0}.Execute()", this.ChildClassName));

     

                IPluginExecutionContext context = (IPluginExecutionContext)
                serviceProvider.GetService(typeof(IPluginExecutionContext));
                if (context.InputParameters.Contains("Target") &&
                        context.InputParameters["Target"] is Entity)
                {
                    // Obtain the target entity from the input parmameters.
                    Entity entity = (Entity)context.InputParameters["Target"];
                    try
                    {
                        //check if the account number exist

                        if (entity.Attributes.Contains("accountnumber") == false)
                        {

                            //create a task
                            Entity task = new Entity("task");
                            task["subject"] = "Account number is missing";
                            task["regardingobjectid"] = new EntityReference("account", new Guid(context.OutputParameters["id"].ToString()));

                            //adding attribute using the add function
                            // task["description"] = "Account number is missng for the following account. Please enter the account number";
                            task.Attributes.Add("description", "Account number is missng for the following account. Please enter the account number");

     

                            // Obtain the organization service reference.
                            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                            IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);


                            // Create the task in Microsoft Dynamics CRM.
                            service.Create(task);


                        }
                    }


             /*   // Iterate over all of the expected registered events to ensure that the plugin
                // has been invoked by an expected event
                // For any given plug-in event at an instance in time, we would expect at most 1 result to match.
                Action<LocalPluginContext> entityAction =
                    (from a in this.RegisteredEvents
                     where (
                     a.Item1 == localcontext.PluginExecutionContext.Stage &&
                     a.Item2 == localcontext.PluginExecutionContext.MessageName &&
                     (string.IsNullOrWhiteSpace(a.Item3) ? true : a.Item3 == localcontext.PluginExecutionContext.PrimaryEntityName)
                     )
                     select a.Item4).FirstOrDefault();

                if (entityAction != null)
                {
                    localcontext.Trace(string.Format(
                        CultureInfo.InvariantCulture,
                        "{0} is firing for Entity: {1}, Message: {2}",
                        this.ChildClassName,
                        localcontext.PluginExecutionContext.PrimaryEntityName,
                        localcontext.PluginExecutionContext.MessageName));

                    entityAction.Invoke(localcontext);

                    // now exit - if the derived plug-in has incorrectly registered overlapping event registrations,
                    // guard against multiple executions.
                    return;
                }*/

                    catch (FaultException ex)
                    {
                        throw new InvalidPluginExecutionException("An error occurred in the plug-in.", ex);
                    }
                    finally
                    {
                        //localcontext.Trace(string.Format(CultureInfo.InvariantCulture, "Exiting {0}.Execute()", this.ChildClassName));
                    }
                }
            }
        }
    }

    after debugging this plugin, i am facing this below error:

    ////////////////////////////////////

    Unhandled Exception: System.ServiceModel.FaultException`1[[Microsoft.Xrm.Sdk.OrganizationServiceFault, Microsoft.Xrm.Sdk, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]: Account With Id = d557ef8b-5011-e211-9133-984be17313ab Does Not Exist
    Detail: <OrganizationServiceFault xmlns="" xmlns:i="XXXXX">
      <ErrorCode>-2147220970</ErrorCode>
      <ErrorDetails xmlns:a="">
        <KeyValuePairOfstringanyType>
          <a:key>CallStack</a:key>
          <a:value i:type="b:string" xmlns:b="">   at PluginProfiler.Library.ProfilerContextAppDomainOrganizationService.DeserializeResponse(Tuple`2 serializedValue)
       at PluginProfiler.Library.ProfilerContextAppDomainOrganizationService.Create(Entity entity)
       at CRMPlugins1.Plugin.Execute(IServiceProvider serviceProvider)</a:value>
        </KeyValuePairOfstringanyType>
      </ErrorDetails>
      <Message>Account With Id = d557ef8b-5011-e211-9133-984be17313ab Does Not Exist</Message>
      <Timestamp>2012-10-08T14:06:37.8850575Z</Timestamp>
      <InnerFault>
        <ErrorCode>0</ErrorCode>
        <ErrorDetails xmlns:a="" />
        <Message i:nil="true" />
        <Timestamp>0001-01-01T00:00:00</Timestamp>
        <InnerFault i:nil="true" />
        <TraceText i:nil="true" />

     

    ///////////////////////////////////////////////////////////////

     

    I registered this plugin in create and account as primary entity, and post operation with syncronous mode

    Thanks in advance

    Sv Rupesh

    Tuesday, October 9, 2012 5:29 AM

Answers

  • Hi andrii,

    Can you please explain me why Asynchrousnous Mode?

    With Regards,

    Sv,Rupesh


    Because of new transactional engine that appeared in CRM 2011. Have you tried Async Mode?

    Freelance Developer for Dynamics CRM 4.0/2011

    Tuesday, October 9, 2012 6:44 AM
    Moderator
  • Hi andrii,

    I run this plugin in asyncronous mode.Know the plugin is working fine.

    Can you let me know why this is not happening if i run this in synchronous mode?.

    With Regards,
    Sv,Rupesh 


    This works in Async Mode because Asynchronous Operation is executed outside the transaction, transaction is already committed and record is inside DB.

    Freelance Developer for Dynamics CRM 4.0/2011

    • Marked as answer by Siddhu336 Thursday, March 21, 2013 2:21 PM
    Tuesday, October 9, 2012 7:09 AM
    Moderator

All replies

  • Hi,

    did you add your plugin to the post-create or the pre-create message? I think you registered it to the pre-create message. Then you are trying to create a task with a reference to the account that is about to be created. But since the account hasn't been created yet, there is no account with the above Guid.

    So what you have to do is register your plugin to the post-create message. Then you can read the account Id using 

    var accountId = context.PrimaryEntityId;

    Greetings,

    Pavlos


    Please mark this reply as an answer and vote it as helpful if it helps you find a resolution to your problem.


    Tuesday, October 9, 2012 6:14 AM
  • Hello,

    You should switch your plugin in AsyncMode and everything will work like a charm.


    Freelance Developer for Dynamics CRM 4.0/2011

    Tuesday, October 9, 2012 6:32 AM
    Moderator
  • Hi pavlos,

    Thanks for the reply :)

    I registered plugin using plugin registration tool. I registered the step as follows:

    1) Message : Create

    2) Primary Entity : account

    3)Secondary Entity: none

    4)EventHandler:(Plugin) CRMPlugins1.Plugin

    5) Name: CRMPlugins1.Plugin: Create of account

    6)Run in User's Context: Calling User

    7)Execution Order: 1

    8)Event Pipe line Stage

        - Post Operation(CRM 2011 Only)

    9)Execution Mode

       - Synchronous

    10)Deployment

         -Server

    These are steps i followed to register this plugin.Please guide me if there is any wrong this registration?.

    With Regards,
    Sv,Rupesh

    Tuesday, October 9, 2012 6:38 AM
  • Hi andrii,

    Can you please explain me why Asynchrousnous Mode?

    With Regards,

    Sv,Rupesh

    Tuesday, October 9, 2012 6:40 AM
  • Hi andrii,

    Can you please explain me why Asynchrousnous Mode?

    With Regards,

    Sv,Rupesh


    Because of new transactional engine that appeared in CRM 2011. Have you tried Async Mode?

    Freelance Developer for Dynamics CRM 4.0/2011

    Tuesday, October 9, 2012 6:44 AM
    Moderator
  • Try replace:

     task["regardingobjectid"] = new EntityReference("account", new Guid(context.OutputParameters["id"].ToString()));

    with:

    task["regardingobjectid"] = new EntityReference("account", context.PrimaryEntityId);

    -Paul

    Tuesday, October 9, 2012 6:47 AM
  • Hi andrii,

    I run this plugin in asyncronous mode.Know the plugin is working fine.

    Can you let me know why this is not happening if i run this in synchronous mode?.

    With Regards,
    Sv,Rupesh 

    Tuesday, October 9, 2012 6:56 AM
  • Hi andrii,

    I run this plugin in asyncronous mode.Know the plugin is working fine.

    Can you let me know why this is not happening if i run this in synchronous mode?.

    With Regards,
    Sv,Rupesh 


    This works in Async Mode because Asynchronous Operation is executed outside the transaction, transaction is already committed and record is inside DB.

    Freelance Developer for Dynamics CRM 4.0/2011

    • Marked as answer by Siddhu336 Thursday, March 21, 2013 2:21 PM
    Tuesday, October 9, 2012 7:09 AM
    Moderator
  • Thanks Andrii I got know the difference:)

    Thanks a lot for helping me to sort out this problem :)

    • Marked as answer by Siddhu336 Thursday, March 21, 2013 2:20 PM
    • Unmarked as answer by Siddhu336 Thursday, March 21, 2013 2:21 PM
    Wednesday, October 10, 2012 3:59 AM