예제 #1
2
        /// <summary>
        /// Pre-Validation method will default the values of contact preference fields
        /// </summary>
        private static void PreValidateContactCreate(IPluginExecutionContext context, IOrganizationService service)
        {
            Entity contactEntity = (Entity)context.InputParameters["Target"];
            OptionSetValue doNotAllow = new OptionSetValue(1);

            contactEntity.SetAttribute("donotemail", doNotAllow);
            contactEntity.SetAttribute("donotpostalmail", doNotAllow);
            contactEntity.SetAttribute("donotbulkemail", doNotAllow);
            contactEntity.SetAttribute("donotfax", doNotAllow);

            // Get a count of child phone call entities associated with this Contact
            QueryExpression query = new QueryExpression();
            query.EntityName = "phonecall";
            query.ColumnSet = new ColumnSet(allColumns: true);
            query.Criteria = new FilterExpression();
            query.Criteria.AddCondition(new ConditionExpression("regardingobjectid", ConditionOperator.Equal, context.PrimaryEntityId));

            RetrieveMultipleRequest request = new RetrieveMultipleRequest();
            request.Query = query;
            IEnumerable<Entity> results = ((RetrieveMultipleResponse)service.Execute(request)).EntityCollection.Entities;
            if (results.Any())
            {
                // Do not default contact preference for phone if there are already some associated phone calls
                // Why? Because! Testing!
                contactEntity.SetAttribute("donotphone", doNotAllow);
            }
        }
예제 #2
0
        /// <summary>
        /// Pre RetrieveMultiple
        /// </summary>
        /// <param name="context"></param>
        /// <param name="service"></param>
        public void GenerateQuery(IPluginExecutionContext context, IOrganizationService service)
        {
            if (context.InputParameters.Contains(Query))
            {
                TableRelationation tableRelation = TableRelationation.GetSinglton();
                // Get the query
                if (context.InputParameters[Query] is QueryExpression)
                {
                    QueryExpression query = (QueryExpression)context.InputParameters[Query];
                    AppendQueryExpression(query, context, service, tableRelation);
                }

                else if (context.InputParameters[Query] is FetchExpression)
                {
                    try
                    {
                        FetchExpression fetchQuery = (FetchExpression)context.InputParameters[Query];
                        var query = fetchQuery.Query;
                        if (!FetchXmlForEntity(query, tableRelation))
                            return;

                        FetchXmlToQueryExpressionRequest request = new FetchXmlToQueryExpressionRequest { FetchXml = query };

                        var response = service.Execute(request) as FetchXmlToQueryExpressionResponse;
                        if (response != null && response.Query != null)
                            AppendQueryExpression(response.Query, context, service, tableRelation);
                    }
                    catch
                    {
                        // for aggrate reason can be exception or other things
                    }
                }
            }
        }
예제 #3
0
 private CuteContext(IPluginExecutionContext context)
 {
     if (context != null)
     {
         BusinessUnitId = context.BusinessUnitId;
         CorrelationId = context.CorrelationId;
         Depth = context.Depth;
         InitiatingUserId = context.InitiatingUserId;
         InputParameters = context.InputParameters;
         IsExecutingOffline = context.IsExecutingOffline;
         IsInTransaction = context.IsInTransaction;
         IsOfflinePlayback = context.IsOfflinePlayback;
         IsolationMode = context.IsolationMode;
         MessageName = context.MessageName;
         Mode = context.Mode;
         OperationCreatedOn = context.OperationCreatedOn;
         OperationId = context.OperationId;
         OrganizationId = context.OrganizationId;
         OrganizationName = context.OrganizationName;
         OutputParameters = context.OutputParameters;
         OwningExtension = context.OwningExtension;
         PostEntityImages = context.PostEntityImages;
         PreEntityImages = context.PreEntityImages;
         PrimaryEntityId = context.PrimaryEntityId;
         PrimaryEntityName = context.PrimaryEntityName;
         RequestId = context.RequestId;
         SecondaryEntityName = context.SecondaryEntityName;
         SharedVariables = context.SharedVariables;
         Stage = context.Stage;
         UserId = context.UserId;
     }
 }
예제 #4
0
        public string GetValue(IPluginExecutionContext context, string attributeName)
        {
            try
            {
                switch (context.MessageName)
                {
                    case MessageName.Create:
                    case MessageName.Update:
                        return CustomDynamicEntity.GetAttributeValue(((DynamicEntity)context.PostEntityImages[ParameterName.Target]).Properties[attributeName], false);
                    case MessageName.Delete:
                        if (context.PreEntityImages["AsynchronousStepPrimaryName"] != null)
                            return CustomDynamicEntity.GetAttributeValue(((DynamicEntity)context.PreEntityImages["AsynchronousStepPrimaryName"]).Properties[attributeName], false);
                        else
                            return CustomDynamicEntity.GetAttributeValue(((DynamicEntity)context.PreEntityImages[ParameterName.Target]).Properties[attributeName], false);
                    default:
                        if (context.PostEntityImages[ParameterName.Target] != null)
                            return CustomDynamicEntity.GetAttributeValue(((DynamicEntity)context.PostEntityImages[ParameterName.Target]).Properties[attributeName], false);
                        if (context.PreEntityImages[ParameterName.Target] != null)
                            return CustomDynamicEntity.GetAttributeValue(((DynamicEntity)context.PreEntityImages[ParameterName.Target]).Properties[attributeName], false);
                        break;
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
                return null;
            }

            return null;
        }
        /// <summary>
        /// Check the plugin registration
        /// </summary>
        /// <returns>False, if registered on wrong entity, otherwise true</returns>
        private bool IsValidContext(IPluginExecutionContext context)
        {
            _tracing.Trace("Checking for Target");
            // The InputParameters collection contains all the data passed in the message request.);
            if (!context.InputParameters.Contains("Target") || !(context.InputParameters["Target"] is Entity))
            {
                return false;
            }

            _tracing.Trace("Checking PrimaryEntityName");
            if (context.PrimaryEntityName != "")
            {
                return false;
            }

            _tracing.Trace("Checking context MessageName");
            if (context.MessageName != "Create" && context.MessageName != "Update")
            {
                return false;
            }

            _tracing.Trace("Checking vor Offline");
            if (context.IsExecutingOffline)
            {
                return false;
            }

            _tracing.Trace("Context is valid");
            return true;
        }
 /// <summary>
 /// Initializes a new instance of class PluginServices
 /// </summary>
 /// <param name="serviceProvider">Service provider</param>
 public PluginServices(IServiceProvider serviceProvider)
 {
     // Instanciation des services
     _executionContext = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
     _serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
     _tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
 }
예제 #7
0
 private static bool ValidatePlugin(IPluginExecutionContext context)
 {
     if (context.PrimaryEntityName != Account.EntityLogicalName)
     {
         return false;
     }
     return true;
 }
예제 #8
0
        public Guid GetEntityId(IPluginExecutionContext context, IMetadataService metaData)
        {
            // Get the metadata about the current entity.
            var req = new RetrieveEntityRequest { LogicalName = context.PrimaryEntityName };
            var res = (RetrieveEntityResponse)metaData.Execute(req);

            return this.GetKeyValue(context, res.EntityMetadata.PrimaryKey);
        }
예제 #9
0
        private void InitializeServices(IServiceProvider serviceProvider, out IPluginExecutionContext context)
        {
            context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

            ((IProxyTypesAssemblyProvider)context).ProxyTypesAssembly = typeof(Contact).Assembly;

            t = (ITracingService)serviceProvider.GetService(typeof(ITracingService));

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

            service = serviceFactory.CreateOrganizationService(context.UserId);

            xrmContext = new crmContext(service);
        }
        public static InvalidPluginStepRegistrationException ImageMissingRequiredAttribute(IPluginExecutionContext context, Entity entity, string attributeName)
        {
            var image = ImageCollection.Post;
            var keyValue = context.PostEntityImages.FirstOrDefault(v => v.Value == entity && !v.Value.Contains(attributeName));
            if (keyValue.Key == null)
            {
                keyValue = context.PreEntityImages.FirstOrDefault(v => v.Value == entity && !v.Value.Contains(attributeName));
                image = ImageCollection.Pre;
            }
            if (keyValue.Key == null)
            {
                throw new Exception("Neither the PostEntityImages or PreEntityImages collections contain the given entity " + entity.GetNameId());
            }

            return new InvalidPluginStepRegistrationException("{0} Entity Image \"{1}\" is missing required parameter {2}!", image, keyValue.Key, attributeName);
        }
        private static string GetTypeSchemaName(IPluginExecutionContext context, bool isRelationship)
        {
            string entityType;
            if (isRelationship)
                entityType = ((Relationship)context.InputParameters["Relationship"]).SchemaName;
            else if (context.MessageName == PluginMessage.RetrieveMultiple)
                entityType = XRMRETRIEVEMULTIPLEFAKESCHEMANAME;
            else if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
                entityType = ((Entity)context.InputParameters["Target"]).LogicalName;
            else if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is EntityReference)
                entityType = ((EntityReference)context.InputParameters["Target"]).LogicalName;
            else if (context.InputParameters.Contains("EntityMoniker") &&
                     context.InputParameters["EntityMoniker"] is EntityReference)
                entityType = ((EntityReference)context.InputParameters["EntityMoniker"]).LogicalName;
            else if (
                new[] { PluginMessage.AddMembers, PluginMessage.AddMember, PluginMessage.AddListMember }.Contains(
                    context.MessageName))
                entityType = "list";
            else if (context.InputParameters.Contains("LeadId") &&
                     context.InputParameters["LeadId"] is EntityReference)
                entityType = "lead";
            else if (context.InputParameters.Contains("EmailId"))
                entityType = "email";

            else
            {
                var args = "";
                args = args + "Message: " + context.MessageName;
                foreach (var item in context.InputParameters)
                {
                    if (args != "")
                        args = args + "\n" + item.Key + ": " + item.Value;
                    else
                        args = args + item.Key + ": " + item.Value;
                }
                throw new InvalidPluginExecutionException("Error Extracting Plugin Entity Type:\n" + args);
            }
            return entityType;
        }
예제 #12
0
        public void Execute(IServiceProvider serviceProvider)
        {
            IPluginExecutionContext     context        = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);
            ITracingService             traceService   = (ITracingService)serviceProvider.GetService(typeof(ITracingService));

            traceService.Trace("Loaded Sent to CAS Plugin");
            traceService.Trace("Plugin Depth:" + context.Depth.ToString());

            if (context.Depth > 2)
            {
                return;
            }

            Entity targetEntity = null;

            if (context.Depth == 1 && context.InputParameters != null && context.InputParameters.Contains("Target") &&
                context.InputParameters["Target"] is Entity && context.PostEntityImages != null &&
                context.PostEntityImages.Count > 0)
            {
                targetEntity = context.InputParameters["Target"] as Entity;
                if (!targetEntity.Contains("statuscode"))
                {
                    return;
                }
                if (targetEntity.Contains("statuscode") && ((OptionSetValue)targetEntity["statuscode"]).Value != 610410001) //Ready for Processing
                {
                    return;
                }
            }
            traceService.Trace("Loaded Target Entity");

            bool       isError       = false;
            string     userMessage   = string.Empty;
            HttpClient httpClient    = null;
            string     invoiceNumber = string.Empty;

            try
            {
                targetEntity = context.InputParameters["Target"] as Entity;
                if (!targetEntity.Contains("statuscode"))
                {
                    return;
                }
                if (targetEntity.Contains("statuscode") && ((OptionSetValue)targetEntity["statuscode"]).Value != 610410001) //Ready for Processing
                {
                    return;
                }

                traceService.Trace("Payment is Ready for Processing");

                var postImageEntity = context.PostEntityImages["PostImage"] as Entity;
                if (!postImageEntity.Contains("educ_amount"))
                {
                    throw new InvalidPluginExecutionException("Amount is empty on the payment");
                }

                SetState(service, targetEntity.ToEntityReference(), 0, 610410000); //Processing

                traceService.Trace("Payment Set as Processing");

                var systemUserConfig         = Helpers.GetSystemConfigurations(service, "Default", "ECASServiceAccountUserId");
                var ecasServiceAccountUserId = Helpers.GetSystemUserId(service, systemUserConfig[0].GetAttributeValue <string>("educ_value")).Id;

                //var ecasServiceAccountUserId = new Guid(Helpers.GetSystemConfigurations(service, "Default", "ECASServiceAccountUserId")[0]["educ_value"].ToString());
                IOrganizationService adminService = serviceFactory.CreateOrganizationService(ecasServiceAccountUserId);
                var configs = Helpers.GetSystemConfigurations(adminService, "CAS-AP", string.Empty);

                string clientKey = Helpers.GetConfigKeyValue(configs, "ClientKey", "CAS-AP");
                string clientId  = Helpers.GetConfigKeyValue(configs, "ClientId", "CAS-AP");
                string url       = Helpers.GetConfigKeyValue(configs, "InterfaceUrl", "CAS-AP");

                traceService.Trace("Loaded Settings");

                var invoice = GenerateInvoice(service, traceService, configs, postImageEntity);
                invoiceNumber = invoice.InvoiceNumber;
                traceService.Trace($"Invoice #{invoiceNumber} loaded");
                var jsonRequest = invoice.ToJSONString();

                httpClient = new HttpClient();
                httpClient.DefaultRequestHeaders.Add("clientID", clientId);
                httpClient.DefaultRequestHeaders.Add("secret", clientKey);
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                //httpClient.BaseAddress = new Uri(url);
                httpClient.Timeout = new TimeSpan(0, 2, 0);  // 2 minutes to execute within the sandbox mode

                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url + "/api/CASAPTransaction");
                request.Content = new StringContent(jsonRequest, Encoding.UTF8, "application/json");

                traceService.Trace("-----JSON Payload Begin-----");
                traceService.Trace(jsonRequest);
                traceService.Trace("-----JSON Payload End-----");

                traceService.Trace("-----REQUEST INFO------");
                traceService.Trace("URL:" + url);
                traceService.Trace("clientID:" + clientId);
                traceService.Trace("secret:" + clientKey);

                HttpResponseMessage response = new HttpResponseMessage();
                try
                {
                    response = httpClient.SendAsync(request).Result;
                }
                catch (Exception ex)
                {
                    while (ex.InnerException != null)
                    {
                        ex = ex.InnerException;
                    }
                    Console.WriteLine(ex.Message);
                    if (!string.IsNullOrWhiteSpace(ex.StackTrace))
                    {
                        Console.WriteLine(ex.StackTrace);
                    }
                    isError = true;
                    throw ex;
                }


                traceService.Trace("Invoked CAS AP Service");

                if (response.StatusCode == HttpStatusCode.OK)
                {
                    userMessage = response.Content.ReadAsStringAsync().Result;
                    if (!userMessage.Contains("SUCCEEDED"))
                    {
                        throw new InvalidPluginExecutionException(userMessage);
                    }
                }
                else
                {
                    throw new InvalidPluginExecutionException(response.StatusCode.ToString() + "\r\n" + jsonRequest); // throw new InvalidPluginExecutionException(string.Format("Error from CAS Interface:\r\nStatus='{0}'\r\nReason='{1}'\r\nRequest={2}", response.StatusCode, response.ReasonPhrase, response.RequestMessage.Content.ReadAsStringAsync().Result));
                }
            }
            catch (InvalidPluginExecutionException ex)
            {
                traceService.Trace("Exception: " + ex.Message + " " + ex.StackTrace);
                isError     = true;
                userMessage = ex.Message;
            }
            catch (FaultException <OrganizationServiceFault> ex)
            {
                traceService.Trace("Exception: " + ex.Message + " " + ex.StackTrace);
                isError     = true;
                userMessage = ex.Message;
            }
            catch (Exception ex)
            {
                traceService.Trace("Exception: " + ex.Message + " " + ex.StackTrace);
                isError     = true;
                userMessage = ex.Message;
            }
            finally
            {
                Entity updatePayment = new Entity("educ_payment");
                updatePayment.Id = ((Entity)context.InputParameters["Target"]).Id;

                if (!string.IsNullOrEmpty(userMessage))
                {
                    updatePayment["educ_casresponse"] = userMessage;
                }

                if (!userMessage.Contains("SUCCEEDED"))
                {
                    updatePayment["statuscode"] = new OptionSetValue(610410004); //Failed when attempting to send to CAS
                }
                else
                {
                    updatePayment["statuscode"]         = new OptionSetValue(610410006); //Sent
                    updatePayment["educ_invoicenumber"] = invoiceNumber;
                }

                if (!string.IsNullOrEmpty(userMessage))
                {
                    service.Update(updatePayment);
                }

                if (httpClient != null)
                {
                    httpClient.Dispose();
                }
            }
        }
