Plug-in C#-Auto number in CRM 2011

Microsoft Dynamics CRM is a Customer Relationship Management software package developed by Microsoft
Post Reply
User avatar
gellee
Posts: 46
Joined: Fri Jan 20, 2012 3:04 pm

Plug-in C#-Auto number in CRM 2011

Post by gellee »

To create an automated generation of number let's consider the following steps

1. Create a new Entity (Auto-number) that contains the following fields:
a. Name
b. Prefix
c. Current Number
d. Number of characters

>>This fields will handle the current generated number, using LINQ we coud query this record and just increment the current number by 1.

2. Install the developertoolkit for CRM 2011 found in sdk\tools\developertoolkit. With the Developer Toolkit you can easily generate strongly typed proxy classes without running the CrmSvcUtil.exe
3. Open your IDE(Integrated Development Environment)-Visual Studio 2010
4. Click on File>>New Project>>Visual C#>>Dynamics CRM
5. Click on New Visual Studio Template for Dynamics CRM 2011
6. Connect to your CRM Organization and fill-up all the fields. Then click OK.

Sample CRM Discovery Server Name: ABC.crm.dynamics.com
Port Number: HTTPS - 80, HTTP - 443
connectToCrm.png
7. After connecting to server, right click on the entities where your plug-in must execute. Then click Create plug-in. You'll notice that there are already generated code for you, the only thing you shoud edit is the Execute Method-Implement your custom Plug-in business logic in this method.

Note: Before deploying, be sure you have signed an assembly for your plug-in and workflows.
-Right-click the project node in Solution Explorer, and click Properties
-Click the Signing tab
-Select the Sign the assembly check box
-Specify a new key file

To deploy: Just right click the CRMPackage on the Solution Explorer then click deploy.

Below is the code:

Code: Select all

// <copyright file="PreAppointmentCreate.cs" company="Microsoft">
// Copyright (c) 2012 All Rights Reserved
// </copyright>
// <author>Microsoft</author>
// <date>6/25/2012 10:24:59 AM</date>
// <summary>Implements the PreAppointmentCreate Plugin.</summary>
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.1
// </auto-generated>
namespace AutoNumber.Plugins
{
    using System;
    using System.ServiceModel;
    using Microsoft.Xrm.Sdk;
    using Microsoft.Xrm.Sdk.Query;

    /// <summary>
    /// PreAppointmentCreate Plugin.
    /// </summary>    
    public class PreAppointmentCreate: Plugin
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="PreAppointmentCreate"/> class.
        /// </summary>
        public PreAppointmentCreate()
            : base(typeof(PreAppointmentCreate))
        {
            base.RegisteredEvents.Add(new Tuple<int, string, string, Action<LocalPluginContext>>(20, "Create", "appointment", new Action<LocalPluginContext>(ExecutePreAppointmentCreate)));

            // Note : you can register for more events here if this plugin is not specific to an individual entity and message combination.
            // You may also need to update your RegisterFile.crmregister plug-in registration file to reflect any change.
        }

