locked
how to main function add to plugin class RRS feed

  • Question

  •  Auto Number Helper Helper class

    PostContactCreate_AutoNumber class

    plugin class

    in autonumber helper class

                

       public static class AutoNumberHelper
        {


           public const string EntityLogicalName = "gortt_autonumbersetup";
           public const string EntityName = "new_autonumberhelper";
           public const string AutoNumberSetupId = "new_gortt_autonumbersetupid";
           public const string EntityType = "new_gortt_entitytype";
           public const string NextNumber = "new_gortt_nextnumber";
           public const string Prefix = "new_gortt_prefix";
           public const string PostFix = "new_gortt_postfix";
           public const string EndingNumber = "new_gortt_endingnumber";
           public const string IncrementNumber = "new_gortt_incrementnumber";
           public const string StartingNumber = "new_gortt_startingnumber";
           public const string NoOfDigit = "new_gortt_noofdigits";
           public const string Format = "new_gortt_suffix";
           public const string Suffix = "new_gortt_suffix";


    public static Entity RetrieveAutoNumberSetting(string entityName, IOrganizationService crmService)
    {
        if (crmService == null)
        {
            throw new ArgumentNullException("crmService");
        }

        if (entityName == null)
        {
            throw new ArgumentNullException("entityName");
        }

        Entity autoNumberSetup = new Entity(AutoNumberHelper.EntityLogicalName);

        ConditionExpression condition1 = new ConditionExpression(
            AutoNumberHelper.EntityName, ConditionOperator.Equal, entityName);

        FilterExpression filter = new FilterExpression();
        filter.Conditions.Add(condition1);
        filter.FilterOperator = LogicalOperator.And;

        QueryExpression query = new QueryExpression();
        query.EntityName = AutoNumberHelper.EntityLogicalName;
        query.Criteria = filter;
        string[] columns =
                    {
                        AutoNumberHelper.AutoNumberSetupId, AutoNumberHelper.Prefix, AutoNumberHelper.NextNumber, 
                        AutoNumberHelper.IncrementNumber, AutoNumberHelper.StartingNumber,AutoNumberHelper.NoOfDigit,
                        AutoNumberHelper.EndingNumber, AutoNumberHelper.Suffix, AutoNumberHelper.EntityName,AutoNumberHelper.Format,
                    };

        query.ColumnSet = new ColumnSet();
        query.ColumnSet.AddColumns(columns);

        EntityCollection collection = crmService.RetrieveMultiple(query);

        if (collection != null && collection.Entities != null && collection.Entities.Count == 0)
        {
            autoNumberSetup.Attributes.Add(AutoNumberHelper.Format, "GCC");
            autoNumberSetup.Attributes.Add(AutoNumberHelper.Prefix, "AA");
            autoNumberSetup.Attributes.Add(AutoNumberHelper.Suffix, "000000");
            autoNumberSetup.Attributes.Add(AutoNumberHelper.NoOfDigit, 6);
            autoNumberSetup.Attributes.Add(AutoNumberHelper.IncrementNumber, 1);
            autoNumberSetup.Attributes.Add(AutoNumberHelper.StartingNumber, "000001");
            autoNumberSetup.Attributes.Add(AutoNumberHelper.NextNumber, "000001");
            autoNumberSetup.Attributes.Add(AutoNumberHelper.EntityName, entityName);
            autoNumberSetup.Id = crmService.Create(autoNumberSetup);
        }
        else
        {
            autoNumberSetup = collection != null ? collection.Entities[0] : autoNumberSetup;
        }

        return autoNumberSetup;
    }
    private static void UpdateAutoNumberSetting(string nextNumber, string prefix, Entity autoNumberSetup, IOrganizationService crmService)
    {

        Entity autoNumber = new Entity(AutoNumberHelper.EntityLogicalName);
        autoNumber.Id = autoNumberSetup.Id;
        autoNumber.Attributes.Add(AutoNumberHelper.NextNumber, nextNumber);
        autoNumber.Attributes.Add(AutoNumberHelper.Prefix, prefix);
        crmService.Update(autoNumber);
    }
    public static Entity GetAutoNumberSettings(string entityName, IOrganizationService crmService)
    {
        string randomNumber = string.Empty;
        Entity autoNumberSetup = new Entity(AutoNumberHelper.EntityLogicalName);

        autoNumberSetup = RetrieveAutoNumberSetting(entityName, crmService);//preFix


        string prefix = string.Empty;
        string firstLetter = string.Empty;
        string secondLetter = string.Empty;
        if (IsPrefixChange((string)autoNumberSetup[AutoNumberHelper.NextNumber], Convert.ToInt32(autoNumberSetup[AutoNumberHelper.NoOfDigit])))
        {
            if (autoNumberSetup.Contains(AutoNumberHelper.Prefix))
            {
                string prefixValues = autoNumberSetup[AutoNumberHelper.Prefix].ToString();
                char[] splitValues = prefixValues.ToCharArray();
                if (splitValues.Length > 0)
                {
                    var firstChar = Convert.ToChar(splitValues[0].ToString());
                    var secondChar = Convert.ToChar(splitValues[1].ToString());
                    firstLetter = Convert.ToString(firstChar);
                    secondLetter = Convert.ToString(secondChar);
                    if (secondChar != 'Z')
                    {
                        secondChar++;
                        secondLetter = Convert.ToString(secondChar);
                    }
                    else
                    {
                        firstChar++;
                        firstLetter = Convert.ToString(firstChar);
                        secondLetter = "A";
                    }
                }
            }
            prefix = firstLetter + secondLetter;

        }
        else
        {
            prefix = (string)autoNumberSetup[AutoNumberHelper.Prefix];
        }


        int incrementNumber = autoNumberSetup.Attributes.Contains(AutoNumberHelper.IncrementNumber)
                                  ? Convert.ToInt32(((object)autoNumberSetup.Attributes[AutoNumberHelper.IncrementNumber]).ToString(), CultureInfo.InvariantCulture)
                                  : 0;
        int endingNumber = autoNumberSetup.Attributes.Contains(AutoNumberHelper.EndingNumber)
                               ? Convert.ToInt32(
                                   ((object)autoNumberSetup.Attributes[AutoNumberHelper.EndingNumber]).ToString(), CultureInfo.InvariantCulture)
                               : 0;
        int startingNumber = autoNumberSetup.Attributes.Contains(AutoNumberHelper.StartingNumber)
                                 ? Convert.ToInt32(
                                     ((object)autoNumberSetup.Attributes[AutoNumberHelper.StartingNumber]).ToString(), CultureInfo.InvariantCulture)
                                 : 0;
        int noOfDigits = autoNumberSetup.Attributes.Contains(AutoNumberHelper.NoOfDigit)
                                 ? Convert.ToInt32(
                                     ((object)autoNumberSetup.Attributes[AutoNumberHelper.NoOfDigit]).ToString(), CultureInfo.InvariantCulture)
                                 : 0;

        string newNumber = CalculateNextNumber(autoNumberSetup);



        if (!string.IsNullOrEmpty(newNumber))
        {
            //var num = Convert.ToInt32(newNumber) + incrementNumber;
            string numberFormat = "{0:D" + noOfDigits.ToString() + "}";
            string finalNumber = String.Format(numberFormat, newNumber);

            UpdateAutoNumberSetting(newNumber.ToString(), prefix, autoNumberSetup, crmService);
        }
        else
        {
            int num = Convert.ToInt32(startingNumber) + 1;
            string numberFormat = "{0:D" + noOfDigits.ToString() + "}";
            string finalNumber = String.Format(numberFormat, num);

            UpdateAutoNumberSetting(finalNumber, prefix, autoNumberSetup, crmService);
        }

        return autoNumberSetup;
    }
    private static bool CheckAutoNumberExists(string autoNumber, IOrganizationService crmService)
    {
        QueryExpression query = new QueryExpression();
        query.EntityName = "contact";
        ConditionExpression condition1 = new ConditionExpression(
            "new_contactid", ConditionOperator.Equal, autoNumber);
        FilterExpression filter = new FilterExpression();
        filter.Conditions.Add(condition1);
        filter.FilterOperator = LogicalOperator.And;
        query.Criteria = filter;
        string[] columns = { "new_contactid" };

        query.ColumnSet = new ColumnSet();
        query.ColumnSet.AddColumns(columns);

        EntityCollection collection = crmService.RetrieveMultiple(query);

        if (collection != null && collection.Entities != null && collection.Entities.Count > 0)
        {
            return true;
        }

        return false;
    }
    private static bool IsPrefixChange(string nextAutoNumber, int noofdigit)
    {

        int postfixNew = Convert.ToInt32(nextAutoNumber);

        var lastNumber = Math.Pow(10, Convert.ToDouble(noofdigit)) - 1;

        var diffNum = lastNumber - postfixNew;
        if (diffNum == 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    private static string CalculateNextNumber(Entity autonumber)
    {
        string startingNumber = string.Empty; string nextNumber = string.Empty; int incrementNumber = 0; ; int noOfDigits = 0;
        string format = string.Empty; string prefix = string.Empty; string suffix = string.Empty;
        if (autonumber.Attributes.Contains(AutoNumberHelper.NextNumber))
        {
            nextNumber = autonumber.Attributes[AutoNumberHelper.NextNumber].ToString();
            format = autonumber.Attributes[AutoNumberHelper.Format].ToString();
            prefix = autonumber.Attributes[AutoNumberHelper.Prefix].ToString();
            suffix = autonumber.Attributes[AutoNumberHelper.Suffix].ToString();
        }
        if (autonumber.Attributes.Contains(AutoNumberHelper.IncrementNumber))
        {
            incrementNumber = Convert.ToInt32(autonumber.Attributes[AutoNumberHelper.IncrementNumber]);
        }
        if (autonumber.Attributes.Contains(AutoNumberHelper.NoOfDigit))
        {
            noOfDigits = (int)autonumber.Attributes[AutoNumberHelper.NoOfDigit];
        }
        if (autonumber.Attributes.Contains(AutoNumberHelper.StartingNumber))
        {
            startingNumber = (string)autonumber.Attributes[AutoNumberHelper.StartingNumber];
        }

        string numberFormat = "{0:D" + noOfDigits.ToString() + "}";

        string finalNumber = string.Empty;

        if (!IsNumberExceeded(noOfDigits, nextNumber))
        {

            if (nextNumber != "0" && nextNumber != string.Empty)
            {
                int newNumber = Convert.ToInt32(nextNumber) + incrementNumber;

                finalNumber = String.Format(numberFormat, newNumber);

            }
            else if (startingNumber != null && !string.IsNullOrEmpty(startingNumber))
            {
                int newNumber = Convert.ToInt32(startingNumber) + incrementNumber;

                finalNumber = String.Format(numberFormat, newNumber);

            }
        }
        else
        {
            finalNumber = startingNumber;
        }


        return finalNumber;
    }
    public static void InsertAutoNumber(Entity autoNumber, Entity targetEntity, IOrganizationService service)
    {

        string _format, _prefix, _startingNumber;
        _format = _prefix = _startingNumber = string.Empty;

        if (autoNumber.Attributes.Contains("new_gortt_suffix"))
        {
            _format = autoNumber.Attributes["new_gortt_suffix"].ToString();
        }
        if (autoNumber.Attributes.Contains("new_gortt_prefix"))
        {
            _prefix = autoNumber.Attributes["new_gortt_prefix"].ToString();
        }
        Entity contact = new Entity(targetEntity.LogicalName);
        contact.Id = targetEntity.Id;



        if (autoNumber.Attributes.Contains("new_gortt_nextnumber"))
        {
            if (CheckAutoNumberExists(autoNumber["new_gortt_nextnumber"].ToString(), service))
            {
                contact["new_contactid"] = _format + _prefix + CalculateNextNumber(autoNumber);
                //null, autoNumber["gortt_nextnumber"].ToString(), Convert.ToInt32(autoNumber["gortt_incrementnumber"].ToString()), (string)autoNumber[AutoNumberHelper.NoOfDigit]);
            }
            else
            {
                contact["new_contactid"] = _format + _prefix + autoNumber["new_gortt_nextnumber"].ToString();
            }
        }
        else
        {

            if (autoNumber.Attributes.Contains("new_gortt_startingnumber"))
            {
                _startingNumber = autoNumber.Attributes["new_gortt_startingnumber"].ToString();
                contact["new_contactid"] = _format + _prefix + _startingNumber;
            }


        }
        service.Update(contact);
    }
    private static bool IsNumberExceeded(int noOfDigits, string number)
    {
        string numberFormat = "{0:D" + noOfDigits.ToString() + "}";

        var lastNumber = Math.Pow(10, Convert.ToDouble(noOfDigits)) - 1;
        string exceededNumber = String.Format(numberFormat, number);

        string endingDigit = "9";
        string totEndDigit = string.Empty;
        for (int i = 0; i < Convert.ToInt32(noOfDigits); i++)
        {
            totEndDigit += endingDigit;
        }
        if (totEndDigit.Equals(exceededNumber))
            return true;
        else
            return false;
    }


        }

                          

    using System

    ;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using Microsoft.Crm.Sdk;
    using System.ServiceModel;
    using System.Globalization;
    using Microsoft.Xrm.Sdk;
    using Microsoft.Xrm.Sdk.Query;

    namespace Microsoft.Crm.Sdk.Samples
    {
        public class PostContactCreate_AutoNumber : Plugin
        {

            public PostContactCreate_AutoNumber()
                : base(typeof(PostContactCreate_AutoNumber))
            {
                base.RegisteredEvents.Add(new Tuple<int, string, string, Action<LocalPluginContext>>(40, "Create", "contact", new Action<LocalPluginContext>(ExecutePostContactCreate)));
            }

            private void ExecutePostContactCreate(LocalPluginContext localContext)
            {

                if (localContext == null)
                {
                    throw new ArgumentNullException("localContext");
                }
                ITracingService tracingService = localContext.TracingService;
                IPluginExecutionContext context = localContext.PluginExecutionContext;
                IOrganizationService service = localContext.OrganizationService;
                  try
                {
                    var target = localContext.PluginExecutionContext.InputParameters.ContainsKey("Target")
                                         ? localContext.PluginExecutionContext.InputParameters["Target"] as Entity
                                         : null;

                    if (target == null)
                    {
                        return;
                    }

                    Entity autoNumberSetting = AutoNumberHelper.GetAutoNumberSettings(target.LogicalName, service);
                    AutoNumberHelper.InsertAutoNumber(autoNumberSetting,target, service);




                }
                  catch (FaultException<OrganizationServiceFault> e)
                  {
                      tracingService.Trace(string.Format(CultureInfo.InvariantCulture, "{0} {1}", "Exception: {0}", e.ToString()), null, tracingService);
                      throw;
                  }
                  finally
                  {
                      tracingService.Trace(string.Format(CultureInfo.InvariantCulture, "{0} {1}", "Exiting {0}.Execute()", this.ChildClassName), null, tracingService);
                  }
            }

            }
        }

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.ServiceModel;
    using Microsoft.Xrm.Sdk;
    using System.Collections.ObjectModel;
    using System.Globalization;

    namespace Microsoft.Crm.Sdk.Samples
    {
       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;
               }
           }
           protected string ChildClassName
           {
               get;

               private set;
           }
           internal Plugin(Type childClassName)
           {
               this.ChildClassName = childClassName.ToString();
           }
             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));

                try
                {
                    // 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<OrganizationServiceFault> e)
                {
                    localcontext.Trace(string.Format(CultureInfo.InvariantCulture, "Exception: {0}", e.ToString()));

                    // Handle the exception.
                    throw;
                }
                finally
                {
                    localcontext.Trace(string.Format(CultureInfo.InvariantCulture, "Exiting {0}.Execute()", this.ChildClassName));
                }
            }
        }
           }

     i have to add to main function AutoNumberHelper class it is difficult to me please replay me how to add main funtion to the

     AutoNumberHelper class 


    Wednesday, September 16, 2015 8:31 AM