예제 #13
0
        public void Execute(IServiceProvider serviceProvider)
        {
            #region "Parâmetros essenciais para o plugin"
            IPluginExecutionContext     context        = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId); //Contexto do Usuário
            IOrganizationService        serviceGlobal  = serviceFactory.CreateOrganizationService(null);           //Contexto Global
            ITracingService             tracing        = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
            Helper helper = new Helper(serviceGlobal, context, tracing);
            #endregion

            /*
             * Desenvolver um Plug-In na alteração para Aprovar/Reprovar a tarefa de Limite vai ser encerrada
             * Mensagem de update: Ideal para validar regras e executar ações na própria etidade ou entidades relacionadas
             * Pré-Imagem: Guarda as informações do registro antes da ação, nem todas ações podem ter preimage, alguns exemplos que podem são: update e delete
             */
            if (context.MessageName.ToLower().Trim() == StepMessage.update.ToString())
            {
                if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
                {
                    Entity entityContext = context.InputParameters["Target"] as Entity;

                    /*
                     * Campos da Pré Imagem
                     * regardingobjectid
                     */
                    if (context.PreEntityImages.Contains("PreImage") && context.PreEntityImages["PreImage"] is Entity)
                    {
                        Entity preImage = context.PreEntityImages["PreImage"] as Entity;

                        /*
                         * Campos em que a alteração deve rodar
                         * curso_statusaprovacaolimite
                         */
                        if (context.Stage == (int)StepEventStage.PostOperation && context.Mode == (int)StepExecutionMode.Synchronous)
                        {
                            helper.ConcluirTarefa(entityContext, preImage);
                        }
                    }
                }
            }

            /*
             * Criar Plugin na alteração de status para obrigar estar em concordância com o campo de Status da Aprovação
             * Mensagem de setstatedynamicentity: Ideal para validar regras e executar ações quando o STATUS é alterado
             * OBS: A entidade relacionada é trazida como referência
             */
            if (context.MessageName.ToLower() == "setstatedynamicentity")
            {
                if (!context.InputParameters.Contains("EntityMoniker"))
                {
                    return;
                }
                if (!context.InputParameters.Contains("State"))
                {
                    return;
                }

                EntityReference entidade = (EntityReference)context.InputParameters["EntityMoniker"];
                OptionSetValue  state    = (OptionSetValue)context.InputParameters["State"];

                if (context.Stage == (int)StepEventStage.PreOperation)
                {
                    helper.ValidarConclusaoTarefa(entidade, state);
                }
            }

            /*
             * Criar Plugin na criação para não deixar criar Tarefa de Limite se existir um limite aprovado com o valor maior
             * Mensagem de create: Ideal para validar se a criação do registro é válida ou disparar ações a partir da criação do registro
             */
            if (context.MessageName.ToLower() == "create")
            {
                if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
                {
                    Entity entityContext = context.InputParameters["Target"] as Entity;
                    if (context.Stage == (int)StepEventStage.PreValidation)
                    {
                        helper.ValidarCriacao(entityContext);
                    }
                }
            }
        }
        public void Execute(IServiceProvider serviceProvider)
        {
            // Obtain the tracing service
            ITracingService tracingService =
                (ITracingService)serviceProvider.GetService(typeof(ITracingService));

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

            // 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"];

                // Obtain the organization service reference which you will need for
                // web service calls.
                IOrganizationServiceFactory serviceFactory =
                    (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

                try
                {
                    // Create a task activity to follow up with the account customer in 7 days.
                    Entity followup = new Entity("task");

                    followup["subject"]     = "Send e-mail to the new customer.";
                    followup["description"] =
                        "Follow up with the customer. Check if there are any new issues that need resolution.";
                    followup["scheduledstart"] = DateTime.Now.AddDays(7);
                    followup["scheduledend"]   = DateTime.Now.AddDays(7);
                    followup["category"]       = context.PrimaryEntityName;

                    // Refer to the account in the task activity.
                    if (context.OutputParameters.Contains("id"))
                    {
                        Guid   regardingobjectid     = new Guid(context.OutputParameters["id"].ToString());
                        string regardingobjectidType = "account";

                        followup["regardingobjectid"] =
                            new EntityReference(regardingobjectidType, regardingobjectid);
                    }

                    // Create the task in Microsoft Dynamics CRM.
                    tracingService.Trace("FollowupPlugin: Creating the task activity.");
                    service.Create(followup);
                }

                catch (FaultException <OrganizationServiceFault> ex)
                {
                    throw new InvalidPluginExecutionException("An error occurred in FollowUpPlugin.", ex);
                }

                catch (Exception ex)
                {
                    tracingService.Trace("FollowUpPlugin: {0}", ex.ToString());
                    throw;
                }
            }
        }
예제 #15
0
 /// <summary>
 /// Sets the parent context for the context.
 /// </summary>
 /// <param name="context">The context.</param>
 /// <returns></returns>
 public TDerived WithParentContext(IPluginExecutionContext context)
 {
     Context.ParentContext = context;
     return(This);
 }
예제 #16
0
        public void Execute(IServiceProvider serviceProvider)
        {
            ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));

            IPluginExecutionContext     context        = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);

            try
            {
                var logicToBeUsexecuted = new Logic();
                logicToBeUsexecuted.LogicToCreateSomehting(service);
            }
            catch (Exception ex)
            {
                throw new InvalidPluginExecutionException(String.Format("Error on Plugin xpto with message: {0}", ex.Message));
            }
            //Validar se o context é diferente de null assim como os inputParameters
            if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
            {
                //TODO:
                //Dentro do método Execute não quero mais nda para além de um global try catch e depois criam toda a logica na paste BusinessLogicHelper dentro da class Logic
                //Exemplo: todas as regions que defeniram devem ser uma função dentro da class enumerada anteriormente

                Entity jobDestination = (Entity)context.InputParameters["Target"];
                var    destVessel     = (EntityReference)jobDestination["dia_vessel"];
                //var qtdDestination = (decimal)jobDestination.Attribute["dia_quantity"] ou assim ou com o getAttributeValue não várias maneiras no mesmo codigo;
                var qtdDestination = (decimal)jobDestination["dia_quantity"];
                var jobRef         = (EntityReference)jobDestination["dia_job"];
                var jobEnt         = service.Retrieve(jobRef.LogicalName, jobRef.Id, new ColumnSet("dia_schelduledstart", "dia_quantity", "dia_type"));

                #region JobsToFill
                var queryJobDestinations = new QueryExpression("dia_jobdestinationvessel");
                queryJobDestinations.ColumnSet = new ColumnSet("dia_vessel", "dia_quantity");
                queryJobDestinations.Criteria  = new FilterExpression(LogicalOperator.And);
                queryJobDestinations.Criteria.AddCondition("dia_vessel", ConditionOperator.Equal, destVessel.Id);

                var jobLinkEntityDest = new LinkEntity("dia_jobdestinationvessel", "dia_job", "dia_job", "dia_jobid", JoinOperator.Inner);
                jobLinkEntityDest.Columns      = new ColumnSet(false);
                jobLinkEntityDest.LinkCriteria = new FilterExpression(LogicalOperator.And);
                jobLinkEntityDest.LinkCriteria.AddCondition("dia_schelduledstart", ConditionOperator.LessEqual, (DateTime)jobEnt["dia_schelduledstart"]);
                jobLinkEntityDest.LinkCriteria.AddCondition("statuscode", ConditionOperator.Equal, 914440001);//Addicionem comentários o name deste valor é qual? nínguem vai saber
                queryJobDestinations.LinkEntities.Add(jobLinkEntityDest);
                var vesselFills = service.RetrieveMultiple(queryJobDestinations);

                //TODO:
                //deveria ser outra função simples de ser usada em muitos locais como por exemplo
                //var logiHelper = new LogicHelper();
                //var value = logiHelper.SumOfQuantities(vesselFills, "dia_quantity");
                var qtdFill = 0m;
                foreach (var vessFill in vesselFills.Entities)
                {
                    qtdFill += (decimal)vessFill["dia_quantity"];
                }
                #endregion JobsToFill

                #region JobsToEmpty
                var queryJobSource = new QueryExpression("dia_jobsourcevessel");
                queryJobSource.ColumnSet = new ColumnSet("dia_quantity");
                queryJobSource.Criteria  = new FilterExpression(LogicalOperator.And);
                queryJobSource.Criteria.AddCondition("dia_vessel", ConditionOperator.Equal, destVessel.Id);

                var jobLinkEntitySource = new LinkEntity("dia_jobdestinationvessel", "dia_job", "dia_job", "dia_jobid", JoinOperator.Inner);
                jobLinkEntitySource.Columns      = new ColumnSet(false);
                jobLinkEntitySource.LinkCriteria = new FilterExpression(LogicalOperator.And);
                jobLinkEntitySource.LinkCriteria.AddCondition("dia_schelduledstart", ConditionOperator.LessEqual, (DateTime)jobEnt["dia_schelduledstart"]);
                jobLinkEntitySource.LinkCriteria.AddCondition("statuscode", ConditionOperator.Equal, 914440001);
                queryJobSource.LinkEntities.Add(jobLinkEntitySource);
                var vesselEmpty = service.RetrieveMultiple(queryJobSource);

                var qtdDrop = 0m;
                foreach (var vessEmpty in vesselEmpty.Entities)
                {
                    qtdDrop += (decimal)vessEmpty["dia_quantity"];
                }
                #endregion JobsToEmpty

                var vesselEnt        = service.Retrieve("dia_vessel", destVessel.Id, new ColumnSet("dia_occupation", "dia_capacity", "dia_name"));
                var occVessel        = vesselEnt.GetAttributeValue <decimal>("dia_occupation");
                var capVessel        = vesselEnt.GetAttributeValue <decimal>("dia_capacity");
                var qtdJobDestVessel = (decimal)jobDestination["dia_quantity"];


                var finalOccupation = capVessel - occVessel - qtdJobDestVessel - qtdFill + qtdDrop;


                //throw new InvalidPluginExecutionException(" Final Occupation " + finalOccupation + " capJobDestVessel: " + capVessel + " occupation: " + occVessel + " qtdJobDestVessel " + qtdJobDestVessel + " qtdFill: " + qtdFill + " qtdDrop: " + qtdDrop);

                if (finalOccupation < 0)
                {
                    throw new InvalidPluginExecutionException("Sorry but the vessel " + vesselEnt["dia_name"] + " at this date " + jobEnt["dia_schelduledstart"] + " will not have that capacity, will exceeed in " + finalOccupation);
                }

                #region different actions
                var VesselEntity     = (EntityReference)jobDestination["dia_vessel"];
                var vesselInfo       = service.Retrieve("dia_vessel", VesselEntity.Id, new ColumnSet("dia_occupation", "dia_capacity", "dia_name", "dia_remainingcapacity"));
                var vesselOccupation = vesselInfo.GetAttributeValue <decimal>("dia_occupation");

                var JobEntity = (EntityReference)jobDestination["dia_job"];
                var JobInfo   = service.Retrieve(jobRef.LogicalName, JobEntity.Id, new ColumnSet("dia_schelduledstart", "dia_quantity", "dia_type"));
                var jobtype   = JobInfo.GetAttributeValue <OptionSetValue>("dia_type") != null?JobInfo.GetAttributeValue <OptionSetValue>("dia_type") : null;


                if (jobtype != null && jobtype.Value == 914440002) // if job type intake
                {
                    if (vesselOccupation != 0)
                    {
                        throw new InvalidPluginExecutionException("Sorry but the vessel " + vesselEnt["dia_name"] + " at this date " + jobEnt["dia_schelduledstart"] + "is full");
                    }
                }

                if (jobtype != null && jobtype.Value == 914440000 || jobtype.Value == 914440003)   //if job type in-situ or dispatch +


                {
                    if (vesselOccupation == 0)
                    {
                        throw new InvalidPluginExecutionException("The vessel" + vesselEnt["dia_name"] + " is empty");
                    }
                }


                #endregion
            }
        }
예제 #17
0
        public void Execute(IServiceProvider serviceProvider)
        {
            SqlDataAccess sda = null;

            sda = new SqlDataAccess();
            sda.openConnection(Globals.ConnectionString);

            try
            {
                #region | SERVICE |
                IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

                #region | Validate Request |
                //Target yoksa veya Entity tipinde değilse, devam etme.
                if (!context.InputParameters.Contains("Target") || !(context.InputParameters["Target"] is Entity))
                {
                    return;
                }
                #endregion

                IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);

                #endregion

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

                #region | CHECK DUPLICATE |
                if (entity.Attributes.Contains("name") && entity["name"] != null)
                {
                    if (entity["name"] != null)
                    {
                        string name = GeneralHelper.ToTitleCase(entity["name"].ToString());

                        MsCrmResult nameResult = AccountHelper.CheckDuplicateName(name, sda);
                        if (!nameResult.Success)
                        {
                            throw new Exception(nameResult.Result);
                        }

                        entity["name"] = name;
                    }
                }

                if (entity.Attributes.Contains("new_taxnumber") && entity["new_taxnumber"] != null)
                {
                    string taxNumber = entity["new_taxnumber"].ToString();

                    MsCrmResult taxResult = AccountHelper.CheckDuplicateTaxNumber(taxNumber, sda);
                    if (!taxResult.Success)
                    {
                        throw new Exception(taxResult.Result);
                    }
                }

                #endregion
            }
            catch (Exception ex)
            {
                throw new InvalidPluginExecutionException(ex.Message);
            }
            finally
            {
                if (sda != null)
                {
                    sda.closeConnection();
                }
            }
        }
예제 #18
0
파일: Audit.cs 프로젝트: ccellar/crmaudit
        public void Execute(IPluginExecutionContext context)
        {
            // Get a reference to the CRM Web Service & metadata service
            ICrmService crmService = context.CreateCrmService(true);
            IMetadataService metaData = context.CreateMetadataService(true);

            // Get the metadata about the current entity.
            var req = new RetrieveEntityRequest
            {
                EntityItems = EntityItems.IncludeAttributes,
                LogicalName = context.PrimaryEntityName
            };

            var res = (RetrieveEntityResponse)metaData.Execute(req);

            // Create the record & set it to the audit entity.
            var auditRecord = new DynamicEntity { Name = _mAuditEntity };

            // Set the Entity name, Message Type, Primary attribute value.
            auditRecord.Properties["custom_entity"] = context.PrimaryEntityName;
            auditRecord.Properties["custom_entity_label"] = res.EntityMetadata.DisplayName.UserLocLabel.Label;

            string primaryAttribute = GetValue(context, res.EntityMetadata.PrimaryField);

            if (string.IsNullOrEmpty(primaryAttribute))
            {
                if (context.PostEntityImages != null)
                {
                    if (context.PostEntityImages.Contains("Target"))
                    {
                        var de = (DynamicEntity)context.PostEntityImages["Target"];

                        if (de.Properties.Contains(res.EntityMetadata.PrimaryField))
                        {
                            primaryAttribute = de.Properties[res.EntityMetadata.PrimaryField].ToString();
                        }
                    }
                }

                // attribute was not in post image
                if (string.IsNullOrEmpty(primaryAttribute))
                {
                    if (context.PreEntityImages != null)
                    {
                        if (context.PreEntityImages.Contains("Target"))
                        {
                            var de = (DynamicEntity)context.PreEntityImages["Target"];

                            if (de.Properties.Contains(res.EntityMetadata.PrimaryField))
                            {
                                primaryAttribute = de.Properties[res.EntityMetadata.PrimaryField].ToString();
                            }
                        }
                    }
                }
            }

            if (!string.IsNullOrEmpty(primaryAttribute))
            {
                auditRecord.Properties["custom_primary_attribute"] = primaryAttribute;
            }

            //auditRecord.Properties["custom_primary_attribute"] = this.GetValue(context, res.EntityMetadata.PrimaryField);
            auditRecord.Properties["custom_message"] = context.MessageName;

            // Get the current object's id and save it for audit.
            Guid entityId = GetKeyValue(context, res.EntityMetadata.PrimaryKey);
            if (entityId != Guid.Empty)
                auditRecord.Properties["custom_entityid"] = entityId.ToString("D");

            // If the Audit entity has a relationship to the Primary entity, then populate the lookup key.
            if (!string.IsNullOrEmpty(_mLookupKey) && entityId != Guid.Empty)
                auditRecord.Properties[_mLookupKey] = new Lookup(context.PrimaryEntityName, entityId);

            // Create the audit record.
            Guid auditId = crmService.Create(auditRecord);

            // Process the modified records
            if (context.PostEntityImages.Contains(ParameterName.Target))
            {
                // Get a reference to the images.
                DynamicEntity pre;

                var post = (DynamicEntity)context.PostEntityImages[ParameterName.Target];

                // If the message is "Create" then dummy up a pre-image.
                if (context.MessageName == MessageName.Create)
                {
                    pre = new DynamicEntity();
                }
                else
                {
                    pre = (DynamicEntity)context.PreEntityImages[ParameterName.Target];
                }

                // Iterate through the entity's attributes to determine change.
                foreach (AttributeMetadata metaAttribute in res.EntityMetadata.Attributes)
                {
                    // Ensure the attribute is a parent level attribute.
                    if (metaAttribute.AttributeOf == null)
                    {
                        // Get the property objects
                        object preProp = GetObjectFromProperty(pre.Properties, metaAttribute.LogicalName);
                        object postProp = GetObjectFromProperty(post.Properties, metaAttribute.LogicalName);

                        // Ensure we have at least a pre/post property.
                        bool bProcess = (preProp != null);
                        if (!bProcess) bProcess = (postProp != null);

                        if (bProcess)
                        {
                            // Get the value of the properties
                            string preVal = CustomDynamicEntity.GetAttributeValue(preProp, true);
                            string postVal = CustomDynamicEntity.GetAttributeValue(postProp, true);

                            // Has the property changed?
                            if (preVal != postVal)
                            {
                                // Create an object for saving the changed detail.
                                var auditDetail = new DynamicEntity { Name = _mAuditDetailEntity };

                                auditDetail.Properties["custom_auditid"] = new Lookup(_mAuditEntity, auditId);

                                string displayName = metaAttribute.DisplayName.UserLocLabel != null ? metaAttribute.DisplayName.UserLocLabel.Label :
                                                                                           metaAttribute.LogicalName;

                                auditDetail.Properties["custom_display_name"] = displayName;
                                auditDetail.Properties["custom_schema_name"] = metaAttribute.LogicalName;

                                // Determine whether a value is too big for the value field.
                                bool bPreValueTooBig = false;
                                bool bPostValueTooBig = false;

                                // Evaluate too big for Pre Value.
                                if (preVal != null)
                                {
                                    if (preVal.Length > _mMaxLength)
                                    {
                                        bPreValueTooBig = true;
                                        auditDetail.Properties["custom_original_value"] = _mMsgTooBig;
                                    }
                                    else
                                        auditDetail.Properties["custom_original_value"] = preVal;
                                }

                                // Evaluate too big for Post Value.
                                if (postVal != null)
                                {
                                    if (postVal.Length > _mMaxLength)
                                    {
                                        bPostValueTooBig = true;
                                        auditDetail.Properties["custom_new_value"] = _mMsgTooBig;
                                    }
                                    else
                                        auditDetail.Properties["custom_new_value"] = postVal;
                                }

                                // Create the audit detail record.
                                Guid auditDetailId = crmService.Create(auditDetail);

                                // If the Post Value is too big, save it as a note.
                                if (bPostValueTooBig)
                                {
                                    const string cPostNoteToobigSubject = "Modified Value";
                                    CreateNote(crmService, _mAuditDetailEntity, auditDetailId, cPostNoteToobigSubject, postVal);
                                }

                                // If the Pre Value is too big, save it as a note.
                                if (bPreValueTooBig)
                                {
                                    const string cPreNoteToobigSubject = "Original Value";
                                    CreateNote(crmService, _mAuditDetailEntity, auditDetailId, cPreNoteToobigSubject, preVal);
                                }
                            }
                        }
                    }
                }
            }
        }
