Skip to main content

Notifications

Announcements

No record found.

Microsoft Dynamics CRM (Archived)

doubt related my work

Posted on by 190

Hello Everyone,

in my project we have opportunities entity

we have custom plugin to create auto Opportunities number ........like bellow..

Opportunites.JPG 

like you can see this is how it get created opportunities number.

CC is nothing but our product Code.

M0268 is nothing but this is employee code of users.

1819 is nothing but Financial year .

6800 is last 4 digit auto generate number .....

my doubt is from where this 1819 is coming from here ....... i will paste little code here to understand .

4760.Code.JPG

in plugin code i can see here some pcl_financialyear is define, i have one field also on Opportunities entity called financial year

and value is showing 1819 for every Opportunities.

financial-year.JPG 

So what is if we get into in next year after 1st April 2019 and we create Opportunities then will it come 1920 financial year automatic.

and 

Note-

or now value is coming like 1819 So ...can we also get value like this 2018-19 in place of 1819. 

thanks for replying my stupid questions as i am very new to this.

Please help me 

Thanks

amit.

*This post is locked for comments

  • Suggested answer
    Sreevalli Profile Picture
    Sreevalli 3,256 on at
    RE: doubt related my work

    Hi Amity,

    You have an entity named "pcl_numberingscheme". From the unsecure config, its passing record Guid and its retrieving record details in "LockProgramExecution" method and the result is settings. so I suggest you GO check "pcl_numberingscheme" for all the details using in autonumber construction.

  • RaviKashyap Profile Picture
    RaviKashyap 55,410 on at
    RE: doubt related my work

    Check you sytem if you have any entity related to auto number setting. You can look witnin customizations >> entities {It m,ust be a custom entity which stores these settings}

  • Suggested answer
    gdas Profile Picture
    gdas 50,085 on at
    RE: doubt related my work

    Hi Amity ,

    Here in the third line see , calling "GetSettings" , which is missing in plugin code . Please check this method, this is the method where financial year assigned.( Find by class name IncrementalNumbering).

                           Guid numberingSchemeGuid = new Guid(globalConfig["autonumrecordguid"]);

                           this.LockProgramExecution(service, numberingSchemeGuid);

                           IncrementalNumbering setting = IncrementalNumbering.GetSettings(service, numberingSchemeGuid);

  • amity Profile Picture
    amity 190 on at
    RE: doubt related my work

    Hi SIr,

    Here is code ...

    // <summary>Auto Numbering Plugin</summary>

    namespace PCL.AutoNumberingPlugin

    {

       using System;

       using System.Collections.Generic;

       using System.Configuration;

       using System.Globalization;

       using System.Xml.Linq;

       using Microsoft.Xrm.Sdk;

       using Microsoft.Xrm.Sdk.Query;

       /// <summary>

       /// AutoNumberingPlugin Class

       /// </summary>

       public class AutoNumberingPlugin : IPlugin

       {

           /// <summary>

           /// lock object

           /// </summary>

           private static object lockobject = new object();

           /// <summary>

           ///Constant string for Unsecure Exception Message

           /// </summary>

           public const string unsecureExceptionMsg = "Unsecure configuration Missing or Error.";

           /// <summary>

           ///Constant string for Unsecure Exception Message

           /// </summary>

           public const string invalidExceptionMsg = "Plugin registration not valid for {0} message.";

           /// <summary>

           /// string to store configuration data

           /// </summary>

           private string configurationData;

           /// <summary>

           /// Initializes a new instance of the <see cref="AutoNumberingPlugin" /> class.

           /// </summary>

           /// <param name="unsecure">un secured string parameter</param>

           /// <param name="secure">secured string parameter</param>

           public AutoNumberingPlugin(string unsecure, string secure)

           {

               this.configurationData = unsecure;

           }

           /// <summary>

           /// IncrementalNumberingPlugin Method Execute

           /// </summary>

           /// <param name="serviceProvider">service Provider</param>

           public void Execute(IServiceProvider serviceProvider)

           {

               ITracingService tracing = (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);

                string accountNumber = string.Empty;

               string employeeCode = string.Empty;

               string region = string.Empty;

               string oppNumber = string.Empty;

               string groupCode = string.Empty;

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

               {

                   if (context.MessageName.ToLower() != "create")

                   {

                       throw new InvalidPluginExecutionException(String.Format(AutoNumberingPlugin.invalidExceptionMsg, context.MessageName));

                   }

                   lock (lockobject)

                   {

                       try

                       {

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

                           //Dictionary to store configuration

                           Dictionary<string, string> globalConfig = new Dictionary<string, string>();

                           if (!string.IsNullOrEmpty(this.configurationData))

                           {

                               globalConfig = ReadUnSecuredConfig(this.configurationData);

                           }

                           else

                           {

                               throw new InvalidPluginExecutionException(AutoNumberingPlugin.unsecureExceptionMsg);

                           }

                           //variable to Store autonumbering record guid

                           Guid numberingSchemeGuid = new Guid(globalConfig["autonumrecordguid"]);

                           this.LockProgramExecution(service, numberingSchemeGuid);

                           IncrementalNumbering setting = IncrementalNumbering.GetSettings(service, numberingSchemeGuid);

                           if (setting.EntityName != null)

                           {

                               int next = setting.CurrentPosition + setting.incrementby;

                               int autonumlength = setting.Autonumberlength;

                               string prefix = string.Empty;

                               string suffix = string.Empty;

                               if (setting.PrefixType == 0)

                               {

                                   prefix = string.Empty;

                               }

                               else if (setting.PrefixType == 1)

                               {

                                   prefix = setting.Prefix;

                               }

                               else if (setting.PrefixType == 2)

                               {

                                   prefix = DateTime.Now.ToString(setting.Prefix, CultureInfo.CurrentCulture);

                               }

                               if (setting.SuffixType == 0)

                               {

                                   suffix = string.Empty;

                               }

                               else if (setting.SuffixType == 1)

                               {

                                   suffix = setting.Suffix;

                               }

                               else if (setting.SuffixType == 2)

                               {

                                   suffix = DateTime.Now.ToString(setting.Suffix, CultureInfo.CurrentCulture);

                               }

                               //daily Reset

                               if (setting.ResetOn == 1)

                               {

                                   if (((setting.LastUpdateOn).ToUniversalTime().Date) != DateTime.UtcNow.Date)

                                   {

                                       next = 1;

                                   }

                               }

                               else if (setting.ResetOn == 2)  //monthly Reset

                               {

                                   if (((setting.LastUpdateOn).ToUniversalTime().Month) != DateTime.UtcNow.Month)

                                   {

                                       next = 1;

                                   }

                               }

                               else if (setting.ResetOn == 3)   //yearly Reset

                               {

                                   if (((setting.LastUpdateOn).ToUniversalTime().Year) != DateTime.UtcNow.Year)

                                   {

                                       next = 1;

                                   }

                               }

                               string nextnum = string.Empty;

                               if (targetEntity.LogicalName == "pcl_territorytargetsheet")

                               {

                                   if (targetEntity.Contains("pcl_employeecode") && targetEntity.Attributes.Contains("pcl_employeecode"))

                                   {

                                       employeeCode = targetEntity.Attributes["pcl_employeecode"].ToString();

                                   }

                                   if (targetEntity.Contains("pcl_region") && targetEntity.Attributes.Contains("pcl_region"))

                                   {

                                       region = targetEntity.Attributes["pcl_region"].ToString();

                                   }

                                   nextnum = next.ToString(CultureInfo.CurrentCulture);

                                   nextnum = nextnum.PadLeft(autonumlength, setting.lengthpad);

                                    targetEntity.Attributes["pcl_financialyear"] = setting.FixPrefix;

                                   nextnum = region + prefix + employeeCode + prefix + setting.FixPrefix + prefix + nextnum + suffix + setting.FixSuffix;

                               }

                               if (targetEntity.LogicalName == "opportunity")

                               {

                                   if (targetEntity.Contains("parentaccountid") && targetEntity.Attributes.Contains("parentaccountid"))

                                   {

                                       EntityReference accountLookup = (EntityReference)targetEntity.Attributes["parentaccountid"];

                                       Entity account = service.Retrieve(accountLookup.LogicalName, accountLookup.Id, new ColumnSet("accountnumber"));

                                       if (account.Contains("accountnumber") && account.Attributes.Contains("accountnumber"))

                                       {

                                           accountNumber = account.Attributes["accountnumber"].ToString();

                                       }

                                   }

                                   if (targetEntity.Contains("pcl_product") && targetEntity.Attributes.Contains("pcl_product"))

                                   {

                                       Guid productId = ((EntityReference)targetEntity.Attributes["pcl_product"]).Id;

                                 //     ConditionExpression conditionStatus = new ConditionExpression("statecode", ConditionOperator.Equal, 0);     //Active

                                       QueryExpression queryMaster = new QueryExpression("pcl_productgroup");

                                       queryMaster.ColumnSet = new ColumnSet("pcl_groupcode", "pcl_productgroupid");

                                       LinkEntity linkDetail = queryMaster.AddLink("product", "pcl_productgroupid", "pcl_productgroup",  JoinOperator.Inner);

                                       ConditionExpression conditionProduct = new ConditionExpression("productid", ConditionOperator.Equal, productId);

                                       linkDetail.LinkCriteria.AddCondition(conditionProduct);

                                    //   linkDetail.LinkCriteria.AddCondition(conditionStatus);

                                       EntityCollection Collection = service.RetrieveMultiple(queryMaster);

                                       if (Collection.Entities.Count > 0)

                                       {

                                           groupCode = Collection.Entities[0].Attributes["pcl_groupcode"].ToString();

                                       }

                                       //tracing.Trace("Count = "+Collection.Entities.Count);

                                       //tracing.Trace("Record Code = "+ Collection.Entities[0].Attributes["pcl_groupcode"]);

                                   }

                                   nextnum = next.ToString(CultureInfo.CurrentCulture);

                                   nextnum = nextnum.PadLeft(autonumlength, setting.lengthpad);

                                   targetEntity.Attributes["pcl_financialyear"] = setting.FixPrefix;

                                   nextnum = groupCode + prefix + accountNumber + prefix + setting.FixPrefix + prefix + nextnum + suffix + setting.FixSuffix;

                                   //tracing.Trace("nextnum" + nextnum);              

                               }

                              if (targetEntity.LogicalName == "pcl_customerrequest")

                               {

                                   tracing.Trace("Step1");

                                   if (targetEntity.Contains("pcl_opportunity") && targetEntity.Attributes.Contains("pcl_opportunity"))

                                   {

                                       EntityReference oppLookup = (EntityReference)targetEntity.Attributes["pcl_opportunity"];

                                       Entity oppourtunity = service.Retrieve(oppLookup.LogicalName,oppLookup.Id, new ColumnSet("pcl_opportunitynumber"));

                                       if (oppourtunity.Contains("pcl_opportunitynumber") && oppourtunity.Attributes.Contains("pcl_opportunitynumber"))

                                       {

                                           oppNumber = oppourtunity.Attributes["pcl_opportunitynumber"].ToString();

                                       }

                                      var Count = getCustomerRequest(service,oppLookup.Id);

                                       nextnum = next.ToString(CultureInfo.CurrentCulture);

                                       nextnum = nextnum.PadLeft(autonumlength, setting.lengthpad);

                                       nextnum =setting.FixPrefix + prefix + oppNumber + prefix + Count;

                                   }

                               }

                               // nextnum = setting.FixPrefix + prefix + nextnum + suffix + setting.FixSuffix;

                               //nextnum = setting.FixPrefix + prefix + accountNumber + nextnum + suffix + setting.FixSuffix;

                               //Increment Number

                               if (setting.Increment(service, next))

                               {

                                   targetEntity[setting.PropertyName] = nextnum;

                               }

                           }

                       }

                       catch (Exception ex)

                       {

                           throw new InvalidPluginExecutionException(ex.Message, ex);

                       }

                   }

               }

           }

           public static int getCustomerRequest(IOrganizationService service,Guid oppId)

           {

               int count=0;

               QueryExpression CR = new QueryExpression("pcl_customerrequest");

               CR.ColumnSet = new ColumnSet("pcl_opportunity");

               CR.Criteria.AddCondition("pcl_opportunity", ConditionOperator.Equal, oppId);

               EntityCollection result = service.RetrieveMultiple(CR);

               count = result.Entities.Count + 1;

               return count;

           }

           /// <summary>

           /// Creates Key pair dictionary from unsecured configuration text

           /// </summary>

           /// <param name="localConfig">unsecured configuration text</param>

           private Dictionary<string, string> ReadUnSecuredConfig(string configData)

           {

               Dictionary<string, string> globalConfig = new Dictionary<string, string>();

               if (!string.IsNullOrEmpty(configData))

               {

                   XDocument xmlConfigData = XDocument.Parse(configData);

                   foreach (XElement element in xmlConfigData.Descendants("appSettings"))

                   {

                       foreach (XElement childEllement in element.Descendants())

                       {

                           globalConfig.Add(childEllement.FirstAttribute.Value, childEllement.LastAttribute.Value);

                       }

                   }

               }

               return globalConfig;

           }

           /// <summary>

           /// lock execution program

           /// </summary>

           /// <param name="service">Organization Service</param>

           /// <param name="traceservice">Tracing Service</param>

           /// <param name="numberingSchemeGuid">numbering Scheme </param>

           private void LockProgramExecution(IOrganizationService service, Guid numberingSchemeGuid)

           {

               try

               {

                   Random randNo = new Random();

                   int newRandomNo = randNo.Next(1, 1000);

                   Entity numSchemeRecordEntity = new Entity("pcl_numberingscheme");

                   numSchemeRecordEntity.Id = numberingSchemeGuid;

                   numSchemeRecordEntity.Attributes["pcl_randomnumber"] = newRandomNo.ToString();

                   service.Update(numSchemeRecordEntity);

               }

               catch (Exception ex)

               {

                   throw new Exception("Exception in LockProgramExecution", ex);

               }

           }

       }

    }

    This is my complete

    Can someone explain me steps ..what value is taking from where?

  • Suggested answer
    Mahendar Pal Profile Picture
    Mahendar Pal 45,095 on at
    RE: doubt related my work

    Check your setting entity and paste your full code here for checking, this is depend on the setting entity and how you are using that configuration.

  • Suggested answer
    RaviKashyap Profile Picture
    RaviKashyap 55,410 on at
    RE: doubt related my work

    Hi,

    It appears that you have some other entity as well which stores these settings and from this setting plugin code is retrieving the prefix and setting it on the field "pcl_financialyear" and also used in generating the number. (I may be wrong though). Basically as suggested above, these values are set in your plugin code so you need first find how these are getting set and then update the source.

    If you wold have provided full plugin code, I guess someone may have already suggested you where/ what to update. Please provide your plugin code if you still can't figure this out.

    Hope this helps.

  • Suggested answer
    gdas Profile Picture
    gdas 50,085 on at
    RE: doubt related my work

    What is "setting" here in the code ?

    As code says  "setting.FixPrefix" is the financial year  which is in the line of  autonumber generate code .

    Check the "setting" object where its define basically that is created the financial year.

  • Suggested answer
    Sreevalli Profile Picture
    Sreevalli 3,256 on at
    RE: doubt related my work

    Hi Amity,

    Since you are generating auto number on opportunity creation, and that should be your target entity.

    Target. And in the marked code it’s adding pcl_financialyear to target attributes so it should be from opportunity entity.

    So you have focus on settings array in the code, it should take you to the input values.

  • Suggested answer
    Mahadeo Matre Profile Picture
    Mahadeo Matre 17,021 on at
    RE: doubt related my work

    Hi..

    In plugin code you are just concatenating string values.. It is all depends on how you are setting pcl_financialyear value.

    If after 1 April 2019 if you are setting value to this attribute as 2019-20 then it will come 2019-20, if it is 1920 then it will be 1920.

    You have to update only pcl_financialyear as per your requirement.

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

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans