コード例 #1
0
        /// <summary>
        /// A plug-in that auto generates a number for provided entity when a record
        /// is created.
        /// </summary>
        /// <remarks>Register this plug-in on the Create message, account entity,
        /// and pre-operation stage.
        /// </remarks>
        //<snippetAssignAutoNumberPlugin2>
        public void Execute(IServiceProvider serviceProvider)
        {
            // Obtain the execution context from the service provider.
            Microsoft.Xrm.Sdk.IPluginExecutionContext context = (Microsoft.Xrm.Sdk.IPluginExecutionContext)
                                                                serviceProvider.GetService(typeof(Microsoft.Xrm.Sdk.IPluginExecutionContext));


            IOrganizationServiceFactory service = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));

            OrganizationService = service.CreateOrganizationService(context.UserId);

            // The InputParameters collection contains all the data passed in the message request.
            if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
            {
                // Obtain the target entity from the input parameters.
                Entity entity = (Entity)context.InputParameters["Target"];
                //</snippetAssignAutoNumberPlugin2>
                string messageName = context.MessageName;

                if (entity.LogicalName == "dots_autonumber")
                {
                    if (messageName == "Create")
                    {
                        //for check duplicate field
                        //if (IsFieldExist(entity.LogicalName, entity.Attributes["new_targetattributelogicalname"].ToString()))
                        //    throw new InvalidPluginExecutionException(string.Format("Field {0} already exist in Entity {1}!", entity.Attributes["new_targetattributelogicalname"].ToString(), entity.LogicalName));
                        if (IsFieldExist2(entity.Attributes["new_targetentitylogicalname"].ToString(), entity.Attributes["new_targetattributelogicalname"].ToString()))
                        {
                            throw new InvalidPluginExecutionException(string.Format("Field {0} already exist in Entity {1}!", entity.Attributes["new_targetattributelogicalname"].ToString(), entity.Attributes["new_targetentitylogicalname"].ToString()));
                        }

                        // allow one fields for one entity
                        if (IsEntityExist2(entity.LogicalName, entity.Attributes["new_targetentitylogicalname"].ToString()))
                        {
                            throw new InvalidPluginExecutionException(string.Format("Already created AutoNumber field for Entity {0}!", entity.Attributes["new_targetentitylogicalname"].ToString()));
                        }



                        SdkMessageProcessingStep step = new SdkMessageProcessingStep
                        {
                            AsyncAutoDelete     = false,
                            Mode                = new OptionSetValue((int)CrmPluginStepMode.Synchronous),
                            Name                = _pluginTypeName + ": " + entity.Attributes["new_name"].ToString(),
                            EventHandler        = new EntityReference("plugintype", GetPluginTypeId()),
                            Rank                = 1,
                            SdkMessageId        = new EntityReference("sdkmessage", GetMessageId()),
                            Stage               = new OptionSetValue((int)CrmPluginStepStage.PreOperation),
                            SupportedDeployment = new OptionSetValue((int)CrmPluginStepDeployment.ServerOnly),
                            SdkMessageFilterId  = new EntityReference("sdkmessagefilter", GetSdkMessageFilterId(entity.Attributes["new_targetentitylogicalname"].ToString())),
                            Description         = entity.Attributes["new_targetattributelogicalname"].ToString()
                        };
                        var SdkMessageProcessingStepId = OrganizationService.Create(step);

                        entity.Attributes.Add("new_sdkmessageprocessingstepid", SdkMessageProcessingStepId.ToString());
                    }
                }
                else
                {
                    var entityDetail = GetEntityByName(entity.LogicalName);
                    if (entity.Attributes.Contains(entityDetail.TargetAttributeLogicalName) == false)
                    {
                        var      InitalValue = GetNewCode(entityDetail);
                        var      setValue    = (InitalValue == null || InitalValue == "") ? "0" : InitalValue;
                        string[] splitValues;
                        if (setValue.Contains("#"))
                        {
                            splitValues = setValue.Split('#');
                            entity.Attributes.Add(entityDetail.TargetAttributeLogicalName, splitValues[0] + "" + splitValues[1]);
                            int incrementValue = Convert.ToInt32(splitValues[1]);
                            IncreaseCurrentNumber(entity.LogicalName, incrementValue);
                        }
                        else
                        {
                            entity.Attributes.Add(entityDetail.TargetAttributeLogicalName, setValue);
                            int incrementValue = Convert.ToInt32(setValue);
                            IncreaseCurrentNumber(entity.LogicalName, incrementValue);
                        }
                    }
                }
            }
            else if (context.InputParameters["Target"] is EntityReference)
            {
                if (context.PrimaryEntityName == "dots_autonumber")
                {
                    if (context.MessageName == "Delete")
                    {
                        Guid         id      = ((EntityReference)context.InputParameters["Target"]).Id;
                        DSAutoNumber entity2 = OrganizationService.Retrieve("dots_autonumber", ((EntityReference)context.InputParameters["Target"]).Id, new ColumnSet(true)).ToEntity <DSAutoNumber>();
                        OrganizationService.Delete("sdkmessageprocessingstep", new Guid(entity2.SdkMessageProcessingStepId.ToString()));
                    }
                }
            }
        }