예제 #19
0
        protected override void ExecuteCrmPlugin(LocalPluginContext localContext)
        {
            if (localContext == null)
            {
                throw new ArgumentNullException("localContext");
            }
            localContext.TracingService.Trace("---------Triggered PreferenceCategoryCreate.cs---------");
            IPluginExecutionContext pluginExecutionContext = localContext.PluginExecutionContext;
            IOrganizationService    organizationService    = localContext.OrganizationService;

            if (pluginExecutionContext.Depth > 2)
            {
                localContext.TracingService.Trace("Context.depth > 2. Exiting Plugin.");
                return;
            }
            Entity queriedEntityRecord = null;
            string messageName         = pluginExecutionContext.MessageName;
            Entity entity           = null;
            Guid   initiatingUserId = pluginExecutionContext.InitiatingUserId;
            Entity entity2          = organizationService.Retrieve("systemuser", initiatingUserId, new ColumnSet("msnfp_configurationid"));

            if (entity2 == null)
            {
                throw new Exception("No user id found. Please ensure the user is valid. Exiting plugin.");
            }
            entity = Utilities.GetConfigurationRecordByUser(pluginExecutionContext, organizationService, localContext.TracingService);
            if (!pluginExecutionContext.InputParameters.Contains("Target"))
            {
                return;
            }
            if (pluginExecutionContext.InputParameters["Target"] is Entity)
            {
                localContext.TracingService.Trace("---------Entering PreferenceCategoryCreate.cs Main Function---------");
                localContext.TracingService.Trace("Message Name: " + messageName);
                Entity entity3 = (Entity)pluginExecutionContext.InputParameters["Target"];
                if (messageName == "Update")
                {
                    queriedEntityRecord = organizationService.Retrieve("msnfp_preferencecategory", entity3.Id, GetColumnSet());
                }
                if (entity3 != null)
                {
                    if (messageName == "Create")
                    {
                        AddOrUpdateThisRecordWithAzure(entity3, entity, localContext, organizationService, pluginExecutionContext);
                    }
                    else if (messageName == "Update")
                    {
                        AddOrUpdateThisRecordWithAzure(queriedEntityRecord, entity, localContext, organizationService, pluginExecutionContext);
                    }
                }
                else
                {
                    localContext.TracingService.Trace("Target record not found. Exiting workflow.");
                }
            }
            if (messageName == "Delete")
            {
                queriedEntityRecord = organizationService.Retrieve("msnfp_preferencecategory", ((EntityReference)pluginExecutionContext.InputParameters["Target"]).Id, GetColumnSet());
                AddOrUpdateThisRecordWithAzure(queriedEntityRecord, entity, localContext, organizationService, pluginExecutionContext);
            }
            localContext.TracingService.Trace("---------Exiting PreferenceCategoryCreate.cs---------");
        }
예제 #20
0
        public void Execute(IServiceProvider serviceProvider)
        {
            // サンドボックスのプラグインをデバッグするために tracing service を展開
            ITracingService tracingService =
                (ITracingService)serviceProvider.GetService(typeof(ITracingService));

            // サービスプロバイダーからプラグイン実行コンテキストを取得
            IPluginExecutionContext context = (IPluginExecutionContext)
                                              serviceProvider.GetService(typeof(IPluginExecutionContext));

            // InputParametersコレクションは、メッセージリクエストで渡されるすべてのデータを含む
            if (context.InputParameters.Contains("Target") &&
                context.InputParameters["Target"] is Entity)
            {
                // インプットパラメーターからターゲットエンティティを取得
                Entity entity = (Entity)context.InputParameters["Target"];

                // エンティティが意図したものであるかどうかを検証。もし違っていたらプラグインは正しく登録されていない。
                if (entity.LogicalName != "account")
                {
                    return;
                }

                // Web サービスをコールするための組織サービスへの参照を取得
                IOrganizationServiceFactory serviceFactory =
                    (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
                //IOrganizationService service = serviceFactory.CreateOrganizationService(new Guid("62B0C976-630B-E611-80F9-3863BB36AD30")); // 竹田 悠弥ユーザー

                try
                {
                    // ここにプラグインのビジネスロジックを記述する

                    // Early-bound の例
                    Task task1 = new Task();
                    task1.Subject     = "_タスクの件名です Early-bound";
                    task1.Description = "こちらはタスクの説明フィールドです。";
                    service.Create(task1);

                    // Late-bound の例
                    Entity task2 = new Entity("task");
                    task2["subject"]     = string.Format("_タスクの件名です Late-bound {0}{1}", unsecure, secure);
                    task2["description"] = "こちらはタスクの説明フィールドです。";
                    service.Create(task2);

                    //// Pre エンティティイメージからエンティティの情報を取得する
                    //// "Target"はプラグイン登録ツールでイメージの Entity Alias として指定した文字列
                    //tracingService.Trace("MyPlugin: PreEntityImages からエンティティの情報を取得");
                    //Entity preImage = (Entity)context.PreEntityImages["Target"];
                    //if (preImage.Attributes.Contains("name"))
                    //{
                    //    tracingService.Trace("MyPlugin: preImage name = {0}", preImage["name"]);
                    //}

                    //// Post エンティティイメージからエンティティの情報を取得する
                    //// "Target"はプラグイン登録ツールでイメージの Entity Alias として指定した文字列
                    //tracingService.Trace("MyPlugin: PostEntityImages からエンティティの情報を取得");
                    //Entity postImage = (Entity)context.PostEntityImages["Target"];
                    //if (postImage.Attributes.Contains("name"))
                    //{
                    //    tracingService.Trace("MyPlugin: postImage name = {0}", postImage["name"]);
                    //}

                    // 例外を発生させる
                    //throw new InvalidPluginExecutionException(
                    //    string.Format("レコード更新処理時のプラグインの処理中ステージ{0}で例外が発生しました。", context.Stage));
                }
                catch (FaultException <OrganizationServiceFault> ex)
                {
                    throw new InvalidPluginExecutionException("MyPlugin でエラーが発生しました。", ex);
                }
                catch (Exception ex)
                {
                    tracingService.Trace("MyPlugin: {0}", ex.ToString());
                    throw;
                }
            }
        }
예제 #21
0
        public Guid GetEntityId(IPluginExecutionContext context)
        {
            IMetadataService metaData = context.CreateMetadataService(true);

            return this.GetEntityId(context, metaData);
        }
예제 #22
0
        /// <summary>
        /// on Post Retrive
        /// </summary>
        /// <param name="context"></param>
        void CanSeeCurrentRecord(IPluginExecutionContext context, IOrganizationService service)
        {
            Entity entity = context.OutputParameters["BusinessEntity"] as Entity;

            //must be a caller id (UserId) and not InitiatingUserId
            // 1. the retrieve must be on caller id and not strong user (not register specific user on plugin
            // 2. and when we register  a Create Step on entity that's has secure field
            //we must grant a strong user to be on a plugin  for get from parent entity the field secure and set him on current entity
            if (entity != null)
            {
                TableRelationation tableRelation = TableRelationation.GetSinglton();
                if (tableRelation.Entities.Contains(entity.LogicalName.ToLower()))
                {
                    ConfigCaching configCaching = GetCacheConfig(service);
                    UsersTeam userteam = UsersTeam.GetSinglton(service, configCaching);
                    if (userteam.UsersPremission.Contains(context.UserId))
                        return;

                    if (entity.Attributes.Contains(General.SecureField))
                    {
                        bool canSee = entity.GetAttributeValue<bool>(General.SecureField);
                        if (canSee == true)
                            throw new InvalidPluginExecutionException("אינך מורשה לראות את הרשומה");
                    }
                }
            }
        }
예제 #23
0
        /// <summary>
        ///    AppendQueryExpression
        /// </summary>
        /// <param name="queryExpression"></param>
        /// <param name="context"></param>
        /// <param name="service"></param>
        /// <param name="tableRelation"></param>
        void AppendQueryExpression(QueryExpression queryExpression, IPluginExecutionContext context, IOrganizationService service, TableRelationation tableRelation)
        {
            ConfigCaching configCaching = GetCacheConfig(service);
            UsersTeam userteam = UsersTeam.GetSinglton(service, configCaching);

            //if (userteam.UsersPremission.Contains(context.InitiatingUserId))
            //    return;
            if (userteam.UsersPremission.Contains(context.InitiatingUserId))
            {
                if (queryExpression.EntityName.ToLower() == TableRelationation.INCIDENT)
                {
                    var filter = queryExpression.Criteria;
                    RemoveSecureFilter(filter);
                    return;
                }
                else
                    return;
            }
            if (queryExpression.EntityName == TableRelationation.ACTIVITYPOINTER)
            {
                AppendAllActivities(queryExpression, tableRelation);
                return;
            }

            if (tableRelation.Entities.Contains(queryExpression.EntityName.ToLower()))
            {
                var filter = queryExpression.Criteria;
                AppendFilter(filter);
            }
        }
 protected abstract bool IsContextValid(IPluginExecutionContext context);
예제 #25
0
        public void Execute(IServiceProvider serviceProvider)
        {
            try
            {
                IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
                if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
                {
                    ITracingService             trace          = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
                    IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                    IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);
                    if (context.MessageName.ToLower() != "create" && context.Stage == 20)
                    {
                        return;
                    }

                    Entity        targetentity = context.InputParameters["Target"] as Entity;
                    Entity        updateAutoNumberConfig = new Entity("app_app_autonumberconfiguration"); //entity custom untuk autonumber
                    StringBuilder autoNumber = new StringBuilder();
                    string        prefix, suffix, separator, current, yeaar, month, day;
                    DateTime      today = DateTime.Now;
                    day   = today.Day.ToString("00");
                    month = today.Month.ToString("00");
                    yeaar = today.Year.ToString();
                    QueryExpression qeAutoNumberConfig = new QueryExpression()
                    {
                        EntityName = "app_app_autonumberconfiguration", //entity custom untuk autonumber
                        ColumnSet  = new ColumnSet("app_prefix", "app_suffix", "app_separator", "app_currentnumber", "app_name")
                    };
                    EntityCollection ecAutoNumberConfig = service.RetrieveMultiple(qeAutoNumberConfig);
                    if (ecAutoNumberConfig.Entities.Count == 0)
                    {
                        return;
                    }

                    foreach (Entity entity in ecAutoNumberConfig.Entities)
                    {
                        if (entity.Attributes["app_name"].ToString().ToLower() == "applicationAutoNumber")
                        {
                            ;                                                                               //field pada entity autonumber
                        }
                        {
                            prefix    = entity.GetAttributeValue <string>("app_prefix");
                            suffix    = entity.GetAttributeValue <string>("app_suffix");
                            separator = entity.GetAttributeValue <string>("app_separator");
                            current   = entity.GetAttributeValue <string>("app_currentnumber");
                            int tempCurrent = int.Parse(current);
                            tempCurrent++;
                            current = tempCurrent.ToString("000000");
                            updateAutoNumberConfig.Id = entity.Id;
                            updateAutoNumberConfig["app_currentnumber"] = tempCurrent.ToString();
                            service.Update(updateAutoNumberConfig);
                            autoNumber.Append(prefix + separator + yeaar + month + day + separator + suffix + current);
                            break;
                        }
                    }

                    targetentity["app_idrent"] = autoNumber.ToString(); //field target pada entity tujuan
                }
            }

            catch (Exception ex)
            {
                throw new InvalidCastException(ex.Message);
            }
        }
 /// <summary>
 /// To assign plugin parameters of context, service and trace
 /// </summary>
 /// <param name="context"></param>
 /// <param name="trace"></param>
 /// <param name="service"></param>
 private void AssignPluginParameters(IPluginExecutionContext context, ITracingService trace, IOrganizationService service)
 {
     this.context = context;
     this.service = service;
     this.trace   = trace;
 }
예제 #27
0
        public void SecretSecureActivityPointer(IPluginExecutionContext context, IOrganizationService service)
        {
            if (!context.OutputParameters.Contains("BusinessEntityCollection"))
                return;

            EntityCollection results = (EntityCollection)context.OutputParameters["BusinessEntityCollection"];
            if (results != null && results.Entities != null && results.Entities.Count > 0)
            {
                if (results.EntityName != TableRelationation.ACTIVITYPOINTER) return;

                ConfigCaching configCaching = GetCacheConfig(service);
                UsersTeam userteam = UsersTeam.GetSinglton(service, configCaching);

                if (userteam.UsersPremission.Contains(context.InitiatingUserId))
                    return;

                TableRelationation tableRelation = TableRelationation.GetSinglton();
                foreach (Entity entity in results.Entities)
                {
                    bool isSecure = false;
                    AliasedValue aliasValue = null;
                    foreach (var activityName in tableRelation.Activities)
                    {
                        var aliasName = TableRelationation.PERFIX_ALIAS + activityName + TableRelationation.DOT_ALIAS + General.SecureField;
                        if (entity.Attributes.Contains(aliasName))
                        {
                            aliasValue = entity.GetAttributeValue<AliasedValue>(aliasName);
                            isSecure = aliasValue != null && aliasValue.Value is bool ? (bool)aliasValue.Value : false;
                            break;
                        }
                    }

                    if (isSecure)
                    {
                        if (entity.Attributes.Contains("subject"))
                            entity.Attributes["subject"] = General.SecretField;

                        if (entity.Attributes.Contains("description"))
                            entity.Attributes["description"] = General.SecretField;

                        if (entity.GetAttributeValue<EntityReference>("regardingobjectid") != null)
                            ((EntityReference)entity["regardingobjectid"]).Name = General.SecretField;

                        if (entity.GetAttributeValue<DateTime?>("actualend") != null)
                            entity.Attributes["actualend"] = null;

                        if (entity.GetAttributeValue<DateTime?>("actualstart") != null)
                            entity.Attributes["actualstart"] = null;

                        if (entity.GetAttributeValue<EntityReference>("ownerid") != null)
                            entity["ownerid"] = null;
                    }
                    //   secureTemp.Add(e);
                    //results.Entities.Remove(e);
                }
                //foreach(var secure in secureTemp)
                //{
                //     results.Entities.Remove(secure);
                //}
            }
        }
예제 #28
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="context"></param>
 /// <returns></returns>
 public bool IsValidEntity(IPluginExecutionContext context)
 {
     return(context.PrimaryEntityName == EntityName);
 }
예제 #29
0
        public Guid GetKeyValue(IPluginExecutionContext context, string keyName)
        {
            string val = this.GetValue(context, keyName);

            return val != null ? new Guid(val) : Guid.Empty;
        }