Answers

  • Hello,

    Please. Please. PLEASE. Stop asking the same questions creating different threads. How can I in other way ask for it?

    In this case the issue is written inside your error message - The entity with a name = 'gortt_autonumbersetup' was not found do you have issues understanding what does it mean? If yes I will explain - that mean that entity with Logical Name gortt_autonumbersetup doesn't exist in instance you've deployed your plugin.


    Dynamics CRM MVP
    My blog

    Tuesday, September 22, 2015 8:11 AM
    Moderator

All replies

  • when  i am trying that i  created accountnumber entity 

    public static void InsertAutoNumber(Entity autoNumber, Entity targetEntity, IOrganizationService service)
    {

        string _format, _prefix, _startingNumber;
        _format = _prefix = _startingNumber = string.Empty;

        if (autoNumber.Attributes.Contains("new_gortt_suffix"))
        {
            _format = autoNumber.Attributes["new_gortt_suffix"].ToString();
        }
        if (autoNumber.Attributes.Contains("new_gortt_prefix"))
        {
            _prefix = autoNumber.Attributes["new_gortt_prefix"].ToString();
        }
        Entity contact = new Entity(targetEntity.LogicalName);
        contact.Id = targetEntity.Id;

    Monday, September 21, 2015 11:36 AM
  • Monday, September 21, 2015 1:44 PM
  • Hi,

    We need more information than this,.

    You need to download the log file and tell us what you were doing. The image is the generic message displayed to users.

    Chris

    Monday, September 21, 2015 2:45 PM
  • Unhandled Exception: System.ServiceModel.FaultException`1[[Microsoft.Xrm.Sdk.OrganizationServiceFault, Microsoft.Xrm.Sdk, Version=7.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]: The entity with a name = 'gortt_autonumbersetup' was not found in the MetadataCache.Detail: 
    <OrganizationServiceFault xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/xrm/2011/Contracts">
      <ErrorCode>-2147217150</ErrorCode>
      <ErrorDetails xmlns:d2p1="http://schemas.datacontract.org/2004/07/System.Collections.Generic" />
      <Message>The entity with a name = 'gortt_autonumbersetup' was not found in the MetadataCache.</Message>
      <Timestamp>2015-09-22T06:46:17.2060326Z</Timestamp>
      <InnerFault i:nil="true" />
      <TraceText

    this is verry need for me pls answer me

    Tuesday, September 22, 2015 7:21 AM
  • Hello,

    Please. Please. PLEASE. Stop asking the same questions creating different threads. How can I in other way ask for it?

    In this case the issue is written inside your error message - The entity with a name = 'gortt_autonumbersetup' was not found do you have issues understanding what does it mean? If yes I will explain - that mean that entity with Logical Name gortt_autonumbersetup doesn't exist in instance you've deployed your plugin.


    Dynamics CRM MVP
    My blog

    Tuesday, September 22, 2015 8:11 AM
    Moderator
  • in contact entity   i created one field that is auto numbering  and i created autonumering entity  in that i  created no  of filds entity type name ,prefix,suffix  ofter than  i created plug in on contact entity   when   i am  trying to save  the  contact entity i am getting  The entity with a name = 'gortt_autonumbersetup' was not found this field  contains  autonumering  entity  cantains 'gortt_autonumbersetup' where i have to plugin register

      not account entity sorry for the mistake

    Tuesday, September 22, 2015 10:28 AM
  • ErrorCode>-2147217150</ErrorCode>
      <ErrorDetails xmlns:d2p1="http://schemas.datacontract.org/2004/07/System.Collections.Generic" />
      <Message>The entity with a name = 'gortt_autonumbersetup' was not found in the MetadataCache.</Message>
      <Timestamp>2015-09-22T07:17:47.232222Z</Timestamp>
      <InnerFault i:nil="true" />
      <TraceText>
    Tuesday, September 22, 2015 10:34 AM
  • please help me  i am geting this error <Message>Incorrect type of attribute value System.Int32</Message>

    please help me i need  answer this  error

    Tuesday, September 22, 2015 12:20 PM