コード例 #2
0
        private string GetNewCode(DSAutoNumber entityDetail)
        {
            string newCode          = entityDetail.FieldFormat;
            string InitializeNumber = entityDetail.InitializeNumber.ToString();

            if (string.IsNullOrEmpty(entityDetail.FieldFormat) && string.IsNullOrEmpty(entityDetail.InitializeNumber.ToString()))
            {
                int currentNumber;
                currentNumber = (entityDetail.CurrentNumber == null) ? 1 : entityDetail.CurrentNumber.Value;
                return(currentNumber.ToString());
            }
            else if (!string.IsNullOrEmpty(entityDetail.FieldFormat) && !string.IsNullOrEmpty(entityDetail.InitializeNumber.ToString()))
            {
                if (entityDetail.FieldFormat.Contains("{dd}"))
                {
                    newCode = newCode.Replace("{dd}", DateTime.UtcNow.ToString("dd"));
                }
                if (entityDetail.FieldFormat.Contains("{MM}"))
                {
                    newCode = newCode.Replace("{MM}", DateTime.UtcNow.ToString("MM"));
                }
                if (entityDetail.FieldFormat.Contains("{MMM}"))
                {
                    newCode = newCode.Replace("{MMM}", DateTime.UtcNow.ToString("MMM"));
                }
                if (entityDetail.FieldFormat.Contains("{yy}"))
                {
                    newCode = newCode.Replace("{yy}", DateTime.UtcNow.ToString("yy"));
                }
                if (entityDetail.FieldFormat.Contains("{yyyy}"))
                {
                    newCode = newCode.Replace("{yyyy}", DateTime.UtcNow.ToString("yyyy"));
                }
                if (entityDetail.FieldFormat.Contains("{0000}"))
                {
                    newCode = newCode.Replace("{0000}", "0000");
                }


                int    currentNumber;
                string result = "";
                currentNumber = (entityDetail.CurrentNumber == null) ? entityDetail.InitializeNumber.Value : entityDetail.CurrentNumber.Value;
                if (entityDetail.FieldFormat == "{0000}")
                {
                    int newcodelength = newCode.Length;
                    int numberlength  = currentNumber.ToString().Length;

                    if (newCode.Length != numberlength)
                    {
                        newCode = newCode.Remove(newCode.ToString().Length - numberlength);
                        result  = newCode + "#" + currentNumber.ToString();
                    }
                    if (numberlength >= newcodelength)
                    {
                        result = currentNumber.ToString();
                    }
                }
                else
                {
                    result = newCode + "#" + currentNumber.ToString();
                }

                return(result);
            }
            else if (!string.IsNullOrEmpty(entityDetail.FieldFormat) && string.IsNullOrEmpty(entityDetail.InitializeNumber.ToString()))
            {
                if (entityDetail.FieldFormat.Contains("{dd}"))
                {
                    newCode = newCode.Replace("{dd}", DateTime.UtcNow.ToString("dd"));
                }
                if (entityDetail.FieldFormat.Contains("{MM}"))
                {
                    newCode = newCode.Replace("{MM}", DateTime.UtcNow.ToString("MM"));
                }
                if (entityDetail.FieldFormat.Contains("{MMM}"))
                {
                    newCode = newCode.Replace("{MMM}", DateTime.UtcNow.ToString("MMM"));
                }
                if (entityDetail.FieldFormat.Contains("{yy}"))
                {
                    newCode = newCode.Replace("{yy}", DateTime.UtcNow.ToString("yy"));
                }
                if (entityDetail.FieldFormat.Contains("{yyyy}"))
                {
                    newCode = newCode.Replace("{yyyy}", DateTime.UtcNow.ToString("yyyy"));
                }
                if (entityDetail.FieldFormat.Contains("{0000}"))
                {
                    newCode = newCode.Replace("{0000}", "0000");
                }


                int    currentNumber;
                string result = "";
                currentNumber = (entityDetail.InitializeNumber == null && entityDetail.CurrentNumber == null) ? 1 : entityDetail.CurrentNumber.Value;

                if (entityDetail.FieldFormat == "{0000}")
                {
                    int newcodelength = newCode.Length;
                    int numberlength  = currentNumber.ToString().Length;

                    if (newCode.Length != numberlength)
                    {
                        newCode = newCode.Remove(newCode.ToString().Length - numberlength);
                        result  = newCode + "#" + currentNumber.ToString();
                    }
                    if (numberlength >= newcodelength)
                    {
                        result = currentNumber.ToString();
                    }
                }
                else
                {
                    result = newCode + "#" + currentNumber.ToString();
                }

                return(result);
            }

            else // if entityDetail.FieldFormat null and entityDetail.InitializeNumber not null
            {
                int currentNumber;
                currentNumber = (entityDetail.InitializeNumber != null && entityDetail.CurrentNumber == null) ? entityDetail.InitializeNumber.Value : entityDetail.CurrentNumber.Value;
                return(currentNumber.ToString());
            }
        }