예제 #30
0
        ////This Plugin will fire on Work order pre Create. it will map all the Required Fields from the Service Request.
        public void UpdateProblemTypeDescription(LocalPluginContext localContext)
        {
            try
            {
                IPluginExecutionContext context        = localContext.PluginExecutionContext;
                ITracingService         tracingService = localContext.TracingService;
                IOrganizationService    service        = localContext.OrganizationService;
                if (context.Depth > 2)
                {
                    return;
                }
                if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
                {
                    Entity target = context.InputParameters["Target"] as Entity;
                    if (target.Attributes.Contains("smp_requestorid") || target.Attributes.Contains("smp_requestoremail") || target.Attributes.Contains("smp_requestorphone") || target.Attributes.Contains("smp_contact") || target.Attributes.Contains("smp_contactphone") || target.Attributes.Contains("smp_contactemail") || target.Attributes.Contains("smp_requestedduedate") || target.Attributes.Contains("smp_problemtypedescription") || target.Attributes.Contains("smp_iocode") || target.Attributes.Contains("smp_costcentercode"))
                    {
                        QueryExpression exp = new QueryExpression("msdyn_workorder");
                        exp.ColumnSet = new ColumnSet("msdyn_workorderid");
                        exp.Criteria.AddFilter(LogicalOperator.Or);
                        exp.Criteria.AddCondition("msdyn_servicerequest", ConditionOperator.Equal, target.Id);
                        EntityCollection existedWorkorders = service.RetrieveMultiple(exp);
                        if (existedWorkorders.Entities != null && existedWorkorders.Entities.Count > 0)
                        {
                            foreach (Entity workorder in existedWorkorders.Entities)
                            {
                                if (target.Attributes.Contains("smp_problemtypedescription"))
                                {
                                    workorder.Attributes.Add("msdyn_workordersummary", target.GetAttributeValue <string>("smp_problemtypedescription"));
                                }

                                if (target.Attributes.Contains("smp_iocode"))
                                {
                                    workorder.Attributes.Add("smp_iocode", target.GetAttributeValue <string>("smp_iocode"));
                                }

                                if (target.Attributes.Contains("smp_costcentercode"))
                                {
                                    workorder.Attributes.Add("smp_costcentercode", target.GetAttributeValue <string>("smp_costcentercode"));
                                }

                                if (target.Attributes.Contains("smp_requestedduedate"))
                                {
                                    workorder.Attributes.Add("msdyn_datewindowend", target.GetAttributeValue <DateTime>("smp_requestedduedate"));
                                }

                                if (target.Attributes.Contains("smp_contactphone"))
                                {
                                    workorder.Attributes.Add("smp_contactphonenumber", target.GetAttributeValue <string>("smp_contactphone"));
                                }

                                if (target.Attributes.Contains("smp_contactemail"))
                                {
                                    workorder.Attributes.Add("smp_contactemail", target.GetAttributeValue <string>("smp_contactemail"));
                                }

                                if (target.Attributes.Contains("smp_contact"))
                                {
                                    workorder.Attributes.Add("msdyn_reportedbycontact", target.GetAttributeValue <EntityReference>("smp_contact"));
                                }

                                if (target.Attributes.Contains("smp_requestorphone"))
                                {
                                    workorder.Attributes.Add("smp_requestorphonenumber", target.GetAttributeValue <string>("smp_requestorphone"));
                                }

                                if (target.Attributes.Contains("smp_requestoremail"))
                                {
                                    workorder.Attributes.Add("smp_requestoremail", target.GetAttributeValue <string>("smp_requestoremail"));
                                }

                                if (target.Attributes.Contains("smp_requestorid"))
                                {
                                    workorder.Attributes.Add("smp_requestorname", target.GetAttributeValue <EntityReference>("smp_requestorid"));
                                }

                                service.Update(workorder);
                            }
                        }
                    }
                }
            }
            catch (FaultException <OrganizationServiceFault> ex)
            {
                throw new Exception(ex.Message);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
예제 #31
0
        private void DeleteMethod(IPluginExecutionContext context, IOrganizationService service)
        {
            bool _havePlan = false;
            Entity _correntEntity;

            using (var orgContext = new OrganizationServiceContext(service))
            {
                _correntEntity = (Entity)context.PreEntityImages["Pre"];
                new_purchase_order _proxyentity = _correntEntity.ToEntity<new_purchase_order>();
                if (_proxyentity.new_cropid == null || _proxyentity.new_volume == null || _proxyentity.new_volume.Value == 0 || _proxyentity.new_approve_purchase_order == false || _proxyentity.new_yearid == null)
                    return;

                _havePlan = _proxyentity.new_line_planningid == null ? false : true;

                EntityReference _planingToUpdate = FindPlaning(orgContext, _proxyentity.new_cropid, _proxyentity.new_yearid);

                if (_planingToUpdate != null)
                {
                    double? _sumOfVolume = (from i in orgContext.CreateQuery<new_purchase_order>()
                                            where i.new_cropid.Id == _proxyentity.new_cropid.Id &&
                                            i.new_yearid.Id == _proxyentity.new_yearid.Id &&
                                            i.new_status != new OptionSetValue(100000002) &&
                                            i.new_approve_purchase_order == true
                                            select i.new_volume).ToList().Sum();

                    _sumOfVolume = _sumOfVolume - _proxyentity.new_volume;

                    new_line_purchase_planning _UpdatePlan = new new_line_purchase_planning()
                    {
                        Id = _planingToUpdate.Id,
                        new_total_volume_tn = _sumOfVolume
                    };

                    List<new_port> _portList = (from port in orgContext.CreateQuery<new_port>()
                                                where port.new_name == "Одеса" ||
                                                port.new_name == "Миколаїв"
                                                select port).ToList();

                    foreach (var item in _portList)
                    {
                        double? _sumOfVolumeFromPort = (from i in orgContext.CreateQuery<new_purchase_order>()
                                                        where i.new_cropid.Id == _proxyentity.new_cropid.Id &&
                                                        i.new_yearid.Id == _proxyentity.new_yearid.Id &&
                                                        i.new_status != new OptionSetValue(100000002) &&
                                                        i.new_portid.Id == item.Id &&
                                            i.new_approve_purchase_order == true
                                                        select i.new_volume).ToList().Sum();
                        if (item.new_name == "Одеса")
                        {
                            _UpdatePlan.new_volume_Odesa = _sumOfVolumeFromPort;
                        }
                        else if (item.new_name == "Миколаїв")
                        {
                            _UpdatePlan.new_volume_Mykolaiv = _sumOfVolumeFromPort;
                        }
                    }

                    service.Update(_UpdatePlan);
                }
            }
        }
예제 #32
0
        /// <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 ExecutePostCommittedFirmOrderUpdate(LocalPluginContext localContext)
        {
            if (localContext == null)
            {
                throw new ArgumentNullException("localContext");
            }

            IPluginExecutionContext context = localContext.PluginExecutionContext;

            Entity preImageEntity  = (context.PreEntityImages != null && context.PreEntityImages.Contains(this.preImageAlias)) ? context.PreEntityImages[this.preImageAlias] : null;
            Entity postImageEntity = (context.PostEntityImages != null && context.PostEntityImages.Contains(this.postImageAlias)) ? context.PostEntityImages[this.postImageAlias] : null;

            IOrganizationService service = localContext.OrganizationService;
            ITracingService      trace   = localContext.TracingService;

            if (!(context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity))
            {
                return;
            }

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

            if (cfoEntity.LogicalName != "gsc_sls_committedfirmorder")
            {
                return;
            }

            if (context.Mode == 0) //Synchronous Plugin
            {
                try
                {
                    CommittedFirmOrderHandler cfoHandler = new CommittedFirmOrderHandler(service, trace);

                    var preBaseModelId = preImageEntity.GetAttributeValue <EntityReference>("gsc_vehiclebasemodelid") != null
                        ? preImageEntity.GetAttributeValue <EntityReference>("gsc_vehiclebasemodelid").Id
                        : Guid.Empty;

                    var preProdId = preImageEntity.GetAttributeValue <EntityReference>("gsc_productid") != null
                        ? preImageEntity.GetAttributeValue <EntityReference>("gsc_productid").Id
                        : Guid.Empty;

                    var preColorId = preImageEntity.GetAttributeValue <EntityReference>("gsc_vehiclecolorid") != null
                        ? preImageEntity.GetAttributeValue <EntityReference>("gsc_vehiclecolorid").Id
                        : Guid.Empty;

                    var preDealerId = preImageEntity.GetAttributeValue <EntityReference>("gsc_dealerfilterid") != null
                        ? preImageEntity.GetAttributeValue <EntityReference>("gsc_dealerfilterid").Id
                        : Guid.Empty;

                    var preBranchId = preImageEntity.GetAttributeValue <EntityReference>("gsc_branchfilterid") != null
                        ? preImageEntity.GetAttributeValue <EntityReference>("gsc_branchfilterid").Id
                        : Guid.Empty;

                    var preSiteId = preImageEntity.GetAttributeValue <EntityReference>("gsc_siteid") != null
                        ? preImageEntity.GetAttributeValue <EntityReference>("gsc_siteid").Id
                        : Guid.Empty;

                    var preGenerate = preImageEntity.GetAttributeValue <Boolean>("gsc_generatecfoquantity");


                    var postBaseModelId = postImageEntity.GetAttributeValue <EntityReference>("gsc_vehiclebasemodelid") != null
                        ? postImageEntity.GetAttributeValue <EntityReference>("gsc_vehiclebasemodelid").Id
                        : Guid.Empty;

                    var postProdId = postImageEntity.GetAttributeValue <EntityReference>("gsc_productid") != null
                        ? postImageEntity.GetAttributeValue <EntityReference>("gsc_productid").Id
                        : Guid.Empty;

                    var postColorId = postImageEntity.GetAttributeValue <EntityReference>("gsc_vehiclecolorid") != null
                        ? postImageEntity.GetAttributeValue <EntityReference>("gsc_vehiclecolorid").Id
                        : Guid.Empty;

                    var postDealerId = postImageEntity.GetAttributeValue <EntityReference>("gsc_dealerfilterid") != null
                        ? postImageEntity.GetAttributeValue <EntityReference>("gsc_dealerfilterid").Id
                        : Guid.Empty;

                    var postBranchId = postImageEntity.GetAttributeValue <EntityReference>("gsc_branchfilterid") != null
                        ? postImageEntity.GetAttributeValue <EntityReference>("gsc_branchfilterid").Id
                        : Guid.Empty;

                    var postSiteId = postImageEntity.GetAttributeValue <EntityReference>("gsc_siteid") != null
                        ? postImageEntity.GetAttributeValue <EntityReference>("gsc_siteid").Id
                        : Guid.Empty;

                    var postGenerate = postImageEntity.GetAttributeValue <Boolean>("gsc_generatecfoquantity");


                    if (preBaseModelId != postBaseModelId || preProdId != postProdId || preColorId != postColorId)
                    {
                        cfoHandler.DeleteSuggestedCFODetails(postImageEntity);
                        cfoHandler.SuggestCFOQuantity(postImageEntity);
                    }

                    if (preGenerate != postGenerate)
                    {
                        cfoHandler.GenerateCFOQuantity(postImageEntity);
                    }
                }

                catch (Exception ex)
                {
                    throw new InvalidPluginExecutionException(ex.Message);
                }
            }
        }
예제 #33
0
        private void UpdateMethod(IPluginExecutionContext context, IOrganizationService service)
        {
            //Проверяем статус на анульовано и удаляем количество с общего плана
            if (WillChangeStatus(context, service))
            {
                return;
            }

            bool _havePlan = false;
            Entity _correntEntity;

            using (var orgContext = new OrganizationServiceContext(service))
            {
                _correntEntity = (Entity)context.PostEntityImages["Post"];
                new_purchase_order _proxyentity = _correntEntity.ToEntity<new_purchase_order>();
                if (_proxyentity.new_cropid == null || _proxyentity.new_volume == null || _proxyentity.new_volume.Value == 0 || _proxyentity.new_approve_purchase_order == false || _proxyentity.new_yearid == null)
                    return;

                _havePlan = _proxyentity.new_line_planningid == null ? false : true;

                EntityReference _planingToUpdate = FindPlaning(orgContext, _proxyentity.new_cropid, _proxyentity.new_yearid);

                if (_planingToUpdate != null)
                {
                    double? _sumOfVolume = (from i in orgContext.CreateQuery<new_purchase_order>()
                                            where i.new_cropid.Id == _proxyentity.new_cropid.Id &&
                                            i.new_yearid.Id == _proxyentity.new_yearid.Id &&
                                            i.new_status != new OptionSetValue(100000002) &&
                                            i.new_approve_purchase_order == true
                                            select i.new_volume).ToList().Sum();

                    new_line_purchase_planning _UpdatePlan = new new_line_purchase_planning()
                    {
                        Id = _planingToUpdate.Id,
                        new_total_volume_tn = _sumOfVolume
                    };

                    List<new_port> _portList = (from port in orgContext.CreateQuery<new_port>()
                                                where port.new_name == "Одеса" ||
                                                port.new_name == "Миколаїв"
                                                select port).ToList();

                    foreach (var item in _portList)
                    {
                        double? _sumOfVolumeFromPort = (from i in orgContext.CreateQuery<new_purchase_order>()
                                                        where i.new_cropid.Id == _proxyentity.new_cropid.Id &&
                                                        i.new_yearid.Id == _proxyentity.new_yearid.Id &&
                                                        i.new_status != new OptionSetValue(100000002) &&
                                                        i.new_portid.Id == item.Id &&
                                            i.new_approve_purchase_order == true
                                                        select i.new_volume).ToList().Sum();
                        if (item.new_name == "Одеса")
                        {
                            _UpdatePlan.new_volume_Odesa = _sumOfVolumeFromPort;
                        }
                        else if (item.new_name == "Миколаїв")
                        {
                            _UpdatePlan.new_volume_Mykolaiv = _sumOfVolumeFromPort;
                        }
                    }

                    service.Update(_UpdatePlan);
                }
                else
                {
                    double? _sumOfVolume = (from i in orgContext.CreateQuery<new_purchase_order>()
                                            where i.new_cropid.Id == _proxyentity.new_cropid.Id &&
                                            i.new_status != new OptionSetValue(100000002)
                                            select i.new_volume).ToList().Sum();

                    new_line_purchase_planning _createPlan = new new_line_purchase_planning()
                    {
                        new_total_volume_tn = _sumOfVolume,
                        new_cropid = _proxyentity.new_cropid,
                        new_planningid = _proxyentity.new_yearid
                    };

                    List<new_port> _portList = (from port in orgContext.CreateQuery<new_port>()
                                                where port.new_name == "Одеса" ||
                                                port.new_name == "Миколаїв"
                                                select port).ToList();

                    foreach (var item in _portList)
                    {
                        double? _sumOfVolumeFromPort = (from i in orgContext.CreateQuery<new_purchase_order>()
                                                        where i.new_cropid.Id == _proxyentity.new_cropid.Id &&
                                                        i.new_yearid.Id == _proxyentity.new_yearid.Id &&
                                                        i.new_status != new OptionSetValue(100000002) &&
                                                        i.new_portid.Id == item.Id &&
                                                        i.new_approve_purchase_order == true
                                                        select i.new_volume).ToList().Sum();

                        if (item.new_name == "Одеса")
                        {
                            _createPlan.new_volume_Odesa = _sumOfVolumeFromPort;
                        }
                        else if (item.new_name == "Миколаїв")
                        {
                            _createPlan.new_volume_Mykolaiv = _sumOfVolumeFromPort;
                        }
                    }

                    Guid _newRecordId = service.Create(_createPlan);
                    _proxyentity.new_line_planningid = new EntityReference() { Id = _newRecordId, LogicalName = new_line_purchase_planning.EntityLogicalName };
                }
            }
        }
예제 #34
0
 protected abstract void ExecuteInternal(IPluginExecutionContext context, IOrganizationServiceFactory orgServiceFactory, ITracingService tracingService);
예제 #35
0
        private bool WillChangeStatus(IPluginExecutionContext context, IOrganizationService service)
        {
            var _pre = (Entity)context.PreEntityImages["Pre"];
            var _post = (Entity)context.PostEntityImages["Post"];

            if (_pre.GetAttributeValue<OptionSetValue>("new_staus")?.Value == _post.GetAttributeValue<OptionSetValue>("new_staus")?.Value)
            {
                //Status  небыл обновлен
                return false;
            }
            else if
               (_pre.GetAttributeValue<OptionSetValue>("new_staus")?.Value != _post.GetAttributeValue<OptionSetValue>("new_staus")?.Value &&
               _post.GetAttributeValue<OptionSetValue>("new_staus")?.Value == 100000002)
            {
                DeleteMethod(context, service);
                return true;
            }
            else
            {
                return false;
            }
        }
예제 #36
0
        protected override void ExecuteCrmPlugin(LocalPluginContext localContext)
        {
            if (localContext == null)
            {
                throw new ArgumentNullException("localContext");
            }
            localContext.TracingService.Trace("---------Triggered TributeOrMemoryUpdate.cs---------");
            IPluginExecutionContext    pluginExecutionContext     = localContext.PluginExecutionContext;
            IOrganizationService       organizationService        = localContext.OrganizationService;
            OrganizationServiceContext organizationServiceContext = new OrganizationServiceContext(organizationService);

            if (pluginExecutionContext.Depth > 1)
            {
                localContext.TracingService.Trace("Context.depth > 1 => Exiting Plugin. context.Depth: " + pluginExecutionContext.Depth);
                return;
            }
            string messageName = pluginExecutionContext.MessageName;
            Entity configurationRecordByUser = Utilities.GetConfigurationRecordByUser(pluginExecutionContext, organizationService, localContext.TracingService);
            Entity entity = null;

            if (!pluginExecutionContext.InputParameters.Contains("Target") || !(pluginExecutionContext.InputParameters["Target"] is Entity))
            {
                return;
            }
            entity = (Entity)pluginExecutionContext.InputParameters["Target"];
            if (entity == null)
            {
                throw new InvalidPluginExecutionException("'Target' is null. Exiting plugin.");
            }
            if (entity.GetAttributeValue <EntityReference>("msnfp_duplicatetributeid") == null)
            {
                return;
            }
            EntityReference  attributeValue   = entity.GetAttributeValue <EntityReference>("msnfp_duplicatetributeid");
            QueryByAttribute queryByAttribute = new QueryByAttribute("msnfp_transaction");

            queryByAttribute.AddAttributeValue("msnfp_tributeid", attributeValue.Id);
            queryByAttribute.ColumnSet = new ColumnSet("msnfp_transactionid");
            EntityCollection entityCollection = organizationService.RetrieveMultiple(queryByAttribute);

            if (entityCollection != null && entityCollection.Entities != null)
            {
                localContext.TracingService.Trace("Found " + entityCollection.Entities.Count + " Transactions for Duplicate Tribute.");
                foreach (Entity entity4 in entityCollection.Entities)
                {
                    localContext.TracingService.Trace("Updating Transaction:" + entity4.Id.ToString());
                    entity4["msnfp_tributeid"] = new EntityReference(entity.LogicalName, entity.Id);
                    organizationService.Update(entity4);
                    localContext.TracingService.Trace("Transaction Updated.");
                }
            }
            Entity entity2 = new Entity(attributeValue.LogicalName, attributeValue.Id);

            entity2["statecode"]  = new OptionSetValue(1);
            entity2["statuscode"] = new OptionSetValue(2);
            organizationService.Update(entity2);
            Entity entity3 = new Entity(entity.LogicalName, entity.Id);

            entity3["msnfp_duplicatetributeid"] = null;
            organizationService.Update(entity3);
            localContext.TracingService.Trace("Cleared Duplicate Field");
        }
예제 #37
0
        private void CreateMethod(IPluginExecutionContext context, IOrganizationService service)
        {
            try
            {
                bool _havePlan = false;
                Entity _correntEntity;

                using (var orgContext = new OrganizationServiceContext(service))
                {
                    _correntEntity = (Entity)context.InputParameters["Target"];
                    new_purchase_order _proxyentity = _correntEntity.ToEntity<new_purchase_order>();
                    if (_proxyentity.new_cropid == null || _proxyentity.new_volume == null || _proxyentity.new_volume.Value == 0 ||
                        _proxyentity.new_approve_purchase_order != false || _proxyentity.new_yearid == null)
                    {
                        return;
                    }

                    _havePlan = _proxyentity.new_line_planningid == null ? false : true;

                    EntityReference _planingToUpdate = FindPlaning(orgContext, _proxyentity.new_cropid, _proxyentity.new_yearid);

                    if (_planingToUpdate != null)
                    {
                        double? _sumOfVolume = (from i in orgContext.CreateQuery<new_purchase_order>()
                                                where i.new_cropid.Id == _proxyentity.new_cropid.Id &&
                                                i.new_yearid.Id == _proxyentity.new_yearid.Id &&
                                                i.new_status != new OptionSetValue(100000002) &&
                                                i.new_approve_purchase_order == true
                                                select i.new_volume).ToList().Sum();

                        new_line_purchase_planning _UpdatePlan = new new_line_purchase_planning()
                        {
                            Id = _planingToUpdate.Id,
                            new_total_volume_tn = _sumOfVolume
                        };

                        List<new_port> _portList = (from port in orgContext.CreateQuery<new_port>()
                                                    where port.new_name == "Одеса" ||
                                                    port.new_name == "Миколаїв"
                                                    select port).ToList();

                        foreach (var item in _portList)
                        {
                            double? _sumOfVolumeFromPort = (from i in orgContext.CreateQuery<new_purchase_order>()
                                                            where i.new_cropid.Id == _proxyentity.new_cropid.Id &&
                                                            i.new_yearid.Id == _proxyentity.new_yearid.Id &&
                                                            i.new_status != new OptionSetValue(100000002) &&
                                                            i.new_portid.Id == item.Id &&
                                                            i.new_approve_purchase_order == true
                                                            select i.new_volume).ToList().Sum();
                            if (item.new_name == "Одеса")
                            {
                                _UpdatePlan.new_volume_Odesa = _sumOfVolumeFromPort;
                            }
                            else if (item.new_name == "Миколаїв")
                            {
                                _UpdatePlan.new_volume_Mykolaiv = _sumOfVolumeFromPort;
                            }
                        }

                        service.Update(_UpdatePlan);

                        _proxyentity.new_line_planningid = new EntityReference() { Id = _UpdatePlan.Id, LogicalName = new_line_purchase_planning.EntityLogicalName };
                    }
                    else
                    {
                        double? _sumOfVolume = (from i in orgContext.CreateQuery<new_purchase_order>()
                                                where i.new_cropid.Id == _proxyentity.new_cropid.Id &&
                                                i.new_status != new OptionSetValue(100000002)
                                                select i.new_volume).ToList().Sum();

                        new_line_purchase_planning _createPlan = new new_line_purchase_planning()
                        {
                            new_total_volume_tn = _sumOfVolume,
                            new_cropid = _proxyentity.new_cropid,
                            new_planningid = _proxyentity.new_yearid
                        };

                        List<new_port> _portList = (from port in orgContext.CreateQuery<new_port>()
                                                    where port.new_name == "Одеса" ||
                                                    port.new_name == "Миколаїв"
                                                    select port).ToList();

                        foreach (var item in _portList)
                        {
                            double? _sumOfVolumeFromPort = (from i in orgContext.CreateQuery<new_purchase_order>()
                                                            where i.new_cropid.Id == _proxyentity.new_cropid.Id &&
                                                            i.new_yearid.Id == _proxyentity.new_yearid.Id &&
                                                            i.new_status != new OptionSetValue(100000002) &&
                                                            i.new_portid.Id == item.Id &&
                                                            i.new_approve_purchase_order == true
                                                            select i.new_volume).ToList().Sum();

                            if (item.new_name == "Одеса")
                            {
                                _createPlan.new_volume_Odesa = _sumOfVolumeFromPort;
                            }
                            else if (item.new_name == "Миколаїв")
                            {
                                _createPlan.new_volume_Mykolaiv = _sumOfVolumeFromPort;
                            }
                        }

                        Guid _newRecordId = service.Create(_createPlan);
                        _proxyentity.new_line_planningid = new EntityReference() { Id = _newRecordId, LogicalName = new_line_purchase_planning.EntityLogicalName };
                    }
                }
            }
            catch (Exception ex)
            {
                throw new InvalidPluginExecutionException(ex.Message);
            }
        }
예제 #38
0
파일: PreUpdate.cs 프로젝트: volkanytu/NEF
        public void Execute(IServiceProvider serviceProvider)
        {
            SqlDataAccess sda = null;

            sda = new SqlDataAccess();
            sda.openConnection(Globals.ConnectionString);

            #region | SERVICE |
            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

            #region | Validate Request |
            //Target yoksa veya Entity tipinde değilse, devam etme.
            if (!context.InputParameters.Contains("Target") || !(context.InputParameters["Target"] is Entity))
            {
                return;
            }
            #endregion

            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService        service        = serviceFactory.CreateOrganizationService(Globals.AdministratorId);

            #region |DEFINE IMAGE IF EXISTS|
            Entity preImage = null;

            if (context.PreEntityImages.Contains("PreImage") && context.PreEntityImages["PreImage"] is Entity)
            {
                preImage = (Entity)context.PreEntityImages["PreImage"];
            }
            #endregion

            #endregion
            Entity entity = (Entity)context.InputParameters["Target"];
            try
            {
                if (entity.Attributes.Contains("new_issendingapproval"))
                {
                    if (entity.GetAttributeValue <bool>("new_issendingapproval"))
                    {
                        EntityReference currency  = preImage.Attributes.Contains("transactioncurrencyid") && preImage["transactioncurrencyid"] != null ? (EntityReference)preImage["transactioncurrencyid"] : null;
                        EntityReference projectId = preImage.Attributes.Contains("new_projectid") && preImage["new_projectid"] != null ? (EntityReference)preImage["new_projectid"] : null;


                        MsCrmResultObject productResult = RentalHelper.GetRentalProducts(entity.Id, sda);
                        if (productResult.Success)
                        {
                            //Ürün alındı
                            Product product = ((List <Product>)productResult.ReturnObject)[0];
                            //Rule alındı
                            RentalControlSetting control = ProductHelper.GetRentalControlSettingByProject(product.Project.Id, sda);
                            //Kiralama tutarı alındı
                            decimal rentalAmount = preImage.GetAttributeValue <Money>("new_rentalfee").Value;
                            if (control.RentalControlSettingId != Guid.Empty)
                            {
                                if (control.ConsultantRate != null)
                                {
                                    if (control.ConsultantRate != decimal.MaxValue)
                                    {
                                        decimal rate    = (product.PaymentOfHire.Value * (control.ConsultantRate.Value / 100));
                                        decimal minRate = product.PaymentOfHire.Value - rate;
                                        decimal maxRate = product.PaymentOfHire.Value + rate;

                                        if (rentalAmount >= minRate && rentalAmount <= maxRate)
                                        {
                                            //Opsiyona takılmaz.
                                            Entity ent = new Entity("product");
                                            ent.Id = product.ProductId;
                                            ent["new_usedrentalandsalesstatus"] = new OptionSetValue(4);               //Kiralandı.
                                            service.Update(ent);
                                            entity["statuscode"] = new OptionSetValue((int)RentalStatuses.Tamamlandi); //Kiralama Durumu
                                        }
                                        else
                                        {
                                            //Ürün kiralama opsiyonlu
                                            //Onaya gönder
                                            Entity ent = new Entity("product");
                                            ent.Id = product.ProductId;
                                            ent["new_usedrentalandsalesstatus"] = new OptionSetValue(3);                   //konut durumu kiralama opsiyonlu
                                            service.Update(ent);
                                            entity["statuscode"] = new OptionSetValue((int)RentalStatuses.OnayBekleniyor); //Kiralama Durumu
                                            MsCrmResult mailResult = RentalHelper.SendMailRentalToApproval(product, preImage, UserTypes.IkinciElSatisDirektoru, sda, service);
                                            if (!mailResult.Success)
                                            {
                                                throw new Exception(mailResult.Result);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new InvalidPluginExecutionException(ex.Message + ex.StackTrace);
            }
            finally
            {
                if (sda != null)
                {
                    sda.closeConnection();
                }
            }
        }
예제 #39
0
        public void Execute(IServiceProvider serviceProvider)
        {
            // Extract the tracing service for use in debugging sandboxed plug-ins.
            // If you are not registering the plug-in in the sandbox, then you do
            // not have to add any tracing service related code.
            ITracingService tracingService =
                (ITracingService)serviceProvider.GetService(typeof(ITracingService));

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

            // Obtain the organization service reference which you will need for
            // web service calls.
            IOrganizationServiceFactory serviceFactory =
                (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService service = serviceFactory.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 contact = (Entity)context.InputParameters["Target"];


                try
                {
                    // Plug-in business logic goes here.
                    string email = string.Empty;

                    if (contact.Attributes.Contains("emailaddress1"))
                    {
                        email = contact.Attributes["emailaddress1"].ToString();

                        // select * from contact where emailaddress1 == 'email'

                        QueryExpression query = new QueryExpression("contact");
                        query.ColumnSet = new ColumnSet(new string[] { "emailaddress1" });
                        query.Criteria.AddCondition("emailaddress1", ConditionOperator.Equal, email);

                        EntityCollection collection = service.RetrieveMultiple(query);

                        if (collection.Entities.Count > 0)
                        {
                            throw new InvalidPluginExecutionException("Contact with email already exists!!!");
                        }
                    }
                }

                catch (FaultException <OrganizationServiceFault> ex)
                {
                    throw new InvalidPluginExecutionException("An error occurred in MyPlug-in.", ex);
                }

                catch (Exception ex)
                {
                    tracingService.Trace("MyPlugin: {0}", ex.ToString());
                    throw;
                }
            }
        }
예제 #40
0
        private void AddOrUpdateThisRecordWithAzure(Entity queriedEntityRecord, Entity configurationRecord, LocalPluginContext localContext, IOrganizationService service, IPluginExecutionContext context)
        {
            localContext.TracingService.Trace("---------Send the Record to Azure---------");
            string messageName = context.MessageName;
            string text        = "PreferenceCategory";
            string text2       = Utilities.GetAzureWebAPIURL(service, context);

            localContext.TracingService.Trace("Got API URL: " + text2);
            if (text2 != string.Empty)
            {
                localContext.TracingService.Trace("Getting Latest Info for Record: " + queriedEntityRecord["msnfp_preferencecategoryid"].ToString());
                MSNFP_PreferenceCategory mSNFP_PreferenceCategory = new MSNFP_PreferenceCategory();
                mSNFP_PreferenceCategory.preferencecategoryid = (Guid)queriedEntityRecord["msnfp_preferencecategoryid"];
                if (queriedEntityRecord.Contains("msnfp_categorycode") && queriedEntityRecord["msnfp_categorycode"] != null)
                {
                    mSNFP_PreferenceCategory.categorycode = ((OptionSetValue)queriedEntityRecord["msnfp_categorycode"]).Value;
                    localContext.TracingService.Trace("Got msnfp_categorycode.");
                }
                else
                {
                    mSNFP_PreferenceCategory.categorycode = null;
                    localContext.TracingService.Trace("Did NOT find msnfp_categorycode.");
                }
                if (queriedEntityRecord.Contains("msnfp_name") && queriedEntityRecord["msnfp_name"] != null)
                {
                    mSNFP_PreferenceCategory.name = (string)queriedEntityRecord["msnfp_name"];
                    localContext.TracingService.Trace("Got msnfp_name.");
                }
                else
                {
                    mSNFP_PreferenceCategory.name = null;
                    localContext.TracingService.Trace("Did NOT find msnfp_name.");
                }
                if (queriedEntityRecord.Contains("statecode") && queriedEntityRecord["statecode"] != null)
                {
                    mSNFP_PreferenceCategory.StateCode = ((OptionSetValue)queriedEntityRecord["statecode"]).Value;
                    localContext.TracingService.Trace("Got statecode.");
                }
                else
                {
                    mSNFP_PreferenceCategory.StateCode = null;
                    localContext.TracingService.Trace("Did NOT find statecode.");
                }
                if (queriedEntityRecord.Contains("statuscode") && queriedEntityRecord["statuscode"] != null)
                {
                    mSNFP_PreferenceCategory.StatusCode = ((OptionSetValue)queriedEntityRecord["statuscode"]).Value;
                    localContext.TracingService.Trace("Got statuscode.");
                }
                else
                {
                    mSNFP_PreferenceCategory.StatusCode = null;
                    localContext.TracingService.Trace("Did NOT find statuscode.");
                }
                if (messageName == "Create")
                {
                    mSNFP_PreferenceCategory.createdon = DateTime.UtcNow;
                }
                else if (queriedEntityRecord.Contains("createdon") && queriedEntityRecord["createdon"] != null)
                {
                    mSNFP_PreferenceCategory.createdon = (DateTime)queriedEntityRecord["createdon"];
                }
                else
                {
                    mSNFP_PreferenceCategory.createdon = null;
                }
                mSNFP_PreferenceCategory.syncdate = DateTime.UtcNow;
                if (messageName == "Delete")
                {
                    mSNFP_PreferenceCategory.deleted     = true;
                    mSNFP_PreferenceCategory.deleteddate = DateTime.UtcNow;
                }
                else
                {
                    mSNFP_PreferenceCategory.deleted     = false;
                    mSNFP_PreferenceCategory.deleteddate = null;
                }
                localContext.TracingService.Trace("JSON object created");
                if (messageName == "Create")
                {
                    text2 = text2 + text + "/Create" + text;
                }
                else if (messageName == "Update" || messageName == "Delete")
                {
                    text2 = text2 + text + "/Update" + text;
                }
                MemoryStream memoryStream = new MemoryStream();
                DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(typeof(MSNFP_PreferenceCategory));
                dataContractJsonSerializer.WriteObject(memoryStream, mSNFP_PreferenceCategory);
                byte[] array = memoryStream.ToArray();
                memoryStream.Close();
                string       @string      = Encoding.UTF8.GetString(array, 0, array.Length);
                WebAPIClient webAPIClient = new WebAPIClient();
                webAPIClient.Headers[HttpRequestHeader.ContentType] = "application/json";
                webAPIClient.Headers["Padlock"] = (string)configurationRecord["msnfp_apipadlocktoken"];
                webAPIClient.Encoding           = Encoding.UTF8;
                localContext.TracingService.Trace("---------Preparing JSON---------");
                localContext.TracingService.Trace("Converted to json API URL : " + text2);
                localContext.TracingService.Trace("JSON: " + @string);
                localContext.TracingService.Trace("---------End of Preparing JSON---------");
                localContext.TracingService.Trace("Sending data to Azure.");
                string str = webAPIClient.UploadString(text2, @string);
                localContext.TracingService.Trace("Got response.");
                localContext.TracingService.Trace("Response: " + str);
            }
            else
            {
                localContext.TracingService.Trace("No API URL or Enable Portal Pages. Exiting workflow.");
            }
        }
예제 #41
0
        /// <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 ExecutePostVehicleandItemCatalogUpdate(LocalPluginContext localContext)
        {
            if (localContext == null)
            {
                throw new ArgumentNullException("localContext");
            }

            IPluginExecutionContext context = localContext.PluginExecutionContext;

            Entity preImageEntity  = (context.PreEntityImages != null && context.PreEntityImages.Contains(this.preImageAlias)) ? context.PreEntityImages[this.preImageAlias] : null;
            Entity postImageEntity = (context.PostEntityImages != null && context.PostEntityImages.Contains(this.postImageAlias)) ? context.PostEntityImages[this.postImageAlias] : null;


            IOrganizationService service = localContext.OrganizationService;
            ITracingService      trace   = localContext.TracingService;
            Entity countEntryDetail      = (Entity)context.InputParameters["Target"];

            if (!(context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity))
            {
                return;
            }

            if (countEntryDetail.LogicalName != "product")
            {
                return;
            }

            if (context.Mode == 0) //Synchronous Plug-in
            {
                string message = context.MessageName;

                try
                {
                    ProductHandler productHandler = new ProductHandler(service, trace);

                    var preImageTax = preImageEntity.GetAttributeValue <EntityReference>("gsc_taxid") != null
                        ? preImageEntity.GetAttributeValue <EntityReference>("gsc_taxid").Id
                        : Guid.Empty;

                    var preImagePriceList = preImageEntity.GetAttributeValue <EntityReference>("pricelevelid") != null
                        ? preImageEntity.GetAttributeValue <EntityReference>("pricelevelid").Id
                        : Guid.Empty;

                    var postImageTax = postImageEntity.GetAttributeValue <EntityReference>("gsc_taxid") != null
                        ? postImageEntity.GetAttributeValue <EntityReference>("gsc_taxid").Id
                        : Guid.Empty;

                    var postImagePriceList = postImageEntity.GetAttributeValue <EntityReference>("pricelevelid") != null
                        ? postImageEntity.GetAttributeValue <EntityReference>("pricelevelid").Id
                        : Guid.Empty;

                    if (preImageTax != postImageTax)
                    {
                        productHandler.PopulateTaxRate(postImageEntity);
                    }
                    if (preImagePriceList != postImagePriceList)
                    {
                        productHandler.ClearSellingPrice(postImageEntity);
                    }
                }
                catch (Exception ex)
                {
                    throw new InvalidPluginExecutionException(String.Concat(ex.Message));
                }
            }
        }
예제 #42
0
        public void Execute(IServiceProvider serviceProvider)
        {
            IPluginExecutionContext     context        = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);
            ITracingService             traceService   = (ITracingService)serviceProvider.GetService(typeof(ITracingService));

            traceService.Trace(Strings.LOADED_CAS_PAYMENT_RESULTS_PLUGIN);
            traceService.Trace(Strings.PLUGIN_DEPTH + context.Depth.ToString());

            if (context.Depth > 2)
            {
                return;
            }

            traceService.Trace(Strings.LOADED_TARGET_ENTITY);

            //Fetch configurations from Configuration Entity in Dynamics to prepare for HTTP API Call
            var    configs   = Helper.GetSystemConfigurations(service, ConfigConstants.CAS_AP, string.Empty);
            string clientKey = Helper.GetConfigKeyValue(configs, ConfigConstants.CLIENT_KEY, ConfigConstants.CAS_AP);
            string clientId  = Helper.GetConfigKeyValue(configs, ConfigConstants.CLIENT_ID, ConfigConstants.CAS_AP);
            string url       = Helper.GetConfigKeyValue(configs, ConfigConstants.INTERFACE_URL, ConfigConstants.CAS_AP);
            string endPoint  = Helper.GetConfigKeyValue(configs, ConfigConstants.ENDPOINT, ConfigConstants.CAS_AP);


            // Get the Pending Payment records with the status "Sent To CAS"
            List <Entity> pendingPayments = Helper.GetPaymentRecordsForProcessing(service);

            //Get the response for each payment in the fetched payment records
            foreach (Entity payment in pendingPayments)
            {
                string invoiceNumber = String.Empty;

                if (payment.Attributes.Keys.Contains(Payment.INVOICE_NUMBER))
                {
                    invoiceNumber = payment[Payment.INVOICE_NUMBER].ToString();

                    EntityReference assignment = (EntityReference)payment[Payment.Assignment.ENTITY_NAME]; //Get the EntityReference of the related assignment of the payment record

                    //Fetch the Related Assignment Entity fields from Dynamics
                    Entity relatedAssignment = service.Retrieve(Payment.Assignment.ENTITY_NAME, assignment.Id, new ColumnSet(new string[] { Payment.Assignment.RELATED_CONTACT }));

                    EntityReference contactReference = (EntityReference)relatedAssignment[Payment.Assignment.RELATED_CONTACT];//Fetch the related contact entity reference from the assignment record

                    //Fetch the Related Contact Entity fields from Dynamics
                    Entity relatedContact = service.Retrieve(Contact.ENTITY_NAME, contactReference.Id, new ColumnSet(new string[] { Contact.SITE_NUMBER, Contact.SUPPLIER_NUMBER }));

                    //Prepare Invoice object for Serialization
                    Invoice invoice = new Invoice
                    {
                        InvoiceNumber      = invoiceNumber,
                        SupplierNumber     = relatedContact[Contact.SUPPLIER_NUMBER].ToString(),
                        SupplierSiteNumber = relatedContact[Contact.SITE_NUMBER].ToString(),
                        PaymentID          = payment.Id
                    };

                    //Get Json from Invoice Object
                    string jsonRequest = JsonConvert.SerializeObject(invoice);

                    //Call the API and deserialize the response to PaymentResponse object
                    PaymentResponse response = JsonConvert.DeserializeObject <PaymentResponse>(Helper.GetAPIResponse(clientKey, clientId, url, endPoint, jsonRequest));

                    if (response.invoice_status == CASResponseStatus.InvoiceStatus.VALIDATED)
                    {
                        Entity updatedPayment = new Entity(Payment.ENTITY_NAME);
                        updatedPayment[Payment.INVOICE_STATUS] = response.invoice_status;
                        updatedPayment[Payment.PAYMENT_STATUS] = response.payment_status;
                        updatedPayment[Payment.PAYMENT_DATE]   = DateTime.Parse(response.payment_date);
                        updatedPayment[Payment.PAYMENT_NUMBER] = response.payment_number;
                        updatedPayment[Payment.PAYMENT_ID]     = payment.Id;

                        service.Update(updatedPayment);
                        SetState(service, new EntityReference(Payment.ENTITY_NAME, payment.Id), Payment.InActiveStatus.STATE_CODE, Payment.InActiveStatus.PAYMENT_PROCESSED_STATUS_REASON);

                        //Update Expenses for this payment to PAID
                        //Get related expenses
                        List <Entity> expenses = Helper.GetRelatedChildRecords(service, payment.Id, Expense.RELATED_PAYMENT, Expense.ENTITY_NAME, false);

                        if (expenses.Count > 0)
                        {
                            //Update the status to Inactive -- Paid for all related expenses
                            foreach (Entity expense in expenses)
                            {
                                SetState(service, new EntityReference(Expense.ENTITY_NAME, expense.Id), Expense.InActiveStatus.STATE_CODE, Expense.InActiveStatus.PAID_STATUS_REASON);
                            }
                        }
                        else
                        {
                            //Unhandled case as Payment is not supposed to have Sent To CAS status without a expense associted
                        }
                    }
                    else if (response.invoice_status == CASResponseStatus.InvoiceStatus.NOT_VALIDATED)
                    {
                        //Create the log when the INVOICE STATUS is not found in CAS
                        Helper.LogIntegrationError(service, Strings.NOT_PAID, response.ToString(Strings.INVOICE_DESC_NOT_PAID),
                                                   IntegrationErrorCodes.GetIntValueFromCode(IntegrationErrorCodes.FETCH_PAYMENT_RESULTS_FROM_CAS), new EntityReference(Payment.ENTITY_NAME, payment.Id));
                    }

                    else //Handle all other errors
                    {
                        if (response.invoice_status == CASResponseStatus.InvoiceStatus.NOT_FOUND)
                        {
                            //Create the log when the INVOICE STATUS is not found in CAS
                            Helper.LogIntegrationError(service, Strings.INVOICE_STATUS_NOT_FOUND, response.ToString(Strings.INVOICE_NOT_FOUND_DESC),
                                                       IntegrationErrorCodes.GetIntValueFromCode(IntegrationErrorCodes.FETCH_PAYMENT_RESULTS_FROM_CAS), new EntityReference(Payment.ENTITY_NAME, payment.Id));
                        }
                        else
                        {
                            //Everything else
                            Helper.LogIntegrationError(service, Strings.UNKNOWN_INVOICE_ERROR, response.ToString(Strings.UNKNOWN_INVOICE_ERROR),
                                                       IntegrationErrorCodes.GetIntValueFromCode(IntegrationErrorCodes.FETCH_PAYMENT_RESULTS_FROM_CAS), new EntityReference(Payment.ENTITY_NAME, payment.Id));
                        }

                        //set the status of the payment to Failed
                        SetState(service, new EntityReference(Payment.ENTITY_NAME, payment.Id), Payment.ActiveStatus.STATE_CODE,
                                 Payment.ActiveStatus.CAS_PROCESSING_ERROR_STATUS_REASON);
                    }
                }
                else //if no invoice number on the payment
                {
                    Helper.LogIntegrationError(service, Strings.INOVICE_NOT_FOUND_TITLE, Strings.INVOICE_NOT_FOUND_DESC, IntegrationErrorCodes.GetIntValueFromCode(IntegrationErrorCodes.FETCH_PAYMENT_RESULTS_FROM_CAS),
                                               new EntityReference(Payment.ENTITY_NAME, payment.Id));

                    SetState(service, new EntityReference(Payment.ENTITY_NAME, payment.Id), Payment.ActiveStatus.STATE_CODE, Payment.ActiveStatus.FAILED_STATUS_REASON);

                    traceService.Trace(Strings.INOVICE_NOT_FOUND_TITLE + "-" + payment[Payment.PAYMENT_NAME]);
                }
            } // End of For-each loop for payments.

            traceService.Trace(Strings.FINISHED_PAYMENTS_FETCH_PROCESSING);
            //Since the singleton record is deleted, create new CAS AP Cron Job Proxy Singleton record
            Helper.CreateCronJobSingletonRecord(Payment.CAS_AP_CRON_JOB_PROXY.ENTITY_NAME, service);

            traceService.Trace(Strings.CREATED_SINGLETON_CAS_AP_CRON_JOB);
        }
예제 #43
0
 protected abstract void Execute(IPluginExecutionContext context, IOrganizationService service, ITracingService tracingService);
예제 #44
0
 /// <summary>
 /// Post Create method will share the Contact with a user specified in the custom 'ShareWithUser' field
 /// </summary>
 private static void PostContactCreate(IPluginExecutionContext context, IOrganizationService service)
 {
 }
예제 #45
0
        protected override void Execute(IPluginExecutionContext context, IOrganizationServiceFactory serviceFactory, IOrganizationService adminService, IOrganizationService userService)
        {
            switch (Util.Utilitario.ConverterEnum <Domain.Enum.Plugin.MessageName>(context.MessageName))
            {
                #region Create

            case Domain.Enum.Plugin.MessageName.Create:

                var entidade             = (Entity)context.InputParameters["Target"];
                var solicitacaoBeneficio = entidade.Parse <Domain.Model.SolicitacaoBeneficio>(context.OrganizationName, context.IsExecutingOffline);

                new SharepointServices(context.OrganizationName, context.IsExecutingOffline, adminService)
                .CriarDiretorio <Domain.Model.SolicitacaoBeneficio>(solicitacaoBeneficio.Nome, solicitacaoBeneficio.ID.Value);

                break;

                #endregion

                #region Update

            case Domain.Enum.Plugin.MessageName.Update:

                if (context.Depth > 1)
                {
                    return;
                }

                if (context.PreEntityImages.Contains("imagem") && context.PreEntityImages["imagem"] is Entity)
                {
                    var ServiceSolicitacaoBeneficio = new SolicitacaoBeneficioService(context.OrganizationName, context.IsExecutingOffline, adminService);

                    var entityMerge = context.PostEntityImages["imagem"];
                    var solicMerge  = entityMerge.Parse <Domain.Model.SolicitacaoBeneficio>(context.OrganizationName, context.IsExecutingOffline, adminService);

                    ServiceSolicitacaoBeneficio.CriarSolicitacaoComProdutosCancelados(solicMerge);

                    if (solicMerge.TipoPriceProtection.HasValue && solicMerge.TipoPriceProtection == (int)Domain.Enum.SolicitacaoBeneficio.TipoPriceProtection.Autorizacao)
                    {
                        if (solicMerge.StatusCalculoPriceProtection.HasValue && solicMerge.StatusCalculoPriceProtection == (int)Domain.Enum.SolicitacaoBeneficio.StatusCalculoPriceProtection.Calcular)
                        {
                            // Instanciando objetos utilizados para buscas
                            var ServiceProdSolicitacao = new ProdutosdaSolicitacaoService(context.OrganizationName, context.IsExecutingOffline, adminService);
                            var ServiceProd            = new ProdutoService(context.OrganizationName, context.IsExecutingOffline, adminService);
                            var ServiceSellout         = new SellOutService(context.OrganizationName, context.IsExecutingOffline);
                            var ServiceFatura          = new FaturaService(context.OrganizationName, context.IsExecutingOffline);
                            var ServiceConta           = new ContaService(context.OrganizationName, context.IsExecutingOffline);
                            var ServiceUnidade         = new UnidadeNegocioService(context.OrganizationName, context.IsExecutingOffline);
                            var ServiceFamilia         = new FamiliaComercialService(context.OrganizationName, context.IsExecutingOffline);
                            var ServiceEstabelecimento = new EstabelecimentoService(context.OrganizationName, context.IsExecutingOffline);
                            var ServiceArquivo         = new ArquivoService(context.OrganizationName, context.IsExecutingOffline);


                            //trocar status para calculando
                            solicMerge.StatusCalculoPriceProtection = (int)Domain.Enum.SolicitacaoBeneficio.StatusCalculoPriceProtection.Calculando;
                            ServiceSolicitacaoBeneficio.Persistir(solicMerge);

                            // Obtendo dados para busca de quantidade de itens vendidos no Sellout
                            var lstProdSolic = ServiceProdSolicitacao.ListarPorSolicitacaoAtivos(solicMerge.ID.Value);
                            if (lstProdSolic.Count > 0)
                            {
                                var lstTmpFilter = lstProdSolic.Select(c => (Guid)c.Produto.Id).ToList();

                                var lstObjProd          = ServiceProd.ListarProduto(lstTmpFilter);
                                var listFilterSelloutWS = lstObjProd.Select(c => c.Codigo).ToList();
                                var listFilterFatura    = lstObjProd.Select(c => c.ID).ToList();

                                var strListFilter = String.Join("','", listFilterSelloutWS);

                                DateTime dataIni = (DateTime)solicMerge.DataCriacao;
                                dataIni = dataIni.AddMonths(-1);
                                DateTime dataFim = new DateTime(dataIni.Year, dataIni.Month, DateTime.DaysInMonth(dataIni.Year, dataIni.Month), 23, 59, 59);
                                dataIni = dataIni.AddMonths(-2);
                                dataIni = new DateTime(dataIni.Year, dataIni.Month, 1, 0, 0, 0);

                                //Lista de total de unidades reportadas pelo sellout nos ultimos 90 dias, divididos por 2, para os produtos solicitados.
                                var listValueSellout = ServiceSellout.listarContagemVenda(dataIni, dataFim, solicMerge.Canal.Id, strListFilter);

                                //TODO - Determinar data referencia dos 6 meses para as faturas
                                var listProdFaturas = ServiceFatura.listarContagemVendaPrice(solicMerge.Canal.Id, listFilterFatura, lstObjProd);

                                //Ajuste de valor de quantidade
                                foreach (var ajusteValuesTmp in listValueSellout)
                                {
                                    var prodTmp = lstObjProd.Find(x => x.Codigo == ajusteValuesTmp.CodigoProdutoERP);
                                    if (prodTmp != null)
                                    {
                                        var prodSolicTmp = lstProdSolic.Find(x => x.Produto.Id == prodTmp.ID);
                                        if (prodSolicTmp != null)
                                        {
                                            if (prodSolicTmp.QuantidadeAjustada.HasValue)
                                            {
                                                ajusteValuesTmp.TotalUnidades = (decimal)prodSolicTmp.QuantidadeAjustada;
                                            }
                                            else
                                            {
                                                if (ajusteValuesTmp.TotalUnidades > prodSolicTmp.QuantidadeSolicitada)
                                                {
                                                    ajusteValuesTmp.TotalUnidades = (decimal)prodSolicTmp.QuantidadeSolicitada;
                                                }
                                            }
                                        }
                                    }
                                }

                                //Busca de preços atuais
                                var listPrecoProduto = new List <PrecoProduto>();
                                foreach (var objSolicProd in lstProdSolic)
                                {
                                    PrecoProduto precoProduto = new PrecoProduto(context.OrganizationName, context.IsExecutingOffline);
                                    Product      objProd      = lstObjProd.Find(x => x.ID == objSolicProd.Produto.Id);

                                    precoProduto.CodigoProduto = objProd.Codigo;
                                    precoProduto.ProdutoId     = objProd.ID.Value;
                                    precoProduto.Produto       = objProd;

                                    var contaObjTmp = ServiceConta.BuscaConta(solicMerge.Canal.Id);
                                    List <ProdutoPortfolio> lstProdutoPortifolio = ServiceProd.ProdutosPortfolio(contaObjTmp, contaObjTmp.Classificacao.Id, solicMerge.UnidadedeNegocio.Id);
                                    ProdutoPortfolio        produtoPortfolioTmp  = lstProdutoPortifolio.Find(x => x.Produto.Id == objProd.ID.Value);

                                    Estabelecimento estTmp = ServiceEstabelecimento.BuscaEstabelecimento(objSolicProd.Estabelecimento.Id);
                                    precoProduto.codEstabelecimento = (int)estTmp.Codigo;

                                    var unidadeTmp = ServiceUnidade.BuscaUnidadeNegocio(solicMerge.UnidadedeNegocio.Id);
                                    precoProduto.codUnidade = unidadeTmp.ChaveIntegracao;
                                    var famComTmp = ServiceFamilia.ObterPor(objProd.FamiliaComercial.Id);
                                    precoProduto.codFamiliaComl = famComTmp.Codigo;

                                    precoProduto.tipoPortofolio = produtoPortfolioTmp.PortfolioTipo;

                                    precoProduto.ContaId      = solicMerge.Canal.Id;
                                    precoProduto.ValorProduto = 0;
                                    precoProduto.Quantidade   = (int)objSolicProd.QuantidadeSolicitada;

                                    listPrecoProduto.Add(precoProduto);
                                }
                                listPrecoProduto = ServiceProd.ListarPor(listPrecoProduto);

                                MSG0138 msg0138 = new MSG0138(context.OrganizationName, context.IsExecutingOffline);
                                List <ValorProdutoICMSViewModel> lstPrecoProdICMS = msg0138.Enviar(lstObjProd, lstProdSolic, listPrecoProduto, solicMerge);

                                List <ProdutoFaturaViewModel> lstProdFatGenerate = new List <ProdutoFaturaViewModel>();

                                List <string> errorNoSellout = new List <string>();
                                foreach (var objProdSolic in lstProdSolic)
                                {
                                    Product           objProd       = lstObjProd.Find(x => x.ID == objProdSolic.Produto.Id);
                                    QtdProdutoSellout objQtdSellout = listValueSellout.Find(x => x.CodigoProdutoERP == objProd.Codigo);

                                    if (objQtdSellout == null || objQtdSellout.TotalUnidades <= 0)
                                    {
                                        string strError = "Produto: " + objProd.Codigo + " " + objProd.Nome + " | Nenhuma entrada de sellout para o produto";
                                        errorNoSellout.Add(strError);
                                    }
                                }

                                string urlSharepoint    = string.Empty;
                                var    retUrlSharepoint = ServiceArquivo.ObterUrlArquivo(solicMerge.ID.ToString(), context.OrganizationName, out urlSharepoint);

                                if (errorNoSellout.Count == 0)
                                {
                                    foreach (var objProdSolic in lstProdSolic)
                                    {
                                        Product           objProd       = lstObjProd.Find(x => x.ID == objProdSolic.Produto.Id);
                                        QtdProdutoSellout objQtdSellout = listValueSellout.Find(x => x.CodigoProdutoERP == objProd.Codigo);
                                        objProdSolic.QuantidadeAprovada = 0;
                                        objProdSolic.ValorTotalAprovado = 0;
                                        objProdSolic.ValorTotal         = 0;

                                        PrecoProduto objPrecoProd = listPrecoProduto.Find(x => x.Produto.ID == objProdSolic.Produto.Id);
                                        ValorProdutoICMSViewModel objValProdICMS = lstPrecoProdICMS.Find(x => x.CodigoProduto == objProd.Codigo);

                                        var lstProdFatLocal = listProdFaturas.Where(x => x.CodigoProduto == objProd.Codigo).OrderByDescending(x => x.DataEmissaoFatura).ToList();

                                        foreach (var objProdFaturas in lstProdFatLocal)
                                        {
                                            if (objQtdSellout.TotalUnidades == 0)
                                            {
                                                objProdFaturas.QtdCalculo = 0;
                                            }
                                            else if (objProdFaturas.QtdFatura >= objQtdSellout.TotalUnidades)
                                            {
                                                objProdFaturas.QtdCalculo = objQtdSellout.TotalUnidades;
                                            }
                                            else
                                            {
                                                objProdFaturas.QtdCalculo = objProdFaturas.QtdFatura;
                                            }

                                            objProdFaturas.SaldoDiferenca = objProdFaturas.PrecoFatura - objValProdICMS.PrecoLiquido;

                                            if (objProdFaturas.SaldoDiferenca > 0)
                                            {
                                                objProdFaturas.ValorIPIProduto   = objProd.PercentualIPI;
                                                objProdFaturas.PrecoCalculoAtual = objValProdICMS.PrecoLiquido;
                                                objProdFaturas.TotalDiferenca    = objProdFaturas.SaldoDiferenca * objProdFaturas.QtdCalculo;
                                                objProdFaturas.TotalComIPI       = objProdFaturas.TotalDiferenca + (objProdFaturas.TotalDiferenca * (objProd.PercentualIPI / 100));

                                                objProdSolic.QuantidadeAprovada += objProdFaturas.QtdCalculo;
                                                if (objProdFaturas.QtdFatura >= objQtdSellout.TotalUnidades)
                                                {
                                                    objQtdSellout.TotalUnidades = 0;
                                                }
                                                else
                                                {
                                                    objQtdSellout.TotalUnidades -= objProdFaturas.QtdFatura;
                                                }

                                                if (objProdSolic.ValorTotalAprovado.HasValue)
                                                {
                                                    objProdSolic.ValorTotalAprovado += objProdFaturas.TotalComIPI;
                                                }
                                                else
                                                {
                                                    objProdSolic.ValorTotalAprovado = objProdFaturas.TotalComIPI;
                                                }

                                                if (objProdSolic.ValorTotal.HasValue)
                                                {
                                                    objProdSolic.ValorTotal += objProdFaturas.TotalComIPI;
                                                }
                                                else
                                                {
                                                    objProdSolic.ValorTotal = objProdFaturas.TotalComIPI;
                                                }
                                            }
                                            else if (objProdFaturas.SaldoDiferenca <= 0)
                                            {
                                                objProdFaturas.ValorIPIProduto   = objProd.PercentualIPI;
                                                objProdFaturas.PrecoCalculoAtual = objValProdICMS.PrecoLiquido;
                                            }
                                            lstProdFatGenerate.Add(objProdFaturas);
                                        }

                                        if (objProdSolic.QuantidadeAprovada > 0 && objProdSolic.ValorTotalAprovado > 0)
                                        {
                                            var dateTime = DateTime.Now;
                                            ServiceArquivo.CriarExcelRecalculo(lstProdFatGenerate, dateTime.ToString("dd/MM/yyyy"), urlSharepoint, NameFileTable, context.OrganizationName, context.IsExecutingOffline);

                                            ServiceProdSolicitacao.Persistir(objProdSolic);
                                        }
                                        else if (lstProdFatLocal.Count > 0 && objProdSolic.ValorTotalAprovado <= 0)
                                        {
                                            string strError = "Produto: " + objProd.Codigo + " " + objProd.Nome + " | Nenhuma entrada nas Faturas do Canal com diferença positiva de preço para o Produto";
                                            errorNoSellout.Add(strError);
                                        }
                                        else
                                        {
                                            string strError = "Produto: " + objProd.Codigo + " " + objProd.Nome + " | Nenhuma entrada nas Faturas do Canal para o Produto";
                                            errorNoSellout.Add(strError);
                                        }
                                    }

                                    if (errorNoSellout.Count == 0)
                                    {
                                        solicMerge.StatusCalculoPriceProtection = (int)Domain.Enum.SolicitacaoBeneficio.StatusCalculoPriceProtection.Calculado;
                                        ServiceSolicitacaoBeneficio.Persistir(solicMerge);
                                    }
                                    else
                                    {
                                        ServiceArquivo.CriarArquivosErros(errorNoSellout, urlSharepoint, NameFileLog);
                                        solicMerge.StatusCalculoPriceProtection = (int)Domain.Enum.SolicitacaoBeneficio.StatusCalculoPriceProtection.ErroCalcular;
                                        ServiceSolicitacaoBeneficio.Persistir(solicMerge);
                                    }
                                }
                                else
                                {
                                    ServiceArquivo.CriarArquivosErros(errorNoSellout, urlSharepoint, NameFileLog);
                                    solicMerge.StatusCalculoPriceProtection = (int)Domain.Enum.SolicitacaoBeneficio.StatusCalculoPriceProtection.ErroCalcular;
                                    ServiceSolicitacaoBeneficio.Persistir(solicMerge);
                                }
                            }
                            else
                            {
                                solicMerge.StatusCalculoPriceProtection = (int)Domain.Enum.SolicitacaoBeneficio.StatusCalculoPriceProtection.Calculado;
                                ServiceSolicitacaoBeneficio.Persistir(solicMerge);
                            }
                        }
                    }
                }

                break;

                #endregion
            }
        }
예제 #46
0
        private static string GetTypeSchemaName(IPluginExecutionContext context, bool isRelationship)
        {
            string entityType;

            if (isRelationship)
            {
                entityType = ((Relationship)context.InputParameters["Relationship"]).SchemaName;
            }
            else if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
            {
                entityType = ((Entity)context.InputParameters["Target"]).LogicalName;
            }
            else if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is EntityReference)
            {
                entityType = ((EntityReference)context.InputParameters["Target"]).LogicalName;
            }
            else if (context.InputParameters.Contains("EntityMoniker") &&
                     context.InputParameters["EntityMoniker"] is EntityReference)
            {
                entityType = ((EntityReference)context.InputParameters["EntityMoniker"]).LogicalName;
            }
            else if (
                new[] { PluginMessage.AddMembers, PluginMessage.AddMember, PluginMessage.AddListMember }.Contains(
                    context.MessageName))
            {
                entityType = "list";
            }
            else if (context.InputParameters.Contains("LeadId") &&
                     context.InputParameters["LeadId"] is EntityReference)
            {
                entityType = "lead";
            }
            else if (context.InputParameters.Contains("EmailId"))
            {
                entityType = "email";
            }
            else if (context.MessageName == PluginMessage.Lose && context.InputParameters.Contains("OpportunityClose"))
            {
                entityType = "opportunity";
            }
            else if (context.MessageName == PluginMessage.Cancel)
            {
                entityType = "salesorder";
            }
            else if (context.MessageName == PluginMessage.Win || context.MessageName == PluginMessage.Lose)
            {
                entityType = "opportunity";
            }
            else if (context.MessageName == PluginMessage.Cancel)
            {
                entityType = "salesorder";
            }
            else
            {
                var args = "";
                args = args + "Message: " + context.MessageName;
                foreach (var item in context.InputParameters)
                {
                    if (args != "")
                    {
                        args = args + "\n" + item.Key + ": " + item.Value;
                    }
                    else
                    {
                        args = args + item.Key + ": " + item.Value;
                    }
                }
                throw new InvalidPluginExecutionException("Error Extracting Plugin Entity Type:\n" + args);
            }
            return(entityType);
        }
        private void HandleCustomAction(IPluginExecutionContext context, PersistentTracingService tracing, IOrganizationService service)
        {
            var config = ProcessorConfig.Parse(context.InputParameters["jsonInput"] as string);

            if (config.Target == null && config.TargetEntity == null)
            {
                throw new InvalidPluginExecutionException("Target property inside JSON parameters is needed for custom actions");
            }

            ColumnSet columnSet;

            if (config.TargetColumns != null)
            {
                columnSet = new ColumnSet(config.TargetColumns);
            }
            else
            {
                columnSet = new ColumnSet(true);
            }

            try
            {
                var dataSource = config.TargetEntity != null ? config.TargetEntity : service.Retrieve(config.Target.LogicalName, config.Target.Id, columnSet);

                if (!CheckExecutionCriteria(config, dataSource, service, tracing))
                {
                    tracing.Trace("Execution criteria not met, aborting");

                    var abortResult = new ProcessingResult
                    {
                        Success  = true,
                        Result   = config.Template,
                        TraceLog = tracing.TraceLog
                    };
                    context.OutputParameters["jsonOutput"] = SerializeResult(abortResult);

                    return;
                }

                var output = ProcessTemplate(config.Template, dataSource, new OrganizationConfig {
                    OrganizationUrl = config.OrganizationUrl
                }, service, tracing);

                var result = new ProcessingResult
                {
                    Success  = true,
                    Result   = output,
                    TraceLog = tracing.TraceLog
                };
                context.OutputParameters["jsonOutput"] = SerializeResult(result);

                TriggerUpdateConditionally(output, dataSource, config, service);
            }
            catch (Exception ex)
            {
                var result = new ProcessingResult
                {
                    Success  = false,
                    Error    = ex.Message,
                    TraceLog = tracing.TraceLog
                };
                context.OutputParameters["jsonOutput"] = SerializeResult(result);

                if (config.ThrowOnCustomActionError)
                {
                    throw;
                }
            }
        }
예제 #48
0
        public void CreateAccountContractRequest(IOrganizationService service, Entity SAF, String canId, IPluginExecutionContext context, Entity workorder, Guid opportunityid, Entity uSites)
        {
            #region variables and decalaration
            int      servicegroupno = 0, subcrino = 0;
            string   SafNo               = string.Empty;
            String   advanceBilling      = String.Empty;
            String   billCycle           = String.Empty;
            int      billcycleno         = 0;
            DateTime billStartDate       = new DateTime();
            string   billstartDateString = null;

            Int32  billingFrequency = 0;
            String productId        = String.Empty;

            // int billProfileNo = 1, invoiceTemplateNo = 5, domSegment = 0;
            int     billProfileNo = 242, invoiceTemplateNo = 5, domSegment = 0;
            decimal RC                       = 0;
            decimal NRC                      = 0;
            decimal IPAmount                 = 0;
            decimal PremiumInstallationCarge = 0;
            string  ProdRatePlanId           = string.Empty;
            string  ipRatePlanId             = string.Empty;
            //string seg = null;
            EntityReference seg = null;
            #endregion
            DateTime customerAcceptdate = workorder.GetAttributeValue <DateTime>("spectra_acceptedbycustomerdate");
            int      days = customerAcceptdate.Day;
            tracingService.Trace("Customer Accepted date : " + customerAcceptdate);
            tracingService.Trace("Customer Accepted date days : " + days);
            #region Account values

            tracingService.Trace("Acccount no: " + canId);
            QueryExpression query = new QueryExpression("account");
            query.NoLock = true;
            query.ColumnSet.AddColumns("alletech_subscriptionno", "alletech_servicegroupno");
            query.Criteria.AddCondition("alletech_accountid", ConditionOperator.Equal, canId);
            //query.Criteria.AddCondition("statecode", ConditionOperator.Equal, 0);
            EntityCollection acccollection = service.RetrieveMultiple(query);
            tracingService.Trace("Account retrive sucessfully");
            tracingService.Trace("Count: ", acccollection.Entities.Count);
            if (acccollection.Entities.Count > 0)
            {
                Entity account = acccollection.Entities[0];
                if (account.Attributes.Contains("alletech_subscriptionno"))
                {
                    subcrino = account.GetAttributeValue <int>("alletech_subscriptionno");
                    tracingService.Trace("alletech_subscriptionno: ", subcrino);
                }
                else
                {
                    throw new InvalidPluginExecutionException("Unify subcrino is empty for child account");
                }
                if (account.Attributes.Contains("alletech_servicegroupno"))
                {
                    servicegroupno = int.Parse(account.GetAttributeValue <string>("alletech_servicegroupno"));
                    tracingService.Trace("alletech_subscriptionno: ", servicegroupno);
                }
            }
            else
            {
                throw new InvalidPluginExecutionException(" Account not found");
            }

            #endregion
            //throw new InvalidPluginExecutionException("Account Service :-" + servicegroupno);
            Entity Parent_SAfName = service.Retrieve("onl_saf", SAF.Id, new ColumnSet("onl_name")); //getting SAF Name on behalf of safid
            SafNo = Parent_SAfName.GetAttributeValue <String>("onl_name");                          //getting SAF Name
            tracingService.Trace("SAF No : " + SafNo);

            Entity          safref   = service.Retrieve("onl_saf", SAF.Id, new ColumnSet("onl_opportunityidid"));
            EntityReference owneropp = (EntityReference)safref.Attributes["onl_opportunityidid"];

            Entity Productrecord = service.Retrieve("opportunity", owneropp.Id, new ColumnSet("alletech_productsegment"));
            seg = Productrecord.GetAttributeValue <EntityReference>("alletech_productsegment");
            tracingService.Trace("segment : " + seg);

            tracingService.Trace("prod seg: " + seg);

            DateTime billStartDate2 = DateTime.Now;

            if (SAF.Attributes.Contains("onl_billtypeonl"))
            {
                //Advance
                if (SAF.GetAttributeValue <OptionSetValue>("onl_billtypeonl").Value == 122050000)
                {
                    advanceBilling = "true";
                }
                else
                {
                    advanceBilling = "false";
                }
            }


            #region First Invoice Date AND Bill End Date
            DateTime firstInvoiceDate   = new DateTime();
            DateTime billEndDate        = new DateTime();
            DateTime billInvoiceEndDate = new DateTime();

            #endregion
            #region bill cyle
            string firstInvoiceDateString      = null;
            string billEndDateString           = null;
            string subscriptionStartDateString = null;

            subscriptionStartDateString = DateFormater(DateTime.Now);

            tracingService.Trace("Get Bill cycle on Site Entity");
            Entity oppbillcycle = service.Retrieve("onl_customersite", uSites.Id, new ColumnSet("onl_billcycle"));
            tracingService.Trace("Bill cycle ID:" + oppbillcycle.GetAttributeValue <EntityReference>("onl_billcycle").Id);
            tracingService.Trace("Bill cycle Name:" + oppbillcycle.GetAttributeValue <EntityReference>("onl_billcycle").Name);
            if (oppbillcycle.Attributes.Contains("onl_billcycle"))
            {
                Entity billCycleEnt = service.Retrieve("alletech_billcycle", oppbillcycle.GetAttributeValue <EntityReference>("onl_billcycle").Id, new ColumnSet("alletech_id", "alletech_days", "alletech_billcycleday"));
                billCycle   = billCycleEnt.GetAttributeValue <String>("alletech_id").ToString();
                billcycleno = Convert.ToInt32(billCycle);

                tracingService.Trace("Bill cycle No:" + billcycleno);

                if (billCycleEnt.Attributes.Contains("alletech_billcycleday"))
                {
                    firstInvoiceDate = new DateTime(billStartDate2.Year, billStartDate2.Month, billCycleEnt.GetAttributeValue <int>("alletech_billcycleday"));
                }
                else
                {
                    throw new InvalidPluginExecutionException("Please add bill cycle day");
                }

                if (firstInvoiceDate > DateTime.Now)
                {
                    firstInvoiceDateString = DateFormater(firstInvoiceDate);
                }
                else
                {
                    firstInvoiceDate       = firstInvoiceDate.AddMonths(1);
                    firstInvoiceDateString = DateFormater(firstInvoiceDate);
                }
            }
            tracingService.Trace("First Invoice date string : " + firstInvoiceDateString);


            //if (IR.Attributes.Contains("alletech_date1"))
            //{
            //billStartDate = IR.GetAttributeValue<DateTime>("alletech_date1");
            billStartDate       = DateTime.Now;
            billstartDateString = DateFormater(billStartDate);
            //}
            tracingService.Trace("billstartDateString : " + billstartDateString);

            Entity oppproductonl = service.Retrieve("onl_workorders", workorder.Id, new ColumnSet("onl_productattached"));

            if (oppproductonl.Attributes.Contains("onl_productattached"))
            {
                Entity product = service.Retrieve("product", oppproductonl.GetAttributeValue <EntityReference>("onl_productattached").Id, new ColumnSet("alletech_billingcycle", "name"));
                if (product.Attributes.Contains("alletech_billingcycle"))
                {
                    Entity billingCycle = service.Retrieve("alletech_billingcycle", product.GetAttributeValue <EntityReference>("alletech_billingcycle").Id, new ColumnSet("alletech_monthinbillingcycle"));
                    if (billingCycle.Attributes.Contains("alletech_monthinbillingcycle"))
                    {
                        billingFrequency  = billingCycle.GetAttributeValue <Int32>("alletech_monthinbillingcycle");
                        billEndDate       = firstInvoiceDate.AddMonths(billingFrequency);
                        billEndDateString = DateFormater(billEndDate);
                        if (product.Attributes.Contains("name"))
                        {
                            productId = oppproductonl.GetAttributeValue <EntityReference>("onl_productattached").Name;
                            tracingService.Trace("Product Name : " + productId);
                        }
                        else
                        {
                            throw new InvalidPluginExecutionException("Product does not have name!!");
                        }
                    }
                    else
                    {
                        throw new InvalidPluginExecutionException("Please Enter Bill frequency on Product.");
                    }
                }
                else
                {
                    billEndDateString = DateFormater(billInvoiceEndDate);
                    productId         = oppproductonl.GetAttributeValue <EntityReference>("onl_productattached").Name;
                }
            }
            tracingService.Trace("bill End Date String: " + billEndDateString);
            #endregion


            #region IP Address of Machine
            //IPHostEntry host;
            //string localIP = "?";

            //host = Dns.GetHostEntry(Dns.GetHostName());
            //foreach (IPAddress ip in host.AddressList)
            //{
            //    if (ip.AddressFamily == AddressFamily.InterNetwork)
            //    {
            //        localIP = ip.ToString();
            //        break;
            //    }
            //}
            #endregion

            // Check total no of Opportunity Sites



            // getting Site based on opportunity id
            Entity          opportunitEntity  = service.Retrieve("onl_saf", SAF.Id, new ColumnSet("onl_opportunityidid"));
            EntityReference ownerLookup       = (EntityReference)opportunitEntity.Attributes["onl_opportunityidid"];
            QueryExpression querycustomersite = new QueryExpression();
            querycustomersite.EntityName = "onl_customersite";
            querycustomersite.ColumnSet  = new ColumnSet(true);
            querycustomersite.Criteria.AddCondition("onl_opportunityidid", ConditionOperator.Equal, ownerLookup.Id);
            querycustomersite.Criteria.AddCondition("spectra_siteaccountno", ConditionOperator.Equal, canId);
            EntityCollection resultcustomersite = service.RetrieveMultiple(querycustomersite);
            Entity           SiteEntityCol      = resultcustomersite.Entities[0];
            tracingService.Trace("Count : " + resultcustomersite.Entities.Count);
            #region RC and NRC Amount
            Entity opp = service.Retrieve("opportunity", owneropp.Id, new ColumnSet("alletech_customernameaccountlookup", "opportunityid"));


            string fetch =
                @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
                              <entity name='opportunityproduct'>
                                <attribute name='productid' />
                                <attribute name='extendedamount' />
                                <attribute name='opportunityproductid' />
                                <order attribute='productid' descending='false' />
                                <filter type='and'>
                                  <condition attribute='onl_customerdetailsid' operator='eq' value='{" + SiteEntityCol.Id + @"}' />
                                </filter>
                                <link-entity name='product' from='productid' to='productid' visible='false' link-type='outer' alias='oppprod'>
                                  <attribute name='alletech_plantype' />
                                  <attribute name='alletech_chargetype' />
                                </link-entity>
                              </entity>
                            </fetch>";

            EntityCollection oppProdCol = service.RetrieveMultiple(new FetchExpression(fetch));


            foreach (Entity oppprd in oppProdCol.Entities)
            {
                if (oppprd.Attributes.Contains("productid"))
                {
                    int plantype   = ((OptionSetValue)oppprd.GetAttributeValue <AliasedValue>("oppprod.alletech_plantype").Value).Value;
                    int chargetype = ((OptionSetValue)oppprd.GetAttributeValue <AliasedValue>("oppprod.alletech_chargetype").Value).Value;


                    //normal and RC
                    if (plantype == 569480001 && chargetype == 569480001)
                    {
                        if (oppprd.Attributes.Contains("extendedamount"))
                        {
                            RC = oppprd.GetAttributeValue <Money>("extendedamount").Value;
                        }
                    }
                    else if (plantype == 569480001 && chargetype == 569480002)//nrml OTC
                    {
                        if (oppprd.Attributes.Contains("extendedamount"))
                        {
                            NRC = oppprd.GetAttributeValue <Money>("extendedamount").Value;
                        }
                    }
                    else if (plantype == 569480002 && chargetype == 569480001)//Addon IP
                    {
                        if (oppprd.Attributes.Contains("extendedamount"))
                        {
                            IPAmount     = oppprd.GetAttributeValue <Money>("extendedamount").Value;
                            ipRatePlanId = ((Microsoft.Xrm.Sdk.EntityReference)(oppprd.Attributes["productid"])).Name.ToString();
                        }
                    }
                    else if (plantype == 569480002 && chargetype == 569480002)//addon PremiumInstallationCarge
                    {
                        if (oppprd.Attributes.Contains("extendedamount"))
                        {
                            PremiumInstallationCarge = oppprd.GetAttributeValue <Money>("extendedamount").Value;
                            ProdRatePlanId           = ((Microsoft.Xrm.Sdk.EntityReference)(oppprd.Attributes["productid"])).Name.ToString();
                        }
                    }
                }
            }
            if (RC == 0 || NRC == 0)
            {
                if (IPAmount == 0)
                {
                    throw new InvalidPluginExecutionException("Site Product is Empty");
                }
            }
            tracingService.Trace("RC : " + RC);
            tracingService.Trace("NRC : " + NRC);
            tracingService.Trace("Rate Plan Id : " + ipRatePlanId);
            tracingService.Trace("Prod Rate Plan Id : " + ProdRatePlanId);
            #endregion

            #region request XML
            String requestXml = String.Empty;
            requestXml = "<CreateAccountContractRequest>" +
                         "<CAF_No>" + SafNo + "</CAF_No>" +
                         "<CAN_No>" + canId + "</CAN_No>" +
                         "<CreateAccountContractDetails>" +
                         "<subsNo>" + subcrino + "</subsNo>" +
                         "<ratePlanID>" + productId + "</ratePlanID>" +
                         "<servicegroupno>" + servicegroupno + "</servicegroupno>" +
                         "<startDate>" + subscriptionStartDateString + "</startDate>" +
                         "<RCAmount>" + RC + "</RCAmount>" +
                         "<NRCAmount>" + NRC + "</NRCAmount>" +
                         "<ipRcAmount>" + IPAmount + "</ipRcAmount>" +
                         "<addtnlProdNrcAmount>" + PremiumInstallationCarge + "</addtnlProdNrcAmount>" +
                         "<ipRatePlanId>" + ipRatePlanId + "</ipRatePlanId>" +
                         "<addtnlProdRatePlanId>" + ProdRatePlanId + "</addtnlProdRatePlanId>" +
                         "</CreateAccountContractDetails>" +
                         "<BillRequest>" +
                         "<actNo>" + servicegroupno + "</actNo>" +
                         "<advanceBilling>" + advanceBilling + "</advanceBilling>" +
                         "<billCycleNo>" + billcycleno + "</billCycleNo>" +
                         "<billEndDate>" + billEndDateString + "</billEndDate>" +
                         "<billProfileNo>" + billProfileNo + "</billProfileNo>" +
                         "<billStartDate>" + firstInvoiceDateString + "</billStartDate>" +//installation date
                         "<billCycle>" + billingFrequency + "</billCycle>" +
                         "<billCycleDuration>M</billCycleDuration>" +
                         "<firstInvoiceDate>" + firstInvoiceDateString + "</firstInvoiceDate>" +
                         "<invoiceTemplateNo>205</invoiceTemplateNo>" +
                         "<receiptTemplateNo>3</receiptTemplateNo>";
            domSegment = 0;
            if (domSegment != 0)
            {
                requestXml += "<domSegmentMapId>" + domSegment + "</domSegmentMapId>";
            }
            requestXml += "</BillRequest>" +
                          "<SessionObject>" +
                          "<ipAddress>180.151.100.74</ipAddress>" +
                          "<userName>crm.admin</userName>" +
                          "<usrNo>10651</usrNo>" +
                          "</SessionObject>" +
                          "</CreateAccountContractRequest>";

            #endregion

            // throw new InvalidPluginExecutionException("test:-" + requestXml);
            #region Billing and Subcription request
            var uri = new Uri(this.GetValueForKey("JBossUri"));

            tracingService.Trace("Api URL: " + uri);
            Byte[] requestByte = Encoding.UTF8.GetBytes(requestXml);

            tracingService.Trace("Request XML: " + requestXml);
            WebRequest request;
            try
            {
                request               = WebRequest.Create(uri);
                request.Method        = WebRequestMethods.Http.Post;
                request.ContentLength = requestByte.Length;
                request.ContentType   = "text/xml; encoding='utf-8'";
                request.GetRequestStream().Write(requestByte, 0, requestByte.Length);
            }
            catch (Exception ex)
            {
                throw new InvalidPluginExecutionException("Error in Request byte" + ex.StackTrace);
            }
            bool cflag = false;
            if (context.Depth == 1)
            {
                tracingService.Trace("Context : " + context.Depth);
                //Create Integration Log Enterprise
                using (var response = request.GetResponse())
                {
                    tracingService.Trace("Response : " + response);
                    XmlDocument xmlDoc = new XmlDocument();
                    xmlDoc.Load(response.GetResponseStream());
                    string tmp = xmlDoc.InnerXml.ToString();

                    #region To create Integration Log from Response
                    XmlNodeList node1 = xmlDoc.GetElementsByTagName("CreateAccountContractResponse");
                    for (int i = 0; i <= node1.Count - 1; i++)
                    {
                        string CAF_No = node1[i].ChildNodes.Item(0).InnerText.Trim();
                        string CAN_No = node1[i].ChildNodes.Item(1).InnerText.Trim();
                        //string Code = node1[i].ChildNodes.Item(2).InnerText.Trim();
                        string Message = node1[i].ChildNodes.Item(3).InnerText.Trim();

                        tracingService.Trace("Response Message: " + Message);
                        Entity IntegrationLog = new Entity("alletech_integrationlog_enterprise");
                        IntegrationLog["alletech_cafno"] = CAF_No;
                        IntegrationLog["alletech_canno"] = CAN_No;
                        IntegrationLog["alletech_accountcontractrequest"] = requestXml;
                        //IntegrationLog["alletech_code"] = Code;
                        IntegrationLog["alletech_message"]      = Message;
                        IntegrationLog["alletech_name"]         = "Contract_Created_" + CAF_No + "_" + CAN_No;//Contract_Created_
                        IntegrationLog["alletech_responsetype"] = new OptionSetValue(3);
                        EntityReference refsite = workorder.GetAttributeValue <EntityReference>("onl_sitenameid");
                        IntegrationLog["spectra_siteidid"] = new EntityReference("onl_customersite", refsite.Id);
                        // IntegrationLog["alletech_can"] = new EntityReference("onl_saf", SAF.Id);
                        Guid safid = SAF.Id;
                        IntegrationLog["onl_safid"] = new EntityReference("onl_saf", safid);

                        service.Create(IntegrationLog);
                        cflag = true;
                    }
                    #endregion
                    if (cflag == true)
                    {
                        EntityReference refsite = workorder.GetAttributeValue <EntityReference>("onl_sitenameid");
                        //spectra_contractresponse
                        Entity Sites = service.Retrieve("onl_customersite", refsite.Id, new ColumnSet("spectra_contractresponse"));
                        Sites["spectra_contractresponse"] = "Done";
                        service.Update(Sites);
                    }
                }
            }

            #endregion
            //}
        }
예제 #49
0
        public void Execute(IServiceProvider serviceProvider)
        {
            ITracingService tracingService =
                (ITracingService)serviceProvider.GetService(typeof(ITracingService));
            IPluginExecutionContext context = (IPluginExecutionContext)
                                              serviceProvider.GetService(typeof(IPluginExecutionContext));
            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            var _service = serviceFactory.CreateOrganizationService(context.UserId);
            OrganizationServiceContext ctx = new OrganizationServiceContext(_service);

            // 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"];

                // Verify that the target entity represents an inquiry record.
                // If not, this plug-in was not registered correctly.
                if (entity.LogicalName != "new_inquiry")
                {
                    return;
                }

                try
                {
                    // Download the target URI using a Web client. Any .NET class that uses the
                    // HTTP or HTTPS protocols and a DNS lookup should work.
                    using (WebClient client = new WebClient())
                    {
                        var data = String.Format("{{\"id\": \"{0}\", \"Response\": \"{1}\"}}", entity.Id, "frederick");
                        client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
                        var response      = client.UploadString(new Uri("http://rest.learncode.academy/api/myapi/inquiries/"), "POST", data);
                        var apiID         = response.Substring(response.IndexOf("id\":\"") + 5, 24);
                        var currentRecord = _service.Retrieve("new_inquiry", entity.Id, new Xrm.Sdk.Query.ColumnSet(true));
                        currentRecord["new_name"] = apiID;
                        _service.Update(currentRecord);
                        tracingService.Trace("web client executed successfully, new record created:" + apiID);
                    }
                }

                catch (WebException exception)
                {
                    string str = string.Empty;
                    if (exception.Response != null)
                    {
                        using (StreamReader reader =
                                   new StreamReader(exception.Response.GetResponseStream()))
                        {
                            str = reader.ReadToEnd();
                        }
                        exception.Response.Close();
                    }
                    if (exception.Status == WebExceptionStatus.Timeout)
                    {
                        throw new InvalidPluginExecutionException(
                                  "The timeout elapsed while attempting to issue the request.", exception);
                    }
                    throw new InvalidPluginExecutionException(String.Format(CultureInfo.InvariantCulture,
                                                                            "A Web exception occurred while attempting to issue the request. {0}: {1}",
                                                                            exception.Message, str), exception);
                }
            }
        }
 protected abstract void Execute(IPluginExecutionContext context, IOrganizationService orgService);
예제 #51
0
        public void Execute(IServiceProvider serviceProvider)
        {
            ITracingService tracingService =
                (ITracingService)serviceProvider.GetService(typeof(ITracingService));
            IPluginExecutionContext context = (IPluginExecutionContext)
                                              serviceProvider.GetService(typeof(IPluginExecutionContext));
            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            var _service = serviceFactory.CreateOrganizationService(context.UserId);
            OrganizationServiceContext ctx = new OrganizationServiceContext(_service);

            // 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"];

                // Entity apiId = (Entity)context.PreEntityImages["Image"];

                Entity postEntity = (Entity)context.PostEntityImages["postInquiry"];

                // Verify that the target entity represents an inquiry record.
                // If not, this plug-in was not registered correctly.
                if (entity.LogicalName != "new_inquiry")
                {
                    return;
                }

                try
                {
                    using (WebClient client = new WebClient())
                    {
                        var apiId = postEntity.GetAttributeValue <string>("new_name");
                        tracingService.Trace("1 web client plugin executed successfully, the record id is: " + apiId);
                        var data = String.Format("{{\"id\": \"{0}\", \"Response\": \"{1}\"}}", apiId, entity.GetAttributeValue <string>("new_response"));
                        client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
                        var response = client.UploadString(new Uri("http://rest.learncode.academy/api/myapi/inquiries/" + apiId), "PUT", data);

                        tracingService.Trace("web client plugin executed successfully, the record id is: " + apiId);
                    }
                }

                catch (WebException exception)
                {
                    string str = string.Empty;
                    if (exception.Response != null)
                    {
                        using (StreamReader reader =
                                   new StreamReader(exception.Response.GetResponseStream()))
                        {
                            str = reader.ReadToEnd();
                        }
                        exception.Response.Close();
                    }
                    if (exception.Status == WebExceptionStatus.Timeout)
                    {
                        throw new InvalidPluginExecutionException(
                                  "The timeout elapsed while attempting to issue the request.", exception);
                    }
                    throw new InvalidPluginExecutionException(String.Format(CultureInfo.InvariantCulture,
                                                                            "A Web exception occurred while attempting to issue the request. {0}: {1}",
                                                                            exception.Message, str), exception);
                }
            }
        }
예제 #52
0
        public static CuteContext Copy(IPluginExecutionContext context)
        {
            if (context == null)
            {
                return null;
            }

            var copy = new CuteContext(context);
            if (context.ParentContext != null)
            {
                copy.Parent = Copy(context.ParentContext);
            }

            return copy;
        }
 /// <summary>
 ///  Initializes a new instance of the <see cref="SolutionManagementHelper" /> class.
 /// </summary>
 /// <param name="crmService">Organization service</param>
 /// <param name="crmInitiatingUserService">Initiating User Service</param>
 /// <param name="crmContext">Plugin Execution Context</param>
 /// <param name="crmTracingService">Tracing Service</param>
 public SolutionManagementHelper(IOrganizationService crmService, IOrganizationService crmInitiatingUserService, IPluginExecutionContext crmContext, ITracingService crmTracingService) : base(crmService, crmInitiatingUserService, crmContext, crmTracingService)
 {
 }
 public UserLocaleHelper(IOrganizationService param_service, IPluginExecutionContext param_context)
 {
     _service = param_service;
     _context = param_context;
 }
예제 #55
0
 /// <summary>
 /// on Pre Retrive
 /// </summary>
 /// <param name="context"></param>
 void AddSecureFieldIfNotExists(IPluginExecutionContext context, IOrganizationService service)
 {
     var primaryEntityName = context.PrimaryEntityName;
     if (!String.IsNullOrEmpty(primaryEntityName))
     {
         TableRelationation tableRelation = TableRelationation.GetSinglton();
         ConfigCaching configCaching = GetCacheConfig(service);
         // load userTeam if not loaded yet because is in grant user
         UsersTeam userteam = UsersTeam.GetSinglton(service, configCaching);
         if (tableRelation.Entities.Contains(primaryEntityName.ToLower()))
         {
             if (context.InputParameters.Contains("ColumnSet"))
             {
                 ColumnSet columns = context.InputParameters["ColumnSet"] as ColumnSet;
                 if (columns != null && !columns.AllColumns)
                 { // Validate if exists
                     if (!columns.Columns.Contains(General.SecureField))
                         columns.AddColumn(General.SecureField);
                 }
             }
         }
     }
 }