        /// <summary>
        /// Executes the plug-in.
        /// </summary>
        /// <param name="localContext">The <see cref="LocalPluginContext"/> which contains the
        /// <see cref="IPluginExecutionContext"/>,
        /// <see cref="IOrganizationService"/>
        /// and <see cref="ITracingService"/>
        /// </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>
        protected void ExecutePreAppointmentCreate(LocalPluginContext localContext)
        {
            if (localContext == null)
            {
                throw new ArgumentNullException("localContext");
            }

            // TODO: Implement your custom Plug-in business logic.

            IPluginExecutionContext context = localContext.PluginExecutionContext;

            try
            {

                Entity inputParameters = null;
                // Check if the input parameters property bag contains a target
                // of the create operation and that target is of type Entity.


                if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
                {
                    inputParameters = (Entity)context.InputParameters["Target"];

                }
                else
                {
                    throw new InvalidPluginExecutionException("No inputParameters");
                }


                ColumnSet allColumns = new ColumnSet(new string[] { "prm_activityid" }); //field from the appointment entity
                allColumns.AllColumns = true;

                QueryExpression queryExpr = new QueryExpression();
                queryExpr.EntityName = "prm_autonumber"; //prm_autonumber entity

                queryExpr.ColumnSet = allColumns;

                //EntityCollection autoitem = (EntityCollection)localContext.OrganizationService.RetrieveMultiple(queryExpr);
                EntityCollection autoitem = new EntityCollection();
                autoitem = localContext.OrganizationService.RetrieveMultiple(queryExpr);

                if (autoitem != null)
                {
                    
                    Entity autonumber = (Entity)autoitem.Entities[0];

                    //Format the activityid
                    DateTime now = DateTime.Now;
                    var newPrefix = now.ToString("MM") + now.ToString("yy");
                    var name=autonumber.Attributes["prm_name"];

                    if (name.ToString() == "Activity")
                    {
                        var prefix = autonumber.Attributes["prm_prefix"].ToString();
                        var lengthZeros = autonumber.Attributes["prm_digits"];
                        var incrementNumber = autonumber.Attributes["prm_currentnumber"];
                        incrementNumber = Convert.ToInt16(incrementNumber) + 1;
                        var numberlength = Convert.ToString(incrementNumber).Length;
                        var idFormat = Convert.ToInt32(lengthZeros) - numberlength;

                        var acctnum = string.Format("{0}", newPrefix.ToString()).PadRight(idFormat, '0') + incrementNumber.ToString();
                        //postImageEntity.Attributes["prm_customid"] = acctnum.ToString();
                        //postImageEntity.Attributes["prm_activityid"] = acctnum.ToString();
                        autonumber.Attributes["prm_currentnumber"] = (int)incrementNumber;
                        autonumber.Attributes["prm_prefix"] = newPrefix.ToString();
                        inputParameters.Attributes.Add("prm_customid", acctnum.ToString());
                        //localContext.OrganizationService.Update(postImageEntity);
                        localContext.OrganizationService.Update(autonumber);
                    }

                    


                }

            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
xaeresis
Posts: 196117
Joined: Wed Oct 04, 2023 2:39 pm

Re: Plug-in C#-Auto number in CRM 2011

Post by xaeresis »

инфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфо
инфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфо
инфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфо
инфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинйоинфоинфоинфоинфоинфо
инфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфо
инфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфо
инфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфо
инфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфо
инфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфо
инфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоинфоtuchkasинфоинфо
xaeresis
Posts: 196117
Joined: Wed Oct 04, 2023 2:39 pm

Re: Plug-in C#-Auto number in CRM 2011

Post by xaeresis »

http://audiobookkeeper.ruhttp://cottagenet.ruhttp://eyesvision.ruhttp://eyesvisions.comhttp://factoringfee.ruhttp://filmzones.ruhttp://gadwall.ruhttp://gaffertape.ruhttp://gageboard.ruhttp://gagrule.ruhttp://gallduct.ruhttp://galvanometric.ruhttp://gangforeman.ruhttp://gangwayplatform.ruhttp://garbagechute.ruhttp://gardeningleave.ruhttp://gascautery.ruhttp://gashbucket.ruhttp://gasreturn.ruhttp://gatedsweep.ruhttp://gaugemodel.ruhttp://gaussianfilter.ruhttp://gearpitchdiameter.ru
http://geartreating.ruhttp://generalizedanalysis.ruhttp://generalprovisions.ruhttp://geophysicalprobe.ruhttp://geriatricnurse.ruhttp://getintoaflap.ruhttp://getthebounce.ruhttp://habeascorpus.ruhttp://habituate.ruhttp://hackedbolt.ruhttp://hackworker.ruhttp://hadronicannihilation.ruhttp://haemagglutinin.ruhttp://hailsquall.ruhttp://hairysphere.ruhttp://halforderfringe.ruhttp://halfsiblings.ruhttp://hallofresidence.ruhttp://haltstate.ruhttp://handcoding.ruhttp://handportedhead.ruhttp://handradar.ruhttp://handsfreetelephone.ru
http://hangonpart.ruhttp://haphazardwinding.ruhttp://hardalloyteeth.ruhttp://hardasiron.ruhttp://hardenedconcrete.ruhttp://harmonicinteraction.ruhttp://hartlaubgoose.ruhttp://hatchholddown.ruhttp://haveafinetime.ruhttp://hazardousatmosphere.ruhttp://headregulator.ruhttp://heartofgold.ruhttp://heatageingresistance.ruhttp://heatinggas.ruhttp://heavydutymetalcutting.ruhttp://jacketedwall.ruhttp://japanesecedar.ruhttp://jibtypecrane.ruhttp://jobabandonment.ruhttp://jobstress.ruhttp://jogformation.ruhttp://jointcapsule.ruhttp://jointsealingmaterial.ru
http://journallubricator.ruhttp://juicecatcher.ruhttp://junctionofchannels.ruhttp://justiciablehomicide.ruhttp://juxtapositiontwin.ruhttp://kaposidisease.ruhttp://keepagoodoffing.ruhttp://keepsmthinhand.ruhttp://kentishglory.ruhttp://kerbweight.ruhttp://kerrrotation.ruhttp://keymanassurance.ruhttp://keyserum.ruhttp://kickplate.ruhttp://killthefattedcalf.ruhttp://kilowattsecond.ruhttp://kingweakfish.ruhttp://kinozones.ruhttp://kleinbottle.ruhttp://kneejoint.ruhttp://knifesethouse.ruhttp://knockonatom.ruhttp://knowledgestate.ru
http://kondoferromagnet.ruhttp://labeledgraph.ruhttp://laborracket.ruhttp://labourearnings.ruhttp://labourleasing.ruhttp://laburnumtree.ruhttp://lacingcourse.ruhttp://lacrimalpoint.ruhttp://lactogenicfactor.ruhttp://lacunarycoefficient.ruhttp://ladletreatediron.ruhttp://laggingload.ruhttp://laissezaller.ruhttp://lambdatransition.ruhttp://laminatedmaterial.ruhttp://lammasshoot.ruhttp://lamphouse.ruhttp://lancecorporal.ruhttp://lancingdie.ruhttp://landingdoor.ruhttp://landmarksensor.ruhttp://landreform.ruhttp://landuseratio.ru
http://languagelaboratory.ruhttp://largeheart.ruhttp://lasercalibration.ruhttp://laserlens.ruhttp://laserpulse.ruhttp://laterevent.ruhttp://latrinesergeant.ruhttp://layabout.ruhttp://leadcoating.ruhttp://leadingfirm.ruhttp://learningcurve.ruhttp://leaveword.ruhttp://machinesensible.ruhttp://magneticequator.ruhttp://magnetotelluricfield.ruhttp://mailinghouse.ruhttp://majorconcern.ruhttp://mammasdarling.ruhttp://managerialstaff.ruhttp://manipulatinghand.ruhttp://manualchoke.ruhttp://medinfobooks.ruhttp://mp3lists.ru
http://nameresolution.ruhttp://naphtheneseries.ruhttp://narrowmouthed.ruhttp://nationalcensus.ruhttp://naturalfunctor.ruhttp://navelseed.ruhttp://neatplaster.ruhttp://necroticcaries.ruhttp://negativefibration.ruhttp://neighbouringrights.ruhttp://objectmodule.ruhttp://observationballoon.ruhttp://obstructivepatent.ruhttp://oceanmining.ruhttp://octupolephonon.ruhttp://offlinesystem.ruhttp://offsetholder.ruhttp://olibanumresinoid.ruhttp://onesticket.ruhttp://packedspheres.ruhttp://pagingterminal.ruhttp://palatinebones.ruhttp://palmberry.ru
http://papercoating.ruhttp://paraconvexgroup.ruhttp://parasolmonoplane.ruhttp://parkingbrake.ruhttp://partfamily.ruhttp://partialmajorant.ruhttp://quadrupleworm.ruhttp://qualitybooster.ruhttp://quasimoney.ruhttp://quenchedspark.ruhttp://quodrecuperet.ruhttp://rabbetledge.ruhttp://radialchaser.ruhttp://radiationestimator.ruhttp://railwaybridge.ruhttp://randomcoloration.ruhttp://rapidgrowth.ruhttp://rattlesnakemaster.ruhttp://reachthroughregion.ruhttp://readingmagnifier.ruhttp://rearchain.ruhttp://recessioncone.ruhttp://recordedassignment.ru
http://rectifiersubstation.ruhttp://redemptionvalue.ruhttp://reducingflange.ruhttp://referenceantigen.ruhttp://regeneratedprotein.ruhttp://reinvestmentplan.ruhttp://safedrilling.ruhttp://sagprofile.ruhttp://salestypelease.ruhttp://samplinginterval.ruhttp://satellitehydrology.ruhttp://scarcecommodity.ruhttp://scrapermat.ruhttp://screwingunit.ruhttp://seawaterpump.ruhttp://secondaryblock.ruhttp://secularclergy.ruhttp://seismicefficiency.ruhttp://selectivediffuser.ruhttp://semiasphalticflux.ruhttp://semifinishmachining.ruhttp://spicetrade.ruhttp://spysale.ru
http://stungun.ruhttp://tacticaldiameter.ruhttp://tailstockcenter.ruhttp://tamecurve.ruhttp://tapecorrection.ruhttp://tappingchuck.ruhttp://taskreasoning.ruhttp://technicalgrade.ruhttp://telangiectaticlipoma.ruhttp://telescopicdamper.ruhttp://temperateclimate.ruhttp://temperedmeasure.ruhttp://tenementbuilding.rutuchkashttp://ultramaficrock.ruhttp://ultraviolettesting.ru
xaeresis
Posts: 196117
Joined: Wed Oct 04, 2023 2:39 pm

Re: Plug-in C#-Auto number in CRM 2011

Post by xaeresis »

Post Reply